text
stringlengths
8
6.88M
//#pragma once //#pragma once //#ifndef prob3_h //#define prob3_h //#include <iostream> // //int counter = 0, arraycounter = 0; //int defective[16]; //int y = 0X6a2f, t = 0, i2 = 17; //unsigned int c = 1 << 15; //int number = 0; //int j; // //void getZero() //{ // std::cout << '0'; // defective[arraycounter] = i2 - 1; //} // //void getOne() //{ // std::cout << '1'; //} // //void displayArray() //{ // std::cout << std::endl;; // std::cout << counter << " sprinklers are ON " << std::endl;; // std::cout << "Defective sprinklers: "; //} // //void AXoutput() //{ // std::cout << "AX = "; //} // //void outputNumber() //{ // std::cout << number << " "; //} //void MassonPark() //{ // __asm // { // call AXoutput; // ForLoop: // cmp i2, 1; // je DisplayArray; // Calculate: // mov eax, y; // and eax, c; // mov t, eax; // cmp t, 0; // je DisplayZero; // call getOne; // inc counter; // dec i2; // mov eax, y; // shl eax, 1; // mov y, eax; // jmp ForLoop; // DisplayZero: // call getZero; // dec i2; // inc arraycounter; // mov eax, y; // shl eax, 1; // mov y, eax; // jmp ForLoop; // DisplayArray: // lea esi, defective; // call displayArray; // whileLoop: // cmp arraycounter, 0; // je Done; // mov ebx, [esi]; // mov number, ebx; // call outputNumber; // add esi, 4; // dec arraycounter; // jmp whileLoop; // Done: // } //} // //#endif // !PROGRAM_3
#include "Kernel.hpp" #include "Context.hpp" #include "Device.hpp" #include "SException.hpp" #include <iostream> using namespace std; using namespace rustling; static char* Read_Source_File(const char *filename) { long int size = 0, res = 0; char *src = NULL; FILE *file = fopen(filename, "rb"); if (!file) return NULL; if (fseek(file, 0, SEEK_END)) { fclose(file); return NULL; } size = ftell(file); if (size == 0) { fclose(file); return NULL; } rewind(file); src = (char *) calloc(size + 1, sizeof(char)); if (!src) { src = NULL; fclose(file); return src; } res = fread(src, 1, sizeof(char) * size, file); if (res != sizeof(char) * size) { fclose(file); free(src); return (char*)NULL; } src[size] = '\0'; /* NULL terminated */ fclose(file); return src; } Kernel::Kernel(): name(""), kernel(0x0), program(0x0) {} Kernel::Kernel(const Kernel &other): name(other.getName()), kernel(other.kernel), program(other.program) { auto ret=clRetainKernel(kernel); if(ret!=CL_SUCCESS) throw(SException(ret)); ret=clRetainProgram(program); if(ret!=CL_SUCCESS) throw(SException(ret)); } Kernel Kernel::operator=(const Kernel &other) { name=other.name; kernel=other.kernel; program=other.program; auto ret=clRetainKernel(kernel); if(ret!=CL_SUCCESS) throw(SException(ret)); ret=clRetainProgram(program); if(ret!=CL_SUCCESS) throw(SException(ret)); } Kernel::Kernel( Context &ctx, Device& device, const string kernel_name, const string kernel_src, const string parameters, bool from_string): name(kernel_name) { ret_code ret; char* source = from_string ? 0x0 : Read_Source_File(kernel_src.c_str()); const char *src = from_string ? kernel_src.c_str() : 0x0; if (!source && !src) throw(KernelFileNotFound()); program = clCreateProgramWithSource( ctx.getContext(), 1, from_string ? &src : const_cast<const char**>(&source), NULL, &ret); if(source) free(source); ret |= clBuildProgram( program, 0, NULL, parameters.c_str(), NULL, NULL); if (ret != CL_SUCCESS) { size_t len = 0; char *buffer; clGetProgramBuildInfo( program, device.getID(), CL_PROGRAM_BUILD_LOG, 0, NULL, &len); buffer = (char*)calloc(len, sizeof(char)); clGetProgramBuildInfo( program, device.getID(), CL_PROGRAM_BUILD_LOG, len, buffer, NULL); clReleaseProgram(program); SException e(ret, buffer); free(buffer); throw e; } kernel = clCreateKernel(program, name.c_str(), &ret); if (ret != CL_SUCCESS) throw(SException(ret)); } Kernel::~Kernel() { clReleaseProgram(program); clReleaseKernel(kernel); } EnqueueKernel Kernel::operator()( initializer_list<size_t> global_wsize, initializer_list<size_t> local_wsize, initializer_list<AbstractKernelArg*> enq_args, cl_uint num_events_in_wait_list, const size_t* global_work_offset, const cl_event* enq_event_wait_list) { if (!global_wsize.size()) throw(InvalidGlobalGroupSize()); if (local_wsize.size() && local_wsize.size() != global_wsize.size()) throw(InvalidLocalGroupSize()); return EnqueueKernel( kernel, enq_args, global_wsize, local_wsize, global_work_offset, num_events_in_wait_list, enq_event_wait_list); } const string Kernel::getName() const { return name; } EnqueueKernel::~EnqueueKernel() {} EnqueueKernel::EnqueueKernel( cl_kernel& enq_kernel, initializer_list<AbstractKernelArg*> enq_kernel_args, initializer_list<size_t> enq_global_work_size, initializer_list<size_t> enq_local_work_size, const size_t* enq_global_work_offset, cl_uint enq_num_events_in_wait_list, const cl_event* enq_event_wait_list): kernel(enq_kernel), args(enq_kernel_args), work_dim(enq_global_work_size.size()), global_work_offset(enq_global_work_offset), global_work_size(enq_global_work_size), local_work_size(enq_local_work_size), num_events_in_wait_list(enq_num_events_in_wait_list), event_wait_list(enq_event_wait_list) {} void EnqueueKernel::execute(CmdQueue &queue) { cl_event* p_evt = static_cast<cl_event*>(NULL); if (p_event) p_evt = &getEventToBind(); cl_uint index = 0; // Check that all kernel arguments are provided cl_uint num_args; auto ret = clGetKernelInfo( kernel, CL_KERNEL_NUM_ARGS, sizeof(num_args), static_cast<void*>(&num_args), NULL); if(ret != CL_SUCCESS) throw(SException(ret)); if(static_cast<size_t>(num_args)!=args.size()) throw(InvalidKernelArgs()); // Range-based loop is unapplicable for (auto arg = args.begin(); arg != args.end(); arg++) { ret = clSetKernelArg( kernel, index++, (*arg)->getSize(), (*arg)->getPtr()); if (ret != CL_SUCCESS) throw(SException(ret)); } ret = clEnqueueNDRangeKernel( queue.getQueue(), kernel, work_dim, global_work_offset, &global_work_size[0], local_work_size.size() ? &local_work_size[0] : (size_t*)NULL, num_events_in_wait_list, event_wait_list, p_evt); if (ret != CL_SUCCESS) throw(SException(ret)); } //EnqueueKernel& EnqueueKernel::operator >>(Event &event) //{ // p_event = &event; // return *this; //} AbstractKernelArg::AbstractKernelArg() {} AbstractKernelArg::~AbstractKernelArg() {}
/** * * @file B3MSC1170A.cpp * @authors Yasuo Hayashibara * Naoki Takahashi * **/ #include "B3MSC1170A.hpp" #include <Tools/Byte.hpp> #include "B3MSC1170AControlTable.hpp" #include "../../../Communicator/Protocols/KondoB3M.hpp" namespace IO { namespace Device { namespace Actuator { namespace ServoMotor { B3MSC1170A::B3MSC1170A(RobotStatus::InformationPtr &robot_status_information_ptr) : SerialServoMotor(robot_status_information_ptr) { } B3MSC1170A::B3MSC1170A(const ID &id, RobotStatus::InformationPtr &robot_status_information_ptr) : SerialServoMotor(id, robot_status_information_ptr) { } B3MSC1170A::~B3MSC1170A() { } std::string B3MSC1170A::get_key() { return "B3MSC1170A"; } void B3MSC1170A::ping() { command_controller_access_assertion(); command_controller->set_packet( create_ping_packet(id()) ); } void B3MSC1170A::enable_torque(const bool &flag) { command_controller_access_assertion(); command_controller->set_packet( create_enable_torque_packet(id(), flag) ); } void B3MSC1170A::write_gain(const WriteValue &p, const WriteValue &i, const WriteValue &d) { command_controller_access_assertion(); write_gain_packet(id(), p, i, d); } void B3MSC1170A::write_angle(const float &degree) { command_controller_access_assertion(); command_controller->set_packet( create_write_angle_packet(id(), degree) ); } void B3MSC1170A::command_controller_access_assertion() { if(!command_controller) { throw std::runtime_error("Failed access to command_controller from IO::Device::Actuator::ServoMotor::B3MSC1170A"); } } void B3MSC1170A::write_gain_packet(const ID &packet_id, const WriteValue &, const WriteValue &, const WriteValue &) { } B3MSC1170A::SendPacket B3MSC1170A::create_ping_packet(const ID &) { SendPacket ret_packet; return ret_packet; } B3MSC1170A::SendPacket B3MSC1170A::create_enable_torque_packet(const ID &id, const bool &flag) { SendPacket value; value += flag ? Communicator::Protocols::KondoB3M::ServoMode::run_normal : Communicator::Protocols::KondoB3M::ServoMode::run_free; const auto ret_packet = Communicator::Protocols::KondoB3M::create_write_packet( id, B3MSC1170AControlTable::servo_servo_mode, value ); return ret_packet; } B3MSC1170A::SendPacket B3MSC1170A::create_write_angle_packet(const ID &id, const float &degree) { Communicator::Protocols::KondoB3M::Bytes write_degree_bytes; const auto degree_write_value = static_cast<short>(degree * 10); write_degree_bytes = static_cast<uint8_t>(Tools::Byte::low_byte(degree_write_value)); write_degree_bytes += static_cast<uint8_t>(Tools::Byte::high_byte(degree_write_value)); const auto ret_packet = Communicator::Protocols::KondoB3M::create_write_packet( id, B3MSC1170AControlTable::servo_desired_position, write_degree_bytes ); return ret_packet; } B3MSC1170A::SendPacket B3MSC1170A::create_write_p_gain_packet(const ID &id, const WriteValue &gain) { SendPacket value; value += gain; const auto ret_packet = Communicator::Protocols::KondoB3M::create_write_packet( id, B3MSC1170AControlTable::control_kp0, value ); return ret_packet; } B3MSC1170A::SendPacket B3MSC1170A::create_write_i_gain_packet(const ID &, const WriteValue &) { SendPacket ret_packet; return ret_packet; } B3MSC1170A::SendPacket B3MSC1170A::create_write_d_gain_packet(const ID &, const WriteValue &) { SendPacket ret_packet; return ret_packet; } } } } }
#include <bits/stdc++.h> using namespace std; long int n(long long int); int main() { int t; cin>>t; while(t--) { long long int a, b; cin>>a>>b; if(a==b) { cout<<0<<endl; continue; } if(b==1 && a==0) { cout<<1<<endl; continue; } if(b==1 || b==0) { cout<<-1<<endl; continue; } long int n1 = n(a), n2 = n(b-1), ans = 1; if(n1<n2) ans += n2-n1; else if(n1>n2) ans += 1; cout<<ans<<endl; } } long int n(long long int a) { string ret = ""; long int cnt = 0; while(a) { if(a%2!=0) { ret = "1"+ret; cnt++; } else ret = "0"+ret; a /= 2; } return cnt; }
#pragma once #include "AObject.h" #include "RAsset.h" #include "TDataTypes.h" class RAnimationSequence; class TBone; class BThing; class RAnimationNode: public AObject { DECLARE_CLASS(RAnimationNode,CLASS_Abstract) public: virtual void Tick(float Time) = 0; virtual void CalcBoneMatrices(TArray<TBone*>& Bones, float Weight) = 0; virtual void Activated() = 0; virtual void Deactivated() = 0; }; class RAnimationSequenceNode: public RAnimationNode { DECLARE_CLASS(RAnimationSequenceNode,) public: float ElapsedTime; RAssetPtr<RAnimationSequence> AnimationSequence; virtual void Tick(float Time); virtual void CalcBoneMatrices(TArray<TBone*>& Bones, float Weight); virtual void Activated(); virtual void Deactivated(); }; class RAnimationBlend: public RAnimationNode { DECLARE_CLASS(RAnimationBlend,) public: int TargetIndex; TArray<RAnimationNode*> Children; TArray<float> Weights; TArray<float> BlendRates; void Initialize(class BThing* T, class RBoneHierarchy* B); virtual void SetActiveNode(int NodeIndex, float BlendTime); virtual void Tick(float Time); virtual void CalcBoneMatrices(TArray<TBone*>& Bones, float Weight); virtual void Activated(); virtual void Deactivated(); }; class RAnimationStateBlend: public RAnimationBlend { DECLARE_CLASS(RAnimationStateBlend,) public: BThing* Owner; void Initialize(BThing* InOwner); virtual void Tick(float Time); }; class RAnimationTree: public RAnimationNode { DECLARE_CLASS(RAnimationTree,) public: RAnimationNode* Root; virtual void Tick(float Time); virtual void CalcBoneMatrices(TArray<TBone*>& Bones, float Weight); virtual void Activated() {} virtual void Deactivated() {} };
// This file is subject to the terms and conditions defined in 'LICENSE' in the source code package #ifndef JACTORIO_INCLUDE_CORE_COORDINATE_TUPLE_H #define JACTORIO_INCLUDE_CORE_COORDINATE_TUPLE_H #pragma once #include <tuple> #include "data/cereal/serialize.h" #include <cereal/types/base_class.hpp> namespace jactorio { template <typename TVal> struct Position1 { static_assert(std::is_trivial<TVal>::value); using ValueT = TVal; Position1() : x(0) {} explicit Position1(TVal x) : x(x) {} TVal x; CEREAL_SERIALIZE(archive) { archive(x); } friend bool operator==(const Position1& lhs, const Position1& rhs) { return lhs.x == rhs.x; } friend bool operator!=(const Position1& lhs, const Position1& rhs) { return !(lhs == rhs); } }; template <typename TVal> struct Position2 : Position1<TVal> { using ValueT = TVal; Position2() : Position1<TVal>(), y(0) {} Position2(const Position1<TVal>& x, TVal y) : Position1<TVal>(x), y(y) {} Position2(TVal x, TVal y) : Position1<TVal>(x), y(y) {} TVal y; CEREAL_SERIALIZE(archive) { archive(cereal::base_class<Position1<TVal>>(this), y); } friend bool operator==(const Position2& lhs, const Position2& rhs) { return std::tie(static_cast<const Position1<TVal>&>(lhs), lhs.y) == std::tie(static_cast<const Position1<TVal>&>(rhs), rhs.y); } friend bool operator!=(const Position2& lhs, const Position2& rhs) { return !(lhs == rhs); } }; template <typename TVal> struct Position3 : Position2<TVal> { using ValueT = TVal; Position3() : Position2<TVal>(), z(0) {} Position3(const Position2<TVal>& xy, TVal z) : Position2<TVal>(xy), z(z) {} Position3(TVal x, TVal y, TVal z) : Position2<TVal>(x, y), z(z) {} TVal z; CEREAL_SERIALIZE(archive) { archive(cereal::base_class<Position2<TVal>>(this), z); } friend bool operator==(const Position3& lhs, const Position3& rhs) { return std::tie(static_cast<const Position2<TVal>&>(lhs), lhs.z) == std::tie(static_cast<const Position2<TVal>&>(rhs), rhs.z); } friend bool operator!=(const Position3& lhs, const Position3& rhs) { return !(lhs == rhs); } }; template <typename TPosition> struct QuadPosition { static_assert(std::is_base_of<Position1<typename TPosition::ValueT>, TPosition>::value); using PositionT = TPosition; QuadPosition() = default; QuadPosition(const TPosition top_left, const TPosition bottom_right) : topLeft(top_left), bottomRight(bottom_right) {} TPosition topLeft; TPosition bottomRight; friend bool operator==(const QuadPosition& lhs, const QuadPosition& rhs) { return std::tie(lhs.topLeft, lhs.bottomRight) == std::tie(rhs.topLeft, rhs.bottomRight); } friend bool operator!=(const QuadPosition& lhs, const QuadPosition& rhs) { return !(lhs == rhs); } }; } // namespace jactorio #endif // JACTORIO_INCLUDE_CORE_COORDINATE_TUPLE_H
#include <Arduino.h> #include <ESP8266WebServer.h> #include <PubSubClient.h> #include <ESP_MQTTLogger.h> #include "pixel_peripheral.h" #define PIXEL_PIN 2 #define PIXEL_COUNT 64 // corresponds to 10fps which is fast enough for static displays #define FRAME_MILLIS 30 PixelPeripheral::PixelPeripheral() {} // ESP8266 show() is external to enforce ICACHE_RAM_ATTR execution extern "C" void ICACHE_RAM_ATTR show( uint8_t pin, uint8_t *pixels, uint32_t numBytes); void PixelPeripheral::set_pixel(uint16_t pixel, uint8_t r, uint8_t g, uint8_t b) { // set the pixel value in memory uint16_t pa = pixel * _colour_depth; // assuming GRB addressing with this for speed _px[pa] = g; _px[pa+1] = r; _px[pa+2] = b; } void PixelPeripheral::set_strip(uint8_t r, uint8_t g, uint8_t b) { // sets the entire strip this colour. for (uint16_t i=0; i < _px_count; i++) { set_pixel(i, r, g, b); } } void PixelPeripheral::initialise_pixels(uint16_t num_pixels) { // set up the pixel array, allocate mem etc. // if (_px) { free (_px); _px_count = 0; } if (num_pixels > 0) { if (_px = (uint8_t *)malloc(num_pixels * _colour_depth)) { memset(_px, 0, num_pixels * _colour_depth); _px_count = num_pixels; } else { _px_count = 0; } } pinMode(PIXEL_PIN, OUTPUT); Serial.print("Init pixels. Pixel count: "); Serial.println(_px_count); } void PixelPeripheral::begin(ESP_MQTTLogger& l) { // set up the logger _logger = l; _updateable = true; _publishable = false; initialise_pixels(PIXEL_COUNT); bool subbed = _logger.subscribe("ic/#"); if (! subbed) { Serial.println("Couldn't subscribe to content messages"); _logger.publish("sys/error", "sub_fail"); } else { _logger.publish("oc/status", "available"); } } void PixelPeripheral::publish_data() { // for a pixel display - this is a NOOP } void PixelPeripheral::sub_handler(String topic, String payload) { // bust up the string so we can grab the pertinent parts. char s[256]; strcpy(s, topic.c_str()); char* token = strtok(s, "/"); uint16_t pixel_number; uint8_t r, g, b; PX_STATES state = PXP_START; const char* cmp = "px"; // we can drop the first as it's only going to be the ID. while (token) { token = strtok(NULL, "/"); String t = String(token); switch (state) { case PXP_START: // see if our token is px or strip if (t == "px") { state = PXP_PIXEL; } else if (t == "strip") { state = PXP_STRIP; } else if (t == "data") { state = PXP_DATA; } continue; break; case PXP_PIXEL: // the next token should be a number // explicitly test for 0 if (t == "0") { pixel_number = 0; } else { pixel_number = t.toInt(); if (pixel_number == 0) { // there was an error pixel_number = NULL; } } // get the pixel values off the payload and turn them into // rgb vals r = g = b = 0; // convert to values which are then put into the pixel array. if (payload.length() != 6) { Serial.print("PXP: Error pixel value incorrect: "); Serial.println(payload); } else { // we're good so peel the numbers off and let's go. String v = payload.substring(0, 2); r = (uint8_t)strtol(v.c_str(), NULL, 16); v = payload.substring(2, 4); g = (uint8_t)strtol(v.c_str(), NULL, 16); v = payload.substring(4); b = (uint8_t)strtol(v.c_str(), NULL, 16); if (pixel_number != NULL) { set_pixel(pixel_number, r, g, b); } } break; // PXP_PIXEL case PXP_STRIP: r = g = b = 0; // convert to values which are then put into the pixel array. if (payload.length() != 6) { Serial.print("PXP: Error pixel value incorrect: "); Serial.println(payload); } else { // we're good so peel the numbers off and let's go. String v = payload.substring(0, 2); r = (uint8_t)strtol(v.c_str(), NULL, 16); v = payload.substring(2, 4); g = (uint8_t)strtol(v.c_str(), NULL, 16); v = payload.substring(4); b = (uint8_t)strtol(v.c_str(), NULL, 16); set_strip(r, g, b); } break; case PXP_DATA: // we have here a buffer of pixel data. // reset to zeros uint16_t px_bytes = _px_count * _colour_depth; uint16_t cpy_len = px_bytes; memset(_px, 0, px_bytes); // now overwrite the px buffer if (payload.length() < px_bytes) { cpy_len = payload.length(); } memcpy(_px, payload.c_str(), cpy_len); break; } } } void PixelPeripheral::update() { // update the state of the pixels // // we do this to fps lock the pixels. The reason is that // update is called as fast as possible and it can sometimes // cause issues with flicker. if (millis() > (_last_update + FRAME_MILLIS) ) { show(PIXEL_PIN, _px, _px_count * _colour_depth); _last_update = millis(); } }
#include <bits/stdc++.h> using namespace std; void swap(int a[],int b,int c){ int temp=a[b]; a[b]=a[c]; a[c]=temp; } void dnfSort(int a[],int low,int mid,int high){ while(mid<=high){ if(a[mid]==0){ swap(a,low,mid); low++;mid++; } else if(a[mid]==1){ mid++; } else if(a[mid]==2){ swap(a,mid,high); high--; } } } int main() { int a[]={1,1,0,2,1,1,0,2,0,1}; dnfSort(a,0,0,9); for(int i=0;i<10;i++){ cout<<a[i]<<" "; } return 0; }
#ifndef _TNA_TASKING_THREAD_POOL_H_ #define _TNA_TASKING_THREAD_POOL_H_ #include "../trace/trace.h" #include "../types.h" #include "task.h" #include <assert.h> #include <chrono> namespace tna { struct atomic_counter_t; #define INVALID_THREAD_ID 0xffffffff #define _TNA_TASKING_MAX_INFO_STRING_LENGTH _TNA_TRACE_MAX_INFO_STRING_LENGTH #define _TNA_TASKING_MAX_NAME_STRING_LENGTH _TNA_TRACE_MAX_NAME_STRING_LENGTH using yield_func_t = bool (*)(void*); /** * \brief Initializes and starts the thread pool, and creates the task queues. * Currently, each thred has its own queue id, which equals the id of the thread. */ void tasking_start_thread_pool(uint32_t num_threads); /** * \brief Stops the thread pool */ void tasking_stop_thread_pool(); /** * \brief Sends the given task for execution at the given thread * * \param task The task to run * \param queueId The queueId to add the task to * \param counter A pointer to the atomic_counter_t that will be used for * synchronization * \param info String unsed for debugging/dev */ void tasking_execute_task_async(uint32_t queueId, task_t task, atomic_counter_t* counter, const char* name, const char* info); /** * \brief Sends the given task for execution at the given thread, and blocks * until it finishes * * \param task The task to run * \param queueId The queueId to add the task to * \param counter A pointer to the atomic_counter_t that will be used for * synchronization * \param info String unsed for debugging/dev */ void tasking_execute_task_sync(uint32_t queueId, task_t task, atomic_counter_t* counter, const char* name, const char* info); /** * \brief Gets the current thread id * * \return The id of the thread currently running */ uint32_t tasking_get_current_thread_id(); /** * \brief Yields the current task and returns execution path to the thread pool * to pick another task */ void tasking_yield(); void tasking_yield(yield_func_t yield_func, void* data); void tasking_yield(atomic_counter_t* sync_counter); /** * @brief Gets the number of threads available in the buffer pool * * @return Returns the number of available threads */ uint32_t tasking_get_num_threads(); } /* tna */ #endif /* ifndef _TASKING_THREAD_POOL_H_ */
#include <iostream> using namespace std; // --------------------- Edited on github // I am in branch test int fact( int n ) { if ( n == 0 ) return 1; return fact(n-1) * n; } // This is function main int main() { // Get Input int n; cin>>n; cout<<fact(n); return 0; }
// // Recorder - a GPS logger app for Windows Mobile // Copyright (C) 2006-2019 Michael Fink // /// \file WaitEventThread.cpp WaitEvent() thread implementation // #include "stdafx.h" #include "WaitEventThread.hpp" /// note: called from wait thread bool CWaitEventThread::WaitComm() { // wait handle must not be set DWORD dwTest = ::WaitForSingleObject(m_hEventWait, 0); ATLASSERT(WAIT_TIMEOUT == dwTest); // wait for an event //ATLTRACE(_T("T2: calling WaitCommEvent() ...\n")); BOOL bRet = ::WaitCommEvent(m_hPort, &m_dwEventResult, NULL); //ATLTRACE(_T("T2: returned from WaitCommEvent()\n")); if (FALSE == bRet) { DWORD dwLastError = GetLastError(); //ATLTRACE(_T("T2: returned error from WaitCommEvent: %08x\n"), dwLastError); // event mask was set if (m_dwEventResult == 0) return true; if (dwLastError == ERROR_INVALID_HANDLE) return false; } //ATLTRACE(_T("T2: event result from wait: %08x, mask is %08x\n"), m_dwEventResult, m_dwEventMask); return true; } int CWaitEventThread::Run() { //ATLTRACE(_T("T2: starting worker thread\n")); bool bLoop = true; do { // setting "ready" event SetEvent(m_hEventReady); //ATLTRACE(_T("T2: waiting for continue or stop event\n")); // wait for continue or stop event HANDLE hWaitHandles[2] = { m_hEventContinue, m_hEventStop }; DWORD dwRet = WaitForMultipleObjects(2, hWaitHandles, FALSE, INFINITE); switch (dwRet) { case WAIT_OBJECT_0: // continue event //ATLTRACE(_T("T2: got continue event\n")); break; case WAIT_OBJECT_0 + 1: // stop event //ATLTRACE(_T("T2: got stop event\n")); break; default: // may be timeout or abandoned handle //ATLTRACE(_T("T2: error while waiting for continue or stop\n")); break; } // stop loop when event was set if (WAIT_OBJECT_0 + 1 == dwRet) break; // reset continue event ResetEvent(m_hEventContinue); ////ATLTRACE(_T("T2: resetting wait event\n")); //ResetEvent(m_hEventWait); ////ATLTRACE(_T("T2: resetting wait event done\n")); // must be reset ATLASSERT(WAIT_TIMEOUT == ::WaitForSingleObject(m_hEventWait, 0)); if (!WaitComm()) break; // error while waiting // must still be reset ATLASSERT(WAIT_TIMEOUT == ::WaitForSingleObject(m_hEventWait, 0)); // set event that wait has succeeded //ATLTRACE(_T("T2: setting wait event\n")); SetEvent(m_hEventWait); //ATLTRACE(_T("T2: setting wait event done\n")); // must be set ATLASSERT(WAIT_OBJECT_0 == ::WaitForSingleObject(m_hEventWait, 0)); // exit loop when stop event was set meanwhile } while (WAIT_TIMEOUT == ::WaitForSingleObject(m_hEventStop, 0)); //ATLTRACE(_T("T2: stopped worker thread\n")); return 0; }
// netbeat.cpp - Netbeat timer display // https://github.com/vividos/OldStuff/ // (c) 1999, 2021 Michael Fink #include <dos.h> #include <stdio.h> #include <conio.h> void main() { printf("Netbeat:\n"); time t; unsigned long sekunden, netbeat; char lastdigit = 10; do { do { gettime(&t); sekunden = t.ti_hour * 3600L + t.ti_min * 60L + t.ti_sec; sekunden *= 100L; sekunden += t.ti_hund; sekunden *= 10L; netbeat = (sekunden / 864); } while ((netbeat & 7) == lastdigit); lastdigit = netbeat & 7; printf("@%03u://%02u\r", (unsigned)((netbeat) / 100), ((unsigned)netbeat % 100)); } while (kbhit() == 0); if (getch() == 0) getch(); };
#include "leaderboard.h" #include "ui_leaderboard.h" #include "functions.h" #include <QFile> #include <QString> leaderboard::leaderboard(QWidget *parent) : QWidget(parent), ui(new Ui::leaderboard) { ui->setupUi(this); } leaderboard::~leaderboard() { delete ui; } void leaderboard::on_backButton_clicked() { this->close();// Закрываем окно emit firstWindow(); // И вызываем сигнал на открытие главного окна } void leaderboard::on_updateButton_clicked() { QString string; QFile file("../God_Tetris/leaderlist"); file.open(QIODevice::ReadOnly); while((string = file.readLine()) != "") { ui->leaderList->append(string); } file.close(); }
#ifndef ANTENNE_H #define ANTENNE_H #include <string> #include "point.h" class Antenne { public: Antenne(); Antenne(double x, double y, std::string nom, double puissance, double frequence); Point position(); const std::string nom(); double puissance(); double frequence(); void setNom(std::string nom); void setPuissance(double puissance); void setFrequence(double frequence); void setPosition(Point position); private: Point d_position; std::string d_nom; double d_frequence; double d_puissance; }; #endif // ANTENNE_H
#include <bits/stdc++.h> using namespace std; class Solution { public: bool validateBinaryTreeNodes(int n, vector<int> &leftChild, vector<int> &rightChild) { queue<int> q; unordered_set<int> s; if (leftChild.size() == 0) return true; for (int i = 0; i < leftChild.size(); i++) { if (leftChild[i] == -1 && rightChild[i] == -1) continue; if (leftChild[i] != -1) { s.insert(leftChild[i]); q.push(leftChild[i]); } if (rightChild[i] != -1) { s.insert(rightChild[i]); q.push(rightChild[i]); } break; } while (q.size() != 0) { int x = q.front(); q.pop(); if (s.count(leftChild[x]) || s.count(rightChild[x])) return false; if (leftChild[x] != -1) { s.insert(leftChild[x]); q.push(leftChild[x]); } if (rightChild[x] != -1) { s.insert(rightChild[x]); q.push(rightChild[x]); } } if (s.size() != n - 1) // for forest return false; return true; } }; int main() { Solution val; vector<int> l = {1, -1, 3, -1}, r = {2, -1, -1, -1}; cout << val.validateBinaryTreeNodes(4, l, r) << endl; return 0; }
#include <xtl.h> #include "..\utils.h" #include "..\main.h" #include "screenshot.h" void CXBScreenShot::NextFreeFile() { while (FileExists(imagefilename) && imagenumber < 9999) { _itoa(imagenumber,textnumber,10); imagenumber++; strncpy(imagefilename+(17-strlen(textnumber)),textnumber,strlen(textnumber)); } return; } void CXBScreenShot::Take() { IDirect3DSurface8 *pFrontBuffer; my3D.Device()->GetBackBuffer(-1,D3DBACKBUFFER_TYPE_MONO,&pFrontBuffer); NextFreeFile(); XGWriteSurfaceToFile(pFrontBuffer, imagefilename); pFrontBuffer->Release(); return; } CXBScreenShot::CXBScreenShot() { strcpy(imagefilename,"e:\\screenshot0000.bmp"); while (FileExists(imagefilename) && imagenumber < 9999) { _itoa(imagenumber,textnumber,10); imagenumber++; strncpy(imagefilename+(17-strlen(textnumber)),textnumber,strlen(textnumber)); } } CXBScreenShot::~CXBScreenShot() { }
#include "Rook.h" #include <math.h> Rook::Rook() { this->xpos = 0; this->ypos = 0; } Rook::Rook(bool pisWhite) { this->xpos = 0; this->ypos = 0; this->isWhite = pisWhite; if (isWhite) this->character = 'R'; else this->character = 'r'; } bool Rook::move(char toxpos, char toypos) { if ((abs(this->xpos - toxpos) == 0) || (abs(this->ypos - toypos) == 0)) { return 1; } else return 0; } Rook::~Rook() { }
#include "stdafx.h" #include <time.h> #include "SimuScanner.h" #include "ScanPointCloud.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define NOISE_RATIO 0.01f /////////////////////////////////////////////////////////////////////////////// BOOL CSimuScanner::LoadWorldModel(char* strFileName) { FILE* fp = fopen(strFileName, "rt"); if (fp == NULL) return FALSE; fscanf(fp, "%d\t%d\n", &m_nRefLineCount, &m_nCircleCount); for (int i = 0; i < m_nRefLineCount; i++) { int nX1, nY1, nX2, nY2; fscanf(fp, "%d\t%d\t%d\%d\n", &nX1, &nY1, &nX2, &nY2); /*float fX1, fY1, fX2, fY2; fX1 = (float)nX1 / 1000; fX2 = (float)nX2 / 1000; fY1 = (float)nY1 / 1000; fY2 = (float)nY2 / 1000;*/ m_ln[i] = CLine(CPnt(nX1, nY1), CPnt(nX2, nY2)); //m_ln[i] = CLine(CPnt(fX1, fY1), CPnt(fX2, fY2)); } for (int i = 0; i < m_nCircleCount; i++) { int nX1, nY1, nRadius; fscanf(fp, "%d\t%d\t%d\n", &nX1, &nY1, &nRadius); m_circle[i] = CCircle(CPnt(nX1, nY1), nRadius / 1.0f); } if (!m_MovingObjSet.Load(fp)) return FALSE; fclose(fp); srand( (unsigned)time( NULL ) ); m_MovingObjSet.Start(); //////////////////////// CScanPointCloud* pCloud = new CScanPointCloud(m_nRefLineCount * 2); for (int i = 0; i < m_nRefLineCount; i++) { pCloud->m_pPoints[2*i].x = m_ln[i].m_ptStart.x; pCloud->m_pPoints[2*i].y = m_ln[i].m_ptStart.y; pCloud->m_pPoints[2*i+1].x = m_ln[i].m_ptEnd.x; pCloud->m_pPoints[2*i+1].y = m_ln[i].m_ptEnd.y; } m_fLeftMost = pCloud->LeftMost(); m_fRightMost = pCloud->RightMost(); m_fTopMost = pCloud->TopMost(); m_fBottomMost = pCloud->BottomMost(); m_ptCenter.x = (m_fLeftMost + m_fRightMost)/2; m_ptCenter.y = (m_fTopMost + m_fBottomMost)/2; m_fSizeX = pCloud->Width(); m_fSizeY = pCloud->Height(); delete pCloud; return TRUE; } void CSimuScanner::AddNoise(CPnt& ptIn, float fNoise, CPnt& ptOut) { int nAng = rand() % 360; CAngle ang(nAng*PI/180); int nRadius = (int)(fNoise); if (nRadius == 0) nRadius = 1; nRadius = rand() % nRadius; if (nRadius == 0) nRadius = 1; float fRadius = nRadius; CLine ln(ptIn, ang, fRadius); ptOut = ln.m_ptEnd; } void CSimuScanner::AddNoise(float fDistIn, float& fDistOut) { float fNoise = fDistIn * NOISE_RATIO; int nAmp = (int)(fNoise); int nNoise = (nAmp == 0) ? 0 : rand() % nAmp; nNoise -= nAmp/2; fDistOut = fDistIn + nNoise; } // // 进行一次扫描。 // int CSimuScanner::Scan(CPnt& ptScanner, float fStartAng, float fEndAng) { int nDetectCount = 0; int nNum = (int)((fEndAng - fStartAng) / m_fAngReso); for (int i = 0; i < nNum; i++) { CAngle ang(fStartAng + i * m_fAngReso); CLine ScanLine(ptScanner, ang, DEFAULT_SCAN_MAX_RANGE); BOOL bFound = FALSE; float fMinDist = DEFAULT_SCAN_MAX_RANGE; CPnt ptClosest; for (int j = 0; j < m_nRefLineCount; j++) { float fDist; CPnt pt; if (ScanLine.IntersectLineAt(m_ln[j], pt, fDist)) { if (fDist < fMinDist) { bFound = TRUE; ptClosest = pt; fMinDist = fDist; } } } for (int j = 0; j < m_nCircleCount; j++) { float fDist; CPnt ptNear; if (m_circle[j].IntersectLineAt(ScanLine, ptNear, fDist)) { if (fDist < fMinDist) { bFound = TRUE; ptClosest = ptNear; fMinDist = fDist; } } } for (int j = 0; j < m_MovingObjSet.m_nCount; j++) { float fDist; CPnt ptNear; if (m_MovingObjSet.m_Obj[j].m_Circle.IntersectLineAt(ScanLine, ptNear, fDist)) { if (fDist < fMinDist) { bFound = TRUE; ptClosest = ptNear; fMinDist = fDist; } } } // 如果发现扫描返回点,则记录最近的那个点 if (bFound) { float fMinDist1 = fMinDist; AddNoise(fMinDist, fMinDist1); m_fDist[nDetectCount] = fMinDist1; } else m_fDist[nDetectCount] = DEFAULT_SCAN_MAX_RANGE; m_nDist[nDetectCount] = (int)(m_fDist[nDetectCount]); TRACE(_T("%.3f "), m_fDist[nDetectCount]/1000.0f); nDetectCount++; } TRACE(_T("\n")); return nDetectCount; } void CSimuScanner::GetWorldSize(CPnt& ptCenter, float& fSizeX, float& fSizeY) { CScanPointCloud* pCloud = new CScanPointCloud(m_nRefLineCount * 2); for (int i = 0; i < m_nRefLineCount; i++) { pCloud->m_pPoints[2*i].x = m_ln[i].m_ptStart.x; pCloud->m_pPoints[2*i].y = m_ln[i].m_ptStart.y; pCloud->m_pPoints[2*i+1].x = m_ln[i].m_ptEnd.x; pCloud->m_pPoints[2*i+1].y = m_ln[i].m_ptEnd.y; } float fLeftMost = pCloud->LeftMost(); float fRightMost = pCloud->RightMost(); float fTopMost = pCloud->TopMost(); float fBottomMost = pCloud->BottomMost(); ptCenter.x = (fLeftMost + fRightMost)/2; ptCenter.y = (fTopMost + fBottomMost)/2; fSizeX = pCloud->Width(); fSizeY = pCloud->Height(); delete pCloud; } void CSimuScanner::DrawWorldModel(CScreenReference& ScrnRef, CDC* pDc, COLORREF color) { CPen Pen(PS_SOLID, 1, color); CPen* pOldPen = pDc->SelectObject(&Pen); for (int i = 0; i < m_nRefLineCount; i++) { CPnt ptStart = m_ln[i].m_ptStart; CPnt ptEnd = m_ln[i].m_ptEnd; CPoint pnt1 = ScrnRef.GetWindowPoint(ptStart); CPoint pnt2 = ScrnRef.GetWindowPoint(ptEnd); pDc->MoveTo(pnt1); pDc->LineTo(pnt2); } pDc->SelectObject(pOldPen); for (int i = 0; i < m_nCircleCount; i++) m_circle[i].Draw(ScrnRef, pDc, color, 1); m_MovingObjSet.NewDraw(); } void CSimuScanner::DrawMovingObj(CScreenReference& ScrnRef, CDC* pDc, COLORREF color) { m_MovingObjSet.Draw(ScrnRef, pDc, color, 1); }
#include <QApplication> #include <QGraphicsScene> #include <QGraphicsRectItem> #include <QGraphicsView> #include <QDebug> #include "Joueur.h" #include "tableauTuile.h" int main(int argc, char* argv[]) { QApplication a(argc, argv); //----------------Paramètre la scène // cree une Scene QGraphicsScene* scene = new QGraphicsScene; // ajoute une vu sur la scene QGraphicsView* view = new QGraphicsView(); view->setScene(scene); view->show(); //affiche la scene -> LES WIDGETS SONT INVISIBLES DE BASE!!! //ajuste la taille de la fenêtre a une valeur fixe view->setFixedSize(1024, 600); scene->setSceneRect(0, 0, 1024, 600); //désactive le scoling view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); //---------------Paramètre le tableau de jeu //crée le plateau de jeux tableauTuile* board = new tableauTuile(); //position d'origine du tableau int hauteur = 4; int largeur = 4; int origine_X = ((view->width()) / 2) - ((largeur * 113) / 2); int origine_Y = ((view->height()) / 2) - ((hauteur * 113) / 2); //place les tuiles board->placegrille(origine_X, origine_Y, hauteur, largeur, scene); //---------------Paramètre le joueur // Cree un joueur joueur* J1 = new joueur; J1->setRect(100, 100, 113, 113); // ajoute le joueur à la scene scene->addItem(J1); // rend le joueur focussable J1->setFlag(QGraphicsItem::ItemIsFocusable); // met le joueur comme focus de la scenne (pour qu'il puisse reçevoir les KeyEvents) J1->setFocus(); return a.exec(); }
// Copyright (c) 2014-2019 winking324 // #include "view/main_window.h" namespace avc { MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { central_widget_ = new CentralWidget(this); setCentralWidget(central_widget_); setFixedSize(600, 600); } } // namespace avc
/* * Copyright (C) 2007-2015 Frank Mertens. * * Use of this source is governed by a BSD-style license that can be * found in the LICENSE file. * */ #ifndef FLUXMAKE_CONFIGURESTAGE_H #define FLUXMAKE_CONFIGURESTAGE_H #include "BuildStage.h" namespace fluxmake { class ConfigureStage: public BuildStage { public: ConfigureStage(BuildPlan *plan): BuildStage(plan) {} bool run(); private: String configureShell(String shellCommand) const; bool findIncludePath(SystemPrerequisite *prerequisite, String *includePath); bool findLibraryPath(SystemPrerequisite *prerequisite, String *libraryPath); }; } // namespace fluxmake #endif // FLUXMAKE_CONFIGURESTAGE_H
//-------------------------------------------------------------------------------------- // File: 20200507.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "resource.h" #include "Director.h" //-------------------------------------------------------------------------------------- // Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED) // and aren't tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnD3D9CreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { Director::getins()->DirectorInit(); return S_OK; } //-------------------------------------------------------------------------------------- // Render the scene using the D3D9 device //-------------------------------------------------------------------------------------- void CALLBACK OnD3D9FrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { HRESULT hr; // Clear the render target and the zbuffer V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB( 0, 45, 50, 170 ), 1.0f, 0 ) ); // Render the scene if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { Director::getins()->UpdateScene(); V( pd3dDevice->EndScene() ); } } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9CreateDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnD3D9DestroyDevice( void* pUserContext ) { exit(0); } //-------------------------------------------------------------------------------------- // Initialize everything and go into a render loop //-------------------------------------------------------------------------------------- //INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) int main(void) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // Set the callback functions DXUTSetCallbackD3D9DeviceCreated( OnD3D9CreateDevice ); DXUTSetCallbackD3D9FrameRender( OnD3D9FrameRender ); DXUTSetCallbackD3D9DeviceDestroyed( OnD3D9DestroyDevice ); // TODO: Perform any application-level initialization here // Initialize DXUT and create the desired Win32 window and Direct3D device for the application DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, true, true ); // handle the default hotkeys DXUTSetCursorSettings( true, true ); // Show the cursor and clip it when in full screen DXUTCreateWindow( L"20200507" ); DXUTCreateDevice( true, ScreenWidth, ScreenHeight ); // Start the render loop DXUTMainLoop(); // TODO: Perform any application-level cleanup here return DXUTGetExitCode(); }
#ifndef _PROHIBITION_GENERATOR_H_ #define _PROHIBITION_GENERATOR_H_ #include "CAN_interface.h" #include "proto_def.h" #include <map> #include <vector> struct pt { U8 prior; U32 timer; pt( U8 inprior, U32 intimer ){ prior = inprior; timer = intimer; } pt(){} }; class CProhibitionGenerator { public: CProhibitionGenerator( systems_t system, C_CAN_CHANNELL * chan ){ _system = system; _chan = chan; } void process_100ms( void ); std::map< U32, pt > prohibitions; private: systems_t _system; C_CAN_CHANNELL * _chan; std::vector< U32 > _vecProhibitions; void _addVecProhibition( systems_t address, U32 message, U8 prior ); }; extern CProhibitionGenerator * prohibitionGenerator; #endif
#include "graph/table_node.hpp" #include <cstdlib> #include <string> #include <libgccjit.h> #include "graph/nullary_node.hpp" #include "graph/query_scope.hpp" extern "C" { void my_internal_function(std::int64_t input_arg) { std::printf("%ld\n", input_arg * 2); } } namespace flow { TableNode::TableNode(const std::string &name, const std::string &table_name) : NullaryNode(name), m_table_name(table_name), m_capacity(128), m_data(reinterpret_cast<std::int64_t*>(std::malloc(128 * sizeof(std::int64_t)))) { } std::int64_t TableNode::getNumTuples() const { return m_num_tuples; } TableNode::~TableNode() { std::free(m_data); } void TableNode::insert(const std::int64_t value) { if (m_num_tuples >= m_capacity) { m_data = reinterpret_cast<std::int64_t *>( std::realloc(m_data, (m_capacity * 2) * sizeof(std::int64_t))); m_capacity = 2 * m_capacity; } m_data[m_num_tuples] = value; ++m_num_tuples; } void TableNode::codegen(gcc_jit_context *context, QueryScope *scope) { gcc_jit_function *query_function = scope->getQueryFunction(); // Initial block. gcc_jit_block *table_node_initial = gcc_jit_function_new_block(query_function, "TableNodeInitial"); // Loop condition. gcc_jit_block *table_node_loop_cond = gcc_jit_function_new_block(query_function, "TableNodeLoopCond"); // Loop body gcc_jit_block *table_node_loop_body = gcc_jit_function_new_block(query_function, "TableNodeLoopBody"); // Loop body-end gcc_jit_block *table_node_loop_body_end = gcc_jit_function_new_block(query_function, "TableNodeLoopBodyEnd"); // Loop exit gcc_jit_block *table_node_loop_exit = gcc_jit_function_new_block(query_function, "TableNodeLoopExit"); gcc_jit_type *int64_type = gcc_jit_context_get_type(context, GCC_JIT_TYPE_LONG_LONG); // Intial block actions. gcc_jit_lvalue *tuple_id = gcc_jit_function_new_local(query_function, nullptr, int64_type, "tuple_id"); gcc_jit_block_add_assignment(table_node_initial, nullptr, tuple_id, gcc_jit_context_zero(context, int64_type)); gcc_jit_lvalue *total_num_tuples = gcc_jit_function_new_local(query_function, nullptr, int64_type, "total_num_tuples"); gcc_jit_block_add_assignment(table_node_initial, nullptr, total_num_tuples, gcc_jit_context_new_rvalue_from_long(context, int64_type, getNumTuples())); gcc_jit_type *int64_pointer_type = gcc_jit_type_get_pointer(int64_type); gcc_jit_rvalue *column_begin = gcc_jit_context_new_rvalue_from_ptr(context, int64_pointer_type, m_data); gcc_jit_lvalue *value = gcc_jit_context_new_array_access(context, nullptr, column_begin, gcc_jit_lvalue_as_rvalue(tuple_id)); // Loop condition actions. gcc_jit_rvalue *loop_guard = gcc_jit_context_new_comparison( context, nullptr, GCC_JIT_COMPARISON_GE, gcc_jit_lvalue_as_rvalue(tuple_id), gcc_jit_lvalue_as_rvalue(total_num_tuples)); gcc_jit_block_end_with_conditional(table_node_loop_cond, nullptr, loop_guard, table_node_loop_exit, table_node_loop_body); // Loop body actions. gcc_jit_block *table_node_parent_begin = gcc_jit_function_new_block(query_function, "Parent1Begin"); gcc_jit_block_end_with_jump(table_node_loop_body, nullptr, table_node_parent_begin); gcc_jit_block *table_node_parent_end = gcc_jit_function_new_block(query_function, "ParentEnd1"); gcc_jit_block_end_with_jump(table_node_parent_end, nullptr, table_node_loop_body_end); gcc_jit_block_add_assignment_op(table_node_loop_body_end, nullptr, tuple_id, GCC_JIT_BINARY_OP_PLUS, gcc_jit_context_one(context, int64_type)); // Goto loop condition. gcc_jit_block_end_with_jump(table_node_loop_body_end, nullptr, table_node_loop_cond); // Modify the scope. scope->setCurrentValue(gcc_jit_lvalue_as_rvalue(value)); scope->setCurrentEvalBlock(table_node_parent_begin); scope->setCurrentExitBlock(table_node_parent_end); scope->setQueryInitBlock(table_node_initial); scope->setQueryExitBlock(table_node_loop_exit); // Call parent. getParent()->codegen(context, scope); gcc_jit_block_end_with_jump(table_node_initial, nullptr, table_node_loop_cond); // Loop end actions. gcc_jit_block_end_with_void_return(table_node_loop_exit, nullptr); } void TableNode::open() { m_iterator_index = 0; } int64_t* TableNode::next() { return &m_data[m_iterator_index++]; } bool TableNode::hasNext() { return m_iterator_index < m_num_tuples; } }
#include <Euclide.hpp> #include "gtest/gtest.h" TEST(euclide, result_only) { }
#pragma once #include <QtGui> #include <QWidget> #include <unordered_map> #include "TrenchCoat.h" #include <vector> //#include <QtCharts> class BarChart: public QWidget { Q_OBJECT public: BarChart(std::vector<TrenchCoat> coats, QWidget* parent = 0) :QWidget{ parent }, coats{ coats }{} protected: std::vector<TrenchCoat> coats; void paintEvent(QPaintEvent* event); signals: public slots: };
#include <iostream> using namespace std; int n=20; int f[21][6][6]; int main () { memset (f, 0, sizeof(f)); f[2][1][0]=1; f[2][0][2]=1; for (int i=2; i<n; i++) for (int j=0; j<=5; j++) { for (int k=0; k<=3; k++) f[i+1][j][k+1] += f[i][j][k]; for (int k=1; k<=4; k++) f[i+1][j+1][0] += f[i][j][k]; } //cout<<f[2][1][0]; int ans = 0; for (int i=1; i<=4; i++) { cout<< f[n][5][i] << endl; ans += f[n][5][i]; } cout<<ans; system ("pause"); return 0; }
/* ============================================================================== SeaboardComponent.h Created: 22 Aug 2014 12:00:00pm Author: Sean Soraghan ============================================================================== */ #ifndef MAINCOMPONENT_H_INCLUDED #define MAINCOMPONENT_H_INCLUDED #include "../JuceLibraryCode/JuceHeader.h" #include "SeaboardVisualiser.h" #include "SineWaveVoice.cpp" /* The SeaboardComponent class will hold all of our Seaboard responder objects. SeaboardComponent inherits the JUCE Component class, which is a simple graphical container class. The paint() function is the main drawing loop and is called continuously. The resized() function is called when the window is resized. It is used for positioning other (child) components within this component. Child components can be added to a component using the addChildComponent() method. Our SeaboardComponent class contains a Seaboard object which manages all of the incoming seaboard data and passes it on to any of its listeners (see Seaboard.h). SeaboardComponent also contains a visualiser object (see SeaboardVisualiser.h). It also contains a SeaboardPlayer object. We create SeaboardVoice objects and add them to the SeaboardPlayer object in order to produce sound from the Seaboard data (see SineWaveVoice.cpp for an example). */ class SeaboardComponent : public Component { public: //============================================================================== SeaboardComponent(); ~SeaboardComponent(); void paint (Graphics&); void resized(); private: ScopedPointer<Seaboard> theSeaboard; //Seaboard objects manage all of the incoming seaboard data and pass it on to Seaboard::Listener objects (see Seaboard.h). ScopedPointer<SeaboardVisualiser> theVisualiser; //The SeaboardVisualiser produces visual response to Seaboard data ScopedPointer<SeaboardPlayer> theSynth; //We create SeaboardVoice objects and add them to the SeaboardPlayer object in order to produce sound from the Seaboard data (see SineWaveVoice.cpp for an example). JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SeaboardComponent) }; #endif // MAINCOMPONENT_H_INCLUDED
// Fill out your copyright notice in the Description page of Project Settings. #include "ShineCharacter.h" void AShineCharacter::ChangeMultiSkill( float rate ) { // TODO: change Lyre Chart }
#include<bits/stdc++.h> using namespace std; int main(){ string A,B,C="",trans="0123456789JQK"; cin>>A>>B; reverse(A.begin(),A.end()); reverse(B.begin(),B.end()); int len=max(A.size(),B.size());//取A、B字符串中最长的长度 for(int i=0;i<len;++i){ int numA=i<A.size()?A[i]-'0':0;//记录相应A字符串位置的数字,如果超过了A的长度,记0 int numB=i<B.size()?B[i]-'0':0;//记录相应B字符串位置的数字,如果超过了B的长度,记0 if(i%2==0)//字符串下标从0开始,而题目中个位从1开始编号,所以对于奇数位偶数位的处理要反过来 C+=trans[(numA+numB)%13]; else{ int t=numB-numA; if(t<0) t+=10; C+=t+'0'; } } reverse(C.begin(),C.end());//翻转C字符串 puts(C.c_str());//输出 return 0; }
//#include<stdio.h> // //int main() { // int x, y, xy, z; // int gcd = 0, lcm = 0; // do { // x = 0, y = 0; // printf("두발을 심어주세요 : "); // scanf("%d %d", &x, &y); // xy = x * y; // if (x > 0 && y > 0) { // while (1) { // z = x % y; // if (z == 0) { // gcd = y; // lcm = xy / y; // break; // } // else { // x = y; // y = z; // } // // } // printf("GCD : %d, LCM : %d\n\n", gcd, lcm); // } // else if (x != 0 || y != 0) { // printf("\n양의 정수를 입력하세요. Quit(0,0)\n\n"); // } // } while (x != 0 || y != 0); // return 0; //}
// This file has been generated by Py++. #ifndef Tree_hpp__pyplusplus_wrapper #define Tree_hpp__pyplusplus_wrapper void register_Tree_class(); #endif//Tree_hpp__pyplusplus_wrapper
#include "simple-web-server/server_https.hpp" #include "simple-web-server/client_https.hpp" #include "simple-web-server/crypto.hpp" #define BOOST_SPIRIT_THREADSAFE #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <fstream> #include <boost/filesystem.hpp> #include <vector> #include <algorithm> #include <map> using namespace std; using namespace boost::property_tree; typedef SimpleWeb::Server<SimpleWeb::HTTPS> HttpsServer; void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServer::Response> &response, const shared_ptr<ifstream> &ifs); std::shared_ptr<HttpsServer> _server; auto default_post = [_server](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) { auto content=request->content.string(); *response << "HTTP/1.1 200 OK\r\nContent-Length: " << content.length() << "\r\n\r\n" << content; }; auto default_get = [_server](shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request) { try { auto web_root_path = boost::filesystem::canonical("web"); auto path = boost::filesystem::canonical(web_root_path/request->path); //Check if path is within web_root_path if(distance(web_root_path.begin(), web_root_path.end())>distance(path.begin(), path.end()) || !equal(web_root_path.begin(), web_root_path.end(), path.begin())) throw invalid_argument("path must be within root path"); if(boost::filesystem::is_directory(path)) path /= "index.html"; if(!(boost::filesystem::exists(path) && boost::filesystem::is_regular_file(path))) throw invalid_argument("file does not exist"); // debug cout << "Get path: " << path.string() << endl; std::string cache_control, etag; auto ifs = make_shared<ifstream>(); ifs->open(path.string(), ifstream::in | ios::binary | ios::ate); if(*ifs) { auto length = ifs->tellg(); ifs->seekg(0, ios::beg); *response << "HTTP/1.1 200 OK\r\n" << cache_control << etag << "Content-Length: " << length << "\r\n\r\n"; default_resource_send(*_server, response, ifs); } else throw invalid_argument("could not read file"); } catch(const exception &e) { string content="Could not open path " + request->path + ": " + e.what(); *response << "HTTP/1.1 400 Bad Request\r\nContent-Length: " << content.length() << "\r\n\r\n" << content; } }; typedef std::function<void(shared_ptr<HttpsServer::Response> response, shared_ptr<HttpsServer::Request> request)> Callback; std::map<string, Callback> _handlers { {"default_get", default_get}, {"default_post", default_post} }; class config { public: string ssl_cert_file; string ssl_key_file; unsigned short port; config(const string &config_file) { initialize(config_file); } void add_handlers(HttpsServer& server) { // handler name : path pattern for (ptree :: value_type &handler : root.get_child("handlers")) { string _handler = handler.first; string _path_pattern = handler.second.get_value<string>("path"); string _verb = handler.second.get_value<string>("verb"); // add resource if (_path_pattern.empty()) { server.default_resource[_verb] = _handlers[_handler]; } else { server.resource[_path_pattern][_verb] = _handlers[_handler]; } } } bool initialize(const ptree &config) { // certs ssl_cert_file = config.get<string>("ssl_cert"); ssl_key_file = config.get<string>("ssl_key"); port = config.get<int>("port"); } bool initialize(const string &config_file) { read_json(config_file, root); initialize(root); } private: ptree root; }; int main(int argc, char **argv) { config _conf(argv[1]); _server = std::make_shared<HttpsServer>(_conf.ssl_cert_file, _conf.ssl_key_file); _server->config.port = _conf.port; //8080; _conf.add_handlers(*_server); thread server_thread([_server](){ //Start server _server->start(); }); //this_thread::sleep_for(chrono::seconds(1)); server_thread.join(); return 0; } void default_resource_send(const HttpsServer &server, const shared_ptr<HttpsServer::Response> &response, const shared_ptr<ifstream> &ifs) { //read and send 128 KB at a time static vector<char> buffer(131072); // Safe when server is running on one thread streamsize read_length; if((read_length = ifs->read(&buffer[0], buffer.size()).gcount())>0) { response->write(&buffer[0], read_length); if(read_length == static_cast<streamsize>(buffer.size())) { server.send(response, [&server, response, ifs](const boost::system::error_code &ec) { if(!ec) default_resource_send(server, response, ifs); else cerr << "Connection interrupted" << endl; }); } } }
#include "_client.h" SCREENINFO g_Screen; cSound g_Sound; cLeis g_Leis; #define GRENADE_DECOY_STR "decoy" #define GRENADE_HE_FLASH_STR "he/flash" #define GRENADE_MOLOTOV_STR "molotov" #define GRENADE_SENSOR_STR "sensor" #define GRENADE_SMOKE_STR "smoke" int GrenadeEspClassID[5] = { CC_CDecoyProjectile, CC_CBaseCSGrenadeProjectile, CC_CMolotovProjectile, CC_CSensorGrenadeProjectile, CC_CSmokeGrenadeProjectile }; char* GrenadeEpsName[5] = { GRENADE_DECOY_STR,GRENADE_HE_FLASH_STR, GRENADE_MOLOTOV_STR,GRENADE_SENSOR_STR, GRENADE_SMOKE_STR }; int WeaponsEspClassID[33] = { // ÏÈÑÒÎËÅÒÛ - 0 - 9 CC_CDEagle,CC_CWeaponElite,CC_CWeaponFiveSeven, CC_CWeaponGlock,CC_CWeaponHKP2000,CC_CWeaponP250, CC_CWeaponUSP,CC_CWeaponP250,CC_CDEagle, // ÀÂÒÎÌÀÒÛ - 9 - 28 CC_CAK47,CC_CWeaponAug,CC_CWeaponFamas,CC_CWeaponGalilAR, CC_CWeaponM249,CC_CWeaponM4A1,CC_CWeaponM4A1,CC_CWeaponMAC10, CC_CWeaponP90,CC_CWeaponUMP45,CC_CWeaponXM1014,CC_CWeaponBizon, CC_CWeaponMag7,CC_CWeaponNegev,CC_CWeaponSawedoff,CC_CWeaponTec9, CC_CWeaponMP7,CC_CWeaponMP9,CC_CWeaponNOVA,CC_CWeaponSG556, // ÑÍÀÉÏÅÐÊÈ - 29 - 32 CC_CWeaponAWP,CC_CWeaponG3SG1,CC_CSCAR17,CC_CWeaponSSG08 }; #define GRENADE_ID_DATA_SIZE ( sizeof( GrenadeEspClassID ) / sizeof( *GrenadeEspClassID ) ) #define WEAPONS_ID_DATA_SIZE ( sizeof( WeaponsEspClassID ) / sizeof( *WeaponsEspClassID ) ) void cSound::AddSound( Vector vOrigin ) { if ( sound.size() < MAX_SOUND_ACTIVE ) { sound_s entry; entry.dwTime = GetTickCount(); entry.vOrigin = vOrigin; sound.push_back( entry ); } else ClearSound(); } void cSound::ClearSound() { sound.clear(); } void cSound::DrawSoundEsp() { for( size_t i = 0; i < g_Sound.sound.size(); i++ ) { if( g_Sound.sound[i].dwTime + 800 <= GetTickCount() ) { g_Sound.sound[i].dwTime = 0; g_Sound.sound[i].vOrigin = Vector( 0 , 0 , 0 ); } else { Vector vScreen; if( WorldToScreen( g_Sound.sound[i].vOrigin , vScreen ) ) { g_Draw.DrawBox( (int)vScreen.x , (int)vScreen.y , 10 , 10 , Color( 255 , 255 , 255 ) ); } } } } void cLeis::InitHack() { g_FontEsp.dwFontId = 0; g_FontMenu.dwFontId = 0; g_FontEsp.SetFont( CFG_VERDANA , 12 , 7 , FONTFLAG_OUTLINE ); g_FontMenu.SetFont( CFG_VERDANA , 12 , 7 , FONTFLAG_NONE ); g_Local.iTeam = TEAM_SPEC; g_Local.bAlive = false; g_Local.bC4Planted = false; g_Cheat.ClearPlayers(); g_Sound.ClearSound(); } void cLeis::HUD_Redraw() { g_Menu.DrawMenu( g_Screen.iWidth / 2 - MENU_ALL_WIDTH , 70 , true ); if ( cvar.radar_enable && g_Local.bAlive ) g_Radar.DrawGuiRadar( cvar.rad_x , cvar.rad_y ); if( cvar.esp_sound && g_Local.bAlive ) g_Sound.DrawSoundEsp(); g_Players.UpdatePlayerInfo(); if ( cvar.esp_bomb || cvar.esp_bombtimer ) { for ( int i = 0; i <= g_pClientEntList->GetHighestEntityIndex(); i++ ) { CBaseAttributableItem* pEntity = (CBaseAttributableItem*)g_pClientEntList->GetClientEntity( i ); if ( !pEntity || IsBadReadPtr( (PVOID)pEntity , sizeof( CBaseAttributableItem ) ) ) continue; if ( cvar.esp_w_weapon ) { for ( int w = 0; w < WEAPONS_ID_DATA_SIZE; w++ ) { if ( pEntity->GetClientClass()->m_ClassID == WeaponsEspClassID[w] ) { Vector vWeaponsPos; if ( WorldToScreen( pEntity->GetAbsOrigin() , vWeaponsPos ) && *pEntity->GetOwnerEntity() == -1 ) { if ( w == 0 && pEntity->GetClientClass()->m_ClassID == CC_CDEagle && *pEntity->GetItemDefinitionIndex() == WEAPON_DEAGLE ) { g_FontEsp.DrawString( vWeaponsPos.x , vWeaponsPos.y , Color( 255 , 255 , 255 ) , true , pWeaponData[w] ); } else if ( w == 5 && pEntity->GetClientClass()->m_ClassID == CC_CWeaponP250 && *pEntity->GetItemDefinitionIndex() == WEAPON_P250 ) { g_FontEsp.DrawString( vWeaponsPos.x , vWeaponsPos.y , Color( 255 , 255 , 255 ) , true , pWeaponData[w] ); } else if ( w == 7 && pEntity->GetClientClass()->m_ClassID == CC_CWeaponP250 && *pEntity->GetItemDefinitionIndex() == WEAPON_CZ75A ) { g_FontEsp.DrawString( vWeaponsPos.x , vWeaponsPos.y , Color( 255 , 255 , 255 ) , true , pWeaponData[w] ); } else if ( w == 8 && pEntity->GetClientClass()->m_ClassID == CC_CDEagle && *pEntity->GetItemDefinitionIndex() == WEAPON_REVOLVER ) { g_FontEsp.DrawString( vWeaponsPos.x , vWeaponsPos.y , Color( 255 , 255 , 255 ) , true , pWeaponData[w] ); } else if ( w != 0 && w != 5 && w != 7 && w != 8 ) { g_FontEsp.DrawString( vWeaponsPos.x , vWeaponsPos.y , Color( 255 , 255 , 255 ) , true , pWeaponData[w] ); } //g_pRenderer->RenderText( vWeaponsPos.x , vWeaponsPos.y + 15 , Color( 255 , 255 , 255 ) , true , nt_itoa( pEntity->GetClientClass()->m_ClassID ) ); } } } } if ( cvar.esp_w_grenade ) { for ( int g = 0; g < GRENADE_ID_DATA_SIZE; g++ ) { if ( pEntity->GetClientClass()->m_ClassID == GrenadeEspClassID[g] ) { Vector vGrenadePos( 0 , 0 , 0 ); if ( WorldToScreen( pEntity->GetAbsOrigin() , vGrenadePos ) ) { g_FontEsp.DrawString( vGrenadePos.x , vGrenadePos.y , Color( 255 , 140 , 0 ) , true , GrenadeEpsName[g] ); } } } } if ( pEntity->GetClientClass()->m_ClassID == CC_CPlantedC4 || pEntity->GetClientClass()->m_ClassID == CC_CC4 ) { Vector vPlantPos = Vector( 0 , 0 , 0 ); if ( cvar.esp_bomb && WorldToScreen( pEntity->GetAbsOrigin() , vPlantPos ) ) { if ( pEntity->GetClientClass()->m_ClassID == CC_CC4 && *pEntity->GetOwnerEntity() == -1 ) { g_FontEsp.DrawString( vPlantPos.x , vPlantPos.y , Color( 255 , 255 , 255 ) , true , "c4" ); } if ( pEntity->GetClientClass()->m_ClassID == CC_CPlantedC4 && g_Local.bC4Planted ) { g_FontEsp.DrawString( vPlantPos.x , vPlantPos.y , Color( 255 , 255 , 255 ) , true , "c4_p" ); } } if ( cvar.esp_bombtimer && g_Local.bC4Planted ) { char szTimer1[20] = { 0 }; static cTimer BombTimer; if ( BombTimer.delay( 1000 ) ) { g_Local.m_c4timer--; BombTimer.reset(); } lstrcpyA( szTimer1 , XorStr( "bomb time: " ) ); lstrcatA( szTimer1 , nt_itoa( g_Local.m_c4timer ) ); g_FontEsp.DrawString( g_Screen.iWidth / 2 , 50 , Color( 255 , 255 , 255 ) , true , szTimer1 ); } } } } } void cLeis::CL_AimbotMove( CUserCmd* cmd ) { if ( g_Cheat.IsLocalWeaponUseAmmo() ) { if ( cvar.weapon_settings[cvar.wpn].aim_enable ) g_Aimbot.Aimbot( cmd ); } } void cLeis::CL_CreateMove( float flInputSampleTime , CUserCmd* cmd ) { if ( !g_Local.bAlive && !g_Cheat.bLastDead ) { g_Cheat.bLastDead = true; } else { if ( g_Cheat.bLastDead && g_Local.bAlive ) { g_Cheat.ClearPlayers(); g_Cheat.bLastDead = false; } } if( g_Cheat.IsLocalWeaponUseAmmo() ) { cvar.wpn = cvar.GetIndexSettingsFromWeapon(); if( cvar.weapon_settings[cvar.wpn].trigger_mode ) g_Trigger.TriggerBot( cmd ); } if ( cvar.misc_Bhop ) { if ( cmd->buttons & IN_JUMP && !( g_Local.iFlags & FL_ONGROUND ) ) { cmd->buttons &= ~IN_JUMP; } } }
#pragma once #include <iostream> using namespace std; class LinearEquations { //用来求解方阵Ax=b private: int n; //A的维度 double* A; double* B; //假设为n*1矩阵 double* C; int* line;//保存换行后行的顺序 double& mA(int i, int j); public: LinearEquations(int n, double* A, double* B, double* C=nullptr); double* solutionB; double* solutionC; void solve(); void elimination(); void lastStep(); bool zeroUp(int i);//换行使得第i行第一个不为0;如果第一行仍然为0,return false void zeroFirstCol(int j);//使得ajj左下元素全为0 void changeLine(int i, int j);//换行 void addLine(int line1, int line2, double mul); //line1 += line2*mul void printABC(); //打印AB };
/************************************************* * Publicly released by Rhoban System, August 2015 * www.rhoban.com * * Freely usable for non-commercial purposes * * Author : Hugo * Licence Creative Commons *CC BY-NC-SA * http://creativecommons.org/licenses/by-nc-sa/3.0 *************************************************/ #ifndef UTILS_MULTISERIAL_H #define UTILS_MULTISERIAL_H #include <cstdlib> #include <cstdio> #include <string> #include <map> #include <vector> #include <threading/Thread.h> #include <threading/Mutex.h> #include <serial/Serial.h> #ifdef WIN32 #include <windows.h> #endif #include <fstream> using namespace std; /* Handles asynchronous reading and writing in several serial ports */ class MultiSerial : private Rhoban::Thread { public: MultiSerial(); virtual ~MultiSerial(); //ports with empty name are ignored MultiSerial( vector<string> ports, vector<int> baudrates ); /* called when data is received */ virtual void MultiSerialReceived(int port, const string & data){}; /* return how many chars were sent, -1 in case of error */ int Send(int port_id, const string & data); void Disconnect(); void Connect( vector<string> ports, vector<int> baudrates ); vector<int> multiserial_received; vector<int> multiserial_sent; protected: vector<Serial *> ports; void execute(); /* prevents concurrent calls to ports */ Rhoban::Mutex mutex; }; #endif // UTILS_SERIAL_H
#include <vector> using namespace std; vector <int> failure(const vector <int> &arr){ int j = 0; vector <int> pi(arr.size(), 0); for(int i = 1; i < arr.size(); i++){ while ( j > 0 && arr[i] != arr[j]){ j = pi[j-1]; } if(str[i] == str[j] ) { pi[i] = j + 1; j += 1; } else{ pi[i] = 0; } } } bool kmp(const vector<int> &s, const vector<int> &p, const vector<int> &pi, ){ int n = s.size(); int m = p.size(); int i = 0,j = 0; for(i = 0; i < n; i++) { while (j > 0 && s[i] != p[j]){ j = pi[j-1]; } if (s[i] == p[j]) { if (j == m - 1) { return true; } else { j++; } } } return false; }
#pragma once #include "ofMain.h" #define NUM 10 class Ball { public: ofIcoSpherePrimitive isp; ofPoint pos, vel; float z; // convert sphere to mesh for manipulations ofMesh* bmesh; int index; void draw(void); void update(float x, float y); void init(int index); }; class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); Ball b[NUM]; void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); };
#ifndef STATIC_LINK #define IMPLEMENT_API #endif #if defined(HX_WINDOWS) || defined(HX_MACOS) || defined(HX_LINUX) #define NEKO_COMPATIBLE #endif #include "common.h" extern "C" { DEFINE_KIND(k_ui64); DEFINE_KIND(k_raw_ui64); DEFINE_KIND(k_ptr); } typedef struct { hx_uint64 value; } i64_container; hx_uint64 val_uint64(value v) { if (val_is_any_int(v)) { return (hx_uint64) (unsigned int) val_any_int(v); } else if (val_is_abstract(v)) { if (val_is_kind(v,k_ui64)) return ((i64_container *) val_data(v))->value; else return (hx_uint64) val_data(v); } else if (val_is_object(v)) { static field id_high = val_id("high"); static field id_low = val_id("low"); value vhigh = val_field(v,id_high); value vlow = val_field(v,id_low); if (!val_is_any_int(vhigh) || !val_is_any_int(vlow)) { buffer buf = alloc_buffer( "(val_uint64) Invalid haxe.Int64 parameter: " ); val_buffer(buf,v); val_throw( buffer_to_string(buf) ); } return ( ((hx_uint64) val_any_int(vhigh)) << 32 ) | ( (hx_uint64) val_any_int(vlow) ); } else if (val_is_float(v)) { return (hx_uint64) val_float(v); } else { { buffer buf = alloc_buffer( "(val_uint64) Invalid Int64 parameter: " ); val_buffer(buf,alloc_int(val_type(v))); val_buffer(buf,alloc_string(", ")); val_buffer(buf,v); val_throw( buffer_to_string(buf) ); } return 0ULL; } } hx_int64 val_int64(value v) { if (val_is_any_int(v)) { return (hx_int64) val_any_int(v); } else if (val_is_abstract(v)) { if (val_is_kind(v,k_ui64)) return ((i64_container *) val_data(v))->value; else return (hx_int64) val_data(v); } else if (val_is_object(v)) { static field id_high = val_id("high"); static field id_low = val_id("low"); value vhigh = val_field(v,id_high); value vlow = val_field(v,id_low); if (!val_is_any_int(vhigh) || !val_is_any_int(vlow)) { buffer buf = alloc_buffer( "(val_uint64) Invalid haxe.Int64 parameter: " ); val_buffer(buf,v); val_throw( buffer_to_string(buf) ); } return ( ((hx_int64) val_any_int(vhigh)) << 32 ) | ( (hx_int64) val_any_int(vlow) ); } else if (val_is_float(v)) { return (hx_int64) val_float(v); } else { { buffer buf = alloc_buffer( "(val_uint64) Invalid Int64 parameter: " ); val_buffer(buf,alloc_int(val_type(v))); val_buffer(buf,alloc_string(", ")); val_buffer(buf,v); val_throw( buffer_to_string(buf) ); } return 0ULL; } return (hx_int64) val_uint64(v); } static void i64_container_finalize( value v ) { free( val_data(v) ); #ifndef HXCPP_COMPATIBLE val_kind(v) = NULL; #endif } value alloc_uint64(hx_uint64 v) { if (v <= 0xFFFFFFFFULL) { return alloc_best_int( (int) v ); } else if (sizeof(hx_uint64) <= sizeof(void *)) { return alloc_abstract(k_raw_ui64, (void *) v); } else { // only on 32-bit i64_container *container = (i64_container *) malloc( sizeof(i64_container) ); container->value = v; value ret = alloc_abstract(k_ui64, container); val_gc(ret,i64_container_finalize); return ret; } } void *val_ptr(value ptr) { if (val_is_null(ptr)) { return NULL; } else if (val_is_abstract(ptr)) { if (val_is_kind(ptr,k_ui64)) return &(((i64_container *) val_data(ptr))->value); // We won't check if it's of kind k_ptr, because other libs may want to // use it, and this is an unsafe library after all return val_data(ptr); } buffer buf = alloc_buffer("Invalid pointer: "); val_buffer(buf,ptr); val_throw( buffer_to_string(buf) ); return NULL; } value alloc_ptr(void *ptr) { if (NULL == ptr) return val_null; else return alloc_abstract(k_ptr, ptr); }
// // main.cpp // https://open.kattis.com/problems/bookingaroom // // Created by Sofian Hadianto on 31/12/18. // Copyright © 2018 Sofian Hadianto. All rights reserved. // #include <bits/stdc++.h> using namespace std; int main(int argc, const char * argv[]) { ios::sync_with_stdio(false); cin.tie(NULL); int r,n; cin >> r >> n; bool* room = new bool[r]; int reserved; while (n--) { cin >> reserved; // room number reserved room[reserved-1] = true; // convert to zero index based } bool available = false; for (int i = 0; i < r; i++) { if (room[i] == false) { available = true; cout << (i+1) << "\n"; break; } } if (!available) cout << "too late" << "\n"; return 0; }
/* Copyright (c) 2005-2023, University of Oxford. All rights reserved. University of Oxford means the Chancellor, Masters and Scholars of the University of Oxford, having an administrative office at Wellington Square, Oxford OX1 2JD, UK. This file is part of Chaste. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Oxford nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef SIMPLEDATAWRITER_HPP_ #define SIMPLEDATAWRITER_HPP_ #include <string> #include <vector> /** * A basic data writer that is easier to use than ColumnDataWriter but has less * functionality. NOTE: this is not an efficient writer. * * This class does not writer header lines so is ideal for immediately reading * with MATLAB or Gnuplot. */ class SimpleDataWriter { public: /** * Write the provided data out to the given file in columns * * @param rDirectory The directory, relative to TEST_OUTPUT * @param rFileName The full file name (no format will be apended) * @param rData The data. data[0] will written as the first column, data[1] the * second, and so on. An exception is thrown if they are not the same size * @param cleanDirectory Whether to clean the directory (defaults to true) */ SimpleDataWriter(const std::string& rDirectory, const std::string& rFileName, const std::vector<std::vector<double> >& rData, bool cleanDirectory=true); /** * Write the provided data out to the given file in 2 columns * * @param rDirectory The directory, relative to TEST_OUTPUT * @param rFileName The full file name (no format will be apended) * @param rT The first column of data * @param rX The second column of data. An exception is thrown if the size * of x is not the same as the size of t. * @param cleanDirectory Whether to clean the directory (defaults to true) */ SimpleDataWriter(const std::string& rDirectory, const std::string& rFileName, const std::vector<double>& rT, const std::vector<double>& rX, bool cleanDirectory=true); /** * Write the provided data out to the given file in one column * * @param rDirectory The directory, relative to TEST_OUTPUT * @param rFileName The full file name (no format will be apended) * @param rData A std::vec of data * @param cleanDirectory Whether to clean the directory (defaults to true) */ SimpleDataWriter(const std::string& rDirectory, const std::string& rFileName, const std::vector<double>& rData, bool cleanDirectory=true); }; #endif /*SIMPLEDATAWRITER_HPP_*/
#include "VulkanPipeline.h" #include "VulkanSwapchain.h" #include "VulkanDevice.h" #include "VulkanShaderStage.h" #include "VulkanRenderPass.h" #include "VulkanDescriptorSetLayout.h" #include "VulkanException.h" #include "Vertex.h" #include <vulkan\vulkan.h> VulkanPipeline::VulkanPipeline(VulkanDevice* device, VulkanSwapchain* swapchain, VulkanShaderStage* shaderStage, VulkanRenderPass* renderPass, std::vector<VulkanDescriptorSetLayout*> descriptorSets) : device(device) { VkPipelineVertexInputStateCreateInfo vertexInputInfo = {}; vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO; auto bindingDescription = Vertex::getBindingDescription(); auto attributeDescriptions = Vertex::getAttributeDescriptions(); vertexInputInfo.vertexBindingDescriptionCount = 1; vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size()); vertexInputInfo.pVertexBindingDescriptions = &bindingDescription; vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data(); VkPipelineInputAssemblyStateCreateInfo inputAssembly = {}; inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO; inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; inputAssembly.primitiveRestartEnable = VK_FALSE; VkExtent2D swapChainExtent = swapchain->GetExtent(); VkViewport viewport = {}; viewport.x = 0.0f; viewport.y = 0.0f; viewport.width = (float)swapChainExtent.width; viewport.height = (float)swapChainExtent.height; viewport.minDepth = 0.0f; viewport.maxDepth = 1.0f; VkRect2D scissor = {}; scissor.offset = { 0, 0 }; scissor.extent = swapChainExtent; VkPipelineViewportStateCreateInfo viewportState = {}; viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO; viewportState.viewportCount = 1; viewportState.pViewports = &viewport; viewportState.scissorCount = 1; viewportState.pScissors = &scissor; VkPipelineRasterizationStateCreateInfo rasterizer = {}; rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO; rasterizer.depthClampEnable = VK_FALSE; rasterizer.rasterizerDiscardEnable = VK_FALSE; rasterizer.polygonMode = VK_POLYGON_MODE_FILL; rasterizer.lineWidth = 1.0f; rasterizer.cullMode = VK_CULL_MODE_BACK_BIT; rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE; rasterizer.depthBiasEnable = VK_FALSE; VkPipelineMultisampleStateCreateInfo multisampling = {}; multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO; multisampling.sampleShadingEnable = VK_FALSE; multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; VkPipelineDepthStencilStateCreateInfo depthStencil = {}; depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO; depthStencil.depthTestEnable = VK_TRUE; depthStencil.depthWriteEnable = VK_TRUE; depthStencil.depthCompareOp = VK_COMPARE_OP_LESS; depthStencil.depthBoundsTestEnable = VK_FALSE; depthStencil.stencilTestEnable = VK_FALSE; VkPipelineColorBlendAttachmentState colorBlendAttachment = {}; colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT; colorBlendAttachment.blendEnable = VK_FALSE; VkPipelineColorBlendStateCreateInfo colorBlending = {}; colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO; colorBlending.logicOpEnable = VK_FALSE; colorBlending.logicOp = VK_LOGIC_OP_COPY; colorBlending.attachmentCount = 1; colorBlending.pAttachments = &colorBlendAttachment; colorBlending.blendConstants[0] = 0.0f; colorBlending.blendConstants[1] = 0.0f; colorBlending.blendConstants[2] = 0.0f; colorBlending.blendConstants[3] = 0.0f; std::vector<VkDescriptorSet> descriptorSetLayout(descriptorSets.size()); for (uint32_t i = 0; i < descriptorSets.size(); ++i) descriptorSetLayout[i] = *descriptorSets[i]; VkPipelineLayoutCreateInfo pipelineLayoutInfo = {}; pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO; pipelineLayoutInfo.setLayoutCount = descriptorSetLayout.size(); pipelineLayoutInfo.pSetLayouts = descriptorSetLayout.data(); if (vkCreatePipelineLayout(*device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) { throw new VulkanException("failed to create pipeline layout!", __LINE__, __FILE__); } VkGraphicsPipelineCreateInfo pipelineInfo = {}; pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO; auto shaders = shaderStage->GetStages(); pipelineInfo.stageCount = shaders.size(); pipelineInfo.pStages = shaders.data(); pipelineInfo.pVertexInputState = &vertexInputInfo; pipelineInfo.pInputAssemblyState = &inputAssembly; pipelineInfo.pViewportState = &viewportState; pipelineInfo.pRasterizationState = &rasterizer; pipelineInfo.pMultisampleState = &multisampling; pipelineInfo.pDepthStencilState = &depthStencil; pipelineInfo.pColorBlendState = &colorBlending; pipelineInfo.layout = pipelineLayout; pipelineInfo.renderPass = *renderPass; pipelineInfo.subpass = 0; if (vkCreateGraphicsPipelines(*device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &pipeline) != VK_SUCCESS) { throw new VulkanException("failed to create graphics pipeline!", __LINE__, __FILE__); } } VulkanPipeline::~VulkanPipeline() { vkDestroyPipeline(*device, pipeline, nullptr); vkDestroyPipelineLayout(*device, pipelineLayout, nullptr); } VkPipelineLayout VulkanPipeline::GetLayout() { return pipelineLayout; } VulkanPipeline::operator VkPipeline() const { return pipeline; }
#include "DrawingObject.h" #include <iostream> void DrawingObject::setclass( std::string dclass ) { this->dclass = dclass; } void DrawingObject::setid(std::string id ) { this->id = id; } std::string DrawingObject::getid() { return id; } std::string DrawingObject::getclass() { return dclass; }
#include <Book/GameState2.hpp> #include <Book/MusicPlayer.hpp> #include <Book/Utility.hpp> #include <SFML/Graphics/RenderWindow.hpp> GameState2::GameState2(StateStack& stack, Context context) : State(stack, context) , mWorld(*context.window, *context.fonts, *context.sounds) , mPlayer(*context.player) , mGame2Text() { sf::Font& font = context.fonts->get(Fonts::Main); sf::Vector2f windowSize(context.window->getSize()); mPlayer.setMissionStatus(Player::MissionRunning); // Play game theme context.music->play(Music::MissionTheme); mGame2Text.setFont(font); if (context.player->getMissionStatus() == Player::MissionRunning) { mGame2Text.setString("Mission Two"); } mGame2Text.setCharacterSize(70); centerOrigin(mGame2Text); mGame2Text.setPosition(0.5f * windowSize.x, 0.05 * windowSize.y); } void GameState2::draw() { sf::RenderWindow& window = *getContext().window; window.setView(window.getDefaultView()); mWorld.draw(); window.draw(mGame2Text); } bool GameState2::update(sf::Time dt) { mWorld.update(dt); if (!mWorld.hasAlivePlayer()) { mPlayer.setMissionStatus(Player::MissionFailure); requestStackPush(States::GameOver); } else if (mWorld.hasPlayerReachedEnd()) { mPlayer.setMissionStatus(Player::MissionSuccess); requestStackPush(States::GameOver); } CommandQueue& commands = mWorld.getCommandQueue(); mPlayer.handleRealtimeInput(commands); return true; } bool GameState2::handleEvent(const sf::Event& event) { // Game input handling CommandQueue& commands = mWorld.getCommandQueue(); mPlayer.handleEvent(event, commands); // Escape pressed, trigger the pause screen if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) requestStackPush(States::Pause); return true; }
#include "string.hpp" sf::String String::get_string() const { return str; } void String::set_string(sf::String _str) { str = _str; } String::String() { str = sf::String(); } String::String(char ansiChar, const std::locale &locale) { str = sf::String(ansiChar, locale); } String::String (const char *ansiString, const std::locale &locale) { str = sf::String(ansiString, locale); } String::String (const std::string &ansiString, const std::locale &locale) { str = sf::String(ansiString, locale); } String::String (const String &copy) { str = copy.get_string(); } String& String::operator= (const String &right) { str = right.get_string(); } String& String::operator+= (const String &right) { str += right.get_string(); } void String::clear() { str.clear(); } std::size_t String::getSize () const { return str.getSize(); } bool String::isEmpty() const { return str.isEmpty(); } void String::erase(std::size_t position, std::size_t count) { str.erase(position, count); } void String::insert(std::size_t position, const String &_str) { str.insert(position, _str.get_string()); } std::size_t String::find(const String &str, std::size_t start) const { return str.find(str, start); } void String::replace(std::size_t position, std::size_t length, const String &replaceWith) { str.replace(position, length, replaceWith.get_string()); } void String::replace(const String &searchFor, const String &replaceWith) { str.replace(searchFor.get_string(), replaceWith.get_string()); } String String::substring(std::size_t position, std::size_t length) const { String r_str; r_str.set_string(str.substring(position, length)); return r_str; } sf::String::Iterator String::begin() { return str.begin(); } sf::String::ConstIterator String::begin() const { return str.begin(); } std::string String::toAnsiString (const std::locale &locale) const { return str.toAnsiString(); } sf::String::Iterator String::end() { return str.end(); } sf::String::ConstIterator String::end() const { return str.end(); }
 /// @file src/pt/PtUnaryOp.cc /// @brief PtUnaryOp の実装ファイル /// @author Yusuke Matsunaga (松永 裕介) /// /// Copyright (C) 2005-2011 Yusuke Matsunaga /// All rights reserved. #include "PtUnaryOp.h" BEGIN_NAMESPACE_YM_BB // @brief コンストラクタ // @param[in] file_region ファイル上の位置 // @param[in] opr1 オペランド PtUnaryOp::PtUnaryOp(const FileRegion& file_region, PtNode* opr1) : PtNode(file_region), mOpr1(opr1) { } // @brief デストラクタ PtUnaryOp::~PtUnaryOp() { } // @brief オペランド数を返す. ymuint PtUnaryOp::operand_num() const { return 1; } // @brief オペランドを返す. // @param[in] pos 位置番号 ( 0 <= pos < operand_num() ) PtNode* PtUnaryOp::operand(ymuint pos) const { return mOpr1; } END_NAMESPACE_YM_BB
/* Reverse List in K groups Difficulty: EASY Avg. time to solve 15 min Success Rate 85% Problem Statement You are given a linked list of N nodes and an integer K. You have to reverse the given linked list in groups of size K i.e if the list contains x nodes numbered from 1 to x, then you need to reverse each of the groups (1,k),(k+1,2*k), and so on. For example, if the list is 1 2 3 4 5 6 and K = 2, then the new list will be 2 1 4 3 6 5. As a follow-up, try to solve the question using constant extra space. Note: 1. In case the number of elements in the last cannot be evenly divided into groups of size k, then just reverse the last group(with any size). For example if the list is 1 2 3 4 5 and K = 3, then the answer would be 3 2 1 5 4. 2. All the node values will be distinct. Input Format: The first line of input contains an integer T representing the number of Test cases. The first line of each test case contains a Linked list whose elements are separated by space and the linked list is terminated by -1. The second line of each test case contains an integer K. Output Format: The one and only line of each test case contains the modified linked list. Note: You don’t need to print anything. It has already been taken care of. Just implement the given function. Constraints: 1 <= T <= 100 1 <= N <= 10^4 1 <= K <= 10^4 Time Limit: 1sec Sample Input 1: 2 1 2 3 4 5 6 -1 2 5 4 3 7 9 2 -1 4 Sample Output 1: 2 1 4 3 6 5 7 3 4 5 2 9 Explanation Of The Sample Input1: For the first test case, we reverse the nodes in groups of two, so we get the modified linked list as 2 1 4 3 6 5. For the second test case, we reverse the nodes in groups of four. But for the last 2 elements, we cannot form a group of four, so we reverse those two elements only. Hence the linked list becomes 7 3 4 5 2 9. Previous Next */ /**************************************************************** Following is the Linked List node structure class Node { public: int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } }; *****************************************************************/ pair<Node*,Node*> solve(Node* head,Node* tail) { if(head==tail) { pair<Node*,Node*> m1; m1.first=tail; m1.second=head; return m1; } pair<Node*,Node*> m; m=solve(head->next,tail); m.second->next=head; pair<Node*,Node*> m2; m2.first=tail; m2.second=head; return m2; } Node* kReverse(Node* head, int K) { // Write your code here. Node* temp=head; for(int i=1;i<K && temp->next!=NULL ;i++) { temp=temp->next; } Node *ans=NULL; if(temp->next!=NULL){ ans=kReverse(temp->next,K); } Node *f=NULL; Node *e=NULL; pair<Node*,Node*>val; val=solve(head,temp); f=val.first; e=val.second; e->next=ans; return f; }
#include "data.h" #include <fstream> #include <iostream> #include <string> #include <sstream> #include <algorithm> std::string &strip(std::string&s, const char c){ s.erase(std::remove(s.begin(), s.end(), c), s.end()); return s; } std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { if (!item.empty()) { elems.push_back(item); } } return elems; } std::vector<std::string> split(const std::string &s, char delim) { std::vector<std::string> elems; split(s, delim, elems); return elems; } void data::loadARFF(std::string name, int maxItems){ int itemsCount = 0; std::string line; std::ifstream f(name); if (f.is_open()){ while (getline(f, line)){ if (line.size() == 0){ continue; } else if (line.at(0) == '%'){ continue; } else if (line.find("@attribute") != std::string::npos){ std::string att_name = split(split(line, ' ')[1], '\'')[0]; if (att_name == "class"){ unsigned first = line.find('{'); unsigned last = line.find('}'); std::string sub = line.substr(first, last - first); sub = strip(strip(sub, ' '), '{'); std::vector<std::string> cn = split(sub, ','); for (auto c : cn){ class_names[class_names.size()] = c; } } else{ attribute_names[attribute_names.size()] = att_name; attributes.push_back(std::vector<float >()); } } else if (line.find("@") == std::string::npos){ //Line contains data std::vector<std::string> d = split(line, ','); for (int i = 0; i < attributes.size(); i++){ attributes[i].push_back(std::stof(d[i])); } for (auto &i : class_names){ if (d[d.size() - 1] == i.second){ classes.push_back(i.first); } } itemsCount++; if (itemsCount >= maxItems&&maxItems>0){ break; } } } f.clear(); } else{ std::cerr << "Unable to open file " << name << "\n"; exit(-1); } }
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this); QPixmap pixmap_sort(":/resources/img/sort.jpg"); QIcon ButtonIcon(pixmap_sort); ui->incrementShell->setIcon(ButtonIcon); ui->incrementShell->setIconSize(pixmap_sort.rect().size()); QPixmap pixmap_array(":/resources/img/array.png"); QIcon ButtonIconArray(pixmap_array); ui->array->setIcon(ButtonIconArray); ui->array->setIconSize(pixmap_array.rect().size()); QPixmap pixmap_info(":/resources/img/info.png"); QIcon ButtonIconInfo(pixmap_info); ui->info1->setIcon(ButtonIconInfo); ui->info1->setIconSize(pixmap_info.rect().size()); ui->info2->setIcon(ButtonIconInfo); ui->info2->setIconSize(pixmap_info.rect().size()); QPixmap pixmap_steps(":/resources/img/steps.png"); QIcon ButtonIconSteps(pixmap_steps); ui->step1->setIcon(ButtonIconSteps); ui->step1->setIconSize(pixmap_steps.rect().size()); ui->comboBox->addItem("Шелла"); ui->comboBox->addItem("Седжвика"); ui->comboBox->addItem("Хиббарда"); ui->comboBox->addItem("Пратта"); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_array_clicked() { srand(time(0)); QString str_n = ui->lineEdit->text(); int n = str_n.toInt(); int array[n]; QString arrayStr; for(int i = 0; i < n; i++) { array[i] = rand()%100; arrayStr += QString::number(array[i]) + " "; } ui->before_sort->setText(arrayStr); } void MainWindow::on_info1_clicked() { QMessageBox::information(this, "Массив", "Генерация массива"); } void MainWindow::on_incrementShell_clicked() { QString before_sort_str = ui->before_sort->toPlainText(); QString after_sort_str; ShellSort sort; int value = ui->comboBox->currentIndex(); switch(value) { case(0): { after_sort_str = sort.Shell(before_sort_str, 0, 0); break; } case(1): { after_sort_str = sort.Shell(before_sort_str, 1, 0); break; } case(2): { after_sort_str = sort.Shell(before_sort_str, 2, 0); break; } case(3): { after_sort_str = sort.Shell(before_sort_str, 3, 0); break; } } ui->after_sort->setText(after_sort_str); } void MainWindow::on_info2_clicked() { int value = ui->comboBox->currentIndex(); switch(value) { case(0): { QMessageBox::information(this, "Последовательность Шелла", "Первоначально используемая Шеллом последовательность длин промежутков: d[1] = N/2, d[i] = d[i-1]/2, d[k] = 1\nВ худшем случае, сложность алгоритма составит O(N^{2})"); break; } case(1): { QMessageBox::information(this, "Последовательность Седжвика", "Предложенная Седжвиком последовательность: d[i] = 9*2^{i} - 9*2^{i/2} + 1, если i четное и d[i] = 8*2^{i} - 6*2^{(i+1)/2} + 1, если i нечетное\nПри использовании таких приращений средняя сложность алгоритма составляет: O(N^{7/6}), а в худшем случае порядка O(N^{4/3})"); break; } case(2): { QMessageBox::information(this, "Последовательность Хиббарда", "Предложенная Хиббардом последовательность:\nвсе значения 2^{i} - 1 ≤ N, i ∈ N\nТакая последовательность шагов приводит к алгоритму сложностью O(N^{3/2})"); break; } case(3): { QMessageBox::information(this, "Последовательность Пратта", "Предложенная Праттом последовательность: все значения 2^{i} * 3^{j} ≤ N/2, i,j ∈ N; В таком случае сложность алгоритма составляет O(N(logN)^{2})"); break; } default: exit(1); } } void MainWindow::on_step1_clicked() { QString before_sort_str = ui->before_sort->toPlainText(); QString after_sort_str; ShellSort sort; int value = ui->comboBox->currentIndex(); switch(value) { case(0): { after_sort_str = sort.Shell(before_sort_str, 0, 1); break; } case(1): { after_sort_str = sort.Shell(before_sort_str, 1, 1); break; } case(2): { after_sort_str = sort.Shell(before_sort_str, 2, 1); break; } case(3): { after_sort_str = sort.Shell(before_sort_str, 3, 1); break; } } ui->after_sort->setText(after_sort_str); }
/* * Lesson18.cpp * * Created on: Nov 9, 2018 * Author: Akash Lohani */ #include <iostream> using namespace std; // @suppress("Symbol is not resolved") int main(){ /* * for (initialization; condition; inc/dec){ * instruction-to-repeat */ for (int i = 0; i < 5; i++){ cout<< i <<endl; } int arr[4]; for(int i=0; i<4; i++){ arr[i] = i; } //infinite loop for(;;){ cout<<"lala"<<endl; } for(int i=0; i<5;){ cout<<"lala"<<endl; } }
#include "FlyweightFactory.h" #include <string> #include <iostream> int main(int argc, char *argv[]) { std::string name = "goooogllleee"; std::cout << "Original name: " << name << std::endl; std::shared_ptr<FlyweightFactory> factory = std::make_shared<FlyweightFactory>(); for (size_t i = 0; i < name.size(); i++) { std::cout << name[i] << "-> "; factory->getCode(name[i])->code(); std::cout << std::endl; } return 0; }
//--------------------------------------------------------------------------- #include "stdafx.h" //--------------------------------------------------------------------------- #include "ExampleExperiment3DGraphics.h" //--------------------------------------------------------------------------- #include "Properties.h" #include "GLGeometryViewer3D.h" #include "GeoXOutput.h" //--------------------------------------------------------------------------- IMPLEMENT_GEOX_CLASS( ExampleExperiment3DGraphics ,0) { BEGIN_CLASS_INIT( ExampleExperiment3DGraphics ); ADD_NOARGS_METHOD(ExampleExperiment3DGraphics::addTriangles) ADD_NOARGS_METHOD(ExampleExperiment3DGraphics::testCosine) } QWidget *ExampleExperiment3DGraphics::createViewer() { viewer = new GLGeometryViewer3D(); return viewer; } ExampleExperiment3DGraphics::ExampleExperiment3DGraphics() { viewer = NULL; } ExampleExperiment3DGraphics::~ExampleExperiment3DGraphics() {} void ExampleExperiment3DGraphics::addTriangles() { // first way to describe a point Point3D p1; p1.position = makeVector3f(-3.0f,1.0f,1.0f); int p1Handle = viewer->addPoint(p1); // second way to describe a point Point3D p2(makeVector3f(-1.0f,1.0f,-2.0f)); int p2Handle = viewer->addPoint(p2); // third way to describe a point Point3D p3(-1.0f,-1.0f,3.0f); int p3Handle = viewer->addPoint(p3); // then declare connectivity Triangle t1; t1.vertices[0] = p1Handle; t1.vertices[1] = p2Handle; t1.vertices[2] = p3Handle; viewer->addTriangle(t1); // or directly describe a triangle, be aware of introducing multiple new vertices viewer->addTriangle(makeVector3f(1.0,1.0,0.0),makeVector3f(3.0,1.0,3.0),makeVector3f(3.0,1.0,1.0)); // display changes viewer->refresh(); } std::pair<Vector3f, float> generatePowerCosineWeightedDirection( const Vector3f& aUp, const Vector3f& aLeft, const Vector3f& aForward, //local coordinate system const float aRandNum1, const float aRandNum2, //two random numbers provided from outside const float aPower) //the power of the cosine lobe { //TODO: Implement float power = 2.0f / (aPower + 1); float term = sqrt(1 - powf(aRandNum2, power)); Vector3f direction = Vector3f(); direction[0] = cosf(2 * M_PI*aRandNum1)*term; direction[1] = sinf(2 * M_PI*aRandNum1)*term; direction[2] = sqrt(powf(aRandNum2, 0.5f * term)); direction = aLeft * direction[0] + aForward * direction[1] + aUp * direction[2]; direction.normalize(); float theta = acos(direction[2]); return std::make_pair(direction, powf(cosf(theta), aPower) / (power * M_PI)); } std::pair<Vector3f, float> generateHemisphereSample( const Vector3f& aUp, const Vector3f& aLeft, const Vector3f& aForward, //local coordinate system const float aRandNum1, const float aRandNum2) //two random numbers provided from outside { //TODO: Implement float term = sqrt(1 - powf(aRandNum2, 2)); float phi = 2 * M_PI*aRandNum1; Vector3f direction = Vector3f(); direction[0] = cosf(phi)*term; direction[1] = sinf(phi)*term; direction[2] = aRandNum2; direction = aLeft * direction[0] + aForward * direction[1] + aUp * direction[2]; direction.normalize(); return std::make_pair(direction, 1.f / (2 * M_PI)); } void ExampleExperiment3DGraphics::testCosine() { Vector3f up; up[0] = 0; up[1] = 1; up[2] = 0; Vector3f left; left[0] = 1; left[1] = 0; left[2] = 0; Vector3f forward; forward[0] = 0; forward[1] = 0; forward[2] = 1; float power = 10; Vector3f o; o[0] = o[1] = o[2] = 0; Vector3f d = Vector3f(); d[0] = 0.152343228; d[1] = 1.00000000; d[2] = -0.157788336; Vector3f n = Vector3f(); n[0] = -0.301709116; n[1] = 0.953400016; n[2] = 0.0; Vector3f r2 = n * (2 * (n * d)) - d; Vector3f r = Vector3f(); r[0] = 0.440226525; r[1] = -0.884559870; r[2] = -0.154124737; /*viewer->addLine(o, n, makeVector4f(1.0f, 0.0f, 0.0f, 1.0f)); viewer->addLine(o, -d, makeVector4f(0.0f, 1.0f, 0.0f, 1.0f)); viewer->addLine(o, r, makeVector4f(0.0f, 0.0f, 1.0f, 1.0f));*/ //viewer->addLine(o, r2, makeVector4f(0.0f, 0.0f, 1.0f, 1.0f)); for(int i=0 ; i<1000 ; i++) { float rnd1 = (float)rand() / (float)RAND_MAX; float rnd2 = (float)rand() / (float)RAND_MAX; std::pair<Vector3f, float> p = generatePowerCosineWeightedDirection(left, up, forward, rnd1, rnd2, power); //std::pair<Vector3f, float> p = generateHemisphereSample(left, up, forward, rnd1, rnd2); //viewer->addLine(o, p.first, makeVector4f(1.0f* p.second, 1.0f* p.second, 1.0f* p.second, 1.0f)); } viewer->refresh(); }
// This file has been generated by Py++. #ifndef Rectf_hpp__pyplusplus_wrapper #define Rectf_hpp__pyplusplus_wrapper void register_Rectf_class(); #endif//Rectf_hpp__pyplusplus_wrapper
/************************************************************* * > File Name : c1090_2.cpp * > Author : Tony_Wong * > Created Time : 2019/11/13 20:59:00 * > Algorithm : **************************************************************/ #include <bits/stdc++.h> using namespace std; inline int read() { int x = 0; int f = 1; char ch = getchar(); while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();} while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();} return x * f; } const int maxn = 80; struct Edge { int from, to; }edges[150]; int n, m, w[maxn], G[maxn][maxn], dis[maxn][maxn]; int ans1 = 0, ans2 = 0; bool vis[maxn]; void dfs(int u) { vis[u] = true; for (int i = 1; i <= n; ++i) { if (dis[u][i] != 0x3f3f3f3f && !vis[i]) dfs(i); } } int main() { n = read(); m = read(); for (int i = 1; i <= n; ++i) { w[i] = read(); } memset(G, 0x3f, sizeof(G)); for (int i = 1; i <= n; ++i) G[i][i] = 0; for (int i = 1; i <= m; ++i) { int u = read(), v = read(), opt = read(); G[u][v] = 1; G[v][u] = 1; edges[i].from = u; edges[i].to = v; } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { dis[i][j] = G[i][j]; } } for (int k = 1; k <= n; ++k) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]); } } } for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (dis[i][j] != 0x3f3f3f3f && i != j) { ans1 += dis[i][j] + w[j]; } } } for (int del = 1; del <= m; ++del) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { dis[i][j] = G[i][j]; } } dis[edges[del].from][edges[del].to] = dis[edges[del].to][edges[del].from] = 0x3f3f3f3f; memset(vis, 0, sizeof(vis)); dfs(1); bool connected = true; for (int i = 1; i <= n; ++i) if (!vis[i]) connected = false; if (!connected) break; for (int k = 1; k <= n; ++k) { for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { dis[i][j] = min(dis[i][j], dis[i][k] + dis[k][j]); } } } int res = 0; for (int i = 1; i <= n; ++i) { for (int j = 1; j <= n; ++j) { if (dis[i][j] != 0x3f3f3f3f && i != j) { res += dis[i][j] + w[j]; } } } ans2 = max(ans2, res); } printf("%d %d\n", ans1, ans2); return 0; }
/* * hardwareCall.cpp * * Created on: Jul 7, 2015 * Author: shapa */ #include "hardwareCall.h" #include "BoardSupportPackage.h" #include "stm32f4xx_hal_conf.h" #include <string.h> #include <stdlib.h> extern "C" { void SysTick_Handler(void); void UART8_IRQHandler(void); void DMA1_Stream0_IRQHandler(void); void DMA1_Stream1_IRQHandler(void); } void initLedGpio() { /* PG13 - Green, PG14 - Red */ GPIO_InitTypeDef initializer; initializer.Alternate = 0; initializer.Mode = GPIO_MODE_OUTPUT_PP; initializer.Pin = GPIO_PIN_13 | GPIO_PIN_14; initializer.Pull = GPIO_NOPULL; initializer.Speed = GPIO_SPEED_LOW; __HAL_RCC_GPIOG_CLK_ENABLE(); HAL_GPIO_Init(GPIOG, &initializer); } void setGreenLedState(bool state) { HAL_GPIO_WritePin(GPIOG, GPIO_PIN_13, state ? GPIO_PIN_SET : GPIO_PIN_RESET); } void setRedLedState(bool state) { HAL_GPIO_WritePin(GPIOG, GPIO_PIN_14, state ? GPIO_PIN_SET : GPIO_PIN_RESET); } void initDebugGpio(void) { /* PE0 - RX, PE1 - TX, UART8 */ GPIO_InitTypeDef initializer; initializer.Alternate = GPIO_AF8_UART8; initializer.Mode = GPIO_MODE_AF_PP; initializer.Pin = GPIO_PIN_0 | GPIO_PIN_1; initializer.Pull = GPIO_PULLUP; initializer.Speed = GPIO_SPEED_LOW; __HAL_RCC_GPIOE_CLK_ENABLE(); HAL_GPIO_Init(GPIOE, &initializer); __HAL_RCC_UART8_CLK_ENABLE(); __HAL_RCC_DMA1_CLK_ENABLE(); } void initWiFiGpio(void) { /* PF6 - RX, PF7 - TX, UART7 */ GPIO_InitTypeDef initializer; initializer.Alternate = GPIO_AF8_UART7; initializer.Mode = GPIO_MODE_AF_PP; initializer.Pin = GPIO_PIN_6 | GPIO_PIN_7; initializer.Pull = GPIO_PULLUP; initializer.Speed = GPIO_SPEED_LOW; __HAL_RCC_GPIOF_CLK_ENABLE(); HAL_GPIO_Init(GPIOF, &initializer); __HAL_RCC_UART7_CLK_ENABLE(); __HAL_RCC_DMA1_CLK_ENABLE(); } void initSteeringPWMGpio(void) { } HAL_StatusTypeDef initUartIface(UART_HandleTypeDef &huart) { HAL_StatusTypeDef stat = HAL_UART_DeInit(&huart); stat = HAL_UART_Init(&huart); __HAL_UART_ENABLE_IT(&huart, UART_IT_RXNE); stat = HAL_DMA_Init(huart.hdmatx); return HAL_OK; } void allowInterrupts(void) { /* debug interrupts */ HAL_NVIC_EnableIRQ(UART8_IRQn); HAL_NVIC_EnableIRQ(DMA1_Stream0_IRQn); /* wifi interrupts */ HAL_NVIC_EnableIRQ(UART7_IRQn); HAL_NVIC_EnableIRQ(DMA1_Stream1_IRQn); } void uartSendLocked(UART_HandleTypeDef *huart, const char *string, uint32_t size) { if (!string) { return; } HAL_StatusTypeDef stat = HAL_UART_Transmit(huart, (uint8_t*)string, static_cast<uint16_t>(size), 0xFFFF); while (stat == HAL_BUSY || stat == HAL_TIMEOUT) { stat = HAL_UART_Transmit(huart, (uint8_t*)string, static_cast<uint16_t>(size), 0xFFFF); } } bool uartSendDMA(UART_HandleTypeDef *huart, const char *string, uint32_t size) { if (!string || !size) { return false; } #if 1 HAL_StatusTypeDef stat = HAL_UART_Transmit_DMA(huart, (uint8_t*)string, static_cast<uint16_t>(size)); #else HAL_StatusTypeDef stat = HAL_UART_Transmit_IT(huart, (uint8_t*)string, static_cast<uint16_t>(size)); #endif return stat == HAL_OK; } extern "C" void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) { // HAL sender is incrementing address. Compute the real ptr for free char *prt = (char *)(huart->pTxBuffPtr - huart->TxXferSize); delete prt; onDebugTransmitComplete(BSP::system); } extern "C" { void SysTick_Handler(void) { HAL_IncTick(); onSystemTick(BSP::system); } void UART8_IRQHandler(void) { onDebugUartInterrupt(BSP::system); } void DMA1_Stream0_IRQHandler(void) { onDebugTransmitComplete(BSP::system); } void DMA1_Stream1_IRQHandler(void) { // onWifiTransmitComplete(BSP::system); } }
#include <iostream> #include <string> #include <climits> #define MAX 999999999 using namespace std; class Long { private: unsigned int first; unsigned int second; public: Long() : first(0), second(0){} void Init(int, int); void Read(); string toString(); void Display(); int countOfDigits(int); Long operator+ (Long l); Long operator- (Long l); Long operator* (Long l); Long operator/ (Long l); }; Long Long::operator+ (Long l){ Long a; a.first = this->first + l.first; a.second = this->second + l.second; if (a.second > MAX){ a.first += 1; a.second -= MAX + 1; } return a; } Long Long::operator- (Long l){ Long a; if (l.second > this->second){ a.first = this->first - l.first - 1; a.second = MAX - l.second + this->second; }else { a.first = this->first - l.first; a.second = this->second - l.second; } return a; } Long Long::operator* (Long l){ Long a; a.first = this->first * l.first + this->first * l.second + this->second * l.first; a.second = this->second * l.second; if (a.second > MAX){ a.first += 1; a.second -= MAX + 1; } return a; } Long Long::operator/ (Long l){ Long a; a.first = this->first / l.first; a.second = 0; return a; } int Long::countOfDigits(int Num){ //Считаем к-ство цифр в числе int count = 0; while (Num >= 1){ Num /= 10; count++; } return count; } void Long::Init(int x, int y){ if (y > UINT_MAX) throw "Error!"; //Если поля больше максимального значения то ошибка if (x > UINT_MAX) throw "Error!"; if (y < 0)throw "Error!"; //Если второе поле отрицательное то ошибка if (y > MAX){ x += 1; y -= MAX; } if (x < 0) throw "Error!"; first = x; second = y; } void Long::Display(){ cout << toString() << endl; } string Long::toString(){ // Первод в строку string Zeros = ""; int countOfZeros = (9 - countOfDigits(first)) + (9 - countOfDigits(second)); //Добавляем нули неиспользованным разрядам if (first != 0){ for (int i = 0; i < countOfZeros; i++){ Zeros += "0"; } return to_string(first) + Zeros + to_string(second); //Если старшая часть не равна нулю } else return to_string(second); //Если старшая часть равна нулю } int main() { setlocale(LC_ALL, "RUS"); unsigned long long c; unsigned int a; unsigned int b; Long l1; Long l2; Long l3; cout << "введите первое число: " << endl; cin >> c; b = c/1000000000; a = c%1000000000; l1.Init(b, a); cout << "введите второе число: " << endl; cin >> c; b = c/1000000000; a = c%1000000000; l2.Init(b, a); int opt, opt_exit = 1; while(opt_exit == 1) { cout << "\n\t Выберите действие:"; cout << "\n\t 1.Сложение"; cout << "\n\t 2.Вычитание"; cout << "\n\t 3.Умножение"; cout << "\n\t 4.Деление"; cout << "\n\t 5.Выход\n"; cin >> opt; switch(opt) { case 1: l3 = l1 + l2; cout << "\n\n"; l1.Display(); cout << " + "; l2.Display(); cout << " = "; l3.Display(); break; case 2: l3 = l1 - l2; cout << "\n\n"; l1.Display(); cout << " - "; l2.Display(); cout << " = "; l3.Display(); break; case 3: l3 = l1 * l2; cout << "\n\n"; l1.Display(); cout << " * "; l2.Display(); cout << " = "; l3.Display(); break; case 4: l3 = l1 / l2; cout << "\n\n"; l1.Display(); cout << " / "; l2.Display(); cout << " = "; l3.Display(); break; case 5: return 0; default: cout << "\n\n\t---Invalid choice....... try again\n"; break; } cout << "\n\n\t---Press 1 to continue--> "; cin >> opt_exit; } return 0; }
#include <iostream> #include<cmath> using namespace std; string funnynot(string str) { unsigned int n=str.length(); for(unsigned int i=1,j=n-1;i<n&&j>0;i++,j--) { if((abs(str[i]-str[i-1])^abs(str[j]-str[j-1]))) return "Not Funny"; } return "Funny"; } int main() { // your code goes here unsigned int tc; cin>>tc; while(tc--) { string str; cin>>str; cout<<funnynot(str)<<endl; } return 0; }
#include "Group3D.h" Group3D::Group3D() { } Group3D::~Group3D() { } void Group3D::translate(const QVector3D& t) { translation += t; QMatrix4x4 localMatrix; localMatrix.setToIdentity(); localMatrix.translate(translation); localMatrix.rotate(rotation); localMatrix.scale(scaling); localMatrix = globalTransformMatrix * localMatrix; for (int i = 0; i < objects.size(); i++) { objects[i]->setGlobalTransform(localMatrix); } } void Group3D::rotate(const QQuaternion& r) { rotation = r * rotation; QMatrix4x4 localMatrix; localMatrix.setToIdentity(); localMatrix.translate(translation); localMatrix.rotate(rotation); localMatrix.scale(scaling); localMatrix = globalTransformMatrix * localMatrix; for (int i = 0; i < objects.size(); i++) { objects[i]->setGlobalTransform(localMatrix); } } void Group3D::scale(const float& s) { scaling *= s; QMatrix4x4 localMatrix; localMatrix.setToIdentity(); localMatrix.translate(translation); localMatrix.rotate(rotation); localMatrix.scale(scaling); localMatrix = globalTransformMatrix * localMatrix; for (int i = 0; i < objects.size(); i++) { objects[i]->setGlobalTransform(localMatrix); } } void Group3D::setGlobalTransform(const QMatrix4x4& g) { globalTransformMatrix = g; QMatrix4x4 localMatrix; localMatrix.setToIdentity(); localMatrix.translate(translation); localMatrix.rotate(rotation); localMatrix.scale(scaling); localMatrix = globalTransformMatrix * localMatrix; for (int i = 0; i < objects.size(); i++) { objects[i]->setGlobalTransform(localMatrix); } } void Group3D::addObject(Transformational* obj) { objects.append(obj); } void Group3D::draw(QOpenGLShaderProgram* shaderProgram, QOpenGLFunctions* functions) { for (int i = 0; i < objects.size(); i++) { objects[i]->draw(shaderProgram, functions); } } void Group3D::deleteObject(Transformational* obj) { objects.removeAll(obj); } void Group3D::deleteObject(const int& index) { objects.remove(index); }
#ifndef __DUI_SCROLLBAR_H__ #define __DUI_SCROLLBAR_H__ #include "DUIControlBase.h" DUI_BGN_NAMESPCE class DUILIB_API IDUIScrollBar: public CDUIControlBase { public: virtual ~IDUIScrollBar() { NULL; } virtual BOOL SetScrollBarInfo(LPSCROLLINFO pSi) = 0; virtual VOID GetScrollBarInfo(LPSCROLLINFO pSi) = 0; virtual VOID SetScrollOwner(const CDUIString& strOwnerName) = 0; virtual VOID SetScrollOwner(IDUIControl* pOwner) = 0; virtual IDUIControl* GetScrollOwner() = 0; }; class DUILIB_API IDUIScrollSink { public: virtual LRESULT OnVScrollEvent(WPARAM wParam, LPARAM lParam) { return S_OK; } virtual LRESULT OnHScrollEvent(WPARAM wParam, LPARAM lParam) { return S_OK; } virtual BOOL IsVerticalSB() = 0; }; class IDUIButton; class DUILIB_API CDUIScrollBarBase: public IDUIScrollBar, public IDUIScrollSink { public: typedef IDUIScrollBar theBase; CDUIScrollBarBase(); virtual ~CDUIScrollBarBase(); virtual LPVOID GetInterface(const CDUIString& strName); virtual VOID SetAttribute(const CDUIString& strName, const CDUIString& strValue); virtual VOID SetControlRect(const RECT& rt); virtual VOID ModifyStatus(DWORD dwRemove, DWORD dwAdd); virtual VOID SetScrollOwner(const CDUIString& strOwnerName); virtual VOID SetScrollOwner(IDUIControl* pOwner); virtual IDUIControl* GetScrollOwner(); virtual BOOL SetScrollBarInfo(LPSCROLLINFO pSi); virtual VOID GetScrollBarInfo(LPSCROLLINFO pSi); virtual LRESULT ProcessEvent(const DUIEvent& info, BOOL& bHandled); virtual LRESULT OnVScrollEvent(WPARAM wParam, LPARAM lParam); virtual LRESULT OnHScrollEvent(WPARAM wParam, LPARAM lParam); protected: BOOL CreateCtrls(); IDUIButton* GetElement(INT nType); BOOL CheckCtrlsSink(); VOID UpdateCtrlsAttributes(); VOID UpdateThumUI(); VOID StartMessageLoop(); BOOL SetMsgSink(BOOL bSet); VOID EnableScrollBar(BOOL bEnable); protected: virtual VOID OnCreate(); virtual VOID OnDestroy(); virtual VOID PaintBkgnd(HDC dc); protected: INT m_nMin; INT m_nMax; INT m_nPos; INT m_nPage; SIZE m_sizeArrow1; SIZE m_sizeArrow2; RECT m_rtScrollPage1; RECT m_rtScrollPage2; IDUIControl* m_pNotifier; CDUIString m_strNotifierName; BOOL m_bMsgLoop; BOOL m_bScrollPage1; POINT m_ptCursor; double m_fRatio; CARGB m_clrBK; }; class DUILIB_API CDUIVerticalSB: public CDUIScrollBarBase { public: virtual CRefPtr<IDUIControl> Clone(); virtual BOOL IsVerticalSB() { return TRUE; } }; class DUILIB_API CDUIHorizontalSB: public CDUIScrollBarBase { public: virtual CRefPtr<IDUIControl> Clone(); virtual BOOL IsVerticalSB() { return FALSE; } }; DUI_END_NAMESPCE #endif //__DUI_SCROLLBAR_H__
#include "ZigZag.h" void ZigZag::Encryption(string& mesaj, const int key) { string* satir = new string[key]; int liner = 0; int positioner = +1; for (int i = 0; i < mesaj.length(); i++) { if (liner == key-1) { positioner=-1; } else if (liner == 0) { positioner=+1; } (*(satir+liner)).push_back(mesaj.at(i)); liner += positioner; } string temp; for (int i = 0; i < key; i++) { temp.append(*(satir+i)); } mesaj = temp; } void ZigZag::Decryption(string& mesaj,const int key) { int msgLen = mesaj.length(), i, j, k = -1, row = 0, col = 0, m = 0; char** railMatrix = new char* [key]; for (int i = 0; i < key; i++) railMatrix[i] = new char[mesaj.length()]; for (i = 0; i < key; ++i) for (j = 0; j < msgLen; ++j) railMatrix[i][j] = '\n'; for (i = 0; i < msgLen; ++i) { railMatrix[row][col++] = '*'; if (row == 0 || row == key - 1) k = k * (-1); row = row + k; } for (i = 0; i < key; ++i) for (j = 0; j < msgLen; ++j) if (railMatrix[i][j] == '*') railMatrix[i][j] = mesaj[m++]; row = col = 0; k = -1; string temp; for (i = 0; i < msgLen; ++i) { temp.push_back(railMatrix[row][col++]); if (row == 0 || row == key - 1) k = k * (-1); row = row + k; } mesaj = temp; }
void setup() { Serial.begin(9600); pinMode(13,OUTPUT); } void loop() { // 아날로그 데이터 읽기 - 0~1023 사이값을 읽을 수 있다. // 어두울수록 숫자가 크다. 빛이 얼마나 세냐에 따라서 저항이 달리진다. // 어두울 때는 값이 커지고, 밝을 때는 값이 작아진다. => 큰값 어둠, 작은값 밝음 // 100k 657 ~ 5 => 652 // 10k 49 ~ 969 => 920 사잇값이 제일 크다. 빛의 세기에 따라 민감하게 반응하다. // 10k 보다 낮은 저항을 쓰거나 큰 저항을 쓰면 사잇값이 작아진다. // 저항을 뭘 주냐에 따라서 값이 달라진다. int photoresistorVal = analogRead(A0); Serial.println(photoresistorVal); if(photoresistorVal > 500) { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); } delay(1000); }
// // Box.h // Assignment_5_Project // // Created by Mohamad Awab Alkhiami & Ghiyath Alaswad on 21/06/2018. // #ifndef Box_h #define Box_h #include<algorithm> class Box { private: std::vector<int> triangleIndices; std::vector<Box> Boxes; Vec3Df min; Vec3Df max; public: Box() { } Box(std::vector<int> _triangles, Vec3Df _min, Vec3Df _max) { this->min = _min; this->max = _max; this->triangleIndices = _triangles; if (triangleIndices.size() < 50) { //it is fine because the triangles vector has less than 50 triangles } else { // Longest axis char _theLongestAxes = findLongestAxis(); Vec3Df leftMAx; Vec3Df rightMin; computeTheLeftMaxAndRightMin(min, max, leftMAx, rightMin, _theLongestAxes); std::vector<int> _LTriangles; std::vector<int> _RTriangles; split(&this->triangleIndices, &_LTriangles, &_RTriangles, this->min, leftMAx, rightMin, this->max); Box _L = Box(_LTriangles, this->min, leftMAx); Box _R = Box(_RTriangles, rightMin, this->max); Boxes.push_back(_L); Boxes.push_back(_R); } } void split(std::vector<int> *triangles, std::vector<int> *_LTriangles, std::vector<int> *_RTriangles, Vec3Df Lmin, Vec3Df Lmax, Vec3Df Rmin, Vec3Df Rmax) { std::vector<int> _Temp; for (const int& _tri : *triangles) { if (hasVertexInBox(_tri, Lmin, Lmax) && hasVertexInBox(_tri, Rmin, Rmax)) {//in both boxes _Temp.push_back(_tri); } else if (hasVertexInBox(_tri, Lmin, Lmax)) {//in left box _LTriangles->push_back(_tri); } else if (hasVertexInBox(_tri, Rmin, Rmax)) {//in right box _RTriangles->push_back(_tri); } } *triangles = _Temp; } //function that takes thie min max vec3Df and decide that we gonna split our box according to X,Y or Z char findLongestAxis() { Vec3Df min = this->min; Vec3Df max = this->max; float _X = max[0] - min[0]; float _Y = max[1] - min[1]; float _Z = max[2] - min[2]; if (_X == std::max(_X, _Y) && _X == std::max(_X, _Z)) { return 'x'; } else if (_Y == std::max(_X, _Y) && _Y == std::max(_Y, _Z)) { return 'y'; } else if (_Z == std::max(_X, _Z) && _X == std::max(_Y, _Z)) { return 'z'; } return 'x'; } //function to tell wether the ray is hitting the nox or not bool hit(Box box, Vec3Df origin, Vec3Df dir) { Vec3Df min = box.min; Vec3Df max = box.max; float xmin = min[0]; float ymin = min[1]; float zmin = min[2]; float xmax = max[0]; float ymax = max[1]; float zmax = max[2]; float txmin = (xmin - origin[0]) / dir[0]; float txmax = (xmax - origin[0]) / dir[0]; if (txmin > txmax) { std::swap(txmin, txmax); } float tymin = (ymin - origin[1]) / dir[1]; float tymax = (ymax - origin[1]) / dir[1]; if (tymin > tymax) { std::swap(tymin, tymax); } if ((txmin > tymax) || (tymin > txmax)) { return false; } if (tymin > txmin) { txmin = tymin; } if (tymax < txmax) { txmax = tymax; } float tzmin = (zmin - origin[2]) / dir[2]; float tzmax = (zmax - origin[2]) / dir[2]; if (tzmin > tzmax) { std::swap(tzmin, tzmax); } if ((txmin > tzmax) || (tzmin > txmax)) { return false; } return true; } void computeTheLeftMaxAndRightMin(Vec3Df &finalmin, Vec3Df &finalmax, Vec3Df &leftMAx, Vec3Df &rightMin, char _theLongestAxes) { switch (_theLongestAxes) { case 'x': leftMAx[0] = finalmin[0] + ((finalmax[0] - finalmin[0]) / 2); leftMAx[1] = max[1]; leftMAx[2] = max[2]; rightMin[0] = min[0] + ((max[0] - min[0]) / 2); rightMin[1] = min[1]; rightMin[2] = min[2]; break; case 'y': leftMAx[0] = max[0]; leftMAx[1] = min[1] + ((max[1] - min[1]) / 2); leftMAx[2] = max[2]; rightMin[0] = min[0]; rightMin[1] = min[1] + ((max[1] - min[1]) / 2); rightMin[2] = min[2]; break; case 'z': leftMAx[0] = max[0]; leftMAx[1] = max[1]; leftMAx[2] = min[2] + ((max[2] - min[2]) / 2); rightMin[0] = min[0]; rightMin[1] = min[1]; rightMin[2] = min[2] + ((max[2] - min[2]) / 2); break; } } //function to determine wether a vertix or more of a triangle is in a box bool hasVertexInBox(int triangle, Vec3Df _min, Vec3Df _max) { for (int i = 0; i < 3; i++) { if (isVertexInBox(MyMesh.vertices[MyMesh.triangles[triangle].v[i]], _min, _max)) { return true; } } return false; } bool isVertexInBox(Vertex vertex, Vec3Df _min, Vec3Df _max) { Vec3Df pos = vertex.p; return pos[0] >= _min[0] && pos[0] <= _max[0] && pos[1] >= _min[1] && pos[1] <= _max[1] && pos[2] >= _min[2] && pos[2] <= _max[2]; } std::vector<int> trace(const Vec3Df & origin, const Vec3Df & dir) { std::vector<int> returnable; // if (hit(this->Boxes[0], origin,dir) && hit(this->Boxes[1], origin,dir)) { // //box has items or box hit ??? // if(hit(this->Boxes[0], origin,dir)) returnable.push_back(this->Boxes[0].trace(origin,dir)); // if(hit(this->Boxes[1], origin,dir)) returnable.push_back(this->Boxes[1].trace(origin,dir)); // } if(this->triangleIndices.size()>0){ returnable.insert(returnable.end(), this->triangleIndices.begin(),this->triangleIndices.end()); } if(this->Boxes.size()>0){ if(hit(this->Boxes[0], origin,dir)){ std::vector<int> _TEMPVECTOR = this->Boxes[0].trace(origin,dir); returnable.insert(returnable.end(),_TEMPVECTOR.begin(),_TEMPVECTOR.end()); } if (hit(this->Boxes[1], origin,dir)){ std::vector<int> _TEMPVECTOR = this->Boxes[1].trace(origin,dir); returnable.insert(returnable.end(),_TEMPVECTOR.begin(),_TEMPVECTOR.end()); } } return returnable; } }; #endif /* Box_h */
#include "SignalHandling.hpp" #include "SignOut.hpp" #include "ConversationControl.hpp" #include "FileHandling.hpp" #include "GlobalVariables.hpp" #include "ClasslessLogger.hpp" #include "ConsoleWindow.hpp" #include "ChatWindow.hpp" #include <utility> #include <cstring> namespace SignalHandling { namespace { static bool isChatResourcesDealocated = false; std::string getChatFolderName() { auto fileNamesFormFolder = FileInterface::Accesor::getFilenamesFromFolder(ENVIRONMENT_PATH::TO_FOLDER::CHATS); if (fileNamesFormFolder) { for (const auto& x : *fileNamesFormFolder) { if (std::string::npos != x.find(getenv("USER"))) { return x; } } } return ""; } void closeMessegner() { SignOut signOut; signOut.signOutUser(); exit (EXIT_SUCCESS); } }//namespace void posixSignalHandlerInMainConsole(int signal) { const std::string log = "Signal nr=" + std::to_string(signal) + "handled in main console"; fileLog(log.c_str(), LogSpace::Common); if (not isChatResourcesDealocated) { isChatResourcesDealocated = true; fileLog("Start of remove chat resources", LogSpace::Common); closeMessegner(); } } void posixSignalHandlerInChatConsole(int signal) { const std::string log = "Signal nr=" + std::to_string(signal) + "handled in chat console"; fileLog(log.c_str(), LogSpace::Common); if (not isChatResourcesDealocated) { isChatResourcesDealocated = true; fileLog("Start of remove chat resources", LogSpace::Common); std::string chatFolderName = getChatFolderName(); if (FileInterface::Managment::isFileExist(ENVIRONMENT_PATH::TO_FOLDER::CHATS + chatFolderName + "/END")) { std::string command = "rm -rf " + ENVIRONMENT_PATH::TO_FOLDER::CHATS + chatFolderName; system(command.c_str()); closeMessegner(); } else { FileInterface::Managment::createFile(ENVIRONMENT_PATH::TO_FOLDER::CHATS + chatFolderName + "/END"); closeMessegner(); } } } void createPosixSignalsHandling(void(*handlingFunction)(int)) { for (const auto posixSignal : SignalHandling::posixSignalsCausingUnexpectedApplicationEndings) { std::signal(posixSignal, handlingFunction); } } namespace NCurses { void resizeHandlerInMainWindow(int) { fileLog("Console resize handled in main window", LogSpace::Common); endwin(); refresh(); clear(); initscr(); ConsoleWindow::displayMainWindow(); } void resizeHandlerInRegistrationWindow(int) { fileLog("Console resize handled in registration window", LogSpace::Common); endwin(); refresh(); clear(); ConsoleWindow::displayRegistrationWindow(); } void resizeHandlerInSignInWindow(int) { fileLog("Console resize handled in sign window", LogSpace::Common); endwin(); refresh(); clear(); ConsoleWindow::displaySignInWindow(); } void resizeHandlerInChatWindow(int) { fileLog("Console resize handled in chat window", LogSpace::Common); endwin(); refresh(); clear(); ChatWindow::displayChatWindows(); ChatWindow::displayEnterMessageWindow(); ChatWindow::displayDisplayMessageWindow(""); } }//NCurses }//SignalHandling
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QString> #include <math.h> double num_first; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); connect(ui->pushButton0,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton1,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton2,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton3,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton4,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton5,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton6,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton7,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton8,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton9,SIGNAL(clicked()),this,SLOT(digits_numbers())); connect(ui->pushButton_plusminus,SIGNAL(clicked()),this,SLOT(operations())); connect(ui->pushButton_pl,SIGNAL(clicked()),this,SLOT(math_operations())); connect(ui->pushButton_min,SIGNAL(clicked()),this,SLOT(math_operations())); connect(ui->pushButton_umn,SIGNAL(clicked()),this,SLOT(math_operations())); connect(ui->pushButton_del,SIGNAL(clicked()),this,SLOT(math_operations())); connect(ui->pushButtonxn,SIGNAL(clicked()),this,SLOT(math_operations())); ui->pushButton_pl->setCheckable(true); ui->pushButton_min->setCheckable(true); ui->pushButton_umn->setCheckable(true); ui->pushButton_del->setCheckable(true); ui->pushButtonxn->setCheckable(true); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_pushButton_clicked() { double a; a = ui->lineEdit_a->text().toDouble(); double b; b = ui->lineEdit_b->text().toDouble(); double s = a + b; QString sss; sss.setNum(s); ui->lineEdit_s->setText(sss); } void MainWindow::on_pushButtonm_clicked() { double a; a = ui->lineEdit_a->text().toDouble(); double b; b = ui->lineEdit_b->text().toDouble(); double m = a - b; QString mmm; mmm.setNum(m); ui->lineEdit_s->setText(mmm); } void MainWindow::on_pushButtonu_clicked() { double a; a = ui->lineEdit_a->text().toDouble(); double b; b = ui->lineEdit_b->text().toDouble(); double u = a * b; QString uuu; uuu.setNum(u); ui->lineEdit_s->setText(uuu); } void MainWindow::on_pushButtond_clicked() { double a; a = ui->lineEdit_a->text().toDouble(); double b; b = ui->lineEdit_b->text().toDouble(); double d = a / b; QString ddd; ddd.setNum(d); ui->lineEdit_s->setText(ddd); } void MainWindow::digits_numbers() { QPushButton *button = (QPushButton *)sender(); double all_numbers; QString new_label; all_numbers = (ui->result->text() + button->text()).toDouble(); new_label = QString::number(all_numbers, 'g', 15); ui->result->setText(new_label); } void MainWindow::on_pushButtondot_clicked() { if(!(ui->result->text().contains('.'))) ui->result->setText(ui->result->text() + "."); } void MainWindow::operations() { QPushButton *button = (QPushButton *)sender(); double all_numbers; QString new_label; if(button->text() == "+/-") { all_numbers = (ui->result->text()).toDouble(); all_numbers = all_numbers * -1; new_label = QString::number(all_numbers, 'g', 15); ui->result->setText(new_label); } } void MainWindow::math_operations() { QPushButton *button = (QPushButton *)sender(); num_first = ui->result->text().toDouble(); ui->result->setText(""); button->setChecked(true); } void MainWindow::on_pushButton_6_clicked() { double labelNumber, num_second; QString new_label; num_second = ui->result->text().toDouble(); if(ui->pushButton_pl->isChecked()) { labelNumber = num_first + num_second; new_label = QString::number(labelNumber, 'g', 15); ui->result->setText(new_label); ui->pushButton_pl->setChecked(false); } else if(ui->pushButton_min->isChecked()) { labelNumber = num_first - num_second; new_label = QString::number(labelNumber, 'g', 15); ui->result->setText(new_label); ui->pushButton_min->setChecked(false); } else if(ui->pushButton_umn->isChecked()) { labelNumber = num_first * num_second; new_label = QString::number(labelNumber, 'g', 15); ui->result->setText(new_label); ui->pushButton_umn->setChecked(false); } else if(ui->pushButton_del->isChecked()) { if (num_second == 0) { ui->result->setText("error"); } else { labelNumber = num_first / num_second; new_label = QString::number(labelNumber, 'g', 15); ui->result->setText(new_label); ui->pushButton_del->setChecked(false); } } else if(ui->pushButtonxn->isChecked()) { labelNumber = pow(num_first, num_second); new_label = QString::number(labelNumber, 'g', 15); ui->result->setText(new_label); ui->pushButtonxn->setChecked(false); } } void MainWindow::on_pushButtontg_clicked() { double all_numbers; QString res; all_numbers = (ui->result->text()).toDouble(); res = QString::number(tan(all_numbers)); ui->result->setText(res); } void MainWindow::on_pushButtonfac_clicked() { double all_numbers; QString resu; all_numbers = (ui->result->text()).toDouble(); int n = all_numbers; for (int i = 1; i < n; i++) { all_numbers = all_numbers * i; } resu = QString::number(all_numbers, 'g', 15); ui->result->setText(resu); } void MainWindow::on_pushButtonDB_clicked() { double all_numbers; QString rer; all_numbers = (ui->result->text()).toDouble(); rer = QString::number(10 * (log10(all_numbers))); ui->result->setText(rer); } void MainWindow::on_pushButton_2_clicked() { ui->pushButton_pl->setChecked(false); ui->pushButton_min->setChecked(false); ui->pushButton_umn->setChecked(false); ui->pushButton_del->setChecked(false); ui->result->setText("0"); }
// // PartyVideoDJ - YouTube crossfading app // Copyright (C) 2008-2017 Michael Fink // /// \file ControlBarForm.hpp Form for upper control bar // #pragma once #include <functional> class ControlBarForm : public CDialogImpl<ControlBarForm>, public CDialogResize<ControlBarForm>, public CWinDataExchange<ControlBarForm> { public: typedef std::function<void(const CString&)> T_fnOnSearchCallback; ControlBarForm() {} enum { IDD = IDD_CONTROLBAR_FORM }; BOOL PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN && pMsg->wParam == VK_RETURN && pMsg->hwnd == m_ecSearchText.m_hWnd) { if (m_fnOnSearchCallback != NULL) { CString cszText; int iLen = m_ecSearchText.GetWindowTextLength(); m_ecSearchText.GetWindowText(cszText.GetBuffer(iLen + 1), iLen + 1); cszText.ReleaseBuffer(); m_fnOnSearchCallback(cszText); } return TRUE; } return CWindow::IsDialogMessage(pMsg); } CString GetSearchText() const { UINT uiLen = m_ecSearchText.GetWindowTextLength(); CString cszText; m_ecSearchText.GetWindowText(cszText.GetBuffer(uiLen), uiLen); cszText.ReleaseBuffer(); return cszText; } bool IsButtonPlaylistPressed() const { return false; } void SetStartPauseButton(bool bPaused) { m_btnStartPause.SetWindowText(bPaused ? _T("&Play") : _T("&Pause")); } void SetPlaylistButton(bool bPressed) { m_btnPlaylist.SetCheck(bPressed ? BST_CHECKED : BST_UNCHECKED); } void SetSearchButton(bool bPressed) { m_btnSearch.SetCheck(bPressed ? BST_CHECKED : BST_UNCHECKED); } void SetSearchCallback(T_fnOnSearchCallback fnOnSearchCallback = T_fnOnSearchCallback()) { m_fnOnSearchCallback = fnOnSearchCallback; } private: BEGIN_DDX_MAP(ControlBarForm) DDX_CONTROL_HANDLE(IDC_BUTTON_START_PAUSE, m_btnStartPause) DDX_CONTROL_HANDLE(IDC_BUTTON_SEARCH, m_btnSearch) DDX_CONTROL_HANDLE(IDC_EDIT_SEARCH, m_ecSearchText) DDX_CONTROL_HANDLE(IDC_BUTTON_PLAYLIST, m_btnPlaylist) END_DDX_MAP() BEGIN_DLGRESIZE_MAP(ControlBarForm) DLGRESIZE_CONTROL(IDC_EDIT_SEARCH, DLSZ_SIZE_X) DLGRESIZE_CONTROL(IDC_BUTTON_PLAYLIST, DLSZ_MOVE_X) END_DLGRESIZE_MAP() friend CDialogResize<ControlBarForm>; BEGIN_MSG_MAP(ControlBarForm) MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog) if (uMsg == WM_COMMAND) // route command messages to parent ::SendMessage(GetParent(), uMsg, wParam, lParam); CHAIN_MSG_MAP(CDialogResize<ControlBarForm>) REFLECT_NOTIFICATIONS() END_MSG_MAP() // Handler prototypes (uncomment arguments if needed): // LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) // LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) // LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/) LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { // create font for buttons and edit control HFONT hFont = AtlGetDefaultGuiFont(); LOGFONT lf = { 0 }; ATLVERIFY(::GetObject(hFont, sizeof(LOGFONT), &lf) == sizeof(LOGFONT)); lf.lfWeight = FW_BOLD; lf.lfHeight = 28; m_hFontBig = ::CreateFontIndirect(&lf); DoDataExchange(DDX_LOAD); DlgResize_Init(false, false); CWindow(GetDlgItem(IDC_BUTTON_START_PAUSE)).SetFont(m_hFontBig); CWindow(GetDlgItem(IDC_BUTTON_NEXT)).SetFont(m_hFontBig); CWindow(GetDlgItem(IDC_BUTTON_SEARCH)).SetFont(m_hFontBig); CWindow(GetDlgItem(IDC_EDIT_SEARCH)).SetFont(m_hFontBig); CWindow(GetDlgItem(IDC_BUTTON_PLAYLIST)).SetFont(m_hFontBig); return 1; } private: T_fnOnSearchCallback m_fnOnSearchCallback; CButton m_btnStartPause; CButton m_btnSearch; CButton m_btnPlaylist; CEdit m_ecSearchText; CFontHandle m_hFontBig; };
// // GA-SDK-CPP // Copyright 2018 GameAnalytics C++ SDK. All rights reserved. // #pragma once #include <vector> #include <string> #include <map> #include <mutex> #include <functional> #include "Foundation/GASingleton.h" #include <json/json.h> #include "GameAnalytics.h" namespace gameanalytics { namespace state { // TODO(nikolaj): needed? remove.. if not // typedef void(*Callback) (); class GAState : public GASingleton<GAState> { public: GAState(); static void setUserId(const std::string& id); static const std::string getIdentifier(); static bool isInitialized(); static Json::Int64 getSessionStart(); static int getSessionNum(); static int getTransactionNum(); static const std::string getSessionId(); static const std::string getCurrentCustomDimension01(); static const std::string getCurrentCustomDimension02(); static const std::string getCurrentCustomDimension03(); static const std::string getGameKey(); static const std::string getGameSecret(); static void setAvailableCustomDimensions01(const std::vector<std::string>& dimensions); static void setAvailableCustomDimensions02(const std::vector<std::string>& dimensions); static void setAvailableCustomDimensions03(const std::vector<std::string>& dimensions); static void setAvailableResourceCurrencies(const std::vector<std::string>& availableResourceCurrencies); static void setAvailableResourceItemTypes(const std::vector<std::string>& availableResourceItemTypes); static void setBuild(const std::string& build); static bool isEnabled(); static void setCustomDimension01(const std::string& dimension); static void setCustomDimension02(const std::string& dimension); static void setCustomDimension03(const std::string& dimension); static void setFacebookId(const std::string& facebookId); static void setGender(EGAGender gender); static void setBirthYear(int birthYear); static void incrementSessionNum(); static void incrementTransactionNum(); static void incrementProgressionTries(const std::string& progression); static int getProgressionTries(const std::string& progression); static void clearProgressionTries(const std::string& progression); static bool hasAvailableCustomDimensions01(const std::string& dimension1); static bool hasAvailableCustomDimensions02(const std::string& dimension2); static bool hasAvailableCustomDimensions03(const std::string& dimension3); static bool hasAvailableResourceCurrency(const std::string& currency); static bool hasAvailableResourceItemType(const std::string& itemType); static void setKeys(const std::string& gameKey, const std::string& gameSecret); static void endSessionAndStopQueue(bool endThread); static void resumeSessionAndStartQueue(); static Json::Value getEventAnnotations(); static Json::Value getSdkErrorEventAnnotations(); static Json::Value getInitAnnotations(); static void internalInitialize(); static Json::Int64 getClientTsAdjusted(); static void setManualSessionHandling(bool flag); static bool useManualSessionHandling(); static void setEnableErrorReporting(bool flag); static bool useErrorReporting(); static void setEnabledEventSubmission(bool flag); static bool isEventSubmissionEnabled(); static bool sessionIsStarted(); static const Json::Value validateAndCleanCustomFields(const Json::Value& fields); static std::string getConfigurationStringValue(const std::string& key, const std::string& defaultValue); static bool isCommandCenterReady(); static void addCommandCenterListener(const std::shared_ptr<ICommandCenterListener>& listener); static void removeCommandCenterListener(const std::shared_ptr<ICommandCenterListener>& listener); static std::string getConfigurationsContentAsString(); private: static void setDefaultUserId(const std::string& id); static Json::Value getSdkConfig(); static void cacheIdentifier(); static void ensurePersistedStates(); static void startNewSession(); static void validateAndFixCurrentDimensions(); static const std::string getBuild(); static const std::string getFacebookId(); static const std::string getGender(); static int getBirthYear(); static Json::Int64 calculateServerTimeOffset(Json::Int64 serverTs); static void populateConfigurations(Json::Value sdkConfig); std::string _userId; std::string _identifier; bool _initialized = false; Json::Int64 _sessionStart = 0; int _sessionNum = 0; int _transactionNum = 0; std::string _sessionId; std::string _currentCustomDimension01; std::string _currentCustomDimension02; std::string _currentCustomDimension03; std::string _gameKey; std::string _gameSecret; std::vector<std::string> _availableCustomDimensions01; std::vector<std::string> _availableCustomDimensions02; std::vector<std::string> _availableCustomDimensions03; std::vector<std::string> _availableResourceCurrencies; std::vector<std::string> _availableResourceItemTypes; std::string _build; std::string _facebookId; std::string _gender; int _birthYear = 0; bool _initAuthorized = false; Json::Int64 _clientServerTimeOffset = 0; std::string _defaultUserId; std::map<std::string, int> _progressionTries; Json::Value _sdkConfigDefault; Json::Value _sdkConfig; Json::Value _sdkConfigCached; static const std::string CategorySdkError; bool _useManualSessionHandling = false; bool _enableErrorReporting = true; bool _enableEventSubmission = true; Json::Value _configurations; bool _commandCenterIsReady; std::vector<std::shared_ptr<ICommandCenterListener>> _commandCenterListeners; std::mutex _mtx; }; } }
#ifndef NOMA_TEST_SCREEN_HPP_ #define NOMA_TEST_SCREEN_HPP_ #include "Screen.hpp" namespace noma { class TestScreen : public Screen { public: TestScreen() {} virtual ~TestScreen() {} virtual void initialize() override {} virtual void update(double dt) override {} virtual void render() override {} private: }; } #endif // !NOMA_TEST_SCREEN_HPP_
#include"util.h" using namespace std; float *Initialize(int size, int seed) { default_random_engine e; uniform_real_distribution<float> distribution(0.0,10000000.0); e.seed(seed); float *data = (float*)malloc(sizeof(float) * size); for (int i = 0; i < size; ++i){ *(data + i) = distribution(e); } return data; }
#ifndef _HS_SFM_SFM_FILE_IO_EXTRINSIC_PARAMS_SET_LOADER_HPP_ #define _HS_SFM_SFM_FILE_IO_EXTRINSIC_PARAMS_SET_LOADER_HPP_ #include <string> #include <fstream> #include "hs_sfm/sfm_utility/camera_type.hpp" namespace hs { namespace sfm { namespace fileio { template <typename _Scalar> struct ExtrinsicParamsSetLoader { typedef _Scalar Scalar; typedef int Err; typedef hs::sfm::CameraExtrinsicParams<Scalar> ExtrinsicParams; typedef EIGEN_STD_VECTOR(ExtrinsicParams) ExtrinsicParamsContainer; Err operator() (const std::string& extrinsic_set_path, ExtrinsicParamsContainer& extrinsic_params_set) const { std::ifstream extrinsic_set_file(extrinsic_set_path.c_str(), std::ios::in); if (!extrinsic_set_file.is_open()) { return -1; } size_t number_of_cameras; extrinsic_set_file>>number_of_cameras; extrinsic_params_set.resize(number_of_cameras); for (size_t i = 0; i < number_of_cameras; i++) { extrinsic_set_file>>extrinsic_params_set[i].rotation()[0] >>extrinsic_params_set[i].rotation()[1] >>extrinsic_params_set[i].rotation()[2] >>extrinsic_params_set[i].position()[0] >>extrinsic_params_set[i].position()[1] >>extrinsic_params_set[i].position()[2]; } return 0; } }; } } } #endif
#include <iostream> using namespace std; int main() { float N; cin >> N; float r = N / (3.14 * 2); float S = r * r * 3.14; cout << S; }
#ifndef _AMBIENTE_MOCHILA #define _AMBIENTE_MOCHILA #include "Ambiente.h" #include "Poblacion.h" #include "CriaturaMochila.h" #include <fstream> class AmbienteMochila: public Ambiente { friend class CriaturaMochila; private: ifstream lector; int cantidadPiedras; double pesoMochila; double *vectorPrecio; double *vectorPeso; double precioTotal; double pesoMaximo; public: void leerTxtAmbiente(); AmbienteMochila(); ~AmbienteMochila(); double evaluar(Criatura *); Poblacion * crearPoblacionInicial(); }; #endif
//************************************************************************** //** //** See jlquake.txt for copyright info. //** //** 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 //** included (gnu.txt) GNU General Public License for more details. //** //************************************************************************** #ifndef __idSurfaceDecal__ #define __idSurfaceDecal__ #include "Surface.h" #include "public.h" #define MAX_DECAL_VERTS 10 // worst case is triangle clipped by 6 planes struct srfDecal_t { int numVerts; polyVert_t verts[ MAX_DECAL_VERTS ]; }; class idSurfaceDecal : public idSurface { public: srfDecal_t surf; idSurfaceDecal(); virtual void Draw(); }; #endif
#include <algorithm> #include <array> #include <cstdio> #include <iostream> #include <iterator> #include <map> #include <math.h> #include <queue> #include <set> #include <stack> #include <vector> #define ll long long using namespace std; typedef tuple<ll, ll, ll> tp; typedef pair<ll, ll> pr; const ll MOD = 1000000007; const ll INF = 1e18; template <typename T> void print(const T &t) { std::copy(t.cbegin(), t.cend(), std::ostream_iterator<typename T::value_type>(std::cout, " ")); cout << endl; } template <typename T> void print2d(const T &t) { std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>); } void setIO(string s) { // the argument is the filename without the extension freopen((s + ".in").c_str(), "r", stdin); freopen((s + ".out").c_str(), "w", stdout); } int main() { cin.tie(0)->sync_with_stdio(0); cin.exceptions(cin.failbit); setIO("pails"); ll x, y, m; cin >> x >> y >> m; ll res = 0; for (ll i = 0; i <= m / x; i++) { for (ll j = 0; j <= m / y; j++) { if ((x * i + y * j) <= m) { res = max(x * i + y * j, res); } } } cout << res << endl; }
#ifndef CONFIG_H_ #define CONFIG_H_ #include <map> #include <string> #include <sstream> #include <initializer_list> namespace revel { class Config { static std::map<std::string, std::string> s_ConfigMap; private: static std::map<std::string, std::string> init() { std::map<std::string, std::string> configmap; configmap["graphics_api"] = "OpenGL"; configmap["screen_width"] = "1280"; configmap["screen_height"] = "720"; return configmap; } public: template <typename T> static T get(const std::string& name) { T result; std::stringstream ss; ss << s_ConfigMap[name]; ss >> result; return result; } template <typename T> static void set(const std::string& name, T value) { std::stringstream ss; ss << value; s_ConfigMap[name] = ss.str(); } }; } /* namespace revel */ #endif /* CONFIG_H_ */
#include <bits/stdc++.h> using namespace std; int main() { double S = 0, A = 1; for (double i = 1; i < 40; i += 2) { S += i / A; A *= 2; } printf("%.2lf\n", S); return 0; }
#include <iostream> #include <timing/chrono.h> #include "Curve.h" #include "ticks.h" using namespace std; Curve::Curve(string name_, Rhoban::chrono *start_) : name(name_), start(start_), count(0) { values = new deque<CurveEntry*>(); } Curve::~Curve() { delete values; } void Curve::push(double value) { CurveEntry *entry = new CurveEntry(value, elapsed()); values->push_back(entry); } double Curve::elapsed() { Rhoban::chrono n; gettimeofday(&n, NULL); decrease(n, *start); return to_secs(n); } vector<pair<double, double> > Curve::getValues(double time) { vector<pair<double, double> > vals; double nowTime = elapsed(); count++; if (count%CURVE_GC) { garbageCollect(CURVE_EXPIRATION); } for (deque<CurveEntry*>::reverse_iterator it = values->rbegin(); it != values->rend(); it++) { CurveEntry *entry = (*it); if (nowTime-entry->time > time) { break; } else { pair<double, double> p(entry->time, entry->value); vals.push_back(p); } } return vals; } void Curve::garbageCollect(double expiration) { double nowTime = elapsed(); for (deque<CurveEntry*>::iterator it = values->begin(); it != values->end(); it++) { CurveEntry *entry = (*it); if (nowTime - entry->time < expiration) { if (it != values->begin()) { values->erase(values->begin(), it); } break; } } }
// AUTHOR: Sumit Prajapati #include <bits/stdc++.h> using namespace std; #define ull unsigned long long #define ll long long #define pii pair<int, int> #define pll pair<ll, ll> #define pb push_back #define mk make_pair #define ff first #define ss second #define all(a) a.begin(),a.end() #define trav(x,v) for(auto &x:v) #define debug(x) cerr<<#x<<" = "<<x<<'\n' #define llrand() distribution(generator) #define rep(i,n) for(int i=0;i<n;i++) #define repe(i,n) for(int i=1;i<=n;i++) #define FOR(i,a,b) for(int i=a;i<=b;i++) #define printar(a,s,e) FOR(i,s,e)cout<<a[i]<<" ";cout<<'\n' #define endl '\n' #define curtime chrono::high_resolution_clock::now() #define timedif(start,end) chrono::duration_cast<chrono::nanoseconds>(end - start).count() #define INF 1'000'000'000 #define MD 1'000'000'007 #define MDL 998244353 #define MX 200'005 auto time0 = curtime; random_device rd; default_random_engine generator(rd()); uniform_int_distribution<ull> distribution(0,0xFFFFFFFFFFFFFFFF); //Is testcase present? int n; int L[4*MX]; int R[4*MX]; vector<int>to_compress; map<int,int>mp; struct{ char ty; int l; int r; }Q[MX]; int query(int cur,int start,int end,int qs,int qe,bool isL){ if(start>=qs && end<=qe) return isL?L[cur]:R[cur]; if(start>qe || end<qs) return 0; //INVALID RETURN int mid=(start+end)>>1; int A=query(2*cur,start,mid,qs,qe,isL); int B=query(2*cur+1,mid+1,end,qs,qe,isL); //MERGING STEP int res=A+B; return res; } void update(int cur,int start,int end,int ind,int val,bool isL){ if(start==ind && start==end){ //DO UPDATE if(isL) L[cur]+=val; else R[cur]+=val; return; } if(start>ind|| end<ind) return; //OUT OF RANGE int mid=(start+end)>>1; update(cur<<1,start,mid,ind,val,isL); update((cur<<1)^1,mid+1,end,ind,val,isL); //MERGING STEP if(isL) L[cur]=L[2*cur]+L[2*cur+1]; else R[cur]=R[2*cur]+R[2*cur+1]; } void solve(){ cin>>n; repe(i,n){ cin>>Q[i].ty>>Q[i].l; if(Q[i].ty!='C'){ cin>>Q[i].r; to_compress.pb(Q[i].l); to_compress.pb(Q[i].r); } } int cnt=1; int total_lines=0; sort(all(to_compress)); for(auto &el:to_compress) if(mp[el]==0) mp[el]=cnt++; repe(i,n){ if(Q[i].ty!='C'){ Q[i].l=mp[Q[i].l]; Q[i].r=mp[Q[i].r]; } } int nax=cnt; assert(nax<MX); // update(1,1,nax,1,1,1); // update(1,1,nax,3,1,0); // cout<<query(1,1,nax,1,4,0)<<'\n'; // cout<<query(1,1,nax,2,5,1)<<'\n'; // return; vector<int>indx; indx.pb(0); repe(i,n){ // cerr<<Q[i].ty<<" "<<Q[i].l<<" "<<Q[i].r<<'\n'; if(Q[i].ty=='C'){ update(1,1,nax,Q[indx[Q[i].l]].l,-1,1); update(1,1,nax,Q[indx[Q[i].l]].r,-1,0); total_lines--; } else if(Q[i].ty=='D'){ total_lines++; indx.pb(i); update(1,1,nax,Q[i].l,1,1); update(1,1,nax,Q[i].r,1,0); } else{ int res=total_lines-query(1,1,nax,1,Q[i].l-1,0)-query(1,1,nax,Q[i].r+1,nax,1); cout<<res<<'\n'; } } } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); time0 = curtime; int t=1; // cin>>t; repe(tt,t){ //cout<<"Case #"<<tt<<": "; solve(); } // cerr<<"Execution Time: "<<(double)timedif(time0,curtime)*1e-9<<" sec\n"; return 0; }
#include "ClasseB.h" ClasseB::ClasseB() { } ClasseB::~ClasseB() { }
/* * SPDX-FileCopyrightText: (C) 2014 Daniel Nicoletti <dantti12@gmail.com> * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ROOT_H #define ROOT_H #include <Cutelyst/Controller> using namespace Cutelyst; class Root : public Controller { Q_OBJECT C_NAMESPACE("") public: Root(QObject *app); ~Root(); C_ATTR(index, : Path) void index(Context *c); Q_SIGNALS: void indexCalled(Cutelyst::Context *c); }; #endif // ROOT_H
#ifndef _OPTION_H_ #define _OPTION_H_ #include "payoff.h" #include "marketvariable.h" #include "derivatives.h" #include <vector> enum OptionType { Call = 1, Put = -1 }; /* Barrier feature : In, Out */ enum BarrierFeature { UI, UO, DI, DO }; class Option: public Derivative { public: Option() {}; Option(double strike, double maturity, OptionType type); ~Option(); /* Get the closest value below and above of input value from the tree */ double getLambda(double value, unsigned int steps, unsigned int node, BinomialType bntType); /* Set function */ void setSpot(double s); void setRate(double r); void setMaturity(double t); virtual double bntprice(unsigned int steps, BinomialType bntType) = 0; protected: /* Strike */ double strike_; /* Option Characteristic */ OptionType type_; /* Internal functions */ double getd1(); double getd2(); double h(double x, double n); virtual std::vector<double> makeTree(unsigned int steps, BinomialType bntType); /* Swap function */ void Swap(Option* lhs, Option* rhs); }; #endif
/************************************************************************* > File Name : CmePermissions.cpp > Author : YangShuai > Created Time: 2016年08月12日 星期五 16时31分35秒 > Description : ************************************************************************/ #include"Primitive.h" int32 Cme_Permissions::len(){ switch(type){ case PM_ITS_AID: return u.its_aid_vec.size(); case PM_ITS_AID_SSP: return u.its_aid_ssp_vec.size(); default: return 0; } }
#include <Adafruit_MotorShield.h> #include <Wire.h> #include "utility/Adafruit_MS_PWMServoDriver.h" #include <Servo.h> #define PHOTO_GATE 7 Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_StepperMotor *foodPodMotor = AFMS.getStepper(200,2); Servo foodPodServo; int8_t currentFoodPodPosition = -1; String rxString = ""; char rxByte = 0; int rxInt = 0; void setup() { Serial.begin(9600); AFMS.begin(); Wire.begin(0x7F); pinMode(2, OUTPUT); foodPodMotor->setSpeed(10); foodPodServo.attach(9); } void loop() { while(Serial.available()){ rxByte = Serial.read(); if(rxByte != '\n'){ rxString += rxByte; //Serial.println(rxByte); //Serial.println(rxString); }else{ rxInt = rxString.toInt(); if(rxInt > 12 || (rxInt < 0)){ Serial.println("Invalid input!"); }else{ Serial.print("Moving to pod: "); Serial.println(rxString); TurnToFoodPod(rxInt); } rxString = ""; } } } void TurnToFoodPod(int foodPod){ CloseFoodPod(); float degreesBetweenPods = 0; float degreesToTurn = 0; int tempCurrentPos; if(currentFoodPodPosition == -1){ if(!(FindPosZero())){ Serial.println("*************ERROR!***********"); Serial.println("Zero position not found!!"); Serial.println("Not able to continue operation"); } } delay(750); tempCurrentPos = currentFoodPodPosition*30; foodPod *= 30; degreesBetweenPods = abs(foodPod-tempCurrentPos); degreesToTurn = abs(foodPod-tempCurrentPos)*0.9; while(degreesToTurn < degreesBetweenPods){ degreesToTurn += 0.9; } if(degreesToTurn > degreesBetweenPods){ degreesToTurn -= 0.9; } if((foodPod-tempCurrentPos)>0){ foodPodMotor->step((degreesToTurn/0.9), FORWARD, INTERLEAVE); }else{ foodPodMotor->step((degreesToTurn/0.9), BACKWARD, INTERLEAVE); } currentFoodPodPosition = foodPod/30; OpenFoodPod(); delay(3000); CloseFoodPod(); } int FindPosZero(){ if(!digitalRead(PHOTO_GATE)){ currentFoodPodPosition = 1; return(1); } int turnCount = 0; while(digitalRead(PHOTO_GATE)){ foodPodMotor->step(1, FORWARD, INTERLEAVE); turnCount++; if(turnCount > 400){ return(0); } } currentFoodPodPosition = 1; foodPodMotor->step(10, FORWARD, INTERLEAVE); return(1); } void OpenFoodPod(){ foodPodServo.write(135); } void CloseFoodPod(){ foodPodServo.write(90); }
/* NO WARRANTY * * BECAUSE THE PROGRAM IS IN THE PUBLIC DOMAIN, THERE IS NO * WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE * LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE AUTHORS * AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT * WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO * THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD * THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL * NECESSARY SERVICING, REPAIR OR CORRECTION. * * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN * WRITING WILL ANY AUTHOR, OR ANY OTHER PARTY WHO MAY MODIFY * AND/OR REDISTRIBUTE THE PROGRAM, BE LIABLE TO YOU FOR DAMAGES, * INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL * DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM * (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES * OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER * PROGRAMS), EVEN IF SUCH AUTHOR OR OTHER PARTY HAS BEEN ADVISED * OF THE POSSIBILITY OF SUCH DAMAGES. */ #pragma warning(disable : 4786) #include "math.h" #include "stdafx.h" #include "Application\Objects\buildin\digital\ElectricNode.h" #include "Application\Dialogs\ObjectDialogs\DialogDemultiplexerParam.h" #include "Application\Debug\LogManager.h" #include "ElectricNodeContextDemultiplexer.h" IMPLEMENT_REGISTER(CElectricNodeContextDemultiplexer); //---------------------------------------------------------------------------- CElectricNodeContextDemultiplexer::CElectricNodeContextDemultiplexer(){ //---------------------------------------------------------------------------- PROC_TRACE; } //---------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::AdjustInputOutputCount(int &inCount, int &outCount){ //---------------------------------------------------------------------------- PROC_TRACE; // Ein demultiplexer hat einen Eingang und mehrere Addressleitungen // Die Anzahl der Ausgänge wird durch die Anzahl der Addressleitungen // bestimmt // outCount = (int)pow(2,inCount-1); } //----------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::LayoutInput(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; CPoint topLeft = data.icons[0]->GetBoundingRect().TopLeft(); CPoint bottomRight= data.icons[0]->GetBoundingRect().BottomRight(); float xOffset = data.icons[0]->GetBoundingRect().Width() / (float)(data.param[addressCount]+1); // Eingang plazieren // long xPos = topLeft.x; long yPos = topLeft.y+ data.icons[0]->GetBoundingRect().Height()/2; data.inPorts[0]->SetSpotLocation(DragDropObject::spotRightCenter,xPos,yPos); // Adresspunkte plazieren // for(int loop=0 ;loop < data.param[addressCount]; loop++) { yPos = bottomRight.y - (xOffset*(loop)); xPos = (int)(topLeft.x+(xOffset*(loop+1))); assert((loop+1) < data.inPorts.GetSize() ); data.inPorts[1+loop]->SetSpotLocation(DragDropObject::spotTopCenter,xPos,yPos); } } //----------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::SetInputCount( CElectricNode::CElectricNodeDokument& data, long count){ //----------------------------------------------------------------------------- PROC_TRACE; data.param[addressCount] = count-1; data.inCount= count; } //----------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::SetOutputCount(CElectricNode::CElectricNodeDokument& data, long count){ //----------------------------------------------------------------------------- PROC_TRACE; if(count ==2){ data.param[addressCount] = 1; } else if(count ==4){ data.param[addressCount] = 2; } else if(count ==8){ data.param[addressCount] = 3; } else if(count ==16){ data.param[addressCount] = 4; } else assert(FALSE); data.param[outputCount] = count; data.outCount= count; } //----------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::DoCalculate(CElectricNode::CElectricNodeDokument& data){ //----------------------------------------------------------------------------- PROC_TRACE; int address = 0; long loop =0; // Adresse ermitteln // for (loop =1; loop<data.param[addressCount]+1; loop++) { if(data.inPorts[loop]->IsHigh()){ address += pow(2,loop-1); } } assert(address < data.param[outputCount]); assert(address >= 0); for( loop=0 ;loop <data.outPorts.GetSize() ; loop++) { if(address==loop) data.outPorts[loop]->SetValue(data.inPorts[0]->GetValue()); else data.outPorts[loop]->SetValue(CLogicValue::Low); } } //---------------------------------------------------------------------------- void CElectricNodeContextDemultiplexer::onOption(CElectricNode::CElectricNodeDokument& data){ //---------------------------------------------------------------------------- PROC_TRACE; CDialogDemultiplexerParam d(NULL,data); if(d.DoModal()==IDOK){ data.param[addressCount] = d.m_addressCount; data.param[outputCount] = d.m_outputCount ; Initialize(data); } }
#include<stdio.h> #include "myLog.h" int main() { LOGINIT(); for (int i = 0; i < 1000; i++) { LOGE("%f .....%d ", 12563.0 * i, i); } LOGEnd(); getchar(); return 0; }
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <vector> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget* parent = 0); ~MainWindow(); void initializeGraph(); void nextColor(); private slots: void on_btnRandomGraph_clicked(); void on_btnGraphEntropy_clicked(); void on_btnClear_clicked(); void on_sliderBlockSize_sliderMoved(int position); void on_sliderPointCount_sliderMoved(int position); private: Ui::MainWindow* ui; bool _initialized; }; #endif // MAINWINDOW_H
/* * Timer0.cpp * * Created: 26.06.2015 10:03:45 * Author: User */ #include "Timer0.h" // default constructor Timer0::Timer0(prsk p) { div=p; } //Timer0 void Timer0::Start () { TCCR0 &= ~(0x07); TCCR0 |= div; } void Timer0::Stop () { TCCR0 &= ~(0x07); } void Timer0::Set_Tcnt (unsigned char val) { TCNT0 = val; } void Timer0::interpt (intr i) { TIMSK &= ~ (1 << TOIE0); TIMSK |= i << TOIE0; sei(); }
class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> temp_map; vector<int> result; unordered_map<int, int>::iterator hit; int index = 0; int temp = 0; if(nums.size() < 2) { return result; } for(vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++) { temp_map.insert(make_pair(*iter, index)); index++; } index = 0; for(vector<int>::iterator iter = nums.begin(); iter != nums.end(); iter++) { temp = target - *iter; hit = temp_map.find(temp); if(hit != temp_map.end()) { if(index != hit->second) { if(index < hit->second) { result.push_back(index); result.push_back(hit->second); } else { result.push_back(hit->second); result.push_back(index); } return result; } } index++; } return result; } };
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n, k, m; cin >> n >> k; m = n%(2*k); ll ans = 0LL; if(2*k > n){ ans = 10; } else { ans += 5*(((n-m)/(2*k)) + ((n-m)%(2*k) != 0)); n -= ((2*k)-m); ans += 5; ans += 5*((n/(2*k)) + ((n%(2*k)) != 0)); } cout << ans << endl; }
/* * Copyright (c) 2009-2012 André Tupinambá (andrelrt@gmail.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ //----------------------------------------------------------------------------- #ifndef _DCL_REMOTE_PLATFORM_H_ #define _DCL_REMOTE_PLATFORM_H_ #if (defined _MSC_VER) && (_MSC_VER >= 1200) #pragma once #endif #include <vector> #include "distributedcl_internal.h" #include "library_exception.h" #include "remote_object.h" #include "info/object_manager.h" #include "info/dcl_objects.h" #include "info/platform_info.h" #include "info/context_info.h" //----------------------------------------------------------------------------- namespace dcl { namespace remote { //----------------------------------------------------------------------------- class remote_device; //----------------------------------------------------------------------------- class remote_platform : public dcl::info::generic_platform, public remote_object< remote_platform, dcl::network::message::msg_dummy_message > { public: remote_platform( dcl::network::client::session_manager::session_t& session_ref ) : remote_object< remote_platform, dcl::network::message::msg_dummy_message >( session_ref ) { load_devices(); } ~remote_platform(){} dcl::info::generic_context* create_context( const dcl::devices_t& devices ) const; dcl::info::generic_context* create_context( cl_device_type device_type = CL_DEVICE_TYPE_ALL ) const; private: void load_devices(); dcl::info::object_manager< remote_device > device_manager_; }; //----------------------------------------------------------------------------- }} // namespace dcl::remote //----------------------------------------------------------------------------- #endif // _DCL_REMOTE_PLATFORM_H_
#pragma once #include "DataBase.h" namespace Admin = ECommerce::Admin; void Admin::Menu(App::DataBase* const& database) { std::string user_name{}; std::string password{}; std::cout << "User Name: "; getline(std::cin, user_name); std::cout << "Password: "; getline(std::cin, password); bool is_here = false; for (int i = 0; i < database->Get_database_admins()->Get_item_count(); i++) { if (database->Get_database_admins()->At(i)->Get_user_name() == user_name && database->Get_database_admins()->At(i)->Get_password() == password) { is_here = true; break; } } if (!is_here) throw DatabaseException("User Name or password didn't Exist", 28, "Source.cpp"); short choice{}; while (true) { std::cout << "1)Show All Product Info\n2)Add Product\n3)Delete Product\n4)Show Notification\n5)Exit\nEnter: "; std::cin >> choice; is_here = false; if (choice < 0 || choice > 5) throw InvalidArgumentException("Choice must be between 0 and 5!", 38, "Admin_Menu.h"); if (choice == 1) { database->Show_all_product(); } else if (choice == 2) { std::cin.ignore(1, '\n'); std::string name; std::cout << "Name: "; getline(std::cin, name); int amount{}; for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++) { if (database->Get_database_products()->At(i)->Get_product()->Get_name() == name) { is_here = true; std::cout << "Product is in the Database, how many Amounts do you want to add: "; std::cin >> amount; database->Get_database_products()->At(i)->Set_amount(database->Get_database_products()->At(i)->Get_amount() + amount); break; } } if (!is_here) { std::string description; std::cout << "Description: "; getline(std::cin, description); double price; std::cout << "Price: "; std::cin >> price; double discount; std::cout << "Discount: "; std::cin >> discount; double tax; std::cout << "Tax: "; std::cin >> tax; std::cout << "Amount: "; std::cin >> amount; App::Product* product = new App::Product(name, description, price, discount, tax); App::ProductItem* product_item = new App::ProductItem(product, amount); database->Get_database_products()->Add(product_item); } } else if (choice == 3) { std::cout << "DataBase has this IDs\n\n"; for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++) { std::cout << "ID = " << database->Get_database_products()->At(i)->Get_product()->Get_id() << '\n'; } int id{}; std::cout << "Enter Product ID which you want to delete: "; std::cin >> id; for (int i = 0; i < database->Get_database_products()->Get_item_count(); i++) { if (id == database->Get_database_products()->At(i)->Get_product()->Get_id()) { is_here = true; break; } } if (is_here) database->Get_database_products()->Delete_by_id(id); else std::cout << "There is no ID " << id << " product in DataBase\n\n"; } else if (choice == 4) database->Show_all_notification(); else return; } }
#include "stringutil.h" #include <CORE/BASE/checks.h> #include <algorithm> /** * Identifiers for {@link core::util::prettySize} */ static const char *g_sizePostfix[] = {" B", " KiB", " MiB", " GiB", " TiB", " PiB", " EiB", " ZiB", " YiB", " ERROR"}; namespace core { namespace util { /** * */ std::vector< std::string > Splitter::split(const std::string &item, const unsigned maxLen) { std::vector< std::string > rVal; std::string::size_type offset = 0; std::string::size_type itr; do { if (rVal.size() + 1 < maxLen) { itr = item.find_first_of(m_ch, offset); } else { itr = item.npos; } if (m_trim) { rVal.push_back(TrimWhitespace(item.substr(offset, itr - offset))); } else { rVal.push_back(item.substr(offset, itr - offset)); } offset = itr + 1; } while (itr != item.npos); return rVal; } /** * */ std::string TrimWhitespace(const std::string &v) { if (v.empty()) { return v; } std::string::size_type beg = 0; std::string::size_type end = v.length(); while ((v.at(beg) == ' ' || v.at(beg) == '\t') && beg < end) { beg++; } while (v.at(end - 1) == ' ' && end >= beg) { end--; } if (end > beg) { return v.substr(beg, end - beg); } return ""; } /** * */ std::string TrimQuotes(const std::string &v) { if (v.empty()) { return v; } std::string::size_type beg = 0; std::string::size_type end = v.length(); if (v.at(0) == '\"') { beg++; } if (v.at(end - 1) == '\"') { end--; } if (end > beg) { return v.substr(beg, end - beg); } return ""; } /** * */ std::string Unescape(const std::string &str) { std::string rVal; rVal.reserve(str.size()); std::string::const_iterator itr = str.begin(); while (itr != str.end()) { if (*itr == '\\') { ++itr; if (itr == str.end()) { break; } switch (*itr) { case 'n': rVal.push_back('\n'); break; case 'r': rVal.push_back('\r'); break; case 't': rVal.push_back('\t'); break; case '"': rVal.push_back('\"'); break; case '\\': rVal.push_back('\\'); break; default: if (isdigit(*itr) && isdigit(*(itr + 1)) && isdigit(*(itr + 2))) { const int d1 = *(itr++) - '0'; if (itr == str.end()) { break; } const int d2 = *(itr++) - '0'; if (itr == str.end()) { break; } const int d3 = *itr - '0'; const char ch = d1 * 100 + d2 * 10 + d3; rVal.push_back(ch); } else { rVal.push_back('\\'); rVal.push_back(*itr); } break; } } else { rVal.push_back(*itr); } ++itr; } return rVal; } /** * */ std::string Escape(const std::string &str) { std::string rVal; rVal.reserve(str.size()); std::string::const_iterator itr = str.begin(); while (itr != str.end()) { switch (*itr) { case '\n': rVal.push_back('\\'); rVal.push_back('n'); break; case '\r': rVal.push_back('\\'); rVal.push_back('r'); break; case '\t': rVal.push_back('\\'); rVal.push_back('t'); break; case '\"': rVal.push_back('\\'); rVal.push_back('\"'); break; case '\\': rVal.push_back('\\'); rVal.push_back('\\'); break; default: if (isprint(*itr)) { rVal.push_back(*itr); } else { rVal.push_back('\\'); char buf[4] = {}; const unsigned int v = static_cast< unsigned char >(*itr); sprintf(buf, "%03d", v); rVal.append(buf); } break; } ++itr; } return rVal; } /** * */ std::string ReplaceStr( const std::string &input, const std::string &match, const std::string &replacement) { std::string rVal; // reserve the correct space { int count = 0; std::string::size_type itr = 0; while ((itr = input.find(match, itr)) != input.npos) { ++itr; ++count; } size_t delta = replacement.size() - match.size(); rVal.reserve(input.size() + delta * count + 1); } // Replace all instances std::string::size_type begin = 0; while (begin < input.length()) { std::string::size_type end = input.find(match, begin); if (end == input.npos) { rVal.append(input.substr(begin, end - begin)); begin = end; } else { rVal.append(input.substr(begin, end - begin)); rVal.append(replacement); begin = end + match.length(); } } return rVal; } /** * */ std::string IdentifierSafe(const std::string &input) { if (input.length() == 0) { return input; } std::string rVal; rVal.reserve(input.size()); std::string::const_iterator itr = input.begin(); if (!(*itr >= 'a' && *itr <= 'z') && !(*itr >= 'A' && *itr <= 'Z')) { rVal.push_back('_'); ++itr; } for (; itr != input.end(); ++itr) { if (!(*itr >= 'a' && *itr <= 'z') && !(*itr >= 'A' && *itr <= 'Z') && !(*itr >= '0' && *itr <= '9')) { rVal.push_back('_'); } else { rVal.push_back(*itr); } } return rVal; } /** * */ std::string PrettySize(const u64 v) { u64 nv = v; unsigned idx = 0; while (nv >= 1024ull && ((idx + 1) < ARRAY_LENGTH(g_sizePostfix))) { nv /= 1024; idx++; } std::stringstream formatter; formatter << nv; formatter << g_sizePostfix[idx]; return formatter.str(); } /** * */ size_t CountLines( const std::string::const_iterator &begin, const std::string::const_iterator &end) { return std::count(begin, end, '\n'); } } // namespace util } // namespace core
#pragma once #include <landstalker-lib/patches/game_patch.hpp> #include <landstalker-lib/constants/offsets.hpp> #include <landstalker-lib/constants/item_codes.hpp> #include "../../logic_model/hint_source.hpp" #include "../../logic_model/randomizer_world.hpp" class PatchSpellBookTeleportOnUse : public GamePatch { private: bool _consumable_spell_book = false; public: explicit PatchSpellBookTeleportOnUse(bool consumable_spell_book) : _consumable_spell_book(consumable_spell_book) {} void inject_code(md::ROM& rom, World& world) override { // Replace "consume Spell Book" by a return indicating success and signaling there is a post-use effect // to handle. md::Code func_pre_use; if(_consumable_spell_book) { func_pre_use.moveb(reg_D0, addr_(0xFF1152)); func_pre_use.jsr(0x8B98); // ConsumeItem } func_pre_use.jmp(offsets::PROC_ITEM_USE_RETURN_SUCCESS_HAS_POST_USE); uint32_t func_pre_use_addr = rom.inject_code(func_pre_use); world.item(ITEM_SPELL_BOOK)->pre_use_address(func_pre_use_addr); uint32_t func_warp_to_start = inject_func_warp_to_start(rom, world); world.item(ITEM_SPELL_BOOK)->post_use_address(func_warp_to_start); } private: static uint32_t inject_func_warp_to_start(md::ROM& rom, const World& world) { uint16_t spawn_x = world.spawn_position_x(); uint16_t spawn_y = world.spawn_position_y(); uint16_t spawn_position = (spawn_x << 8) + spawn_y; uint16_t spawn_map_id = world.spawn_map_id(); md::Code func; func.movem_to_stack({ reg_D0_D7 }, { reg_A0_A6 }); { func.movew(spawn_position, addr_(0xFF5400)); func.movew(0x0708, addr_(0xFF5402)); // Reset subtiles position func.trap(0, { 0x00, 0x4D }); func.jsr(0x44C); // sub_44C --> warp special effect? func.movew(spawn_map_id, reg_D0); // Set MapID to spawn map func.movew(0x0000, addr_(0xFF5412)); // Reset player height func.moveb(0x00, addr_(0xFF5422)); // Reset ground height func.moveb(0x00, addr_(0xFF5439)); // ^ func.jsr(0x1586E); // SetRoomNumber func.jsr(0x434); // sub_434 func.clrb(reg_D0); func.jsr(0x2824); // LoadRoom_0 func.jsr(0x410); // sub_410 func.jsr(0x8EB4); // FadeInFromDarkness } func.movem_from_stack({ reg_D0_D7 }, { reg_A0_A6 }); func.rts(); return rom.inject_code(func); } };
#include <cstdio> #include <iostream> #include <set> #include <iostream> #include <cstdlib> #include <ctime> #include <map> #include "llvm/IR/Function.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Support/SourceMgr.h" using namespace llvm; using namespace std; void traverse(BasicBlock *BB, set<Instruction *> entrySet); set<Instruction *> generate(BasicBlock *bb); set<Instruction *> combine(set<Instruction *> entry, set<Instruction *> generate, set<Instruction *> previous); void print(const Value *bb); void print(const map<string, set<Instruction *>> analysisMap); string label(const Value *Node); map<string, set<Instruction *>> analysisMap; int main(int argc, char **argv) { // Read the IR file. static LLVMContext Context; SMDiagnostic Err; unique_ptr<Module> M = parseIRFile(argv[1], Err, Context); if (M == nullptr) { fprintf(stderr, "error: failed to load LLVM IR file \"%s\"", argv[1]); return EXIT_FAILURE; } for (auto &F : *M) { if (strncmp(F.getName().str().c_str(), "main", 4) == 0) { BasicBlock *BB = dyn_cast<BasicBlock>(F.begin()); set<Instruction *> emptySet; traverse(BB, emptySet); } } print(analysisMap); return 0; } set<Instruction *> generate(BasicBlock *bb) { set<Instruction *> generate; for (auto &I : *bb) { if (isa<StoreInst>(I)) { Value *v = I.getOperand(1); Instruction *var = dyn_cast<Instruction>(v); if (label(var).compare("retval") != 0) { generate.insert(var); } } } return generate; } set<Instruction *> combine(set<Instruction *> entry, set<Instruction *> generate, set<Instruction *> previous) { set<Instruction *> combined; combined.insert(entry.begin(), entry.end()); combined.insert(generate.begin(), generate.end()); combined.insert(previous.begin(), previous.end()); return combined; } void traverse(BasicBlock *BB, set<Instruction *> entrySet) { const TerminatorInst *TInst = BB->getTerminator(); unsigned NSucc = TInst->getNumSuccessors(); unsigned originalCount = 0; bool traversed = false; string bblabel = label(BB); if (analysisMap.count(bblabel) == 0) { // Initialize set<Instruction *> empty; analysisMap[bblabel] = empty; } else { originalCount = analysisMap[bblabel].size(); traversed = true; } set<Instruction *> generated = generate(BB); set<Instruction *> exitSet = combine(entrySet, generated, analysisMap[bblabel]); analysisMap[bblabel] = exitSet; if (NSucc == 0) { return; } unsigned finalCount = exitSet.size(); if (traversed && originalCount == finalCount) { return; } for (unsigned i = 0; i < NSucc; i++) { BasicBlock *Succ = TInst->getSuccessor(i); traverse(Succ, exitSet); } } void print(const map<string, set<Instruction *>> analysisMap) { for (auto &row : analysisMap) { set<Instruction *> initializedVars = row.second; string BBLabel = row.first; outs() << BBLabel << "\t: {"; bool first = true; for (Instruction *var : initializedVars) { if (!first) { outs() << ", "; } outs() << label(var); first = false; } outs() << "} \n"; } } void print(const Value *bb) { outs() << "Label:" << label(bb) << "\n"; } string label(const Value *Node) { if (!Node->getName().empty()) return Node->getName().str(); string Str; raw_string_ostream OS(Str); Node->printAsOperand(OS, false); return OS.str(); }
#pragma once #include <ctime> #include <iostream> #include <string> #include <boost/array.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <boost/asio.hpp> //#include // logging set #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/expressions.hpp> #include <boost/log/sinks/text_file_backend.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/attributes/timer.hpp> #include <boost/log/attributes/named_scope.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/sources/record_ostream.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/support/date_time.hpp> #include <boost/log/utility/setup/console.hpp> namespace src = boost::log::sources; using boost::asio::ip::udp; #define SIZE 26 #define PORT 9999 class udp_server { public: udp_server(boost::asio::io_service& io_service, unsigned short port=PORT); ~udp_server(void); private: void start_receive(); void handle_receive(const boost::system::error_code& error, std::size_t /*bytes_transferred*/); void handle_send(boost::shared_ptr<std::string> /*message*/, const boost::system::error_code& /*error*/, std::size_t /*bytes_transferred*/); void log(char * buf); udp::socket socket_; udp::endpoint remote_endpoint_; boost::array<char, 4096> recv_buffer_; src::logger lg; };
#include <iostream> #include<stdlib.h> #include<stdio.h> #include<cstdlib> #include<time.h> using namespace std; struct node { int data; node * next; node * prior; } node; typedef struct node * nodeLink; //双向循环链表的创建 nodeLink create() { int n; printf("请输入要创建的链表的个数\t"); scanf("%d",&n); nodeLink head ; nodeLink p; nodeLink q; head = (nodeLink)malloc(sizeof(node)); if(NULL==head) { printf("内存分配失败"); exit(1); } head->data =0; head->prior=NULL; head->next=NULL; p = head; for(int i=1; i<=n; i++) { q = (nodeLink)malloc(sizeof(node)); q->data = i; q->prior = p; q->next = p->next; p->next = q; p = q; } p->next = head->next; head->next->prior = p; return head; } //打印链表 void printLink(nodeLink head) { nodeLink L =head->next; do { cout<<L->data<<endl; L = L->next; } while(L !=head->next); } /***********双向循环链表插入************/ int insertLink(nodeLink head) { nodeLink p; nodeLink q; int pos,newdata; printf("请输入要插入的位置"); scanf("%d",&pos); printf("请输入要插入的值"); scanf("%d",&newdata); ///这里省去了异常case的判断,只在正常情况下进行 自己可以加上。 养成好习惯 不要像我哈! nodeLink L =head->next; for(int i=1; i<pos-1; i++) { L=L->next; } q = (nodeLink)malloc(sizeof(node)); q->data =newdata; q->next = L->next; L->next->prior = q; L->next = q; q->prior = L; printf("插入后\n"); printLink(head); return 1; } //删除 思想差不多 这里由于时间原因 省去了删除和插入的位置异常case ! int main() { nodeLink head = create(); printf("插入前\n"); printLink(head); insertLink(head); return 0; }
#include <SPI.h> #include <FreeStack.h> #include <SdFat.h> #include <vs1053_SdFat.h> /* // Below is not needed if interrupt driven. Safe to remove if not using. #if defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_Timer1 #include <TimerOne.h> #elif defined(USE_MP3_REFILL_MEANS) && USE_MP3_REFILL_MEANS == USE_MP3_SimpleTimer #include <SimpleTimer.h> #endif */ SdFat sd; vs1053 MP3player; void setup() { Serial.begin(115200); //Initialize the SdCard. if(!sd.begin(SD_SEL, SPI_FULL_SPEED)) sd.initErrorHalt(); if(!sd.chdir("/")) sd.errorHalt("sd.chdir"); //Initialize the MP3 Player Shield MP3player.begin(); // Play file track001.mp3 MP3player.playTrack(1); } void loop() {}
// CSV2PCD.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <stdio.h> #include <iostream> #include <string> #include <vector> #include <fstream> #include <sstream> using namespace std; #define FILE_PATH "pts_camera_frame.csv" void tokenize(const string& str, vector<string>& tokens, const string& delimiters) { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.push_back(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } void parseLine(const string& str) { double Xc; double Yc; double Zc; vector<string> tokens; tokenize(str, tokens, ","); cout << tokens.at(0) << endl; cout << tokens.at(1) << endl; cout << tokens.at(2) << endl; istringstream os_Xc(tokens.at(0)); istringstream os_Yc(tokens.at(1)); istringstream os_Zc(tokens.at(2)); os_Xc >> Xc; os_Yc >> Yc; os_Zc >> Zc; cout << Xc << endl; cout << Yc << endl; cout << Zc << endl; cout << endl; } int _tmain(int argc, _TCHAR* argv[]) { char pDataPath[100]; sprintf_s(pDataPath,"%s", FILE_PATH); ifstream file(pDataPath); //CPoint* pPoint = new CPoint[iPOINT_NUMBER]; //CPoint* pPoint_backup = pPoint; string line; for(unsigned long cnt_line = 0; cnt_line < 5; cnt_line++ ) { getline(file, line); parseLine( line ); } while(1); return 0; }
#define MAX_RF 5 #define MAX_AF 10 #define MAX_USER 10001 #define MAX_FCNT 500001 struct USER { int userID; struct USER* prev; }; USER* GetNewFriend(int id) { USER* newFriend = new USER; newFriend->userID = id; newFriend->prev = nullptr; return newFriend; } USER* userList[MAX_USER]; int userFriendCnt[MAX_USER]; int totalUserCnt = 0; void init(int n) { totalUserCnt = n; for (int i = 0; i <= n; i++) { userList[i] = 0; userFriendCnt[i] = 0; } } void add(int id, int f, int ids[MAX_AF]) { userFriendCnt[id] += f; for (int i = 0; i < f; i++) { USER* nF = GetNewFriend(ids[i]); nF->prev = userList[id]; userList[id] = nF; USER* pF = GetNewFriend(id); pF->prev = userList[ids[i]]; userList[ids[i]] = pF; ++userFriendCnt[ids[i]]; } } void Delete(int id1, int id2) { --userFriendCnt[id1]; USER* d = userList[id1]; for (USER *f = userList[id1]; f != 0; f = f->prev) { if (f->userID == id2) { if (d == f) { d = f->prev; userList[id1] = d; } else { d->prev = f->prev; } break; } d = f; } } void del(int id1, int id2) { Delete(id1, id2); Delete(id2, id1); } int recommend(int id, int list[MAX_RF]) { int count[MAX_USER] = { 0, }; for (USER* f = userList[id]; f != 0; f = f->prev) { for (USER* nF = userList[f->userID]; nF != 0; nF = nF->prev) { ++count[nF->userID]; } } for (USER* f = userList[id]; f != 0; f = f->prev) { count[f->userID] = 0; } count[id] = 0; int cnt = 0; for (cnt = 0; cnt < MAX_RF; cnt++) { int maxFriendCnt = 0; int maxFriendIdx = 0; for (int i = 1; i <= totalUserCnt; i++) { if (count[i] > maxFriendCnt) { maxFriendCnt = count[i]; maxFriendIdx = i; } } if (maxFriendIdx == 0) { break; } list[cnt] = maxFriendIdx; count[maxFriendIdx] = 0; } return cnt; }
#include<iostream> #include<string.h> using namespace std; struct node { char data; node *l,*r; }; node* newNode (int data) { node *temp = new node; temp->data = data; temp->l = NULL; temp->r = NULL; return temp; } node *insert(int *i,char *str) { int index = *i; // store the current value of index in pre[] // Base Case: All nodes are constructed if (index <0) return NULL; // Allocate memory for this node and increment index for // subsequent recursive calls struct node *temp = newNode ( str[index] ); (*i)--; // If this is an internal node, construct left and right subtrees and link the subtrees if('A'<=str[index]<='Z') { temp->r = insert(i, str); temp->l = insert(i, str);//constructTreeUtil(pre, preLN, index_ptr, n); } return temp; } int numleaf(node *ptr) { if(ptr==NULL) return 0; if(ptr->l==NULL&&ptr->r==NULL) return 1; return (numleaf(ptr->l)+numleaf(ptr->r)); } int f(node *ptr,string A,int k,int i) { if(ptr==NULL) return 0; if(ptr->data==A[i]&&i==k-1) { return numleaf(ptr); } if(ptr->data==A[i]) { return f(ptr->l,A,k,i+1)+f(ptr->r,A,k,i+1); } return 0; } void inorder(node *ptr) { if(ptr) { inorder(ptr->l); cout<<ptr->data<<" "; inorder(ptr->r); } } int explodePaths(int N, char* S, int K, char* A) { node *root; int i=N-1; root=insert(&i,S); inorder(root); cout<<root->data; return f(root,A,K,0);; } int main() { char s[]="txyBabABA"; char A[]="AA"; cout<<explodePaths(9,s,2,A); return 0; }
#include <bits/stdc++.h> using namespace std; int solve(vector<int> rating) { int ans = 0; for (int i = 0; i < rating.size(); i++) { for (int j = i + 1; j < rating.size(); j++) { for (int k = j + 1; k < rating.size(); k++) { if (rating[i] < rating[j] < rating[k]) ans++; if (rating[i] > rating[j] > rating[k]) ans++; } } } return ans; } int main() { vector<int> a({2, 5, 3, 4, 1}); return 0; }