text
stringlengths
8
6.88M
#include<iostream> using namespace std; int main() { int lado = 2; int horizontal = 0; int vertical = 0; while (vertical <= lado) { while (horizontal <= lado) { if (vertical != 0 && vertical != lado){ if (horizontal != 0 && horizontal != lado){ cout<<' '; horizontal++; }else { cout<<'*'; horizontal++; } }else { cout<<'*'; horizontal++; } } horizontal = 0; cout<<'\n'; vertical++; } return 0; }
#ifndef Included_DVD_h #define Included_DVD_h #include "SaleableItem.h" class DVD :public SaleableItem { public: enum DVDFormat {PAL, NTSC}; DVD(const char* pTitle, unsigned int unitPricePence, unsigned int runningTimeMinsp, DVDFormat formatp); unsigned int getNewPrice(void); private: unsigned int runningTimeMins; DVDFormat format; }; #endif /* #ifndef Included_DVD_h */
//: C14:OperatorInheritance.cpp // Kod zrodlowy pochodzacy z ksiazki // "Thinking in C++. Edycja polska" // (c) Bruce Eckel 2000 // Informacje o prawie autorskim znajduja sie w pliku Copyright.txt // Dziedziczenie przeciazonych operatorow #include "../C12/Byte.h" #include <fstream> using namespace std; ofstream out("ByteTest.out"); class Byte2 : public Byte { public: // Konstruktory nie sa dziedziczone: Byte2(unsigned char bb = 0) : Byte(bb) {} // operator= nie podlega dziedziczeniu, ale jest // generowany dla przypisania za posrednictwem // elementow skladowych. Jednakze, generowany // jest tylko operator= umozliwiajacy przypisanie // w stosunku obiektow tego samego typu, wiec inne // operatory przypisania musza byc utworzone jawnie: Byte2& operator=(const Byte& right) { Byte::operator=(right); return *this; } Byte2& operator=(int i) { Byte::operator=(i); return *this; } }; // Funkcje testowe podobne do zawartych w pliku C12:ByteTest.cpp: void k(Byte2& b1, Byte2& b2) { b1 = b1 * b2 + b2 % b1; #define TRY2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 daje "; \ (b1 OP b2).print(out); \ out << endl; b1 = 9; b2 = 47; TRY2(+) TRY2(-) TRY2(*) TRY2(/) TRY2(%) TRY2(^) TRY2(&) TRY2(|) TRY2(<<) TRY2(>>) TRY2(+=) TRY2(-=) TRY2(*=) TRY2(/=) TRY2(%=) TRY2(^=) TRY2(&=) TRY2(|=) TRY2(>>=) TRY2(<<=) TRY2(=) // Operator przypisania // Operatory warunkowe: #define TRYC2(OP) \ out << "b1 = "; b1.print(out); \ out << ", b2 = "; b2.print(out); \ out << "; b1 " #OP " b2 daje "; \ out << (b1 OP b2); \ out << endl; b1 = 9; b2 = 47; TRYC2(<) TRYC2(>) TRYC2(==) TRYC2(!=) TRYC2(<=) TRYC2(>=) TRYC2(&&) TRYC2(||) // Przypisanie lancuchowe: Byte2 b3 = 92; b1 = b2 = b3; } int main() { out << "funkcje skladowe:" << endl; Byte2 b1(47), b2(9); k(b1, b2); } ///:~
#include "methods.hpp" #include <iostream> #include <string> using namespace std; long long int methods::fact (int number) { if (number == 1) { return 1; } return number * fact (number - 1); } template <typename Type> Type methods::get_num() { Type number; cout << "Enter your number (btw, letters must be uppercase): "; cin >> number; return number; } long long int methods::f2d() { string number_string = get_num <string> (); int number[number_string.size()]; for(int i = 0; i < number_string.size(); ++i) { if(isdigit(number_string[i])) number[i] = (int)number_string[i] - 48; else number[i] = (int)number_string[i] - 55; //uppercase 'A', not 'a', etc } for(int i = 1; i <= number_string.size(); ++i) { int t = number_string.size() - i; if (number[t] > fact(i)) return -1; } long long int result = 0; for(int i = 1; i <= number_string.size(); ++i) { int t = number_string.size() - i; result += number[t] * fact(i); } return result; } string methods::d2f() { long long int number = get_num <long long int> (); if (number == 0) { return 0; } int closest_f = 0; while (fact (++closest_f) <= number); --closest_f; int *number_unconverted = new int[closest_f]; for (int i = 0; i < closest_f; ++i) { number_unconverted[i] = number / fact (closest_f - i); number %= fact (closest_f - i); } string converted_number; for (int i = 0; i < closest_f; ++i) { if (isdigit ((char)(number_unconverted[i] + 48))) { converted_number += (number_unconverted[i] + 48); } else { converted_number = (number_unconverted[i] + 55); //uppercase 'A', not 'a', etc } } delete[] number_unconverted; return converted_number; }
#include <iostream> #include <string> using namespace std; class BallAndHats { public: int getHat(string hats, int numSwaps) { int startPoint = static_cast<int>(hats.find('o')); if (numSwaps == 0) { return startPoint; } if ((numSwaps%2!=0 && startPoint%2!=0) ||(numSwaps%2==0 && startPoint%2==0) ) { return 0; } return 1; } };
#ifndef RECORD_HH_ #define RECORD_HH_ #include <string> // struct of an history record struct history_record { std::string type; std::string command; std::string name; double time; int success; double err; unsigned int id; double lastTimePlayed; }; #endif //RECORD_HH_
#ifndef SHADER_H #define SHADER_H #include <string> #include <fstream> #include <sstream> class Shader { public: Shader(string vs_filename, string fs_filename); virtual ~Shader() {} void enable() const; void sendLight(const float *light) const { glUniform4fv(id_light, 1, light); } void sendVCam(const float *vcam) const { glUniform3fv(id_vcam, 1, vcam); } void sendMVP(const float *MVP) const { glUniformMatrix4fv(id_MVP, 1, GL_TRUE, MVP); } void sendMaterial(const float *coef, const float *exp) const { glUniform3fv(id_coef, 1, coef); glUniform2fv(id_exp, 1, exp); } protected: private: string readFile(string filename); GLuint shaderProgram; GLuint id_MVP; GLuint id_light; GLuint id_vcam; GLuint id_coef; GLuint id_exp; }; string Shader::readFile(string filename) { ifstream t(filename); stringstream buffer; buffer << t.rdbuf(); return buffer.str(); } Shader::Shader(string vs_filename, string fs_filename) { string vss = readFile(vs_filename); string fss = readFile(fs_filename); const char *vertexShaderText = vss.c_str(); const char *fragmentShaderText = fss.c_str(); cout << vertexShaderText << endl << endl; cout << fragmentShaderText << endl << endl; GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderText, nullptr); glCompileShader(vertexShader); GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderText, nullptr); glCompileShader(fragmentShader); shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glUseProgram(shaderProgram); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); id_MVP = 3; id_light = 4; id_vcam = 5; id_coef = 6; id_exp = 7; GLenum ErrorCheckValue = glGetError(); if (ErrorCheckValue != GL_NO_ERROR) { cout << "Problema com os Shaders! " << ErrorCheckValue << endl; exit(-1); } } // Habilita este Shader void Shader::enable() const { glUseProgram(shaderProgram); } #endif // SHADER_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #include "core/pch.h" #include "modules/util/handy.h" #include "modules/util/str.h" #include "modules/url/url2.h" #include "modules/dochand/winman.h" #include "modules/prefs/prefsmanager/collections/pc_network.h" #if defined WEBSERVER_SUPPORT && defined QUICK #include "adjunct/quick/managers/OperaAccountManager.h" #endif // WEBSERVER_SUPPORT && QUICK // UpdateOfflineMode // // Update/toggle offline mode and reflect the new/current setting into the // main menu. Returns the new offline mode. OP_BOOLEAN UpdateOfflineMode(BOOL toggle) { OP_MEMORY_VAR BOOL offline_mode = FALSE; if (g_pcnet) { offline_mode = g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode); if (toggle) { offline_mode = !offline_mode; #ifndef PREFS_NO_WRITE RETURN_IF_LEAVE(g_pcnet->WriteIntegerL(PrefsCollectionNetwork::OfflineMode, offline_mode)); #endif // !PREFS_NO_WRITE if (offline_mode) { g_url_api->CloseAllConnections(); } #ifdef QUICK g_desktop_account_manager->SetIsOffline(offline_mode); #endif // QUICK RETURN_IF_ERROR(g_windowManager->OnlineModeChanged()); } } return offline_mode ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE; } BOOL UpdateOfflineModeL(BOOL toggle) { OP_BOOLEAN ret_val = UpdateOfflineMode(toggle); LEAVE_IF_ERROR(ret_val); return ret_val == OpBoolean::IS_TRUE; }
#include<cstdio> #include<iostream> #include<cstring> #define MAX_LOG 16 //最大可能的log值,注意中间运算的结果可能会超出题目数据范围,所以这个值最好设大点 #define MAX(x,y) ((x)>(y)?(x):(y)) using namespace std; int n; int f[MAX_LOG][MAX_LOG]; //记录2^x(X)2^y的值 //declaration int nim_mul_normal(int x,int y); int nim_mul_power(int x,int y); // int nim_mul_power(int x,int y) //求2^x和2^y的nim积 { int ret=1; if(x==0) return 1<<y; if(y==0) return 1<<x; for(int i=0;x>0 || y>0;++i,x>>=1,y>>=1) { if((x&1)+(y&1)==1) ret=ret*(1<<(1<<i)); if((x&1)+(y&1)==2) ret=nim_mul_normal(ret,(1<<(1<<i))/2*3); //如果有相同的,要用一般nim积来算 } return ret; } int nim_mul_normal(int x,int y) //求一般数的nim积 { int ret=0; if(x==1) return y; if(y==1) return x; for(int i=0;(1<<i)<=x;++i) if(x&(1<<i)) for(int j=0;(1<<j)<=y;++j) if(y&(1<<j)) ret^=f[i][j]; return ret; } void pre_cal_f() //预先计算出所有2^i(X)2^j的值 { memset(f,255,sizeof(f)); for(int i=0;i<MAX_LOG;++i) f[i][0]=f[0][i]=(1<<i); for(int i=1;i<MAX_LOG;++i) for(int j=i;j<MAX_LOG;++j) f[i][j]=f[j][i]=nim_mul_power(i,j); } void solve() { int ans=0; for(int i=0;i<n;++i) { int x,y,z; scanf("%d%d%d",&x,&y,&z); ans^=nim_mul_normal(nim_mul_normal(x,y),z); } if(ans==0) printf("Yes\n"); //先手必败 else printf("No\n"); } int main() { freopen("pku3533.in","r",stdin); pre_cal_f(); while(scanf("%d",&n)!=EOF) solve(); return 0; }
#include <Arduino.h> #define btn 21 int ledStatus = LOW; volatile bool interruptState = false; int totalInterruptCounter=0; hw_timer_s *timer = NULL; portMUX_TYPE timerMux = portMUX_INITIALIZER_UNLOCKED; void IRAM_ATTR gpioISR() { ledStatus = !ledStatus; digitalWrite(BUILTIN_LED,ledStatus); } void setup() { // put your setup code here, to run once: pinMode(BUILTIN_LED,OUTPUT); pinMode(btn, INPUT_PULLUP); attachInterrupt(btn,&gpioISR, RISING); //rising akan menyala jika dilepas falling ketika dipencet akan hidup } void loop() { // put your main code here, to run repeatedly: }
#ifndef GUILITE_CORE_INCLUDE_RECT_H #define GUILITE_CORE_INCLUDE_RECT_H #define MAX(a,b) (((a)>(b))?(a):(b)) #define MIN(a,b) (((a)<(b))?(a):(b)) class c_rect { public: c_rect(){Empty();} c_rect(int left, int top, int right, int bottom){m_left = left;m_top = top;m_right = right;m_bottom = bottom;}; void SetRect(int Left, int Top, int Right, int Bottom) { m_left = MIN(Left, Right); m_top = MIN(Top, Bottom); m_right = MAX(Left, Right); m_bottom = MAX(Top, Bottom); } c_rect(const c_rect& rect) { SetRect(rect.m_left, rect.m_top, rect.m_right, rect.m_bottom); } void Empty() { m_left = m_top = m_right = m_bottom = -1; } int IsEmpty() const { return m_top == m_bottom || m_left == m_right; } bool PtInRect(int x, int y) const { return x >= m_left && x <= m_right && y >= m_top && y <= m_bottom; } int operator==(const c_rect& rect) const { return (m_left == rect.m_left) && (m_top == rect.m_top) && (m_right == rect.m_right) && (m_bottom == rect.m_bottom); } int Width() const {return m_right - m_left + 1;} int Height() const {return m_bottom - m_top + 1;} int m_left; int m_top; int m_right; int m_bottom; }; #endif
#include "test_precomp.hpp" CV_TEST_MAIN("highgui")
#include "../Solution.h" bool Solution::isPalindrome(int x) { int x1 = 0; int temp = 0; if ((x < 0 || x % 10 == 0) && x != 0) { return 0; } while (x1 < x) { x1 = x1 * 10 + x % 10; x /= 10; } return x1 == x || x == x1 / 10; }
#include<iostream> #include<stack> using namespace std; int main() { string s; cin>>s; stack<char> st; int flag=1; for(int i=0;i<s.length();i++) { char c=s[i]; if(c=='{'||c=='['||c=='(') st.push(c); else if(!st.empty()) { if(c==')' && st.top()=='(') st.pop(); else if(c=='}' && st.top()=='{') st.pop(); else if(c==']' && st.top()=='[') st.pop(); else { flag=0; break; } } else { flag=0; break; } } if(flag) cout<<"Yes"<<endl; else cout<<"No"<<endl; return 0; }
#ifndef LWRCONTROLLER_H #define LWRCONTROLLER_H #include <cstdio> #include "ros/ros.h" #include <actionlib/server/action_server.h> #include <control_msgs/FollowJointTrajectoryAction.h> #include <sensor_msgs/JointState.h> #include <geometry_msgs/PoseStamped.h> #include <nav_msgs/Path.h> #include <std_msgs/Empty.h> #include <boost/thread.hpp> #include <visualization_msgs/Marker.h> #include <tf/transform_listener.h> #include <Eigen/Geometry> #include <Eigen/Core> #include "friclient.h" #define SQR(x) x*x class LWRController { public: typedef actionlib::ActionServer<control_msgs::FollowJointTrajectoryAction> TASJT; LWRController(ros::NodeHandle n); /** Action client callback to setup points */ void goalJointTrajectory(TASJT::GoalHandle gh); /** Action client callback to cancel */ void cancelCB(TASJT::GoalHandle gh); /** Action client callback to send result */ void sendResult(TASJT::GoalHandle gh); /** Thread to publish robot state */ void pubStatus(); /** Message callback to set stopping force */ void onForceElement(const geometry_msgs::PoseStamped& f); /** Message callback for cartesian velocity command */ void onCartVelocity(const geometry_msgs::PoseStamped& vel); /** Message callback for cartesion path (nav_msgs::Path) */ void onPath(const nav_msgs::Path& path); /** Message callback to define current force as zero on the force of JR3 sensor */ void onJR3zero(const std_msgs::Empty & m); FRIClient mFriClient; tf::TransformListener mTF; ros::NodeHandle mNode; std::string mTmp; ros::Subscriber mSubForceLimitElement, mSubJR3zero, mSubPath, mSubCartVel; TASJT mJTAction; boost::thread mThreadSend; }; #endif // LWRCONTROLLER_H
/* ========================================== Copyright (c) 2016-2018 Dynamic_Static Patrick Purcell Licensed under the MIT license http://opensource.org/licenses/MIT ========================================== */ #include "Dynamic_Static/Core/Threads/ThreadPool.hpp" #include "Dynamic_Static/Core/Time.hpp" #include "catch.hpp" #include <thread> namespace dst { namespace tests { static constexpr size_t WaitTarget { 5 }; static constexpr size_t CounterTarget { 10 }; static void sleep() { std::this_thread::sleep_for(Millisecond<>(16)); } TEST_CASE("ThreadPool push() and wait()", "[ThreadPool]") { int i = 0; char c = 0; float f = 0; bool b = false; ThreadPool threadPool; threadPool.push([&]{ sleep(); i = 1; }); threadPool.push([&]{ sleep(); c = 1; }); threadPool.push([&]{ sleep(); f = 1; }); threadPool.push([&]{ sleep(); b = true; }); REQUIRE(i == 0); REQUIRE(c == 0); REQUIRE(f == 0); REQUIRE(b == false); threadPool.wait(); REQUIRE(i == 1); REQUIRE(c == 1); REQUIRE(f == 1); REQUIRE(b == true); } TEST_CASE("ThreadPool passes through wait() if no tasks are pending", "[ThreadPool]") { ThreadPool threadPool; bool passed = false; threadPool.wait(); passed = true; REQUIRE(passed); } TEST_CASE("ThreadPool completes pending tasks before destruction", "[ThreadPool]") { int i = 0; char c = 0; float f = 0; bool b = false; auto threadPool = std::make_unique<ThreadPool>(); threadPool->push([&]{ sleep(); i = 1; }); threadPool->push([&]{ sleep(); c = 1; }); threadPool->push([&]{ sleep(); f = 1; }); threadPool->push([&]{ sleep(); b = true; }); REQUIRE(i == 0); REQUIRE(c == 0); REQUIRE(f == 0); REQUIRE(b == false); threadPool.reset(); REQUIRE(i == 1); REQUIRE(c == 1); REQUIRE(f == 1); REQUIRE(b == true); } } // namespace tests } // namespace dst
#include "headers/dbconnector.h" DBConnector::DBConnector(const QString &db_name) { DB_name = db_name; db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(DB_name); QSqlQuery query; db.open(); query.exec(QString("CREATE TABLE IF NOT EXISTS " + DB_tableName_country + " (" "mcc INTEGER, " "code TEXT , " "name TEXT , " "mnc_length INTEGER ); ")); query.exec(QString("CREATE TABLE IF NOT EXISTS " + DB_tableName_operator + " (" "mcc TEXT, " "mnc TEXT, " "name TEXT ); ")); db.close(); } void DBConnector::add(const QString &mcc, const QString &mnc, const QString &name) { db.open(); QSqlQuery query; query.prepare("INSERT INTO " + DB_tableName_operator + " (mcc, mnc, name)" "VALUES (:mcc, :mnc, :name)"); query.bindValue(":mcc", mcc); query.bindValue(":mnc", mnc); query.bindValue(":name", name); query.exec(); db.close(); } QList<DBConnector::listCountry> DBConnector::getAll() { QList<listCountry> res; db.open(); QSqlQuery query; query.exec("SELECT * FROM " + DB_tableName_operator); QMultiMap<QString, DBConnector::Operator> operators; while (query.next()) { QString mcc = query.value(0).toString(); QString mnc(query.value(1).toString()); QString name(query.value(2).toString()); operators.insert(mcc, { mcc, mnc, name }); } for (auto el = operators.begin(); el != operators.end();) { if (el.key() == "" || el.key() == "0") { QString key = el.key(); operators.remove(key); el = operators.begin(); continue; } query.exec("SELECT * FROM " + DB_tableName_country + " WHERE mcc = '" + el.key() + "' ;"); query.next(); QString code = query.value(1).toString(); QString country = query.value(2).toString(); if (country.isEmpty()) { QString key = el.key(); operators.remove(key); el = operators.begin(); continue; } res.append({ country, code, operators.values(el.key()) }); QString key = el.key(); operators.remove(key); el = operators.begin(); } db.close(); return res; } QString DBConnector::getCountyCode(const QString &mcc) { db.open(); QSqlQuery query; query.exec("SELECT code FROM " + DB_tableName_country + " WHERE mcc = '" + mcc + "' ;"); query.next(); QString code = ""; code = query.value(0).toString(); db.close(); return code; } void DBConnector::edit(const QString &_mcc, const QString &_mnc, const QString &_name, const QString &oldName) { db.open(); QSqlQuery query; query.exec("UPDATE operators SET name = '" + _name + "' WHERE mnc = " + _mnc + " AND mcc = " + _mcc + " AND name = '" + oldName + "' ; "); db.close(); }
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(int K, vector<int> &A) { // write your code in C++14 (g++ 6.2.0) int temp=0; int sol=0; for (auto a : A){ temp+=a; if (temp>=K) { sol++; temp=0; } } return sol; }
#include "mesh.h" #include <iostream> #include "../glm/gtc/matrix_transform.hpp" Mesh::Mesh(int m, float length, int numVerts, std::vector<glm::vec3> verts) : Primitive(length, 99) { //Extrusion mtl = new int(m); numVbo = new int(24 * numVerts); bool convex = isConvex(numVerts, verts); if (convex) { *numVbo += ((numVerts - 2) * 24); } glm::vec3 minvert = verts.at(0); float minx = 999999.9f; float maxx = -999999.9f; float miny = 999999.9f; float maxy = -999999.9f; float minz = 999999.9f; float maxz = -999999.9f; for (int i = 1; i < numVerts; i++) { if (verts.at(i).y < minvert.y) { minvert = verts.at(i); } if (verts.at(i).x < minx) { minx = verts.at(i).x; } if (verts.at(i).y < miny) { miny = verts.at(i).y; } if (verts.at(i).z < minz) { minz = verts.at(i).z; } if (verts.at(i).x > maxx) { maxx = verts.at(i).x; } if (verts.at(i).y > maxy) { maxy = verts.at(i).y; } if (verts.at(i).z > maxz) { maxz = verts.at(i).z; } } mybound = new glm::mat4(glm::scale(glm::mat4(), glm::vec3(maxx - minx, maxy - miny, maxz - minz))); float morey = 0.0f;//0.35f; if (minvert.y < 0) { morey = -1 * minvert.z; } numCbo = new int((3 * *numVbo)/4); numIbo = new int(*numVbo/4); vbo = new float[*numVbo]; ibo = new short int[*numIbo]; cbo = new float[*numCbo]; nbo = new float[*numVbo]; for (int c = 0; c < *numCbo; c+=3) { cbo[c] = 0.0f; cbo[c + 1] = 1.0f; cbo[c + 2] = 0.0f; } for (int in = 0; in < *numIbo; in++) { ibo[in] = in; } float x1; float y1; float z1; float x2; float y2; float z2; glm::vec3 v1; glm::vec3 v2; glm::vec3 v3; glm::vec3 norm; int k = 0; for (int i = 0; i < numVerts; i++) { v1 = verts.at(i); if (i + 1 == numVerts) { v2 = verts.at(0); } else { v2 = verts.at(i+1); } x1 = v1.x; x2 = v2.x; y1 = v1.y; y2 = v2.y; z1 = v1.z; z2 = v2.z; v3.x = x1; v3.y = y1 + length + morey; v3.z = z1; norm = glm::normalize(glm::cross(v3 - v1, v2 - v1)); for (int j = k; j < k + 24; j+=4) { nbo[j] = norm.x; nbo[j + 1] = norm.y; nbo[j + 2] = norm.z; nbo[j + 3] = 0.0f; } vbo[k] = x1; vbo[k + 1] = y1 + morey; vbo[k + 2] = z1; vbo[k + 3] = 1.0f; vbo[k + 4] = x1; vbo[k + 5] = y1 + length + morey; vbo[k + 6] = z1; vbo[k + 7] = 1.0f; vbo[k + 8] = x2; vbo[k + 9] = y2 + morey; vbo[k + 10] = z2; vbo[k + 11] = 1.0f; vbo[k + 12] = x2; vbo[k + 13] = y2 + morey; vbo[k + 14] = z2; vbo[k + 15] = 1.0f; vbo[k + 16] = x2; vbo[k + 17] = y2 + length + morey; vbo[k + 18] = z2; vbo[k + 19] = 1.0f; vbo[k + 20] = x1; vbo[k + 21] = y1 + length + morey; vbo[k + 22] = z1; vbo[k + 23] = 1.0f; k += 24; } if (convex) { v1 = verts.at(0); x1 = v1.x; y1 = v1.y; z1 = v1.z; for (int i = 1; i < numVerts - 1; i++) { for (int j = k; j < k + 12; j+=4) { nbo[j] = 0.0f; nbo[j + 1] = -1.0f; nbo[j + 2] = 0.0f; nbo[j + 3] = 0.0f; } v2 = verts.at(i); v3 = verts.at(i + 1); x2 = v2.x; y2 = v2.y; z2 = v2.z; vbo[k] = x1; vbo[k + 1] = y1 + morey; vbo[k + 2] = z1; vbo[k + 3] = 1.0f; vbo[k + 4] = x2; vbo[k + 5] = y2 + morey; vbo[k + 6] = z2; vbo[k + 7] = 1.0f; vbo[k + 8] = v3.x; vbo[k + 9] = v3.y + morey; vbo[k + 10] = v3.z; vbo[k + 11] = 1.0f; k += 12; } for (int i = 1; i < numVerts - 1; i++) { v2 = verts.at(i); v3 = verts.at(i + 1); x2 = v2.x; y2 = v2.y; z2 = v2.z; for (int j = k; j < k + 12; j+=4) { nbo[j] = 0.0f; nbo[j + 1] = 1.0f; nbo[j + 2] = 0.0f; nbo[j + 3] = 0.0f; } vbo[k] = x1; vbo[k + 1] = y1 + length + morey; vbo[k + 2] = z1; vbo[k + 3] = 1.0f; vbo[k + 4] = x2; vbo[k + 5] = y2 + length + morey; vbo[k + 6] = z2; vbo[k + 7] = 1.0f; vbo[k + 8] = v3.x; vbo[k + 9] = v3.y + length + morey; vbo[k + 10] = v3.z; vbo[k + 11] = 1.0f; k += 12; } } } bool Mesh::isConvex(int numVerts, std::vector<glm::vec3> verts) { float mag = 0; bool positive; for (int i = 0; i < numVerts - 1; i++) { mag = glm::cross(verts.at(i), verts.at(i + 1)).z; if (mag > 0) { positive = true; break; } else if (mag < 0) { positive = false; break; } } for (int i = 0; i < numVerts - 1; i++) { mag = glm::cross(verts.at(i), verts.at(i + 1)).y; if ((mag > 0) != positive) { return false; } } return true; } Mesh::Mesh(int m, int numSlices, int numVerts, std::vector<glm::vec4> verts) : Primitive(0, 100) { //Surfrev mtl = new int(m); if (numSlices < 3) { std::cerr << "Invalid number of slices" << std::endl; exit(1); } glm::vec4 maxvert = verts.at(0); glm::vec4 minvert = verts.at(0); float minx, maxx, miny, maxy, minz, maxz; for (int i = 1; i < numVerts; i++) { if (verts.at(i).y > maxvert.y) { maxvert = verts.at(i); } if (verts.at(i).y < minvert.y) { minvert = verts.at(i); } if (verts.at(i).x < minx) { minx = verts.at(i).x; } if (verts.at(i).y < miny) { miny = verts.at(i).y; } if (verts.at(i).z < minz) { minz = verts.at(i).z; } if (verts.at(i).x > maxx) { maxx = verts.at(i).x; } if (verts.at(i).y > maxy) { maxy = verts.at(i).y; } if (verts.at(i).z > maxz) { maxz = verts.at(i).z; } } mybound = new glm::mat4(glm::translate(glm::mat4(), glm::vec3(0.0f, (maxy - miny) * 0.5f, 0.0f)) * glm::scale(glm::mat4(), glm::vec3((maxx - minx) * 2.0f, maxy - miny, (maxx - minx) * 2.0f))); *height = (maxvert.y - minvert.y); float morey = 0.0f; if (minvert.y < 0) { morey += (-1 * minvert.y); } float incr = 360.0f/numSlices; bool topcap = false; //bool bottomcap = false; int add = 0; if (verts.at(numVerts - 1).x != 0) { topcap = true; //add += ((numSlices - 2) * 36); } if (verts.at(0).x != 0) { topcap = true; //bottomcap = true; //add += ((numSlices - 2) * 36); } if (topcap) { numVerts++; verts.push_back(verts.at(0)); } numVbo = new int(((numVerts - 1) * (numSlices + 1) * 24) + add); numCbo = new int((3 * *numVbo)/4); numIbo = new int(*numVbo/4); vbo = new float[*numVbo]; ibo = new short int[*numIbo]; cbo = new float[*numCbo]; nbo = new float[*numVbo]; for (int c = 0; c < *numCbo; c+=3) { cbo[c] = 0.7f; cbo[c + 1] = 0.0f; cbo[c + 2] = 0.7f; } for (int in = 0; in < *numIbo; in++) { ibo[in] = in; } glm::vec4 vec1; glm::vec4 vec2; glm::vec4 vec3; glm::vec4 vec4; glm::vec3 vec31; glm::vec3 vec32; glm::vec3 vec33; glm::mat4 rot; glm::vec3 norm; glm::mat4 rot2 = glm::rotate(glm::mat4(), incr, glm::vec3(0, 1, 0)); int k = 0; int kx; for (float theta = -180.0f; theta <= 180.0f; theta += incr) { rot = glm::rotate(glm::mat4(), theta, glm::vec3(0, 1, 0)); for (int i = 0; i < numVerts - 1; i++) { vec1 = rot * verts.at(i); vec2 = rot2 * vec1; vec3 = rot * verts.at(i + 1); vec4 = rot2 * vec3; vec31 = glm::vec3(vec1.x, vec1.y, vec1.z); vec32 = glm::vec3(vec2.x, vec2.y, vec2.z); vec33 = glm::vec3(vec3.x, vec3.y, vec3.z); norm = glm::normalize(glm::cross(vec31 - vec32, vec32 - vec33)); for (int j = k; j < k + 24; j+=4) { nbo[j] = norm.x; nbo[j + 1] = norm.y; nbo[j + 2] = norm.z; nbo[j + 3] = 0.0f; } vbo[k] = vec1.x; vbo[k + 1] = vec1.y + morey; vbo[k + 2] = vec1.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec2.x; vbo[k + 1] = vec2.y + morey; vbo[k + 2] = vec2.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec3.x; vbo[k + 1] = vec3.y + morey; vbo[k + 2] = vec3.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec4.x; vbo[k + 1] = vec4.y + morey; vbo[k + 2] = vec4.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec2.x; vbo[k + 1] = vec2.y + morey; vbo[k + 2] = vec2.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec3.x; vbo[k + 1] = vec3.y + morey; vbo[k + 2] = vec3.z; vbo[k + 3] = 1.0f; k += 4; } } /* if (topcap) { vec1 = verts.at(numVerts - 1); for (float theta = -180.0f; theta <= 180.0f; theta += incr) { rot = glm::rotate(glm::mat4(), theta, glm::vec3(0, 1, 0)); vec2 = rot * vec1; vec3 = rot2 * vec2; vec31 = glm::vec3(vec1.x, vec1.y, vec1.z); vec32 = glm::vec3(vec2.x, vec2.y, vec2.z); vec33 = glm::vec3(vec3.x, vec3.y, vec3.z); norm = glm::normalize(glm::cross(vec31 - vec32, vec32 - vec33)); for (int n = k; n < k + 12; n+=4) { nbo[n] = norm.x; nbo[n + 1] = norm.y; nbo[n + 2] = norm.z; nbo[n + 3] = 0.0f; } vbo[k] = vec1.x; vbo[k + 1] = vec1.y + morey; vbo[k + 2] = vec1.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec2.x; vbo[k + 1] = vec2.y + morey; vbo[k + 2] = vec2.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec3.x; vbo[k + 1] = vec3.y + morey; vbo[k + 2] = vec3.z; vbo[k + 3] = 1.0f; k += 4; } } if (bottomcap) { vec1 = verts.at(0); for (float theta = -180.0f; theta <= 180.0f; theta += incr) { rot = glm::rotate(glm::mat4(), theta, glm::vec3(0, 1, 0)); vec2 = rot * vec1; vec3 = rot2 * vec2; vec31 = glm::vec3(vec1.x, vec1.y, vec1.z); vec32 = glm::vec3(vec2.x, vec2.y, vec2.z); vec33 = glm::vec3(vec3.x, vec3.y, vec3.z); norm = glm::normalize(glm::cross(vec31 - vec32, vec32 - vec33)); for (int n = k; n < k + 12; n+=4) { nbo[n] = norm.x; nbo[n + 1] = norm.y; nbo[n + 2] = norm.z; nbo[n + 3] = 0.0f; } vbo[k] = vec1.x; vbo[k + 1] = vec1.y + morey; vbo[k + 2] = vec1.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec2.x; vbo[k + 1] = vec2.y + morey; vbo[k + 2] = vec2.z; vbo[k + 3] = 1.0f; k += 4; vbo[k] = vec3.x; vbo[k + 1] = vec3.y + morey; vbo[k + 2] = vec3.z; vbo[k + 3] = 1.0f; k += 4; } } */ }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #include "core/pch.h" #include "modules/hardcore/component/Messages.h" #include "modules/ns4plugins/src/plugin.h" #include "platforms/windows/pi/WindowsOpPluginAdapter.h" #include "platforms/windows/pi/WindowsOpPluginWindow.h" /* static */ OP_STATUS OpNS4PluginAdapter::Create(OpNS4PluginAdapter** new_object, OpComponentType component_type) { WindowsOpNS4PluginAdapter* adapter = OP_NEW(WindowsOpNS4PluginAdapter, ()); RETURN_OOM_IF_NULL(adapter); OP_STATUS ret = adapter->Construct(); if (OpStatus::IsError(ret)) { OP_DELETE(adapter); return ret; } *new_object = adapter; return OpStatus::OK; } #ifdef NS4P_COMPONENT_PLUGINS /* static */ bool OpNS4PluginAdapter::IsBlacklistedFilename(UniString plugin_filepath) { return false; } #endif // NS4P_COMPONENT_PLUGINS /* static */ BOOL OpNS4PluginAdapter::GetValueStatic(NPNVariable, void*, NPError*) { return FALSE; } OP_STATUS WindowsOpNS4PluginAdapter::Construct() { RETURN_OOM_IF_NULL(m_channel = g_opera->CreateChannel()); RETURN_IF_ERROR(m_channel->AddMessageListener(this)); return OpStatus::OK; } OP_STATUS WindowsOpNS4PluginAdapter::OnWindowsPluginWindowInfoMessage(OpWindowsPluginWindowInfoMessage* message) { if (!message) return OpStatus::ERR_NULL_POINTER; OpAutoPtr<OpWindowsPluginWindowInfoResponseMessage> response (OpWindowsPluginWindowInfoResponseMessage::Create()); RETURN_OOM_IF_NULL(response.get()); response->SetWindow(reinterpret_cast<uintptr_t>(m_plugin_window->GetHandle())); return message->Reply(response.release()); } OP_STATUS WindowsOpNS4PluginAdapter::ProcessMessage(const OpTypedMessage* message) { OP_STATUS status = OpStatus::ERR; switch (message->GetType()) { case OpPeerDisconnectedMessage::Type: m_channel = NULL; status = OpStatus::OK; break; case OpWindowsPluginWindowInfoMessage::Type: status = OnWindowsPluginWindowInfoMessage(OpWindowsPluginWindowInfoMessage::Cast(message)); break; default: OP_ASSERT(!"WindowsOpNS4PluginAdapter::ProcessMessage: Received unknown/unhandled message"); break; } return status; } #ifndef NS4P_COMPONENT_PLUGINS BOOL WindowsOpNS4PluginAdapter::GetValue(NPNVariable variable, void* value, NPError* result) { *result = NPERR_NO_ERROR; switch (variable) { case NPNVnetscapeWindow: if (!m_plugin_window) return FALSE; *(static_cast<void**>(value)) = m_plugin_window->GetParentWindowHandle(); break; default: return FALSE; } return TRUE; } BOOL WindowsOpNS4PluginAdapter::ConvertPlatformRegionToRect(NPRegion invalidRegion, NPRect &invalidRect) { RECT rect; if (GetRgnBox(static_cast<HRGN>(invalidRegion), &rect) == SIMPLEREGION) { invalidRect.top = static_cast<uint16>(rect.top); invalidRect.left = static_cast<uint16>(rect.left); invalidRect.bottom = static_cast<uint16>(rect.bottom); invalidRect.right = static_cast<uint16>(rect.right); return TRUE; } return FALSE; } OP_STATUS WindowsOpNS4PluginAdapter::SetupNPWindow(NPWindow* npwin, const OpRect& rect, const OpRect& paint_rect, const OpRect& view_rect, const OpPoint& view_offset, BOOL show, BOOL transparent) { OP_ASSERT(m_plugin_window); if (!m_plugin_window) return OpStatus::ERR; if (m_plugin_window->IsWindowless()) npwin->window = m_plugin_window->GetRenderContext(); else npwin->window = m_plugin_window->GetHandle(); npwin->x = rect.x + view_offset.x; npwin->y = rect.y + view_offset.y; npwin->width = rect.width; npwin->height = rect.height; m_plugin_window->SetNPWindow(npwin); m_plugin_window->SetRect(rect); m_plugin_window->SetViewOffset(view_offset); m_plugin_window->SetViewRect(view_rect); m_plugin_window->SetTransparent(transparent); return OpStatus::OK; } OpWindowsPlatformEvent::~OpWindowsPlatformEvent() { if (m_event.event == WM_WINDOWPOSCHANGED && m_event.lParam) OP_DELETE((WINDOWPOS*)m_event.lParam); } #endif // !NS4P_COMPONENT_PLUGINS
#include <iostream> #include <vector> #include <cstring> #include <queue> int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); int t; std::cin >> t; while(t--) { int n; std::cin >> n; std::vector<int> city(n), link[n]; std::queue<int> q; bool visited[n]; std::memset(visited, 0, sizeof(visited)); for(int i = 0; i < n; i++) { std::cin >> city[i]; } int cnt = 0; q.push(0); visited[0] = 1; while(!q.empty()) { int front = q.front(); q.pop(); for(int i = 0; i < n; i++) { if(visited[i]) { continue; } if(city[front] != city[i]) { cnt++; q.push(i); visited[i] = 1; link[front].push_back(i); } } } if(cnt != n - 1) { std::cout << "NO\n"; } else { std::cout << "YES\n"; for(int now = 0; now < n; now++) { for(int next : link[now]) { std::cout << now + 1 << ' ' << next + 1 << '\n'; } } } } return 0; }
/* Anyone can't live without food , so does the snake . There's two kind of food : animal and fruit . The fruit has fixed position on the screen , while the animal not . The animal perhaps run when you approach it , and it will disappear in 3 or 4 rounds. You can also add your favourite food , just write a little code . Copyright 2005,2006 by Richard Leon */ #ifndef FOOD_H #define FOOD_H const int IAMFRUIT = 311; const int IAMANIMAL = 224; class snd_player; struct point; class food { public: virtual void put_food () = 0; virtual void erase_food (); // common routine virtual int run () = 0; virtual int get_type () const = 0; public: food (); virtual ~ food (); protected: bool has_sound; point girlfriend; // food is my girlfriend ?? snd_player *sound_appear; }; class fruit:public food { public: void put_food (); int run (); int get_type () const; public: fruit (); ~fruit (); }; class animal:public food { public: void put_food (); int run (); int get_type () const; public: animal (); ~animal (); }; #endif
#ifndef OFXACTIONLISTENERH #define OFXACTIONLISTENERH class ofxActionEvent; class ofxActionListener { public: virtual void actionPerformed(const ofxActionEvent& rEvent) = 0; }; #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; -*- * * Copyright (C) 2007-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #ifdef POSIX_OK_ASYNC #include "platforms/posix/src/posix_async.h" PosixAsyncManager::~PosixAsyncManager() { #ifdef THREAD_SUPPORT OP_ASSERT(g_opera->posix_module.OnCoreThread()); Log(NORMAL, "Harvesting %d/%d threads used for asynchronous operations.\n", m_handling, POSIX_ASYNC_THREADS); /* Transfer all pending tasks to a local list, so we can drain the list of * pending jobs after terminating all threads. */ m_flag.Grab(); Head pending; pending.Append(&m_pending); // tell the worker threads to stop: int threads = m_handling; m_handling = -1; m_flag.WakeAll(); m_flag.Give(); # ifdef POSIX_ASYNC_CANCELLATION Log(VERBOSE, "Cancelling threads\n"); for (int current = 0; current < threads; ++current) { int res = PosixThread::Cancel(m_handlers[current]); Log(VERBOSE, "Send cancelling request for thread[%d]: %p (%d)\n", current, m_handlers[current], res); } # endif // POSIX_ASYNC_CANCELLATION #else // !THREAD_SUPPORT g_main_message_handler->UnsetCallBacks(this); #endif // THREAD_SUPPORT // Drain queue: Log(CHATTY, "Draining queue of %d pending asynchronous operations.\n", pending.Cardinal()); while (PendingOp* job = static_cast<PendingOp*>(pending.First())) { job->Out(); if (job->TryLock()) job->Run(); OP_DELETE(job); } #ifdef THREAD_SUPPORT for (int current = 0; current < threads; ++current) { Log(VERBOSE, "Send another cancelling request for thread[%d]: %p (%d)\n", current, m_handlers[current], PosixThread::Cancel(m_handlers[current])); Log(VERBOSE, "Joined thread[%d] %p with return value %d\n", current, m_handlers[current], PosixThread::Join(m_handlers[current])); } DrainDone(); #endif } # ifdef THREAD_SUPPORT /** * This class is used as a cleanup handler to insert a Link (used for an * instance of PosixAsyncManager::PendingOp) into a Head (used for * PosixAsyncManager::m_done) where the operation is protected by a PosixMutex. */ class InsertLink { private: Link* m_item; Head* m_target; PosixMutex* m_mutex; void Into() { POSIX_MUTEX_LOCK(m_mutex); m_item->Into(m_target); POSIX_MUTEX_UNLOCK(m_mutex); } public: InsertLink(Link* item, Head* target, PosixMutex* mutex) : m_item(item), m_target(target), m_mutex(mutex) { OP_ASSERT(item && target && mutex); } ~InsertLink() { if (m_item) Into(); } #ifdef POSIX_ASYNC_CANCELLATION static void CleanupHandler(void* arg) { static_cast<InsertLink*>(arg)->Into(); } #endif }; bool PosixAsyncManager::Process() { /* Run by individual threads. */ OP_ASSERT(!g_opera->posix_module.OnCoreThread()); bool is_active = false; // Test if there is something to do, else take a nap: PendingOp *item; { POSIX_CONDITION_GRAB(&m_flag); if (!HasPending() && IsActive()) m_flag.Wait(false); is_active = IsActive(); item = FirstPending(); if (item) item->Out(); POSIX_CONDITION_GIVE(&m_flag); } // Then do what we were told: if (item) { InsertLink item_into_done(item, &m_done, &m_done_flag); POSIX_CLEANUP_PUSH(InsertLink::CleanupHandler, &item_into_done); if (item->TryLock()) item->Run(); POSIX_CLEANUP_POP(); } return is_active; } static void* process_queue(void* manager) { PosixAsyncManager *mgr = reinterpret_cast<PosixAsyncManager *>(manager); while (mgr->Process()) /* skip */ ; /* We *could* #define _POSIX_THREAD_CPUTIME and return the CPU time used by * this thread (see man 3posix pthread_create). */ return 0; } # else // !THREAD_SUPPORT void PosixAsyncManager::HandleCallback(OpMessage msg, MH_PARAM_1 one, MH_PARAM_2 two) { switch (msg) { case MSG_POSIX_ASYNC_TODO: OP_ASSERT(two == 0); /* Although one was originally a PendingOp*, it may since have been * handled synchronously, so don't try to read it as a PendingOp*. * Queue ensures we get at least as many messages as there are queued * items to process, so we only need to do one at a time. */ if (PendingOp *op = FirstPending()) { #ifdef DEBUG_ENABLE_OPASSERT bool locked = #endif op->TryLock(); OP_ASSERT(locked && "if THREAD_SUPPORT is disabled, we expect to always succeed on locking the operation!"); op->Out(); op->Run(); OP_DELETE(op); } break; } return; } # endif // THREAD_SUPPORT void PosixAsyncManager::Queue(PendingOp *whom) { #ifdef THREAD_SUPPORT OP_ASSERT(m_handling >= 0); OP_ASSERT(g_opera->posix_module.OnCoreThread()); m_flag.Grab(); #endif whom->Into(&m_pending); #ifdef THREAD_SUPPORT m_flag.WakeAll(); int queued = m_pending.Cardinal(); m_flag.Give(); Log(SPEW, "Added %010p to async/%d queue/%d\n", whom, m_handling, queued); /* If too busy, and we're not yet at our limit for active threads, start a * new one. */ if (0 <= m_handling && m_handling < queued && m_handling < POSIX_ASYNC_THREADS) { THREAD_HANDLE thread = PosixThread::CreateThread(process_queue, this); if (!PosixThread::IsNullThread(thread)) m_handlers[m_handling++] = thread; } DrainDone(); #else g_main_message_handler->PostMessage(MSG_POSIX_ASYNC_TODO, (MH_PARAM_1)this, 0); #endif } /* Generic implementation of Find methods. * * Structure is all the same, so use macros ... */ #define ImplementFind(client, type, result) \ PosixAsyncManager::result * \ PosixAsyncManager::Find(const client *whom, bool out) \ { \ PendingOp *item = NULL; \ { \ POSIX_CONDITION_GRAB(&m_flag); \ PendingOp *item = FirstPending(); \ while (item && \ !(item->m_type == PendingOp::type && \ static_cast<result*>(item)->Boss() == whom)) \ item = item->Suc(); \ if (item && out) item->Out(); \ POSIX_CONDITION_GIVE(&m_flag); \ } \ return static_cast<result*>(item); \ } // </ImplementFind> # ifdef POSIX_ASYNC_FILE_OP ImplementFind(OpLowLevelFile, FILE, PendingFileOp) # endif # ifdef POSIX_OK_DNS ImplementFind(OpHostResolver, DNS, PendingDNSOp) # endif #undef ImplementFind #endif // POSIX_OK_ASYNC
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 2002-2012 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ // --------------------------------------------------------------------------------- #ifndef MODULES_UTIL_OPTYPEDOBJECT_H #define MODULES_UTIL_OPTYPEDOBJECT_H // --------------------------------------------------------------------------------- class OpTypedObject { public: enum Type { UNKNOWN_TYPE, INDEX_TYPE, MAIL_TYPE, CONTACT_TYPE, BOOKMARK_TYPE, NOTE_TYPE, GROUP_TYPE, FOLDER_TYPE, MUSIC_TYPE, GADGET_TYPE, UNITE_SERVICE_TYPE, SEPARATOR_TYPE, VISUALDEVICE_TYPE, WIDGET_TYPE, // Widget types must stay in same order.. used to look up their string.. see Application.cpp WIDGET_TYPE_BUTTON, WIDGET_TYPE_RADIOBUTTON, WIDGET_TYPE_CHECKBOX, WIDGET_TYPE_LISTBOX, WIDGET_TYPE_TREEVIEW, WIDGET_TYPE_DROPDOWN, WIDGET_TYPE_EDIT, WIDGET_TYPE_MULTILINE_EDIT, WIDGET_TYPE_LABEL, WIDGET_TYPE_IMAGE, WIDGET_TYPE_WEBIMAGE, WIDGET_TYPE_FILECHOOSER_EDIT, WIDGET_TYPE_FOLDERCHOOSER_EDIT, WIDGET_TYPE_TOOLBAR, WIDGET_TYPE_GROUP, WIDGET_TYPE_SPLITTER, WIDGET_TYPE_BROWSERVIEW, WIDGET_TYPE_PROGRESSBAR, WIDGET_TYPE_TABS, WIDGET_TYPE_PAGEBAR, WIDGET_TYPE_PERSONALBAR, WIDGET_TYPE_STATUS_FIELD, WIDGET_TYPE_PROGRESS_FIELD, WIDGET_TYPE_WORKSPACE, WIDGET_TYPE_ADDRESS_DROPDOWN, WIDGET_TYPE_SEARCH_DROPDOWN, WIDGET_TYPE_SEARCH_EDIT, WIDGET_TYPE_ZOOM_DROPDOWN, WIDGET_TYPE_ACCOUNT_DROPDOWN, WIDGET_TYPE_SCROLLBAR, WIDGET_TYPE_QUICK_FIND, WIDGET_TYPE_BOOKMARKS_VIEW, WIDGET_TYPE_CONTACTS_VIEW, WIDGET_TYPE_GADGETS_VIEW, WIDGET_TYPE_NOTES_VIEW, WIDGET_TYPE_MUSIC_VIEW, WIDGET_TYPE_LINKS_VIEW, WIDGET_TYPE_IDENTIFY_FIELD, WIDGET_TYPE_HOTLIST, WIDGET_TYPE_SPACER, WIDGET_TYPE_DOCUMENT_EDIT, WIDGET_TYPE_PANEL_SELECTOR, WIDGET_TYPE_MULTILINE_LABEL, WIDGET_TYPE_SEPARATOR, WIDGET_TYPE_ATTACHMENT_LIST, WIDGET_TYPE_THUMBNAIL, WIDGET_TYPE_ROOT, WIDGET_TYPE_SPEEDDIAL, WIDGET_TYPE_NUMBER_EDIT, WIDGET_TYPE_SLIDER, WIDGET_TYPE_CALENDAR, WIDGET_TYPE_DATETIME, #ifdef PRODUCT_OPTYPEDOBJECT_WIDGET_FILE #include PRODUCT_OPTYPEDOBJECT_WIDGET_FILE #endif // PRODUCT_OPTYPEDOBJECT_WIDGET_FILE //Add new widget types here WIDGET_TYPE_COLOR_MATRIX, WIDGET_TYPE_COLOR_BOX, // Panels must follow here since they are also widgets PANEL_TYPE_WEB, // generic web panel, special case // Panel types must stay in same order.. used to look up their string.. see Hotlist.cpp PANEL_TYPE_FIRST, PANEL_TYPE_BOOKMARKS = PANEL_TYPE_FIRST, PANEL_TYPE_MAIL, PANEL_TYPE_CONTACTS, PANEL_TYPE_HISTORY, PANEL_TYPE_TRANSFERS, PANEL_TYPE_LINKS, PANEL_TYPE_WINDOWS, PANEL_TYPE_CHAT, PANEL_TYPE_INFO, PANEL_TYPE_GADGETS, PANEL_TYPE_NOTES, PANEL_TYPE_MUSIC, PANEL_TYPE_START, PANEL_TYPE_SEARCH, //Add new panel types here #ifdef PRODUCT_OPTYPEDOBJECT_PANEL_FILE #include PRODUCT_OPTYPEDOBJECT_PANEL_FILE #endif // PRODUCT_OPTYPEDOBJECT_PANEL_FILE PANEL_TYPE_LAST, // must come last WIDGET_TYPE_LAST, // this must be last of all widget types (this comes after the panels) WINDOW_TYPE_UNKNOWN, WINDOW_TYPE_DESKTOP, WINDOW_TYPE_DESKTOP_WITH_BROWSER_VIEW, WINDOW_TYPE_BROWSER, WINDOW_TYPE_MAIL_VIEW, WINDOW_TYPE_MAIL_COMPOSE, WINDOW_TYPE_HOTLIST, WINDOW_TYPE_DOCUMENT, WINDOW_TYPE_CHAT, WINDOW_TYPE_CHAT_ROOM, WINDOW_TYPE_HELP, WINDOW_TYPE_UI_BUILDER, WINDOW_TYPE_JAVASCRIPT_CONSOLE, WINDOW_TYPE_PAGE_CYCLER, WINDOW_TYPE_PANEL, WINDOW_TYPE_SOURCE, WINDOW_TYPE_GADGET, WINDOW_TYPE_ACCESSKEY_CYCLER, WINDOW_TYPE_DEVTOOLS, //Add new window types here #ifdef PRODUCT_OPTYPEDOBJECT_WINDOW_FILE #include PRODUCT_OPTYPEDOBJECT_WINDOW_FILE #endif // PRODUCT_OPTYPEDOBJECT_WINDOW_FILE WINDOW_TYPE_LAST, // must be last of window types.. so we can cast something unknown to DesktopWindow based on type DIALOG_TYPE, // must be first of dialog types.. so we can cast something unknown to Dialog based on type DIALOG_TYPE_ACCOUNT_MANAGER, DIALOG_TYPE_ACCOUNT_PROPERTIES, DIALOG_TYPE_ACCOUNT_SUBSCRIPTION, DIALOG_TYPE_AUTHENTICATION, DIALOG_TYPE_PASSWORD, DIALOG_TYPE_CHANGE_NICK, DIALOG_TYPE_ROOM_PASSWORD, DIALOG_TYPE_JOIN_CHAT, DIALOG_TYPE_KICK_CHAT_USER, DIALOG_TYPE_EDIT_ROOM, DIALOG_TYPE_SEARCH_MAIL, DIALOG_TYPE_ERROR, DIALOG_TYPE_BOOKMARK_PROPERTIES, DIALOG_TYPE_CONTACT_PROPERTIES, DIALOG_TYPE_MAIL_INDEX_PROPERTIES, DIALOG_TYPE_STARTUP, DIALOG_TYPE_SIMPLE, DIALOG_TYPE_CUSTOMIZE_TOOLBAR, DIALOG_TYPE_DELETE_MAIL, DIALOG_TYPE_GO_TO_PAGE, DIALOG_TYPE_MAIL_FILTER, DIALOG_TYPE_DOWNLOAD, DIALOG_TYPE_DOWNLOAD_SETUP, DIALOG_TYPE_BOOKMARK_MANAGER, DIALOG_TYPE_CONTACT_MANAGER, DIALOG_TYPE_LINK_MANAGER, DIALOG_TYPE_FILETYPE, DIALOG_TYPE_CLEAR_PRIVATE_DATA, DIALOG_TYPE_SAVE_SESSION, DIALOG_TYPE_IMAGE_PROPERTIES, DIALOG_TYPE_SET_HOMEPAGE, DIALOG_TYPE_PRINT_OPTIONS, DIALOG_TYPE_VALIDATE_SOURCE, DIALOG_TYPE_PREFERENCES, DIALOG_TYPE_INPUT_MANAGER, DIALOG_TYPE_SERVER_MANAGER, DIALOG_TYPE_FIND_TEXT, DIALOG_TYPE_CHANGE_MASTERPASSWORD, DIALOG_TYPE_CERTIFICATE_MANAGER, DIALOG_TYPE_ADD_WEB_LANGUAGE, DIALOG_TYPE_LINK_STYLE, DIALOG_TYPE_INTERNATIONAL_FONTS, DIALOG_TYPE_CERTIFICATE_DETAILS, DIALOG_TYPE_CERTIFICATE_INSTALL, DIALOG_TYPE_PROXY_SERVERS, DIALOG_TYPE_NAME_COMPLETION, DIALOG_TYPE_SECURITY_PROTOCOLS, DIALOG_TYPE_SECURITY_PASSWORD, DIALOG_TYPE_FILE_UPLOAD, DIALOG_TYPE_ASKTEXT, DIALOG_TYPE_COOKIEWARNING, DIALOG_TYPE_ASKCOOKIE, DIALOG_TYPE_POSTINSECURE, DIALOG_TYPE_COOKIE_ERROR, DIALOG_TYPE_SERVER_PROPERTIES, DIALOG_TYPE_FIRST_TIME_SETUP, DIALOG_TYPE_SELECT_FONT, DIALOG_TYPE_MIDCLICK_PREFERENCES, DIALOG_TYPE_WEB_SEARCH, DIALOG_TYPE_PLUGIN_PATH, DIALOG_TYPE_PLUGIN_CHECK, DIALOG_TYPE_PLUGIN_RECOVERY, DIALOG_TYPE_JAVASCRIPT_CONSOLE, DIALOG_TYPE_MODE_MANAGER, DIALOG_TYPE_TRUSTED_PROTOCOL, DIALOG_TYPE_GROUP_PROPERTIES, DIALOG_TYPE_ADD_FILTER, DIALOG_TYPE_KIOSK_RESET, DIALOG_TYPE_REINDEX_MAIL, DIALOG_TYPE_SCRIPT_OPTIONS, DIALOG_TYPE_NEW_ACCOUNT, DIALOG_TYPE_PROFILE, DIALOG_TYPE_SPELL_CHECK, DIALOG_TYPE_PRINT, DIALOG_TYPE_PRINT_PROGRESS, DIALOG_TYPE_FILE_HANDLER, DIALOG_TYPE_EDIT_FILE_HANDLER, DIALOG_TYPE_ADVANCED_VOICE_OPTIONS_obsolete, DIALOG_TYPE_REPORT_SITE_PROBLEM, DIALOG_TYPE_UPGRADE_AVAILABLE, DIALOG_TYPE_NO_UPGRADE_AVAILABLE, DIALOG_TYPE_ERROR_CHECKING_FOR_UPGRADE, DIALOG_TYPE_ADVANCED_WINDOWS_OPTIONS, DIALOG_TYPE_SECURITY_INFORMATION_DIALOG, DIALOG_TYPE_SAVE_ATTACHMENTS, DIALOG_TYPE_LANGUAGE_PREFERENCES, DIALOG_TYPE_DEFAULT_APPLICATION, DIALOG_TYPE_MESSAGE_CONSOLE_DIALOG, DIALOG_TYPE_BITTORRENT_STARTDOWNLOAD, DIALOG_TYPE_BITTORRENT_CONFIGURATION, DIALOG_TYPE_SEARCH_ENGINE_EDIT, #ifdef SUPPORT_VISUAL_ADBLOCK DIALOG_TYPE_CONTENT_BLOCK_ACCEPT, #endif // SUPPORT_VISUAL_ADBLOCK DIALOG_TYPE_GADGET_PROPERTIES, DIALOG_TYPE_MAILER_SELECTION, DIALOG_TYPE_SPEEDDIAL_CONFIG, DIALOG_TYPE_ASK_MAX_MESSAGES_DOWNLOAD, DIALOG_TYPE_MAIL_MESSAGE, DIALOG_TYPE_SYNC_LOGON, DIALOG_TYPE_SYNC_SIGNUP, DIALOG_TYPE_INSTALL_CERT_WIZARD, DIALOG_TYPE_CERT_WARNING, //Add new dialog types here #ifdef PRODUCT_OPTYPEDOBJECT_DIALOG_FILE #include PRODUCT_OPTYPEDOBJECT_DIALOG_FILE #endif // PRODUCT_OPTYPEDOBJECT_DIALOG_FILE DIALOG_TYPE_LAST, // must be last of dialog types.. so we can cast something unknown to Dialog based on type DRAG_TYPE_BOOKMARK, DRAG_TYPE_CONTACT, DRAG_TYPE_NOTE, DRAG_TYPE_HISTORY, DRAG_TYPE_TRANSFER, DRAG_TYPE_WINDOW, DRAG_TYPE_DOCUMENT, DRAG_TYPE_MAIL, DRAG_TYPE_MAIL_INDEX, DRAG_TYPE_LINK, DRAG_TYPE_IMAGE, DRAG_TYPE_BUTTON, DRAG_TYPE_EDIT, DRAG_TYPE_DROPDOWN, DRAG_TYPE_SPACER, DRAG_TYPE_ADDRESS_DROPDOWN, DRAG_TYPE_SEARCH_DROPDOWN, DRAG_TYPE_SEARCH_EDIT, DRAG_TYPE_ZOOM_DROPDOWN, DRAG_TYPE_ACCOUNT_DROPDOWN, DRAG_TYPE_STATUS, DRAG_TYPE_TEXT, DRAG_TYPE_SEPARATOR, DRAG_TYPE_QUICK_FIND, DRAG_TYPE_SPEEDDIAL, DRAG_TYPE_HTML_ELEMENT, #ifdef PRODUCT_OPTYPEDOBJECT_DRAG_FILE #include PRODUCT_OPTYPEDOBJECT_DRAG_FILE #endif // PRODUCT_OPTYPEDOBJECT_DRAG_FILE //Add new drag types here HISTORY_ELEMENT_TYPE, CHATTER_TYPE, CHATROOM_TYPE, ACCOUNT_TYPE, CONNECTION_TYPE, INDEX_FOLDER_TYPE, CHATROOM_SERVER_TYPE, NEWSGROUP_TYPE, NEWSFEED_TYPE, IMAPFOLDER_TYPE, APPLICATION_TYPE, TRANSFER_ELEMENT_TYPE, SEARCHTEMPLATE_TYPE, VIEWER_TYPE, SOUND_TYPE, PREFERENCE_TYPE, IMPORT_IDENTITY_TYPE, IMPORT_ACCOUNT_TYPE, IMPORT_FOLDER_TYPE, IMPORT_MAILBOX_TYPE, PLUGINVIEWER_TYPE, COOKIE_TYPE, SERVER_TYPE, WAND_TYPE, EMBEDDED_CONTENT_TYPE }; virtual Type GetType() = 0; virtual INT32 GetID() = 0; // getting a new unique ID static INT32 GetUniqueID(); virtual ~OpTypedObject(){} }; // --------------------------------------------------------------------------------- #endif // !MODULES_UTIL_OPTYPEDOBJECT_H
#include "visitor.hpp" using namespace visitor; /* * The tree of boredom. */ void install(Graph & g) { g.clear(); boost::add_vertex(g); boost::add_vertex(g); boost::add_vertex(g); boost::add_vertex(g); boost::add_vertex(g); boost::add_vertex(g); boost::add_edge(0, 1, g); boost::add_edge(0, 2, g); boost::add_edge(1, 3, g); boost::add_edge(1, 4, g); boost::add_edge(2, 5, g); boost::add_edge(2, 6, g); } std::vector<Slots> slots(void) { std::vector<Slots> ss(7); ss[0].push_back(Slot(0,0)); ss[1].push_back(Slot(0,1)); ss[2].push_back(Slot(2,1)); ss[3].push_back(Slot(0,2)); ss[4].push_back(Slot(1,2)); ss[5].push_back(Slot(2,2)); ss[6].push_back(Slot(3,2)); return ss; }
/**/ #include<stdio.h> #include<conio.h> void Arrange(int*, int); void Swap(int*, int, int, int); void main(){ int size; int a[100]; scanf_s("%d", &size); for (int i = 0; i < size; i++) { int temp; scanf_s("%d", &temp); if (temp != 0 && temp != 1) { printf("you have to enter 1 or 0 ! just as a remainder"); i--; continue; } else a[i] = temp; } Arrange(a, size); for (int i = 0; i < size; i++) printf("%d", a[i]); _getch(); } void Swap(int *ap, int size, int i, int j){ int temp; temp = ap[i]; ap[i] = ap[j]; ap[j] = temp; } void Arrange(int *ap, int size){ int i = 0; int j = size - 1; while (i<j){ if (ap[i] == 0)i++; if (ap[j] == 1)j--; if (ap[i] != 0 && ap[j] != 1){ Swap(ap, size, i, j); i++; j--; } } }
#include "MyApp.h" //точка входа int CALLBACK wWinMain(HINSTANCE, HINSTANCE, PWSTR, int) { MyApp app; return app.Run(); }
/* * File: BinaryExpression.h * Author: idox * * Created on December 17, 2018, 8:43 PM */ #ifndef PROJECTPART1_BINARYEXPRESSION_H #define PROJECTPART1_BINARYEXPRESSION_H #include "Expression.h" /** * Binary expressions is any type of binary operation which could hold two * autonomous expressions, and make calculations with them. */ class BinaryExpression : public Expression{ public: Expression* left; Expression* right; virtual void set(Expression*, Expression*); virtual double calculate() = 0; virtual ~BinaryExpression(){ delete (left); delete (right); }; }; #endif //PROJECTPART1_BINARYEXPRESSION_H
#include "vector.h" Vector::Vector() { this->x = 0; this->y = 0; this->z = 0; } Vector::Vector(Point& p1, Point& p2) { this->x = p2.getX() - p1.getX(); this->y = p2.getY() - p1.getY(); this->z = p2.getZ() - p1.getZ(); } Vector::Vector(double x, double y, double z) { this->x = x; this->y = y; this->z = z; } Vector::Vector(const Vector& v2) { Vector& v1 = *this; v1.x = v2.x; v1.y = v2.y; v1.z = v2.z; } //Operations //Addition Vector Vector::operator +(const Vector& v3) { Vector v1; Vector& v2 = *this; v1.x = v2.x + v3.x; v1.y = v2.y + v3.y; v1.z = v2.z + v3.z; return v1; } //Substraction Vector Vector::operator -(const Vector& v3) { Vector v1; Vector& v2 = *this; v1.x = v2.x - v3.x; v1.y = v2.y - v3.y; v1.z = v2.z - v3.z; return v1; } //Scalar multiplication Vector Vector::operator *(double a) { double x = this->x * a; double y = this->y * a; double z = this->z * a; return Vector(x, y, z); } //Dot product double Vector::operator *(const Vector& v2) { Vector& v1 = *this; return ((v1.x * v2.x) + (v1.y * v2.y) + (v1.z * v2.z)); } //Cross product Vector Vector::operator ^(const Vector& v2) { Vector& v1 = *this; double x = v1.y * v2.z - v1.z * v2.y; double y = v1.z * v2.x - v1.x * v2.z; double z = v1.x * v2.y - v1.y * v2.x; return Vector(x, y, z); } //Mixed product double Vector::operator()(Vector& v2, Vector& v3) { Vector& v1 = *this; return v1 * (v2 ^ v3); } //Methods double Vector::length() { return sqrt((this->x * this->x) + (this->y * this->y) + (this->z * this->z)); } Vector Vector::getDirection() { Vector& v1 = *this; double len = v1.length(); if (!len) { throw VLE(); } double x = v1.x / len; double y = v1.y / len; double z = v1.z / len; return Vector(x, y, z); } bool Vector::isNull() { Vector& v1 = *this; return (x == 0) && (y == 0) && (z == 0); //return (v1.getX() == v1.getY() == v1.getZ() == 0); } bool Vector::paralellismCheck(Vector& v2) { Vector& v1 = *this; if ( (!v1.length()) || (!v2.length()) ) { throw VLE(); } return ((v1.x / v2.x) == (v1.y / v2.y) == (v1.z / v2.z)); } bool Vector::ortogonalityCheck(Vector& v2) { Vector& v1 = *this; if ( (v1.isNull()) || (v2.isNull()) ) { throw VLE(); } return (v1 * v2) == 0; } std::ostream& operator <<(std::ostream& out, const Vector& v1) { out << '(' << v1.x << ',' << v1.y << ',' << v1.z << ')'; return out; }
// Homework5View.h : interface of the CHomework5View class // #pragma once class CHomework5View : public CView { protected: // create from serialization only CHomework5View() noexcept; DECLARE_DYNCREATE(CHomework5View) // Attributes public: CHomework5Doc* GetDocument() const; // Operations public: // Overrides public: virtual void OnDraw(CDC* pDC); // overridden to draw this view virtual BOOL PreCreateWindow(CREATESTRUCT& cs); protected: // Implementation public: virtual ~CHomework5View(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: DECLARE_MESSAGE_MAP() public: virtual void OnInitialUpdate(); void ImageFormation(); void cheeryFormation(); afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); afx_msg void OnTimer(UINT_PTR nIDEvent); void displaymessage(); void calltimer(); }; #ifndef _DEBUG // debug version in Homework5View.cpp inline CHomework5Doc* CHomework5View::GetDocument() const { return reinterpret_cast<CHomework5Doc*>(m_pDocument); } #endif
/*************************************************************************** * * Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved * B142877 * **************************************************************************/ /** * @file dfile_lib.cpp * @author liuxufeng (liuxufeng@baidu.com) * @date 2017/05/27 21:01:11 * @version 1.0.0-alpha * @brief * 提供基于文件类的数据处理,例如svm格式转换,或者按列分析等 **/ #include <iostream> #include <fstream> #include <vector> int split_str(std::string src, std::string seps, std::vector<std::string>& dest); int mat2svm(std::string filename, std::string outfile="", const bool header=false, std::string sep="\t", std::string out_sep="\t", std::string filter="0"){ // ignore header if header exists std::ifstream fin(filename); if (fin.fail()){ std::cout << "Fail to open file: " << filename << std::endl; return -1; } if (fin.fail()){ std::cout << "Fail to create output file: " << outfile << std::endl; } if (outfile == ""){ outfile = filename; outfile.append(".svm"); std::cout << "WARN: svm outfile is not set, and use default: " << outfile << std::endl; } std::ofstream fout(outfile); std::string line; std::vector<std::string> items; int col_num = 0; float * data; int total_size = 0; while(!fin.eof()){ items.clear(); std::getline(fin, line); // std::cout << line << std::endl; split_str(line, sep, items); col_num = items.size(); fout << items[0]; for(int i=1; i<col_num; i++){ fout << out_sep; fout << i << ":" << items[i]; } fout << std::endl; total_size += 1; } fin.close(); fout.close(); std::cout << "total lines: " << total_size << std::endl; return 0; } int split_str(std::string src, std::string seps, std::vector<std::string>& dest){ // 用多个字符来分割字符串,填入分割后的字符串的vector向量,返回vector向量的长度 std::string::size_type pos; src += seps; int size = src.size(); for(int i = 0; i < size; i++){ pos = src.find(seps, i); if (pos < size){ std::string s = src.substr(i, pos - i); dest.push_back(s); i = pos + seps.size() - 1; } } return dest.size(); } int main(int argc, char * argv []){ if (argc < 2){ std::cout << "usage: ./mat2svm mat_file svm_file" << std::endl; return -1; } std::string filename = argv[1]; std::string outfile; if(argc == 2){ outfile = ""; }else{ outfile = argv[2]; } std::cout << "input: " << filename.c_str() << std::endl; std::cout << "output: " << outfile.c_str() << std::endl; int ret = mat2svm(filename, outfile); return 0; }
#include <bhand/robot_hand.h> #include <stdexcept> #include <sstream> #include <chrono> #include <map> #include <stack> #include <ros/package.h> #include <kdl_parser/kdl_parser.hpp> namespace as64_ { namespace bhand_ { RobotHand::RobotHand() { std::string robot_description_name; if (!node.getParam("/bhand_robot/robot_description_name",robot_description_name)) { throw std::runtime_error("[RobotHand Error]: Failed to load parameter \"/bhand_robot/robot_description_name\" ...\n"); } if (!node.getParam("/bhand_robot/base_frame",base_link_name)) { throw std::runtime_error("[RobotHand Error]: Failed to load parameter \"/bhand_robot/base_frame\" ...\n"); } if (!node.getParam("/bhand_robot/tool_frame",tool_link_name)) { throw std::runtime_error("[RobotHand Error]: Failed to load parameter \"/bhand_robot/tool_frame\" ...\n"); } if (!node.getParam("/bhand_robot/ctrl_cycle",ctrl_cycle)) { ctrl_cycle = 0.01; } if (!node.getParam("/bhand_robot/check_limits",check_limits)) { check_limits = false; } if (!node.getParam("/bhand_robot/check_singularity",check_singularity)) { check_singularity = false; } if (!urdf_model.initParam(robot_description_name.c_str())) { throw std::ios_base::failure("[RobotHand Error]: Couldn't load urdf model from \"" + robot_description_name + "\"...\n"); } init(); } RobotHand::RobotHand(urdf::Model &urdf_model, const std::string &base_link, const std::vector<std::string> &tool_link, double ctrl_cycle) { this->urdf_model = urdf_model; this->base_link_name = base_link; this->tool_link_name = tool_link; this->ctrl_cycle = ctrl_cycle; this->check_limits = false; this->check_singularity = false; init(); } RobotHand::RobotHand(const std::string &robot_desc_param, const std::string &base_link, const std::vector<std::string> &tool_link, double ctrl_cycle) { if (!urdf_model.initParam(robot_desc_param.c_str())) { throw std::ios_base::failure("Couldn't load urdf model from \"" + robot_desc_param + "\"...\n"); } this->base_link_name = base_link; this->tool_link_name = tool_link; this->ctrl_cycle = ctrl_cycle; this->check_limits = false; this->check_singularity = false; init(); } RobotHand::~RobotHand() {} void RobotHand::init() { mode_name[bhand_::IDLE] = "IDLE"; mode_name[bhand_::FREEDRIVE] = "FREEDRIVE"; mode_name[bhand_::JOINT_POS_CONTROL] = "JOINT_POS_CONTROL"; mode_name[bhand_::JOINT_VEL_CONTROL] = "JOINT_VEL_CONTROL"; mode_name[bhand_::CART_VEL_CONTROL] = "CART_VEL_CONTROL"; mode_name[bhand_::PROTECTIVE_STOP] = "PROTECTIVE_STOP"; mode = bhand_::Mode::IDLE; N_fingers = tool_link_name.size(); fingers.resize(N_fingers); for (int i=0; i<N_fingers; i++) fingers[i].reset(new KinematicChain(urdf_model, base_link_name, tool_link_name[i])); for (int i=0; i<N_fingers; i++) { for (int j=0; j<fingers[i]->joint_names.size(); j++) joint_names.push_back(fingers[i]->joint_names[j]); for (int j=0; j<fingers[i]->joint_pos_lower_lim.size(); j++) joint_pos_lower_lim.push_back(fingers[i]->joint_pos_lower_lim[j]); for (int j=0; j<fingers[i]->joint_pos_upper_lim.size(); j++) joint_pos_upper_lim.push_back(fingers[i]->joint_pos_upper_lim[j]); for (int j=0; j<fingers[i]->joint_vel_lim.size(); j++) joint_vel_lim.push_back(fingers[i]->joint_vel_lim[j]); for (int j=0; j<fingers[i]->effort_lim.size(); j++) effort_lim.push_back(fingers[i]->effort_lim[j]); } // preallocate space for all states N_JOINTS = joint_names.size(); joint_pos.zeros(N_JOINTS); prev_joint_pos.zeros(N_JOINTS); N_fingers = tool_link_name.size(); fingers.resize(N_fingers); } bool RobotHand::isOk() const { return getMode()!=bhand_::Mode::PROTECTIVE_STOP; } void RobotHand::setJointLimitCheck(bool check) { check_limits = check; } void RobotHand::enable() { setMode(bhand_::Mode::IDLE); joint_pos = getJointsPosition(); prev_joint_pos = joint_pos; update(); } std::string RobotHand::getErrMsg() const { return err_msg; } void RobotHand::addJointState(sensor_msgs::JointState &joint_state_msg) { std::unique_lock<std::mutex> lck(robot_state_mtx); arma::vec j_pos = getJointsPosition(); arma::vec j_vel = getJointsVelocity(); for (int i=0;i<N_JOINTS;i++) { joint_state_msg.name.push_back(joint_names[i]); joint_state_msg.position.push_back(j_pos(i)); joint_state_msg.velocity.push_back(j_vel(i)); joint_state_msg.effort.push_back(0.0); } } double RobotHand::getCtrlCycle() const { return ctrl_cycle; } bhand_::Mode RobotHand::getMode() const { return mode; } std::string RobotHand::getModeName(Mode mode) const { return (mode_name.find(mode))->second; } int RobotHand::getNumJoints() const { return N_JOINTS; } bool RobotHand::setJointsTrajectory(const arma::vec &j_targ, double duration) { // keep last known robot mode bhand_::Mode prev_mode = getMode(); // initialize position arma::vec q0 = getJointsPosition(); arma::vec qref = q0; // initalize time double t = 0.0; double Ts = getCtrlCycle(); // start conttroller setMode(bhand_::Mode::JOINT_POS_CONTROL); while (isOk() && getMode()!=bhand_::Mode::IDLE && t<duration) { update(); t += Ts; qref = get5thOrder(t, q0, j_targ, duration)[0]; setJointsPosition(qref); } bool reached_target = t>=duration; if (isOk() && getMode()==bhand_::Mode::JOINT_POS_CONTROL) setMode(prev_mode); return reached_target; } void RobotHand::setJointsPositionHelper(const arma::vec &j_pos) { arma::vec current_j_pos = joint_pos; // getJointsPosition(); arma::vec dj_pos = (j_pos - current_j_pos) / ctrl_cycle; if (check_limits) { if (!checkJointPosLimits(j_pos)) return; if (!checkJointVelLimits(dj_pos)) return; } std::unique_lock<std::mutex> lck(robot_state_mtx); prev_joint_pos = current_j_pos; joint_pos = j_pos; } void RobotHand::setJointsVelocityHelper(const arma::vec &j_vel) { setJointsPositionHelper(getJointsPosition() + j_vel*ctrl_cycle); } void RobotHand::setTaskVelocityHelper(bhand_::ChainName &chain_name, const arma::vec &task_vel) { setJointsVelocityHelper(arma::solve(getJacobian(chain_name),task_vel)); } arma::vec RobotHand::getJointsPosition() const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return joint_pos; } arma::vec RobotHand::getJointsVelocity() const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return (joint_pos - prev_joint_pos)/getCtrlCycle(); } arma::mat RobotHand::getTaskPose(bhand_::ChainName &chain_name) const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return getTaskPose(chain_name, getJointsPosition()); } arma::mat RobotHand::getTaskPose(bhand_::ChainName &chain_name, const arma::vec &j_pos) const { return fingers[(int)chain_name]->getTaskPose(j_pos); } arma::vec RobotHand::getTaskPosition(bhand_::ChainName &chain_name) const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return getTaskPose(chain_name).submat(0,3,2,3); } arma::vec RobotHand::getTaskOrientation(bhand_::ChainName &chain_name) const { // std::unique_lock<std::mutex> lck(robot_state_mtx); arma::mat R = getTaskPose(chain_name).submat(0,0,2,2); arma::vec quat = rotm2quat(R); return quat; } arma::mat RobotHand::getJacobian(bhand_::ChainName &chain_name) const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return getJacobian(chain_name, getJointsPosition()); } arma::mat RobotHand::getJacobian(bhand_::ChainName &chain_name, const arma::vec &j_pos) const { return fingers[(int)chain_name]->getJacobian(j_pos); } arma::mat RobotHand::getEEJacobian(bhand_::ChainName &chain_name) const { // std::unique_lock<std::mutex> lck(robot_state_mtx); arma::mat R = getTaskPose(chain_name).submat(0,0,2,2); arma::mat Jrobot = getJacobian(chain_name); int n_joints = fingers[(int)chain_name]->getNumJoints(); arma::mat Jee(6, n_joints); Jee.submat(0,0,2,n_joints-1) = R * Jrobot.submat(0,0,2,n_joints-1); Jee.submat(3,0,5,n_joints-1) = R * Jrobot.submat(3,0,5,n_joints-1); return Jee; } arma::vec RobotHand::getJointsTorque() const { // std::unique_lock<std::mutex> lck(robot_state_mtx); return arma::vec().zeros(N_JOINTS); } bool RobotHand::checkJointPosLimits(const arma::vec &j_pos) { for (int i=0;i<N_JOINTS;i++) { if (j_pos(i)>joint_pos_upper_lim[i] || j_pos(i)<joint_pos_lower_lim[i]) { std::ostringstream out; out << joint_names[i] << ": position limit reached: " << j_pos(i) << " rad"; err_msg = out.str(); // print_err_msg(err_msg); setMode(bhand_::Mode::PROTECTIVE_STOP); return false; } } return true; } bool RobotHand::checkJointVelLimits(const arma::vec &dj_pos) { for (int i=0;i<N_JOINTS;i++) { if (std::fabs(dj_pos(i))>joint_vel_lim[i]) { std::ostringstream out; out << joint_names[i] << ": velocity limit reached: " << dj_pos(i) << " rad/s"; err_msg = out.str(); // print_err_msg(err_msg); setMode(bhand_::Mode::PROTECTIVE_STOP); return false; } } return true; } }; // namespace bhand_ }; // namespace as64_
/** \class RPCEfficiencySecond * \Original author Camilo Carrillo (Uniandes) */ #include <DataFormats/MuonDetId/interface/RPCDetId.h> #include "FWCore/ServiceRegistry/interface/Service.h" #include "DQMServices/Core/interface/MonitorElement.h" #include "DQMServices/Core/interface/DQMStore.h" #include "DQMServices/Core/interface/DQMEDHarvester.h" #include <Geometry/RPCGeometry/interface/RPCGeometry.h> #include <Geometry/RPCGeometry/interface/RPCGeomServ.h> #include "FWCore/Framework/interface/ESHandle.h" #include <string> #include <map> #include <fstream> class RPCEfficiencySecond : public DQMEDHarvester { public: explicit RPCEfficiencySecond(const edm::ParameterSet &); ~RPCEfficiencySecond() override; int rollY(std::string shortname, const std::vector<std::string> &rollNames); protected: void beginJob() override; void dqmEndLuminosityBlock(DQMStore::IBooker &, DQMStore::IGetter &, edm::LuminosityBlock const &, edm::EventSetup const &) override; //performed in the endLumi void dqmEndJob(DQMStore::IBooker &, DQMStore::IGetter &) override; //performed in the endJob private: void myBooker(DQMStore::IBooker &); //Histograms to use MonitorElement *histoRPC; MonitorElement *histoDT; MonitorElement *histoRealRPC; MonitorElement *histoCSC; MonitorElement *histoPRO; MonitorElement *histoeffIdRPC_DT; MonitorElement *histoeffIdRPC_CSC; //For Duplication MonitorElement *histoRPC2; MonitorElement *histoDT2; MonitorElement *histoRealRPC2; MonitorElement *histoCSC2; // MonitorElement * BXDistribution2; //Eff Global Barrel MonitorElement *EffGlobW[5]; //Eff Distro Barrel MonitorElement *EffDistroW[5]; //Eff Global EndCap MonitorElement *EffGlobD[10]; //EffDistro EndCap MonitorElement *EffDistroD[10]; //Summary Histograms. MonitorElement *WheelSummary[5]; MonitorElement *DiskSummary[10]; //Azimultal Plots MonitorElement *sectorEffW[5]; MonitorElement *OcsectorEffW[5]; MonitorElement *ExsectorEffW[5]; MonitorElement *GregR2D[10]; MonitorElement *GregR3D[10]; MonitorElement *OcGregR2D[10]; MonitorElement *OcGregR3D[10]; MonitorElement *ExGregR2D[10]; MonitorElement *ExGregR3D[10]; MonitorElement *ExpLayerW[5]; MonitorElement *ObsLayerW[5]; edm::ESHandle<RPCGeometry> rpcGeo_; std::map<int, std::map<std::string, MonitorElement *> > meCollection; bool init_; std::string folderPath; int numberOfDisks_; int innermostRings_; };
#include <iostream> #include <cstdio> #include <stack> #include <math.h> #include <cstdlib> using namespace std; int main(){ int q,num1; stack<int>st; cin >> q; //if(1 <= q && q <= pow(10,5)) // exit(0); while(q--){ cin >> num1; if(num1 == 1){ if(st.empty()){ cout << "No Food"<<"\n"; } else{ int x = st.top(); st.pop(); cout << x << "\n"; } } if(num1 == 2){ int x; cin >> x; st.push(x); } } return 0; }
// // ByteOrder.h // // $Id: //poco/1.4/Foundation/include/_/ByteOrder.h#5 $ // // Library: Foundation // Package: Core // Module: ByteOrder // // Copyright (c) 2004-2014, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Foundation_ByteOrder_INCLUDED #define Foundation_ByteOrder_INCLUDED #include "_.h" #include "_/Types.h" #if defined(_MSC_VER) #include <stdlib.h> // builtins #endif namespace _ { class __API ByteOrder /// This class contains a number of static methods /// to convert between big-endian and little-endian /// integers of various sizes. { public: static Int16 flipBytes(Int16 value); static UInt16 flipBytes(UInt16 value); static Int32 flipBytes(Int32 value); static UInt32 flipBytes(UInt32 value); static float flipBytes(float value); static double flipBytes(double value); #if defined(___HAVE_INT64) static Int64 flipBytes(Int64 value); static UInt64 flipBytes(UInt64 value); #endif static Int16 toBigEndian(Int16 value); static UInt16 toBigEndian (UInt16 value); static Int32 toBigEndian(Int32 value); static UInt32 toBigEndian (UInt32 value); #if defined(___HAVE_INT64) static Int64 toBigEndian(Int64 value); static UInt64 toBigEndian (UInt64 value); #endif static Int16 fromBigEndian(Int16 value); static UInt16 fromBigEndian (UInt16 value); static Int32 fromBigEndian(Int32 value); static UInt32 fromBigEndian (UInt32 value); #if defined(___HAVE_INT64) static Int64 fromBigEndian(Int64 value); static UInt64 fromBigEndian (UInt64 value); #endif static Int16 toLittleEndian(Int16 value); static UInt16 toLittleEndian (UInt16 value); static Int32 toLittleEndian(Int32 value); static UInt32 toLittleEndian (UInt32 value); #if defined(___HAVE_INT64) static Int64 toLittleEndian(Int64 value); static UInt64 toLittleEndian (UInt64 value); #endif static Int16 fromLittleEndian(Int16 value); static UInt16 fromLittleEndian (UInt16 value); static Int32 fromLittleEndian(Int32 value); static UInt32 fromLittleEndian (UInt32 value); #if defined(___HAVE_INT64) static Int64 fromLittleEndian(Int64 value); static UInt64 fromLittleEndian (UInt64 value); #endif static Int16 toNetwork(Int16 value); static UInt16 toNetwork (UInt16 value); static Int32 toNetwork(Int32 value); static UInt32 toNetwork (UInt32 value); #if defined(___HAVE_INT64) static Int64 toNetwork(Int64 value); static UInt64 toNetwork (UInt64 value); #endif static Int16 fromNetwork(Int16 value); static UInt16 fromNetwork (UInt16 value); static Int32 fromNetwork(Int32 value); static UInt32 fromNetwork (UInt32 value); #if defined(___HAVE_INT64) static Int64 fromNetwork(Int64 value); static UInt64 fromNetwork (UInt64 value); #endif private: template<typename T> static T flip(T value) { T flip = value; std::size_t halfSize = sizeof(T) / 2; char* flipP = reinterpret_cast<char*>(&flip); for (std::size_t i = 0; i < halfSize; i++) { std::swap(flipP[i], flipP[sizeof(T) - i - 1]); } return flip; } }; #if !defined(___NO_BYTESWAP_BUILTINS) #if defined(_MSC_VER) #if (___MSVC_VERSION > 71) #define ___HAVE_MSC_BYTESWAP 1 #endif #elif defined(__clang__) #if __has_builtin(__builtin_bswap32) #define ___HAVE_GCC_BYTESWAP 1 #endif #elif defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) #define ___HAVE_GCC_BYTESWAP 1 #endif #endif // // inlines // inline UInt16 ByteOrder::flipBytes(UInt16 value) { #if defined(___HAVE_MSC_BYTESWAP) return _byteswap_ushort(value); #else return ((value >> 8) & 0x00FF) | ((value << 8) & 0xFF00); #endif } inline Int16 ByteOrder::flipBytes(Int16 value) { return Int16(flipBytes(UInt16(value))); } inline UInt32 ByteOrder::flipBytes(UInt32 value) { #if defined(___HAVE_MSC_BYTESWAP) return _byteswap_ulong(value); #elif defined(___HAVE_GCC_BYTESWAP) return __builtin_bswap32(value); #else return ((value >> 24) & 0x000000FF) | ((value >> 8) & 0x0000FF00) | ((value << 8) & 0x00FF0000) | ((value << 24) & 0xFF000000); #endif } inline Int32 ByteOrder::flipBytes(Int32 value) { return Int32(flipBytes(UInt32(value))); } inline float ByteOrder::flipBytes(float value) { return flip(value); } inline double ByteOrder::flipBytes(double value) { return flip(value); } #if defined(___HAVE_INT64) inline UInt64 ByteOrder::flipBytes(UInt64 value) { #if defined(___HAVE_MSC_BYTESWAP) return _byteswap_uint64(value); #elif defined(___HAVE_GCC_BYTESWAP) return __builtin_bswap64(value); #else UInt32 hi = UInt32(value >> 32); UInt32 lo = UInt32(value & 0xFFFFFFFF); return UInt64(flipBytes(hi)) | (UInt64(flipBytes(lo)) << 32); #endif } inline Int64 ByteOrder::flipBytes(Int64 value) { return Int64(flipBytes(UInt64(value))); } #endif // ___HAVE_INT64 // // some macro trickery to automate the method implementation // #define ___IMPLEMENT_BYTEORDER_NOOP_(op, type) \ inline type ByteOrder::op(type value) \ { \ return value; \ } #define ___IMPLEMENT_BYTEORDER_FLIP_(op, type) \ inline type ByteOrder::op(type value) \ { \ return flipBytes(value); \ } #if defined(___HAVE_INT64) #define ___IMPLEMENT_BYTEORDER_NOOP(op) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, Int64) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, UInt64) #define ___IMPLEMENT_BYTEORDER_FLIP(op) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, Int64) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, UInt64) #else #define ___IMPLEMENT_BYTEORDER_NOOP(op) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, Int16) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, UInt16) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, Int32) \ ___IMPLEMENT_BYTEORDER_NOOP_(op, UInt32) #define ___IMPLEMENT_BYTEORDER_FLIP(op) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, Int16) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, UInt16) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, Int32) \ ___IMPLEMENT_BYTEORDER_FLIP_(op, UInt32) #endif #if defined(___ARCH_BIG_ENDIAN) #define ___IMPLEMENT_BYTEORDER_BIG ___IMPLEMENT_BYTEORDER_NOOP #define ___IMPLEMENT_BYTEORDER_LIT ___IMPLEMENT_BYTEORDER_FLIP #else #define ___IMPLEMENT_BYTEORDER_BIG ___IMPLEMENT_BYTEORDER_FLIP #define ___IMPLEMENT_BYTEORDER_LIT ___IMPLEMENT_BYTEORDER_NOOP #endif ___IMPLEMENT_BYTEORDER_BIG(toBigEndian) ___IMPLEMENT_BYTEORDER_BIG(fromBigEndian) ___IMPLEMENT_BYTEORDER_BIG(toNetwork) ___IMPLEMENT_BYTEORDER_BIG(fromNetwork) ___IMPLEMENT_BYTEORDER_LIT(toLittleEndian) ___IMPLEMENT_BYTEORDER_LIT(fromLittleEndian) } // namespace _ #endif // Foundation_ByteOrder_INCLUDED
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. * */ #ifndef I18N_H #define I18N_H #include "modules/locale/locale-enum.h" /** @brief Utilities for formatting translated strings * In general our strings can have specifiers in them in the form %1, %2, %3 that * allow us to replace these strings with alternative content at runtime. * %1, %2, %3 etc. stand for first argument, second argument, third argument * but can occur in any order in the actual string. * * As an example, an English string might say * "Are you sure you want to delete %1 items from %2?", 5, "trash" * * In other languages %1 and %2 might be reversed, but they still would need * to be replaced by the correct string. */ class I18n { public: // Maximum number of arguments for the formatting functions static const size_t MaxArguments = 5; /** Format a string * @param formatted On success, contains the formatted string * @note if there is existing content, the formatted string will be appended * @param format A format string with substitutions like %1, %2 etc up to MaxArguments * @param arg1, ... Replacements for placeholders, where arg1 replaces '%1', arg2 replaces '%2', etc. * @return See OpStatus * * @example usage * OpString formatted; * I18n::Format(formatted, UNI_L("Delete %1 items from %2"), 5, UNI_L("Trash")); * Results in the string "Delete 5 items from Trash" in formatted * * @note These functions are type-safe. If your argument is of a type that is not supported by this * implementation, you will get a compile error stating that * I18n::FormatArgument(const FormatArgument* next, X arg) does not exist for type X. */ template<class T1, class T2, class T3, class T4, class T5> static OP_STATUS Format(OpString& formatted, OpStringC format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4, const T5& arg5) { return Format(NULL, formatted, format.CStr(), arg1, arg2, arg3, arg4, arg5); } template<class T1, class T2, class T3, class T4> static OP_STATUS Format(OpString& formatted, OpStringC format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4) { return Format(NULL, formatted, format.CStr(), arg1, arg2, arg3, arg4); } template<class T1, class T2, class T3> static OP_STATUS Format(OpString& formatted, OpStringC format, const T1& arg1, const T2& arg2, const T3& arg3) { return Format(NULL, formatted, format.CStr(), arg1, arg2, arg3); } template<class T1, class T2> static OP_STATUS Format(OpString& formatted, OpStringC format, const T1& arg1, const T2& arg2) { return Format(NULL, formatted, format.CStr(), arg1, arg2); } template<class T1> static OP_STATUS Format(OpString& formatted, OpStringC format, const T1& arg1) { return Format(NULL, formatted, format.CStr(), arg1); } static OP_STATUS Format(OpString& formatted, OpStringC format) { return Format(NULL, formatted, format.CStr()); } /** @overload Overloads for use with string IDs instead of strings as input format */ template<class T1, class T2, class T3, class T4, class T5> static OP_STATUS Format(OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4, const T5& arg5) { return Format(NULL, formatted, format, arg1, arg2, arg3, arg4, arg5); } template<class T1, class T2, class T3, class T4> static OP_STATUS Format(OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4) { return Format(NULL, formatted, format, arg1, arg2, arg3, arg4); } template<class T1, class T2, class T3> static OP_STATUS Format(OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3) { return Format(NULL, formatted, format, arg1, arg2, arg3); } template<class T1, class T2> static OP_STATUS Format(OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2) { return Format(NULL, formatted, format, arg1, arg2); } template<class T1> static OP_STATUS Format(OpString& formatted, Str::LocaleString format, const T1& arg1) { return Format(NULL, formatted, format, arg1); } static OP_STATUS Format(OpString& formatted, Str::LocaleString format) { return Format(NULL, formatted, format); } private: enum FormattingType { FORMAT_INT32, FORMAT_UINT32, FORMAT_STRING, FORMAT_STRING_ID }; struct FormatArgument { FormatArgument(const FormatArgument* next, INT8 arg) : next(next), format(FORMAT_INT32), argument_int(arg) {} FormatArgument(const FormatArgument* next, INT16 arg) : next(next), format(FORMAT_INT32), argument_int(arg) {} FormatArgument(const FormatArgument* next, INT32 arg) : next(next), format(FORMAT_INT32), argument_int(arg) {} FormatArgument(const FormatArgument* next, UINT8 arg) : next(next), format(FORMAT_UINT32), argument_uint(arg) {} FormatArgument(const FormatArgument* next, UINT16 arg) : next(next), format(FORMAT_UINT32), argument_uint(arg) {} FormatArgument(const FormatArgument* next, UINT32 arg) : next(next), format(FORMAT_UINT32), argument_uint(arg) {} FormatArgument(const FormatArgument* next, const uni_char* arg) : next(next), format(FORMAT_STRING), argument_string(arg) {} FormatArgument(const FormatArgument* next, OpStringC arg) : next(next), format(FORMAT_STRING), argument_string(arg.CStr()) {} FormatArgument(const FormatArgument* next, Str::LocaleString arg) : next(next), format(FORMAT_STRING_ID), argument_string_id(arg) {} const FormatArgument* next; FormattingType format; union { INT32 argument_int; UINT32 argument_uint; const uni_char* argument_string; int argument_string_id; }; private: // Private constructors with no implementation: we can't handle these types. Use (smaller) integers instead. FormatArgument(const FormatArgument* next, bool arg); FormatArgument(const FormatArgument* next, double arg); FormatArgument(const FormatArgument* next, INT64 arg); FormatArgument(const FormatArgument* next, UINT64 arg); }; // boilerplate code in the form of inline template functions to handle the different arguments and argument types template<class T1, class T2, class T3, class T4, class T5> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4, const T5& arg5) { FormatArgument arg(argument, arg5); return Format(&arg, formatted, format, arg1, arg2, arg3, arg4); } template<class T1, class T2, class T3, class T4> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4) { FormatArgument arg(argument, arg4); return Format(&arg, formatted, format, arg1, arg2, arg3); } template<class T1, class T2, class T3> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format, const T1& arg1, const T2& arg2, const T3& arg3) { FormatArgument arg(argument, arg3); return Format(&arg, formatted, format, arg1, arg2); } template<class T1, class T2> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format, const T1& arg1, const T2& arg2) { FormatArgument arg(argument, arg2); return Format(&arg, formatted, format, arg1); } template<class T1> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format, const T1& arg1) { FormatArgument arg(argument, arg1); return Format(&arg, formatted, format); } template<class T1, class T2, class T3, class T4, class T5> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4, const T5& arg5) { FormatArgument arg(argument, arg5); return Format(&arg, formatted, format, arg1, arg2, arg3, arg4); } template<class T1, class T2, class T3, class T4> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3, const T4& arg4) { FormatArgument arg(argument, arg4); return Format(&arg, formatted, format, arg1, arg2, arg3); } template<class T1, class T2, class T3> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2, const T3& arg3) { FormatArgument arg(argument, arg3); return Format(&arg, formatted, format, arg1, arg2); } template<class T1, class T2> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format, const T1& arg1, const T2& arg2) { FormatArgument arg(argument, arg2); return Format(&arg, formatted, format, arg1); } template<class T1> static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format, const T1& arg1) { FormatArgument arg(argument, arg1); return Format(&arg, formatted, format); } // Actual functions that do the formatting static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, const uni_char* format); static OP_STATUS Format(const FormatArgument* argument, OpString& formatted, Str::LocaleString format); }; #endif // I18N_H
#include "CollidableModel.h" CollidableModel :: CollidableModel() { } void CollidableModel::SetBoundingBox(AABoundingBox fBoundingBox) { boundingBox = fBoundingBox; } AABoundingBox CollidableModel::GetBoundingBox() { return boundingBox; } AABoundingBox CollidableModel::CalculateBoundingBox(vector<glm::vec3> vertices) { glm::vec3 minCoord = glm::vec3(9999, 9999, 9999), maxCoord = glm::vec3(-9999, -9999, -9999); for (int i = 0;i < vertices.size();i++) { for (int j = 0;j < 3;j++) { if (vertices[i][j] < minCoord[j]) { minCoord[j] = vertices[i][j]; } if (vertices[i][j] > maxCoord[j]) { maxCoord[j] = vertices[i][j]; } } } AABoundingBox temp(minCoord, maxCoord); return temp; }
#include "Main.hpp" #include "LoadingFunctions.hpp" #include "controls.hpp" using namespace std; using namespace glm; GLFWwindow* window; int main() { if( !glfwInit() ) { fprintf( stderr, "Failed to initialize GLFW\n" ); return -1; } window = glfwCreateWindow(1024, 768, "Simple example", NULL, NULL); if( window == NULL ) { fprintf( stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n" ); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glewExperimental=true; // Needed in core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); return -1; } glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glfwSetCursorPos(window, 1024/2, 768/2); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Read our .obj file std::vector<vec3> vertices; std::vector<vec2> uvs; std::vector<vec3> normals; // Won't be used at the moment. bool res = loadOBJ("Models\\Cube.obj", vertices, uvs, normals); GLuint vertexbuffer; GLuint colorbuffer; glGenBuffers(1, &vertexbuffer); glGenBuffers(1, &colorbuffer); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vec3) * vertices.size(), &vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vec2) * uvs.size(), &uvs[0], GL_STATIC_DRAW); GLuint programID = CompileShadersMakeProgram( "Shaders\\vertex_4.glsl", "Shaders\\fragment_4.glsl" ); GLuint texture_1 = loadDDS("Textures\\Cube_UVMap.DDS"); computeMatricesFromInputs(); mat4 ProjectionMatrix = getProjectionMatrix(); mat4 ViewMatrix = getViewMatrix(); mat4 ModelMatrix = mat4(1.0); mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; GLuint MatrixID = glGetUniformLocation(programID, "MVP"); GLuint TextureID = glGetUniformLocation(programID, "myTextureSampler"); // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); glClearColor(0.0f, 0.0f, 0.4f, 0.0f); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glEnable(GL_CULL_FACE); cout << vertices.size() << endl; while (!glfwWindowShouldClose(window) && glfwGetKey(window, GLFW_KEY_ESCAPE ) != GLFW_PRESS) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); computeMatricesFromInputs(); ProjectionMatrix = getProjectionMatrix(); ViewMatrix = getViewMatrix(); ModelMatrix = glm::mat4(1.0); MVP = ProjectionMatrix * ViewMatrix * ModelMatrix; glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &MVP[0][0]); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_1); glUniform1i(texture_1, 0); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer); glVertexAttribPointer( 0, // attribute 0. No particular reason for 0, but must match the layout in the shader. 3, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*)0 // array buffer offset ); glEnableVertexAttribArray(1); glBindBuffer(GL_ARRAY_BUFFER, colorbuffer); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_TRIANGLES, 0, vertices.size()); glDisableVertexAttribArray(0); glDisableVertexAttribArray(1); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glDeleteBuffers(1, &vertexbuffer); glDeleteBuffers(1, &colorbuffer); glDeleteProgram(programID); glDeleteTextures(1, &TextureID); glDeleteVertexArrays(1, &VertexArrayID); glfwTerminate(); return 0; }
#include <iostream> #include <array> #include <chrono> #define ArrayAndSize(arr) \ arr, (sizeof(arr)/sizeof(arr[0])) bool oppg2 = false; void RandomizeArray(int *a, int size) { for(auto i= 0; i < size; i++) { a[i] = rand(); } } void PrintArray(int *a, int size) { for(auto i= 0; i < size; i++) { std::cout << a[i] << std::endl; } } int Partition(int arr[], int low, int high) { const int pivot = arr[high]; int r = 0; int l = 1; for (;;) { for (auto i = low; i < high; i++) { if (arr[i] > pivot) { l = i; break; } } for (auto i = high - 1; i > 0; i--) { if (arr[i] < pivot) { r = i; break; } } if (l < r) { std::swap(arr[l], arr[r]); } else { break; } } if (arr[l] > arr[high]) std::swap(arr[l], arr[high]); return l; } void QuickSort(int arr[], int low, int high) { if (low < high) { const int p = Partition(arr, low, high); QuickSort(arr, low, p - 1); QuickSort(arr, p + 1, high); } } /* C++ implementation of QuickSort */ using namespace std; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller than pivot) to left of pivot and all greater elements to right of pivot */ int partition(int arr[], int low, int high) { int pivot = arr[high]; // pivot int i = (low - 1); // Index of smaller element and indicates the right position of pivot found so far for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // increment index of smaller element swap(&arr[i], &arr[j]); } } swap(&arr[i + 1], &arr[high]); return (i + 1); } /* The main function that implements QuickSort arr[] --> Array to be sorted, low --> Starting index, high --> Ending index */ void quickSort(int arr[], int low, int high) { if (low < high) { /* pi is partitioning index, arr[p] is now at right place */ int pi = partition(arr, low, high); // Separately sort elements before // partition and after partition quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } /* Function to print an array */ void printArray(int arr[], int size) { int i; for (i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } void MergeSort(int a[], int n) { int i, j, k, lower1, lower2, size, upper1, upper2; int* hjelp = new int[n]; size = 1; while (size < n) { lower1 = 0; k = 0; while (lower1 + size < n) { upper1 = lower1 + size - 1; lower2 = upper1 + 1; upper2 = (lower2 + size - 1 < n) ? lower2 + size - 1 : n - 1; for (i = lower1, j = lower2; i <= upper1 && j <= upper2; k++) if (a[i] < a[j]) hjelp[k] = a[i++]; else hjelp[k] = a[j++]; for (; i <= upper1; k++) hjelp[k] = a[i++]; for (; j <= upper2; k++) hjelp[k] = a[j++]; lower1 = upper2 + 1; } for (i = lower1; k < n; i++) hjelp[k++] = a[i]; for (i = 0; i < n; i++) { a[i] = hjelp[i]; if (oppg2) std::cout << a[i] << " "; } if (oppg2) std::cout << std::endl; size = size * 2; } delete[] hjelp; } void InsertSort(int a[], int n) { int i, j, temp; for (i = 1; i < n; i++) { temp = a[i]; j = i - 1; while (j >= 0 && temp <= a[j]) { a[j + 1] = a[j]; j = j - 1; } a[j + 1] = temp; } } void SampleSort(int* arr, int n) { for (int i = 0; i < n - 1; i++) for (int j = i + 1; j < n; j++) if (arr[i] > arr[j]) std::swap(arr[i], arr[j]); } void BubbleSort(int* arr, int n) { for (int i = 0; i < n - 1; i++) for (int j = 0; j < n - 1; j++) if (arr[j] > arr[j + 1]) std::swap(arr[j], arr[j + 1]); } void QuickSortWrapper(int* a, int n) { quickSort(a, 0, n-1); } void TestSort(void sortFunc(int* arr, int n), std::initializer_list<int> nTimes) { int numTimes = 10; for (const auto& l : nTimes) { int* arr = new int[l]; double avg = 0; for (int i= 0; i< numTimes; i++) { RandomizeArray(arr, l); auto start = std::chrono::steady_clock::now(); sortFunc(arr, l); auto end = std::chrono::steady_clock::now(); avg += std::chrono::duration<double, std::milli>(end - start).count(); } avg /= numTimes; std::cout << "For n: " << l << " " << "avg sort time(MS): " << avg << std::endl; //PrintArray(arr, l); delete[] arr; } } void Oppgave3AEksamen2018() { std::cout << "Oppgave 1: " << std::endl; std::initializer_list<int> n{ 10, 100, 1000, 10000 }; std::cout << "Running BubbleSort: " << std::endl; TestSort(BubbleSort, n); std::cout << "Running SampleSort: " << std::endl; TestSort(SampleSort, n); std::cout << "Running InsertSort: " << std::endl; TestSort(InsertSort, n); std::cout << "Running MergeSort: " << std::endl; TestSort(MergeSort, n); std::cout << "Running QuickSort: " << std::endl; TestSort(QuickSortWrapper, n); std::cout << std::endl; } void Oppgave2BEksamen2019() { oppg2 = true; std::cout << "Oppgave 2: " << std::endl; //17,14,5,7,12,1,16,29,13,4,8,18,22,2. int arr[] = { 17, 14, 5 ,7, 12 ,1 ,16, 29 , 13, 4,8,18,22,2 }; MergeSort(arr, _countof(arr)); oppg2 = false; } int main() { srand(time(nullptr)); //OPPGAVE 1 Oppgave3AEksamen2018(); // OPPGAVE2 Oppgave2BEksamen2019(); }
#include<iostream> #include<string.h> #include<stdlib.h> #define max 10000 using namespace std; int main(){ char a[max];int c[26],d[26]; int t; cin>>t; for(int j=0;j<t;j++){ int sum=0;int i; for(i=0;i<26;i++) c[i]=d[i]=0; cin>>a; if(strlen(a)%2!=0) cout<<"-1"; else{ for(i=0;i<strlen(a)/2;i++) c[a[i]-97]++; for(i=strlen(a)/2;i<strlen(a);i++) d[a[i]-97]++; for(i=0;i<26;i++) sum+=abs(c[i]-d[i]); cout<<sum/2; } cout<<"\n"; } return 0; }
#include "rtspserver.h" char const* dateHeader() { static char buf[200]; #if !defined(_WIN32_WCE) time_t tt = time(NULL); strftime(buf, sizeof buf, "Date: %a, %b %d %Y %H:%M:%S GMT\r\n", gmtime(&tt)); #else // WinCE apparently doesn't have "time()", "strftime()", or "gmtime()", // so generate the "Date:" header a different, WinCE-specific way. // (Thanks to Pierre l'Hussiez for this code) // RSF: But where is the "Date: " string? This code doesn't look quite right... SYSTEMTIME SystemTime; GetSystemTime(&SystemTime); WCHAR dateFormat[] = L"ddd, MMM dd yyyy"; WCHAR timeFormat[] = L"HH:mm:ss GMT\r\n"; WCHAR inBuf[200]; DWORD locale = LOCALE_NEUTRAL; int ret = GetDateFormat(locale, 0, &SystemTime, (LPTSTR)dateFormat, (LPTSTR)inBuf, sizeof inBuf); inBuf[ret - 1] = ' '; ret = GetTimeFormat(locale, 0, &SystemTime, (LPTSTR)timeFormat, (LPTSTR)inBuf + ret, (sizeof inBuf) - ret); wcstombs(buf, inBuf, wcslen(inBuf)); #endif return buf; } RtspServer::RtspServer(QObject *parent) : QTcpServer(parent) { connect(this,SIGNAL(newConnection()),this,SLOT(newConnect())); sdpFile=new QFile; sdp=new QString; } RtspServer::~RtspServer() { delete sdpFile; delete sdp; } void RtspServer::newConnect() { if(hasPendingConnections()) { QTcpSocket *tcpClient=nextPendingConnection(); connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError))); connect(tcpClient,SIGNAL(readyRead()),this,SLOT(tcpDate())); connect(tcpClient,SIGNAL(aboutToClose()),this,SLOT(closeSocket())); tcpClientList.append(tcpClient); } } void RtspServer::closeSocket() { if (QTcpSocket* dec = dynamic_cast<QTcpSocket*>(sender())) { for(int i=0;i<tcpClientList.size();i++) { if(tcpClientList.at(i)==dec) tcpClientList.removeAt(i); } } } void RtspServer::initSocked(QString ip,int tcpport) { listen(QHostAddress::LocalHost,tcpport); connect(this,SIGNAL(acceptError(QAbstractSocket::SocketError)),this,SLOT(displayError(QAbstractSocket::SocketError))); connect(this,SIGNAL(newConnection()),this,SLOT(newConnect())); } void RtspServer::displayError(QAbstractSocket::SocketError socketError) { switch (socketError) { case QAbstractSocket::RemoteHostClosedError: break; case QAbstractSocket::HostNotFoundError: qDebug("The host was not found. Please check the " "host name and port settings."); break; case QAbstractSocket::ConnectionRefusedError: qDebug("The connection was refused by the peer. " "Make sure the server is running, " "and check that the host name and port " "settings are correct."); break; default: qDebug("The following error occurred:"); } } void RtspServer::tcpDate() { if (QTcpSocket* dec = dynamic_cast<QTcpSocket*>(sender())) { qDebug()<<"{"; QString buf=dec->readAll(); qDebug()<<buf; qDebug()<<"}"; //qDebug()<<dec->readAll(); if(buf.contains("OPTIONS")) { if(buf.mid(buf.indexOf("CSeq: ")+6,1).toInt()!=2) return; dec->write("RTSP/1.0 200 OK\r\n"); dec->write("CSeq: 2\r\n"); dec->write("{\"Public: OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE\"}\r\n",61); dec->write("\r\n\r\n"); } if(buf.contains("DESCRIBE")) { sdpFile->setFileName("rtp.sdp"); sdpFile->open(QIODevice::ReadOnly); *sdp=sdpFile->readAll(); QString describe= "RTSP/1.0 200 OK\r\nCSeq: %1\r\n" "%2" "Content-Base: %3/\r\n" "Content-Type: application/sdp\r\n" "Content-Length: %4\r\n\r\n" "%5"; dec->write(describe.arg(3) .arg(dateHeader()) .arg("rtsp://127.0.0.1:5500/video") .arg(sdp->length()+describe.length()) .arg(sdp->toUtf8().data()) .toUtf8().data()); dec->write("\r\n\r\n"); qDebug()<<"???"; //表示回应的是sdp信息 sdpFile->close(); } } }
#pragma once //#include "stdafx.h" //#include <iostream> using namespace std; template< typename T > struct element2 { T data; element2<T> *next, *prev ; }; template< typename T > struct List2W { element2<T> *head, *tail; int size; }; template< typename T > List2W<T> CreateEmptyList2W() { List2W<T> temp; temp.head = NULL; temp.tail = NULL; temp.size = 0; return temp; } template< typename T > bool isEmpty(List2W<T> list) { return (list.head == NULL); } template< typename T > void PrintList(List2W<T> list) { element2<T>* temp = list.head; if (temp == NULL) { cout << "List is empty"; } else { while (temp != NULL) { cout << " " << temp->data; temp = temp->next; } } cout << "\n\n"; } template< typename T > void AddFirst(List2W<T> &list, T k) { element2<T>* temp = new element2<T>; temp->data = k; temp->next = list.head; temp->prev = NULL; if(list.head == NULL) list.tail = temp; else list.head->prev = temp; list.head = temp; list.size++; } template< typename T > void AddLast(List2W<T> &list, T k) { element2<T>* temp = new element2<T>; temp->data = k; temp->prev = list.tail; temp->next = NULL; if(list.head == NULL) list.head = temp; else list.tail->next = temp; list.tail = temp; list.size++; } template< typename T > void DeleteFirst(List2W<T> &list) { element2<T>* temp = list.head; list.head = list.head->next; if(list.head!=NULL) list.head->prev = NULL; else list.tail = NULL; delete temp; list.size--; } template< typename T > T GetFirst(List2W<T> list) { return list.head->data; }
#include "xr_file.h" #include "xr_util.h" namespace xr { int file_t::get_dir_file(const char *path, std::vector<std::string> &file_names) { DIR *dirp; dirp = ::opendir(path); if (NULL != dirp) { while (1) { struct dirent *direntp; direntp = ::readdir(dirp); if (NULL == direntp) { break; } if (DT_REG == direntp->d_type) { file_names.push_back(direntp->d_name); } } ::closedir(dirp); } else { return FAIL; } return SUCC; } int file_t::set_io_block(int fd, bool is_block) { int val; if (is_block) { val = (~O_NONBLOCK & ::fcntl(fd, F_GETFL)); } else { val = (O_NONBLOCK | ::fcntl(fd, F_GETFL)); } return ::fcntl(fd, F_SETFL, val); } int file_t::fcntl_add_flag(int fd, int add_flag) { int flag = ::fcntl(fd, F_GETFD, 0); flag |= add_flag; return ::fcntl(fd, F_SETFD, flag); } int file_t::close_fd(int &fd) { int ret = SUCC; if (INVALID_FD != fd) { ret = HANDLE_EINTR(::close(fd)); if (ERR != ret) { fd = INVALID_FD; } } return ret; } int file_t::shutdown_rd(int fd) { int ret = SUCC; if (INVALID_FD != fd) { ret = ::shutdown(fd, SHUT_RD); } return ret; } } //end namespace xr
#include "addpioneer.h" #include "ui_addpioneer.h" #include "utilities/constants.h" #include <QtSql> #include <QtWidgets> #include <QFileDialog> #include <QMessageBox> #include <algorithm> AddPioneer::AddPioneer(QWidget *parent) : QDialog(parent), ui(new Ui::AddPioneer){ ui->setupUi(this); // dropdown list for sex ui->dropdown_pioneer_sex->addItem(""); ui->dropdown_pioneer_sex->addItem("Male"); ui->dropdown_pioneer_sex->addItem("Female"); } AddPioneer::~AddPioneer(){ delete ui; } void AddPioneer::on_button_add_pioneer_clicked(){ // Empty all lines emptyLines(); // Display list of all computers //vector<Computer> allComp = returnAllComputers(); // Fill variables with values in input lines string name = ui->input_pioneer_name->text().toStdString(); string sex = getCurrentSex(); string birthyear = ui->input_pioneer_bYear->text().toStdString(); string deathyear = ui->input_pioneer_dYear->text().toStdString(); string description = ui->input_pioneer_description->toPlainText().toStdString(); if(deathyear.empty()){ deathyear = "0"; } bool error = errorCheck(name, sex, birthyear, deathyear, description); if(error){ return; } int byear = atoi(birthyear.c_str()); int dyear = atoi(deathyear.c_str()); Pioneer pio(name, sex, byear, dyear, description, inByteArray); int answer = QMessageBox::question(this, "Add Pioneer", "Are you sure you want to add " + QString::fromStdString(pio.getName()) + " to the list?"); if(answer == QMessageBox::No){ return; } else{ pioService.addPioneer(pio); int idOfAddedPioneer = pioService.getHighestId(); for(unsigned int i = 0; i < relatedComputersList.size(); i++){ Computer currentComputer = relatedComputersList[i]; relationService.addRelations(idOfAddedPioneer, currentComputer.getId()); } this->done(1); } } void AddPioneer::emptyLines(){ ui->label_pioneer_name_error->setText(""); ui->label_pioneer_sex_error->setText(""); ui->label_pioneer_byear_error->setText(""); ui->label_pioneer_description_error->setText(""); ui->label_pioneer_death_year_error->setText(""); } bool AddPioneer::errorCheck(string name, string sex, string birthyear, string deathyear, string description){ bool error = false; if(name.empty()){ ui->label_pioneer_name_error->setText("<span style ='color: #ff0000'>Input Name!</span>"); error = true; } if(sex.empty()){ ui->label_pioneer_sex_error->setText("<span style ='color: #ff0000'>Choose Sex!</span>"); error = true; } if(birthyear.empty()){ ui->label_pioneer_byear_error->setText("<span style ='color: #ff0000'>Input Birth Year!</span>"); error = true; } if(!is_number(birthyear)){ ui->label_pioneer_byear_error->setText("<span style ='color: #ff0000'>Input a Number!</span>"); error = true; } if(description.empty()){ ui->label_pioneer_description_error->setText("<span style ='color: #ff0000'>Input Description</span>"); error = true; } int byear = atoi(birthyear.c_str()); int dyear = atoi(deathyear.c_str()); if(!is_number(deathyear)){ ui->label_pioneer_death_year_error->setText("<span style ='color: #ff0000'>Input a Number!</span>"); error = true; } else if((byear == dyear || byear > dyear) && dyear != 0){ ui->label_pioneer_death_year_error->setText("<span style ='color: #ff0000'>Incorrect Input!</span>"); error = true; } else if(dyear > constants::CURRENT_YEAR){ ui->label_pioneer_death_year_error->setText("<span style ='color: #ff0000'>Are you trying to predict the future?</span>"); error = true; } if(byear > constants::CURRENT_YEAR){ ui->label_pioneer_byear_error->setText("<span style ='color: #ff0000'>People from the future are not allowed!</span>"); error = true; } if(error == true){ return true; } return false; } bool AddPioneer::is_number(string& s){ string::const_iterator it = s.begin(); while (it != s.end() && isdigit(*it)){ ++it; } return !s.empty() && it == s.end(); } void AddPioneer::displayUnrelatedComputers(vector<Computer> unrelatedComputers){ ui->list_unrelated_computers->clear(); for(unsigned int i = 0; i < unrelatedComputers.size(); i++){ Computer currentComputer = unrelatedComputers[i]; ui->list_unrelated_computers->addItem(QString::fromStdString(currentComputer.getComputerName())); } unrelatedComputersList = unrelatedComputers; } void AddPioneer::displayRelatedComputers(vector<Computer> relatedComputers){ ui->list_related_computers->clear(); for(unsigned int i = 0; i < relatedComputers.size(); i++){ Computer currentComputer = relatedComputers[i]; ui->list_related_computers->addItem(QString::fromStdString(currentComputer.getComputerName())); } relatedComputersList = relatedComputers; } void AddPioneer::on_list_unrelated_computers_clicked(const QModelIndex &/* unused */){ ui->button_pioneer_add_relation->setEnabled(true); } void AddPioneer::on_list_related_computers_clicked(const QModelIndex &/* unused */){ ui->button_pioneer_remove_relation->setEnabled(true); } void AddPioneer::on_button_pioneer_add_relation_clicked(){ int currentlySelectedComputerIndex = ui->list_unrelated_computers->currentIndex().row(); Computer selectedComputer = unrelatedComputersList[currentlySelectedComputerIndex]; relatedComputersList.push_back(selectedComputer); unrelatedComputersList.erase(unrelatedComputersList.begin() + currentlySelectedComputerIndex); displayUnrelatedComputers(unrelatedComputersList); displayRelatedComputers(relatedComputersList); ui->button_pioneer_add_relation->setEnabled(false); } void AddPioneer::on_button_pioneer_remove_relation_clicked(){ int currentlySelectedComputerIndex = ui->list_related_computers->currentIndex().row(); Computer selectedComputer = relatedComputersList[currentlySelectedComputerIndex]; unrelatedComputersList.push_back(selectedComputer); relatedComputersList.erase(relatedComputersList.begin() + currentlySelectedComputerIndex); displayRelatedComputers(relatedComputersList); displayUnrelatedComputers(unrelatedComputersList); ui->button_pioneer_remove_relation->setEnabled(false); } void AddPioneer::on_pushButton_browse_image_clicked(){ QString filePath = QFileDialog::getOpenFileName( this, "Search for images", "/home", "Image files (*.jpg)" ); if (filePath.length()){ // File selected QPixmap pixmap(filePath); ui->input_image->setText(filePath); QBuffer inBuffer( &inByteArray ); inBuffer.open( QIODevice::WriteOnly ); pixmap.save( &inBuffer, "JPG" ); } else{ //didn't open file return; } } void AddPioneer::on_button_add_pioneer_cancel_clicked(){ this->done(0); } string AddPioneer::getCurrentSex(){ string sex = ui->dropdown_pioneer_sex->currentText().toStdString(); if(sex == ""){ return ""; } else if(sex == "Male"){ return constants::MALE; } else if(sex == "Female"){ return constants::FEMALE; } else{ return ""; } }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double ld; typedef long long ll; typedef unsigned long long ull; typedef unsigned int uint; const double PI = 3.1415926535897932384626433832795; template<typename T> T sqr(T x) { return x * x; } using namespace std; vector<int> solve(int n, ll m) { if (n == 1) { vector<int> a(1, 1); return a; } for (int i = 0; i < n - 1; ++i) { if (m >= (1ll << (n - i - 2))) { m -= (1ll << (n - i - 2)); continue; } vector<int> subans = solve(n - i - 1, m); for (int j = 0; j < subans.size(); ++j) subans[j] += i + 1; subans.insert(subans.begin(), i + 1); for (int j = 0; j < i; ++j) subans.push_back(i- j); return subans; } vector<int> ans; for (int i = n; i > 0; --i) ans.push_back(i); return ans; } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n; ll m; cin >> n >> m; vector<int> ans = solve(n, m - 1); for (int i = 0; i < ans.size(); ++i) { cout << ans[i] << " "; } cout << endl; return 0; }
#include<cstdio> #include<iostream> #include<cmath> using namespace std; #define pi 3.1415926 int main(){ double u,t; while(cin>>u>>t){ double a=pi*18/sqrt(2*981*9.794); double r=sqrt((9*1.83*0.00001*2*0.001)/(2*981*9.794*t)); double b=(1.83*0.00001*2*0.001)/(t*(1+8.23*0.001/(1.013*100000*r))); double cb=sqrt(b); double c=5*0.001/u; double ans=a*cb*cb*cb*c; cout<<ans<<endl; } return 0; }
/* * redblacknode.h * * Created on: Apr 27, 2017 * Author: Benjamin Kleinberg */ #ifndef REDBLACKNODE_H_ #define REDBLACKNODE_H_ #include"int.h" #include"binarytreenode.h" #include<iostream> using std::ostream; class RedBlackNode : public BinaryTreeNode { public: int color; RedBlackNode(Int key, int nColor = 0); virtual ~RedBlackNode(); virtual void print(ostream& out); friend ostream& operator<<(ostream& out, RedBlackNode& node); }; namespace RedBlack { static const int RED = 0; static const int BLACK = 1; static const int BLACK_BLACK = 2; } #endif /* REDBLACKNODE_H_ */
#include "Board.h" #include<iostream> Board::Board() : height(0), width(0), board_array(nullptr) { //ctor } Board::Board(int height_in, int width_in,sf::Vector2i& mouse_in){ init(height_in, width_in, mouse_in); } Board::~Board(){ if(board_array != nullptr){ for(int height_index = 0; height_index<height; height_index++) delete [] board_array[height_index]; board_array = nullptr; } DEBUG_MSG("badass Board removing" << std::endl); } void Board::init(int height_in, int width_in, sf::Vector2i& mouse_in){ width = width_in; height = height_in; texture.loadFromFile("textures/square_tex.png"); board_array = new Square*[height_in]; for(int height_index = 0; height_index < height_in; height_index++) board_array[height_index] = new Square[width_in]; for(int height_index = 0; height_index < height; height_index++) { for(int width_index = 0; width_index < width; width_index++) { board_array[height_index][width_index].setPosition(width_index * (SQUARE_SIZE + 2) + MOVE_WIDTH, height_index * (SQUARE_SIZE + 2) + MOVE_HEIGHT); board_array[height_index][width_index].setTexture(&texture); } } } void Board::draw(sf::RenderTarget &target, sf::RenderStates states) const{ states.transform *= getTransform(); for(int height_index = 0; height_index < height; height_index++) { for(int width_index = 0; width_index < width; width_index++) target.draw(board_array[height_index][width_index]); } } sf::Vector2i Board::getBoardPosition(sf::Vector2i mouse_position){ sf::Vector2i board_position; for(int height_index = 0; height_index < height; height_index++) { for(int width_index = 0; width_index < width; width_index++){ if(board_array[height_index][width_index].getGlobalBounds().contains(mouse_position.x,mouse_position.y)) { board_position.x = height_index; board_position.y = width_index; } } } return board_position; } Board::BoardState Board::update(bool& clicked,Player* currrent_turn, sf::Vector2i& current_mouse_position) { bool havent_any_failed = true; BoardState state_tmp = NextTurn; #ifndef NDEBUG static sf::Vector2i last_board_position; sf::Vector2i positioner_tmp; positioner_tmp.x = 0; positioner_tmp.y = 0; positioner_tmp = getBoardPosition(current_mouse_position); if(positioner_tmp != last_board_position) { last_board_position = positioner_tmp; DEBUG_MSG("Position = " << last_board_position.x << " , " << last_board_position.y << std::endl); } #endif for(int height_index = 0; height_index < height; height_index++ ) { for(int width_index = 0; width_index < width; width_index++){ state_tmp = squareAction(clicked, height_index, width_index, currrent_turn, current_mouse_position); if(state_tmp != WaitingForTurn)// TODO(foto) fixxx return state_tmp; } } return state_tmp; } Board::BoardState Board::squareAction(bool& clicked,int height_index, int width_index, Player* currrent_turn, sf::Vector2i &current_mouse_position){ if(board_array[height_index][width_index].getGlobalBounds().contains(current_mouse_position.x, current_mouse_position.y)) { if(!board_array[height_index][width_index].isMarked()) // marking and hillighting only fr ummarked squares { mouse_hilighting = &(board_array[height_index][width_index]); if(board_array[height_index][width_index].getFillColor() != sf::Color::Yellow) mouse_hilighting->setFillColor(sf::Color::Yellow); if(clicked) { //TODO(FOTO#5#) have to fix that mouse_hilighting->mark(currrent_turn); return checkWin(height_index, width_index, currrent_turn); //now engine turns off clicked boolean :) } return WaitingForTurn; } return WaitingForTurn; } else if(board_array[height_index][width_index].getFillColor() != sf::Color::White) board_array[height_index][width_index].setFillColor(sf::Color::White); return WaitingForTurn; } Board::BoardState Board::checkWin(int height_index,int width_index,Player* currrent_turn)const{ ///////// int counter = 1; int i = 1; assert(currrent_turn != nullptr); while(height_index+i < HEIGHT && board_array[height_index+i][width_index].getMarkedBy() == currrent_turn) { counter++; i++; } i = 1; while(height_index-i >= 0 && board_array[height_index-i][width_index].getMarkedBy() == currrent_turn) { counter++; i++; } if(counter >= IN_A_ROW_TO_WIN) { DEBUG_MSG("ENDO GEJMO"); //exit(1); return Winner; } //////////////////////// /////////////////////// counter = 1; i = 1; while(width_index+i < WIDTH && board_array[height_index][width_index+i].getMarkedBy() == currrent_turn) { counter++; i++; } i = 1; while(width_index-i >= 0 && board_array[height_index][width_index-i].getMarkedBy() == currrent_turn) { counter++; i++; } if(counter>=IN_A_ROW_TO_WIN) { DEBUG_MSG("ENDO GEJMO"); //exit(1); return Winner; } //////////////////// /////////////////////// counter = 1; i = 1; while(width_index+i < WIDTH && height_index+i < HEIGHT && board_array[height_index+i][width_index+i].getMarkedBy() == currrent_turn) { counter++; i++; } i = 1; while(width_index-i>=0 && height_index-i >= 0 && board_array[height_index-i][width_index-i].getMarkedBy() == currrent_turn) { counter++; i++; } if(counter >= IN_A_ROW_TO_WIN) { DEBUG_MSG("ENDO GEJMO"); // exit(1); return Winner; } //////////////////// /////////////////////// counter = 1; i = 1; while(width_index-i >= 0 && height_index+i < HEIGHT && board_array[height_index+i][width_index-i].getMarkedBy() == currrent_turn) { counter++; i++; } i = 1; while(width_index+i < WIDTH && height_index-i >= 0 && board_array[height_index-i][width_index+i].getMarkedBy() == currrent_turn) { counter++; i++; } if(counter >= IN_A_ROW_TO_WIN) { DEBUG_MSG("ENDO GEJMO"); // exit(1); return Winner; } //////////////////// return NextTurn; }
#ifndef wN_binrel_BINREL_GUARD #define wN_binrel_BINREL_GUARD 1 /** * @author Nicholas Kidd * @author Prathmesh Prabhu * * An implementation of binary relations. * This class models the relations * using BDDs, and specifically with the BuDDy * BDD library. * * */ /* **************************** Changelog (Prathmesh): (1) Added limited tensor product functionality. 2-STP implemented. No support for more general tensor products. */ #include <map> #include <vector> #include <utility> #include <string> #include <vector> #include <boost/shared_ptr.hpp> // It'd be nice to include the standard version but there are too many ways to get it. #include <unordered_set> #include <unordered_map> #include <boost/function.hpp> #include "wali/wfa/WeightMaker.hpp" #include "wali/Countable.hpp" #include "wali/ref_ptr.hpp" #include "wali/SemElemTensor.hpp" #include "buddy/fdd.h" #include "wali/Key.hpp" /** * * The following describes how to control how the bdd variables are setup in buddy * Let x, y, w and z be variables, each requiring two bdd levels (x1 and x2) * Further, for the bit x1, there are three different levels x1b, x1t1 and x1t2 * -- the first one for base, the second and third for the two tensor spots. * Finally, each spot needs three levels, x1b, x1b' and x1b'', for pre vocabulary, post vocabulary, and an extra. * * Let's disregard tensors for the moment. * By default, the variables are interleaved at the bit level. So, a call to * setInts({(x, 2), (y, 2), (z, 2)}) gives the interleaving * x1b x1b' x1b'' y1b y1b' y1b'' z1b z1b' z1b'' x2b x2b' x2b'' y2b y2b' y2b'' z2b z2b' z2b'' * There is another way of interleaving these variables. Where variables are grouped together. * setInts({{(x, 2), (y, 2)}, {(z, 2), (w, 2)}}) * x1b x1b' x1b'' y1b y1b' y1b'' x2b x2b' x2b'' y2b y2b' y2b'' z1b z1b' z1b'' w1b w1b' w1b'' z2b z2b' z2b'' w2b w2b' w2b'' * * There are various choices with regard to tensors. * (1) TENSOR_MAX_AFFINITY * (Most useful, with BIT_BY_BIT_DETENSOR. DETENSOR_TOGETHER blows up) * This makes sure that all three levels for a bit are always together, i.e., you always get * x1b x1b' x1b'' x1t1 x1t1' x1t1'' x1t2 x1t2' x1t2'' * The interleaving at higher levels remains the same * (2) TENSOR_MIN_AFFINITY * (almost never used) * (You may try either BIT_BY_BIT_DETENSOR or DETENSOR_TOGETHER. But tensor itself is slow) * This makes sure that the three levels for the whole vocabulary are separate and copies of each other. * So, for the example above, the levels would look like. * x1b x1b' x1b'' y1b y1b' y1b'' x2b x2b' x2b'' y2b y2b' y2b'' z1b z1b' z1b'' w1b w1b' w1b'' z2b z2b' z2b'' w2b w2b' w2b'' * x1t1 x1t1' x1t1'' y1t1 y1t1' y1t1'' x2t1 x2t1' x2t1'' y2t1 y2t1' y2t1'' z1t1 z1t1' z1t1'' w1t1 w1t1' w1t1'' z2t1 z2t1' z2t1'' w2t1 w2t1' w2t1'' * x1t2 x1t2' x1t2'' y1t2 y1t2' y1t2'' x2t2 x2t2' x2t2'' y2t2 y2t2' y2t2'' z1t2 z1t2' z1t2'' w1t2 w1t2' w1t2'' z2t2 z2t2' z2t2'' w2t2 w2t2' w2t2'' * (3) BASE_MAX_AFFINITY_TENSOR_MIXED * (almost never used) * (You may try either BIT_BY_BIT_DETENSOR or DETENSOR_TOGETHER. But tensor itself is slow) * This makes sure that base is separate, but mixes together tensors vocabularies. * x1b x1b' x1b'' y1b y1b' y1b'' x2b x2b' x2b'' y2b y2b' y2b'' z1b z1b' z1b'' w1b w1b' w1b'' z2b z2b' z2b'' w2b w2b' w2b'' * followed by tensor levels as x1t1 x1t1' x1t1'' x1t2 x1t2' x1t2'' * (4) TENSOR_MATCHED_PAREN * (Must be used with NWA_DETENSOR) * NOTE: ***This currently only works correctly with boolean variables.*** * Keeps all Three vocabs (base,tensor1,tensor2) separate, like TENSOR_MIN_AFFINITY. * Additionally, the three microlevels in each bit x x' x'' are in reverse order for tensor1. * So, for the example above, the levels would look like. * x1b x1b' x1b'' y1b y1b' y1b'' x2b x2b' x2b'' y2b y2b' y2b'' z1b z1b' z1b'' w1b w1b' w1b'' z2b z2b' z2b'' w2b w2b' w2b'' * x1t1'' x1t1' x1t1 y1t1'' y1t1' y1t1 x2t1'' x2t1' x2t1 y2t1'' y2t1' y2t1 z1t1'' z1t1' z1t1 w1t1'' w1t1' w1t1 z2t1'' z2t1' z2t1 w2t1'' w2t1' w2t1 * x1t2 x1t2' x1t2'' y1t2 y1t2' y1t2'' x2t2 x2t2' x2t2'' y2t2 y2t2' y2t2'' z1t2 z1t2' z1t2'' w1t2 w1t2' w1t2'' z2t2 z2t2' z2t2'' w2t2 w2t2' w2t2'' * * The tensor choice is determined by setting **exactly one** macro to 1. **/ #define TENSOR_MAX_AFFINITY 1 #define TENSOR_MIN_AFFINITY 0 #define BASE_MAX_AFFINITY_TENSOR_MIXED 0 #define TENSOR_MATCHED_PAREN 0 // Make sure exactly one bdd variable order is chosen. #if (TENSOR_MAX_AFFINITY + TENSOR_MIN_AFFINITY + BASE_MAX_AFFINITY_TENSOR_MIXED + TENSOR_MATCHED_PAREN) != 1 #error "Please choose exactly one bdd variable order." #endif /** * There are several ways to implement detensor * (1) DETENSOR_TOGETHER * This creates (and updates) a bdd when variables are added to the vocabulary that contains the constraints * needed by detensor. * During detensor, this bdd is used to enforce constraints at once. * (2) DETENSOR_BIT_BY_BIT * This does not explictly create the constraint bdd. Instead, during detensor, it enforces the equality * constraint on each bdd level one-by-one. * (3) NWA_DETENSOR * Converts the bdd to an Nwa, enforces the constraints by Nwa intersection, and converts back to, obtain * the detensored bdd. * * The detensor choice is made by setting **exactly one** macro to 1 **/ #define DETENSOR_TOGETHER 0 #define DETENSOR_BIT_BY_BIT 1 #define NWA_DETENSOR 0 // Make sure exactly one detensor method is chosen #if (DETENSOR_TOGETHER + DETENSOR_BIT_BY_BIT + NWA_DETENSOR) != 1 #error "Please choose exactly one method for detensor." #endif // Make sure that NWA_DETENSOR is used with TENSOR_MATCHED_PAREN order. #if (NWA_DETENSOR + TENSOR_MATCHED_PAREN) % 2 != 0 #error "Nwa based detensor only works with TENSOR_MATCHED_PAREN variable order" #endif /** To switch on statistics collection in BinRel **/ #define BINREL_STATS /// This checks two implementations of the 'subsumes' operation (subset) off /// each other (one faster, one simpler) #define CHECK_BDD_SUBSUMES_WITH_SLOWER_VERSION 1 #if(NWA_DETENSOR == 1) namespace opennwa { typedef wali::Key State; typedef wali::Key Symbol; } std::size_t hash_value(bdd const& b); #endif namespace wali { namespace domains { namespace binrel { class DetensorNwa; /// Reference-counting bddPair pointer. These must be freed using /// bdd_freepair, not delete, so we can't used ref_ptr. This just wraps /// Boost's shared_ptr, setting bdd_freepair as the custom /// deleter. (And this is the main reason for not just using a typedef.) struct BddPairPtr : public boost::shared_ptr<bddPair> { typedef boost::shared_ptr<bddPair> Base; // We keep with the Boost/std practice of making this constructor // explicit, for it is a Good Idea. explicit BddPairPtr(bddPair * ptr) : Base(ptr, bdd_freepair) {} BddPairPtr(BddPairPtr const & other) : Base(other) {} BddPairPtr() {} }; /** * Used to count the different operations performed by the library */ typedef long long int StatCount; /** * Variable name, maximum value and the different base indices. */ struct BddInfo : public Countable, public Printable { unsigned maxVal; // /fdd indices // The following three indices are for the base relation unsigned baseLhs; unsigned baseRhs; //used for extends unsigned baseExtra; //The following three indices are for the tensored relations when this //variable is in the left operand in the tensor product unsigned tensor1Lhs; unsigned tensor1Rhs; unsigned tensor1Extra; //The following three indices are for the tensored relations when this //variable is in the right operand in the tensor product unsigned tensor2Lhs; unsigned tensor2Rhs; unsigned tensor2Extra; std::ostream& print( std::ostream& o ) const; }; typedef ref_ptr<BddInfo> bddinfo_t; class BinRel; typedef wali::ref_ptr<BinRel> binrel_t; /**A BddContext has the binding information for the variables in the * domain. */ /** * Usage: * -- initialize buddy by creating an object of BddContext * -- add variables to the vocabulary of your relations using add/set Vars variants * Note: If you are particular about the bdd variable order, use * setIntVars or setBoolVars instead of addBoolVars / addIntVars. * It's better tested and more flexible. * -- Create BinRels and play with them as you like. **/ class BddContext : public std::map<const std::string,bddinfo_t> { friend class BinRel; #if (NWA_DETENSOR == 1) public: typedef std::vector<int> VocLevelArray; #endif public: /** * A BddContext manages the vocabularies and stores some useful bdds * that speed up BinRel operations. * @param bddMemSize The size of memory BUDDY should be initialized * with. Default size is used if the argument is 0. * @param cacheSize The size of cache BUDDY should be initialized * with. Default size is used if the argument is 0. */ BddContext(int bddMemeSize=0, int cacheSize=0); BddContext(const BddContext& other); BddContext& operator = (const BddContext& other); virtual ~BddContext(); /** Add a boolean variable to the vocabulary with the name 'name' **/ virtual void addBoolVar(std::string name); /** Add a int variable to the vocabulary with the name 'name'. The * integer can take values between 0...size-1. **/ virtual void addIntVar(std::string name, unsigned size); /** * Add multiple variables to the vocabulary with the given sizes. * This function should not be used after addBoolVar/addIntVar has been * used. This function is meant to be an effecient way of adding multiple variables **/ virtual void setIntVars(const std::map<std::string, int>& vars); virtual void setIntVars(const std::vector<std::map<std::string, int> >& vars); #if (NWA_DETENSOR == 1) /** * These functions are used by an NWA based implementation of detensor. * They provide information about the bit level information per variable. **/ // Setup the sets of levels in the different vocabularies for fast lookup void setupLevelArray(); VocLevelArray const& getLevelArray(); unsigned numVars() const; #endif protected: /** * More fine grained control when setting multiple int vars together. These together * called in order are the same as calling setIntVars **/ void createIntVars(const std::vector<std::map<std::string, int> >& vars); virtual void setupCachedBdds(); public: //using wali::Countable::count; int count; private: /** caches zero/one binrel objects for this context **/ void populateCache(); private: // /////////////////////////////// // We use the name convention for different // sets as B1,B2,B3; TL1,TL2,TL3; TR1, TR2, TR3. // Comments contain the more meaningful, but ghastly names //B1->B2 B2->B1 BddPairPtr baseSwap; //TL1->TL2 TL2->TL1 BddPairPtr tensor1Swap; //B1->B2 B2->B3 BddPairPtr baseRightShift; //TL1->TL2 TR1->TR2 TL2->TL3 TR2->TR3 BddPairPtr tensorRightShift; //B3->B2 BddPairPtr baseRestore; //TL3->TL2 TR3->TR2 BddPairPtr tensorRestore; //B1->LT1 B2->TL2 B3->TL3 BddPairPtr move2Tensor1; //B1->TR1 B2->TR2 B3->TR3 BddPairPtr move2Tensor2; //TL1->B1 TR2->B2 BddPairPtr move2Base; //TL1->B1 TR1->B2 BddPairPtr move2BaseTwisted; //sets for operation //Set: B2 bdd baseSecBddContextSet; //Set: TL2 U TR2 bdd tensorSecBddContextSet; //Set: TL2 U TR1 bdd commonBddContextSet23; //Id: TL2 = TR1 bdd commonBddContextId23; //Set: TL2 U TR2 bdd commonBddContextSet13; //Id: TL2 = TR2 bdd commonBddContextId13; //We cache zero and one BinRel objects, since they are used so much binrel_t cachedBaseOne; binrel_t cachedBaseZero; binrel_t cachedTensorOne; binrel_t cachedTensorZero; #if (NWA_DETENSOR == 1) VocLevelArray tensorVocLevels; VocLevelArray baseLhsVocLevels; VocLevelArray baseRhsVocLevels; bdd t1OneBdd; BddPairPtr rawMove2Tensor2; #endif #ifdef BINREL_STATS private: //Statistics for this contex mutable StatCount numCompose; mutable StatCount numUnion; mutable StatCount numIntersect; mutable StatCount numEqual; mutable StatCount numKronecker; mutable StatCount numReverse; mutable StatCount numTranspose; mutable StatCount numDetensor; mutable StatCount numDetensorTranspose; // Related functions public: std::ostream& printStats( std::ostream& o ) const; void resetStats(); #endif private: //Initialization of buddy is taken care of opaquely //by keeping track of the number of BddContext objects alive static int numBddContexts; }; typedef BddContext::iterator BddContextIter; typedef std::map<const int,std::string> RevBddContext; typedef wali::ref_ptr< BddContext > bdd_context_t; typedef std::map<std::string, int> Assignment; typedef std::vector<std::pair<std::string, bddinfo_t> > VectorVocabulary; extern std::vector<Assignment> getAllAssignments(BddContext const & voc); extern void printImagemagickInstructions(bdd b, BddContext const & voc, std::ostream & os, std::string const & for_file, boost::function<bool (VectorVocabulary const &)> include_component); extern bdd quantifyOutOtherVariables(BddContext const & voc, std::vector<std::string> const & keep_these, bdd b); #if (NWA_DETENSOR == 1) /* * Subclass of opennwa::WeightGen used to attache weights to the nwa used * for detensor. The class is declared in nwa_detensor.hpp. We can * declare it here because we do not want to include Nwa.hpp above. **/ class DetensorWeightGen; #endif class BinRel : public wali::SemElemTensor { public: static void reset(); public: /** @see BinRel::Compose */ friend binrel_t operator*(binrel_t a, binrel_t b); /** @see BinRel::Union */ friend binrel_t operator|(binrel_t a, binrel_t b); /** @see BinRel::Intersect */ friend binrel_t operator&(binrel_t a, binrel_t b); public: BinRel(const BinRel& that); BinRel(BddContext const * con, bdd b, bool is_tensored=false); virtual ~BinRel(); public: binrel_t Compose( binrel_t that ) const; binrel_t Union( binrel_t that ) const; binrel_t Intersect( binrel_t that ) const; bool Equal(binrel_t se) const; binrel_t Transpose() const; binrel_t Kronecker( binrel_t that) const; binrel_t Eq23Project() const; binrel_t Eq13Project() const; public: // //////////////////////////////// // SemElem methods sem_elem_t one() const; sem_elem_t zero() const; bool isOne() const { if(isTensored) return getBdd() == con->cachedTensorOne->getBdd(); else return getBdd() == con->cachedBaseOne->getBdd(); } bool isZero() const { if(isTensored) return getBdd() == con->cachedTensorZero->getBdd(); else return getBdd() == con->cachedBaseZero->getBdd(); } /** @return [this]->Union( cast<BinRel*>(se) ) */ sem_elem_t combine(SemElem* se); /** @return [this]->Compose( cast<BinRel*>(se) ) */ sem_elem_t extend(SemElem* se); sem_elem_t star(); bool underApproximates(SemElem * other); /** @return [this]->Equal( cast<BinRel*>(se) ) */ bool equal(SemElem* se) const; std::ostream& print( std::ostream& o ) const; // //////////////////////////////// // SemElemTensor methods /** @return [this]->Transpose() */ sem_elem_tensor_t transpose(); /** @return [this]->Kronecker( cast<BinRel*>(se) ) */ sem_elem_tensor_t tensor(SemElemTensor* se); /** @return [this]->Eq23Project() */ sem_elem_tensor_t detensor(); /** @return [this]->Eq34Project() */ sem_elem_tensor_t detensorTranspose(); /** @return The backing BDD */ bdd getBdd() const { return rel; } /** @return Get the vocabulary the relation is over */ // TODO: change name -eed May 14 2012 BddContext const & getVocabulary() const { return *con; } virtual bool containerLessThan(SemElem const * other) const; virtual size_t hash() const { return static_cast<size_t>(getBdd().id()); } // //////////////////////////////// // Printing functions //static void printHandler(FILE *o, int var); protected: //This has to be a raw/weak pointer. //BddContext caches some BinRel objects. It is not BinRel's responsibility to //manage memory for BddContext. BddContext const * con; bdd rel; bool isTensored; #if(NWA_DETENSOR == 1) private: //TODO: Cleanup in the destructor for all these typedef std::pair< unsigned, bdd > StateTranslationKey; typedef std::unordered_map< StateTranslationKey, opennwa::State > StateTranslationTable; typedef std::vector< std::vector< opennwa::State > > LevelToStatesTable; typedef std::unordered_set< opennwa::State > StateHashSet; // Maps etc needed during detensor operation // We don't store the Nwa here because we don't have the complete type of DetensorNwa yet // Same goes for wali::domains::binrel::DetensorWeightGen StateTranslationTable tTable; LevelToStatesTable lTable; StateHashSet visited; opennwa::State rejectState; opennwa::State acceptStateNwa; opennwa::State initialStateNwa; opennwa::State initialStateWfa; opennwa::State acceptStateWfa; opennwa::Symbol low, high; // Converts rel to an nwa, and solves a path problem to obtain the detensorTranspose bdd bdd detensorViaNwa(); void populateNwa(DetensorNwa& nwa, DetensorWeightGen& wts); void setupConstraintNwa(DetensorNwa& nwa); void tabulateStates(DetensorNwa& nwa, unsigned v, bdd r); opennwa::State generateTransitions(DetensorNwa& nwa, DetensorWeightGen& wts, unsigned v, bdd n); opennwa::State generateTransitionsLowerPlies(DetensorNwa& nwa, DetensorWeightGen& wts, unsigned v, bdd n); bdd reverse(bdd toReverse) const; bdd tensorViaDetensor(bdd other) const; #endif }; /// Function object that, given two binary relations as weights, /// returns the and/intersection of them. /// /// Useful for intersecting two WFAs. struct AndWeightMaker : wali::wfa::WeightMaker { virtual sem_elem_t make_weight( sem_elem_t lhs, sem_elem_t rhs ) { wali::domains::binrel::BinRel * l_rel = dynamic_cast<wali::domains::binrel::BinRel*>(lhs.get_ptr()), * r_rel = dynamic_cast<wali::domains::binrel::BinRel*>(rhs.get_ptr()); assert(l_rel && r_rel); assert(l_rel->getVocabulary() == r_rel->getVocabulary()); bdd both = bdd_and(l_rel->getBdd(), r_rel->getBdd()); return new wali::domains::binrel::BinRel(&l_rel->getVocabulary(), both); } virtual sem_elem_t make_weight( wali::wfa::ITrans const * UNUSED_PARAMETER(lhs), wali::wfa::ITrans const * UNUSED_PARAMETER(rhs)) { assert(false); } }; // WeightMaker namespace details { bool bddImplies_using_bdd_imp(bdd left, bdd right); bool bddImplies_recursive(bdd left, bdd right); bool bddImplies(bdd left, bdd right); std::vector<std::pair<VectorVocabulary, bdd> > partition(BddContext const & vars, bdd b); } } // namespace binrel } // namespace domains } // namespace wali // Yo, Emacs! // Local Variables: // c-file-style: "ellemtel" // c-basic-offset: 2 // End: #endif // wali_binrel_BINREL_GUARD
#include <iostream> #include <cstdio> #include <cmath> //#define maxn 100 + 5 using namespace std; //typedef long long LL; int main() { int n; while(cin >> n) { int a = (n + 1) * n / 2; cout << a << " " << pow(2, n) - 1 << endl; } return 0; }
void loop() { String data = Serial.readStringUntil("\n"); Serial.println(data); delay(1000); } int red = Serial.readInt(); int green = Serial.readInt(); void setup() { // put your setup code here, to run once: Serial.berin(115200); pinMode(red, OUTPUT); pinMode(green, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(red, HIGH); digitalWrite(green, LOW); delay(2000); digitalWrite(red, LOW); digitalWrite(green, HIGH); delay(2000); }
// // Created by 钟奇龙 on 2019-05-11. // #include <iostream> #include <string> #include <vector> using namespace std; int maxUnique(string s){ if(s.size() == 0) return 0; int pre = -1; int res = 0; vector<int> index_map(256,-1); for(int i=0; i<s.size(); ++i){ pre = max(pre,index_map[s[i]]); res = max(res,i-pre); index_map[s[i]] = i; } return res; } int main(){ cout<<maxUnique("aabcb")<<endl; cout<<maxUnique("abcd")<<endl; return 0; }
// // nehe12.h // NeheGL // // Created by Andong Li on 9/11/13. // Copyright (c) 2013 Andong Li. All rights reserved. // #ifndef __NeheGL__nehe12__ #define __NeheGL__nehe12__ #include <OpenGL/gl.h> #include <OpenGL/glu.h> #include <GLUT/glut.h> #include "utils.h" #include "SOIL.h" #include <iostream> #include <stdlib.h> #include <stdio.h> #include <cmath> #include <ctime> class NEHE12{ public: static GLvoid ReSizeGLScene(GLsizei width, GLsizei height); static GLvoid InitGL(); static GLvoid DrawGLScene(); static GLvoid UpdateScene(int flag); //handle keys press and up functions static GLvoid KeySpecialFuction(int key, int x, int y); static GLvoid KeySpecialUpFuction(int key, int x, int y); static const char* TITLE; const static int EXPECT_FPS = 60; // expect FPS during rendering const static int FPS_UPDATE_CAP = 100; // time period for updating FPS private: static GLfloat sleepTime; //delay time for limiting FPS static void computeFPS(); static bool LoadGLTextures(const char* dir); static GLvoid BuildLists(); static int frameCounter; static int currentTime; static int lastTime; static char FPSstr[15]; static GLfloat xrot; // X Rotation static GLfloat yrot; // Y Rotation static GLuint box; // Storage For The Display List static GLuint top; // Storage For The Second Display List static GLuint xloop; // Loop For X Axis static GLuint yloop; // Loop For Y Axis static GLuint texture[1]; // Storage For One Texture static bool specialKeys[256]; static GLfloat boxcol[5][3]; // Array For Box Colors static GLfloat topcol[5][3]; // Array For Top Colors }; #endif /* defined(__NeheGL__nehe12__) */
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- // // Copyright (C) 2003-2006 Opera Software AS. All rights reserved. // // This file is part of the Opera web browser. It may not be distributed // under any circumstances. // // Adam Minchinton // #include "core/pch.h" #ifdef SUPPORT_SPEED_DIAL #include "adjunct/quick/managers/SpeedDialManager.h" #include "adjunct/quick/extensions/ExtensionUtils.h" #include "adjunct/quick/managers/SyncManager.h" #include "adjunct/quick/managers/KioskManager.h" #include "adjunct/quick/widgets/OpSpeedDialView.h" #include "adjunct/quick/Application.h" #include "adjunct/quick/WindowCommanderProxy.h" #include "adjunct/quick/speeddial/SpeedDialThumbnail.h" #ifdef USE_COMMON_RESOURCES #include "adjunct/desktop_util/resources/ResourceDefines.h" #endif // USE_COMMON_RESOURCES #include "adjunct/desktop_util/resources/ResourceSetup.h" #include "adjunct/desktop_util/widget_utils/WidgetThumbnailGenerator.h" #include "adjunct/desktop_util/adt/hashiterator.h" #include "modules/util/opfile/opfile.h" #include "modules/prefs/prefsmanager/collections/pc_doc.h" #include "modules/prefs/prefsmanager/collections/pc_files.h" #include "modules/prefs/prefsmanager/collections/pc_ui.h" #include "modules/prefsfile/prefsfile.h" #include "modules/thumbnails/src/thumbnail.h" #include "modules/widgets/WidgetContainer.h" #include "modules/logdoc/htm_elm.h" #include "modules/doc/frm_doc.h" #include "modules/dochand/win.h" #include "modules/util/opstrlst.h" #include "modules/windowcommander/OpWindowCommander.h" #include "modules/windowcommander/OpWindowCommanderManager.h" #ifdef USE_COMMON_RESOURCES #define SDM_SPEED_DIAL_FILENAME DESKTOP_RES_STD_SPEEDDIAL #else #define SDM_SPEED_DIAL_FILENAME UNI_L("speeddial_default.ini") #endif // USE_COMMON_RESOURCES // Defines number of milliseconds we should wait with reloading all speed dial cells after zoom is done with ctrl + mouse wheel // It's neeeded because of performance issues #define MILLISECONDS_TO_WAIT_WITH_RELOAD 500 // half of a second const double SpeedDialManager::DefaultZoomLevel = 1; const double SpeedDialManager::MinimumZoomLevel = 0.3; const double SpeedDialManager::MaximumZoomLevel = 2; const double SpeedDialManager::MinimumZoomLevelForAutoZooming = 0.6; const double SpeedDialManager::MaximumZoomLevelForAutoZooming = 1.3; const double SpeedDialManager::ScaleDelta = 0.1; //////////////////////////////////////////////////////////////////////////////////////////////////////// // // SpeedDialManager // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// SpeedDialManager::SpeedDialManager() : m_state(Disabled), m_speed_dial_tabs_count(0), m_widget_window(NULL), m_image_layout(OpImageBackground::BEST_FIT), m_background_enabled(false), m_ui_opacity(0), m_scale(DefaultZoomLevel), m_scaling(false), m_force_reload(false), m_undo_animating_in_speed_dial(NULL), m_is_dirty(false), m_has_loaded_config(false) { TRAPD(rc, g_pcui->RegisterListenerL(this)); m_zoom_timer.SetTimerListener(this); int prefs_scale = g_pcui->GetIntegerPref(PrefsCollectionUI::SpeedDialZoomLevel); m_automatic_scale = prefs_scale == 0; if (!m_automatic_scale) m_scale = prefs_scale * 0.01; // set up the delayed trigger with a delay just so it happens when the call stack has unwound. The delay means less // in reality as it will trigger immediately when the calling code enters the message loop again, unless // explicitly aborted by a CancelUpdate() call. m_delayed_trigger.SetDelayedTriggerListener(this); m_delayed_trigger.SetTriggerDelay(10, 10); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// SpeedDialManager::~SpeedDialManager() { // give speed dials last chance to set dirty flag for (UINT32 i = 0; i < m_speed_dials.GetCount(); ++i) { DesktopSpeedDial *sd = m_speed_dials.Get(i); sd->OnShutDown(); } if(m_is_dirty) { OpStatus::Ignore(Save()); } m_deleted_ids.DeleteAll(); g_thumbnail_manager->Flush(); g_pcui->UnregisterListener(this); if(m_widget_window) { m_widget_window->Close(TRUE); } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::Init() { // Handle Kiosk mode if (KioskManager::GetInstance()->GetEnabled()) { if (KioskManager::GetInstance()->GetKioskSpeeddial()) SetState(SpeedDialManager::ReadOnly); else SetState(SpeedDialManager::Disabled); } // Configure the core thumbnail manager with regard to the boundary sizes, zoom levels and view-mode: minimized // thumbnails behavior. ConfigureThumbnailManager(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SpeedDialManager::SetImageLayout(OpImageBackground::Layout layout) { bool changed = m_image_layout != layout; m_image_layout = layout; if(changed) { UINT32 i; for(i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialBackgroundChanged(); } } } void SpeedDialManager::ConfigureThumbnailManager() { // Configure the core thumbnail manager with regard to the boundary sizes, zoom levels and view-mode: minimized // thumbnails behavior. int x_ratio = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::ThumbnailAspectRatioX); int y_ratio = g_pcdoc->GetIntegerPref(PrefsCollectionDoc::ThumbnailAspectRatioY); double aspect_ratio = ((double)x_ratio) / y_ratio; int base_width = THUMBNAIL_WIDTH; int base_height = double(THUMBNAIL_WIDTH) / aspect_ratio; g_thumbnail_manager->SetThumbnailSize(base_width, base_height, MaximumZoomLevel); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SpeedDialManager::ReloadAll(ReloadPurpose purpose) { UINT32 i; for (i = 0; i < m_speed_dials.GetCount(); i++) { if (m_speed_dials.Get(i) && m_speed_dials.Get(i)->GetURL().HasContent()) { // Readd the thumbnail ref's if they were purged away if (PurposePurge == purpose) m_speed_dials.Get(i)->ReAddThumnailRef(); // SetExpired casues a full reload from core, don't do that if we only want to zoom. // The core will the use the bitmap cache. if (PurposeZoom != purpose) m_speed_dials.Get(i)->SetExpired(); else m_speed_dials.Get(i)->Zoom(); } } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// int SpeedDialManager::GetSpeedDialPositionFromURL(const OpStringC& url) const { int i; for (i = 0; i < (int)m_speed_dials.GetCount(); i++) { DesktopSpeedDial* sd = m_speed_dials.Get(i); if (sd) { OpStringC sd_url(sd->GetURL()); OpString tmp; OpString tmp2; if (g_url_api->ResolveUrlNameL(sd_url, tmp) && g_url_api->ResolveUrlNameL(url, tmp2) && tmp.CompareI(tmp2) == 0) { return i; } } } return -1; } bool SpeedDialManager::SpeedDialExists(const OpStringC& url) { return GetSpeedDialPositionFromURL(url) >= 0; } const DesktopSpeedDial* SpeedDialManager::GetSpeedDialByUrl(const OpStringC& url) const { INT32 position = GetSpeedDialPositionFromURL(url); if (position < 0) { return NULL; } return m_speed_dials.Get(position); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::InsertSpeedDial(int pos, const SpeedDialData* sd, bool use_undo) { if (pos < 0 || pos > int(m_speed_dials.GetCount()) - 1) { OP_ASSERT(false); return OpStatus::ERR_OUT_OF_RANGE; } OpAutoPtr<DesktopSpeedDial> new_sd(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(new_sd.get()); RETURN_IF_ERROR(new_sd->Set(*sd)); RETURN_IF_ERROR(m_speed_dials.Insert(pos, new_sd.get())); new_sd->OnAdded(); NotifySpeedDialAdded(*new_sd.release()); if(use_undo) { RETURN_IF_ERROR(m_undo_stack.AddInsert(pos)); } // The speed dials following the one just removed changed positions. for (int i = pos + 1; i < (int)m_speed_dials.GetCount(); ++i) m_speed_dials.Get(i)->OnPositionChanged(); PostSaveRequest(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::RemoveSpeedDial(int pos, bool use_undo) { if (pos < 0 || pos >= (int)m_speed_dials.GetCount()) { OP_ASSERT(!"Don't know this DesktopSpeedDial"); return OpStatus::ERR; } DesktopSpeedDial* sd = m_speed_dials.Get(pos); if (sd->GetPartnerID().HasContent()) { // deleting speed dials with a partner id, store the id so it's not re-added later RETURN_IF_ERROR(AddToDeletedIDs(sd->GetPartnerID().CStr(), true)); } sd->OnRemoving(); NotifySpeedDialRemoving(*sd); if (use_undo) { RETURN_IF_ERROR(m_undo_stack.AddRemove(pos)); } m_speed_dials.Delete(pos); // The speed dials following the one just removed changed positions. for (int i = pos; i < (int)m_speed_dials.GetCount(); ++i) m_speed_dials.Get(i)->OnPositionChanged(); PostSaveRequest(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::ReplaceSpeedDial(int pos, const SpeedDialData* new_sd, bool from_sync /*=false*/) { if (pos < 0 || pos >= (int)m_speed_dials.GetCount()) { OP_ASSERT(!"Don't know DesktopSpeedDial at pos"); return OpStatus::ERR; } if (!DocumentView::IsUrlRestrictedForViewFlag(new_sd->GetURL().CStr(), DocumentView::ALLOW_ADD_TO_SPEED_DIAL)) return OpStatus::ERR; DesktopSpeedDial* old_sd = m_speed_dials.Get(pos); if (old_sd == new_sd) return OpStatus::OK; const bool replacing_plus = pos == int(m_speed_dials.GetCount()) - 1; if (!replacing_plus) RETURN_IF_ERROR(m_undo_stack.AddReplace(pos)); OpAutoPtr<DesktopSpeedDial> new_sd_copy(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(new_sd_copy.get()); RETURN_IF_ERROR(new_sd_copy->Set(*new_sd)); // Skip this when processing sync item. Server will send DATAITEM_SPEEDDIAL_2_SETTINGS // if this speed dial must be blacklisted. if (old_sd->GetPartnerID().HasContent() && !from_sync) { // Add the speed dial partner id to the deleted section if we // change the URL from one that had a partner id, so it won't be added again. if (old_sd->GetURL() != new_sd_copy.get()->GetURL() || // or if user edited title (DSK-355419) (new_sd_copy->IsCustomTitle() && new_sd_copy->GetTitle() != old_sd->GetTitle())) { RETURN_IF_ERROR(AddToDeletedIDs(old_sd->GetPartnerID().CStr(), true)); } } RETURN_IF_ERROR(m_speed_dials.Replace(pos, new_sd_copy.get())); old_sd->OnRemoving(); new_sd_copy->OnAdded(); NotifySpeedDialReplaced(*old_sd, *new_sd_copy.release()); OP_DELETE(old_sd); // The "adder" must never disappear. if (replacing_plus) { OpAutoPtr<DesktopSpeedDial> adder(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(adder.get()); RETURN_IF_ERROR(m_speed_dials.Add(adder.get())); adder->OnAdded(); NotifySpeedDialAdded(*adder.release()); RETURN_IF_ERROR(m_undo_stack.AddInsert(pos)); } PostSaveRequest(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::MoveSpeedDial(int from_pos, int to_pos) { if (to_pos < 0 || from_pos < 0) { OP_ASSERT(!"Can't move DesktopSpeedDials like that"); return OpStatus::ERR; } if (to_pos == from_pos) return OpStatus::OK; DesktopSpeedDial* tmp_sd = m_speed_dials.Remove(from_pos); m_speed_dials.Insert(to_pos, tmp_sd); NotifySpeedDialMoved(from_pos, to_pos); RETURN_IF_ERROR(m_undo_stack.AddMove(from_pos, to_pos)); // These speed dials just changed positions. for (int pos = min(from_pos, to_pos); pos <= max(from_pos, to_pos); pos++) { m_speed_dials.Get(pos)->OnPositionChanged(); } PostSaveRequest(); return OpStatus::OK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// SpeedDialManager::State SpeedDialManager::GetState() const { // In kiosk mode don't save the preference just hold it internally if (KioskManager::GetInstance()->GetEnabled()) return m_state; return static_cast<State>(g_pcui->GetIntegerPref(PrefsCollectionUI::SpeedDialState)); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// void SpeedDialManager::SetState(State state) { // In kiosk mode don't save the preference just hold it internally if (KioskManager::GetInstance()->GetEnabled()) m_state = state; else { TRAPD(err, g_pcui->WriteIntegerL(PrefsCollectionUI::SpeedDialState, state)); } } bool SpeedDialManager::IsPlusButtonShown() const { return g_pcui->GetIntegerPref(PrefsCollectionUI::ShowAddSpeedDialButton) != 0; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::Undo(OpSpeedDialView* sd) { m_undo_animating_in_speed_dial = sd; OP_STATUS status = m_undo_stack.Undo(); // this will ultimately call AnimateThumbnailOut(...) m_undo_animating_in_speed_dial = NULL; return status; } OP_STATUS SpeedDialManager::Redo(OpSpeedDialView* sd) { m_undo_animating_in_speed_dial = sd; OP_STATUS status = m_undo_stack.Redo(); // this will ultimately call AnimateThumbnailOut(...) m_undo_animating_in_speed_dial = NULL; return status; } void SpeedDialManager::AnimateThumbnailOutForUndoOrRedo(int pos) { // This should only ever be called (indirectly) from Undo(...) or Redo(...). OP_ASSERT(m_undo_animating_in_speed_dial); if (!m_undo_animating_in_speed_dial) return; SpeedDialThumbnail* thumb = m_undo_animating_in_speed_dial->GetSpeedDialThumbnail(pos); thumb->AnimateThumbnailOut(false); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// bool SpeedDialManager::IsAddressSpeedDialNumber(const OpStringC &address, OpString &speed_dial_address, OpString &speed_dial_title) { for(int i=0; i<address.Length(); i++) { if (!op_isdigit(address[i])) return false; } if (address.HasContent()) { UINT32 dial_number = uni_atoi(address.CStr()); const DesktopSpeedDial* sd = GetSpeedDial(dial_number - 1); if (sd != NULL && sd->GetURL().HasContent()) { speed_dial_address.Set(sd->GetURL()); speed_dial_title.Set(sd->GetTitle()); return true; } } return false; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::AddConfigurationListener(SpeedDialConfigurationListener* listener) { return m_config_listeners.Add(listener); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::RemoveConfigurationListener(SpeedDialConfigurationListener* listener) { return m_config_listeners.RemoveByItem(listener); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::Load(bool copy_default_file) { bool prefs_changed = false; OpFile speeddial_file; OpString layout; BOOL speeddialfile_exists = FALSE; bool has_default_file = false; bool add_extra_items = false; PrefsFile default_sd_file(PREFS_STD); m_has_loaded_config = true; RETURN_IF_LEAVE(g_pcfiles->GetFileL(PrefsCollectionFiles::SpeedDialFile, speeddial_file)); RETURN_IF_ERROR(speeddial_file.Exists(speeddialfile_exists)); // if it doesn't exist, it's easy and we just copy the file blindly over if(!speeddialfile_exists) { /* Copy over the default file if it exists and there is no current file and it's a clean install */ if (copy_default_file) { OpFile speeddial_default_file; /* Create and check if the file exists; extra items will be added if default file is from custom folder (DSK-330957) */ if (OpStatus::IsSuccess(ResourceSetup::GetDefaultPrefsFile(SDM_SPEED_DIAL_FILENAME, speeddial_default_file, NULL, &add_extra_items))) { /* Copy the file over */ if (OpStatus::IsSuccess(speeddial_file.CopyContents(&speeddial_default_file, TRUE))) { /* Set the flag to exists on a successful copy */ speeddialfile_exists = TRUE; } } } } // don't try any merging unless we're upgrading else if(g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST_NEW_BUILD_NUMBER || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRSTCLEAN || g_application->DetermineFirstRunType() == Application::RUNTYPE_FIRST || g_run_type->m_added_custom_folder || g_region_info->m_changed) { // otherwise, we have a speed dial ini file already, so we need to merge stuff OpFile speeddial_default_file; /* Create and check if the file exists; extra items will be added if default file is from custom folder (DSK-330957) */ has_default_file = !!OpStatus::IsSuccess(ResourceSetup::GetDefaultPrefsFile(SDM_SPEED_DIAL_FILENAME, speeddial_default_file, NULL, &add_extra_items)); if(has_default_file) { OP_STATUS err; /* Construct and load up the default speeddial.ini pref file */ TRAP(err, default_sd_file.ConstructL(); default_sd_file.SetFileL(&speeddial_default_file); default_sd_file.LoadAllL()); has_default_file = !!OpStatus::IsSuccess(err); } } // we also want extra items if region changed and we're upgrading from version < 11.60 (DSK-353188) if(has_default_file && g_region_info->m_changed) { OperaVersion eleven_sixty; RETURN_IF_ERROR(eleven_sixty.Set(UNI_L("11.60.01"))); if (g_application->GetPreviousVersion() < eleven_sixty) { add_extra_items = true; } } /* If the file exists load it! */ if (speeddialfile_exists) { OP_STATUS err; PrefsFile sd_file(PREFS_STD); /* Construct and load up the speeddial.ini pref file, fail on OOM */ RETURN_IF_LEAVE(sd_file.ConstructL()); RETURN_IF_LEAVE(sd_file.SetFileL(&speeddial_file)); RETURN_IF_LEAVE(sd_file.LoadAllL()); PrefsSection *deleted = NULL; // read the deleted entries, if any TRAP(err, deleted = sd_file.ReadSectionL(UNI_L(SPEEDDIAL_DELETED_ITEMS_SECTION))); OpAutoPtr<PrefsSection> section_ap(deleted); if(OpStatus::IsSuccess(err)) { // the deleted IDs are just a flat list of IDs, so read them by key and put them in a table const PrefsEntry *ientry = deleted->Entries(); while(ientry) { const uni_char *id = ientry->Key(); if(id) { RETURN_IF_ERROR(AddToDeletedIDs(id, false)); } ientry = (const PrefsEntry *) ientry->Suc(); } } RETURN_IF_ERROR(MergeSpeedDialEntries(has_default_file, default_sd_file, sd_file, prefs_changed, add_extra_items)); RETURN_IF_LEAVE(m_force_reload = sd_file.ReadIntL(SPEEDDIAL_VERSION_SECTION, SPEEDDIAL_KEY_FORCE_RELOAD, 0) != 0); RETURN_IF_LEAVE(m_background_image_name.SetL(sd_file.ReadStringL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGENAME))); RETURN_IF_LEAVE(layout.SetL(sd_file.ReadStringL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGELAYOUT)); m_background_enabled = sd_file.ReadIntL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGE_ENABLED, false) ? true : false); if (m_background_image_name.HasContent()) { OpFile background_image_file; //Ensure to unserialize the path. if (OpStatus::IsError(background_image_file.Construct(m_background_image_name, OPFILE_SERIALIZED_FOLDER))) { m_background_image_name.Empty(); } else { RETURN_IF_LEAVE(m_background_image_name.SetL(background_image_file.GetFullPath())); } } // Opacity currently disabled as it's not working properly now // m_ui_opacity = max(0, sd_file.ReadIntL(SPEEDDIAL_UI_SECTION, SPEEDDIAL_UI_OPACITY, 0)); } // add plus button which is not specified in file speeddial.ini OpAutoPtr<DesktopSpeedDial> sd(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(sd.get()); RETURN_IF_ERROR(m_speed_dials.Add(sd.get())); sd->OnAdded(); sd.release(); m_image_type = NONE; if(m_background_image_name.HasContent() && m_background_enabled) { RETURN_IF_ERROR(LoadBackgroundImage(m_background_image_name)); } if(!layout.CompareI(UNI_L("center"))) { m_image_layout = OpImageBackground::CENTER; } else if(!layout.CompareI(UNI_L("stretch"))) { m_image_layout = OpImageBackground::STRETCH; } else if(!layout.CompareI(UNI_L("tile"))) { m_image_layout = OpImageBackground::TILE; } else if (!layout.CompareI(UNI_L("crop"))) { m_image_layout = OpImageBackground::BEST_FIT; } else { m_image_layout = OpImageBackground::BEST_FIT; } if(m_ui_opacity > 100) { m_ui_opacity = 0; } if (m_force_reload) { for (unsigned i = 0; i < m_speed_dials.GetCount(); i++) { OpStatus::Ignore(m_speed_dials.Get(i)->StartLoadingSpeedDial(TRUE, GetThumbnailWidth(), GetThumbnailHeight())); }; /* I'd like to only reset m_force_reload if reloading actually * was successful, but this is probably good enough. */ m_force_reload = false; prefs_changed = true; } OP_STATUS s = OpStatus::OK; if(prefs_changed) { s = Save(); } SetDirty(false); NotifySpeedDialsLoaded(); return s; } bool SpeedDialManager::IsInDeletedList(const OpStringC& partner_id) { for(UINT32 i = 0; i < m_deleted_ids.GetCount(); i++) { if(!partner_id.Compare(*m_deleted_ids.Get(i))) return true; } return false; } OP_STATUS SpeedDialManager::AddToDeletedIDs(const uni_char *id, bool notify) { OpAutoPtr<OpString> key (OP_NEW(OpString, ())); RETURN_OOM_IF_NULL(key.get()); RETURN_IF_ERROR(key->Set(id)); RETURN_IF_ERROR(m_deleted_ids.Add(key.get())); key.release(); if(notify) { NotifySpeedDialPartnerIDAdded(id); } return OpStatus::OK; } bool SpeedDialManager::RemoveFromDeletedIDs(const OpStringC& partner_id, bool notify) { for(UINT32 i = 0; i < m_deleted_ids.GetCount(); i++) { if(!partner_id.Compare(*m_deleted_ids.Get(i))) { OpString* id = m_deleted_ids.Remove(i); if(notify) { NotifySpeedDialPartnerIDDeleted(id->CStr()); } OP_DELETE(id); return true; } } return false; } /* Some rules: - If a partner_id is in the deleted section, don't do anything with it - If the url of a certain partner_id speed dial is different in the default speeddial.ini, replace the users speed dial entry with the new one, regardless of the position - If a partner_id in the default speedial doesn't exist in the user speeddial, add it in the first available blank spot (usually at the end) */ OP_STATUS SpeedDialManager::MergeSpeedDialEntries(bool merge_entries, PrefsFile& default_sd_file, PrefsFile& sd_file, bool& prefs_changed, bool add_extra_items) { OpAutoStringHashTable<DesktopSpeedDial> default_partner_id_speed_dials; // we use this for faster lookups on partner_ids OpStringHashTable<DesktopSpeedDial> default_url_speed_dials; // we use this for faster lookups on URLs prefs_changed = false; if(merge_entries) { // first read the default sd file OpString_list sections; RETURN_IF_LEAVE(default_sd_file.ReadAllSectionsL(sections)); OpString8 section_name; for(unsigned i = 0; i < sections.Count(); ++i) { RETURN_IF_ERROR(section_name.Set(sections[i])); if(!section_name.Compare(SPEEDDIAL_SECTION_STR, strlen(SPEEDDIAL_SECTION_STR))) { OpAutoPtr<DesktopSpeedDial> sd(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(sd.get()); RETURN_IF_LEAVE(RETURN_IF_ERROR(sd->LoadL(default_sd_file, section_name))); // only check anything with speed dials that has a partner id // otherwise we'll just drop it again when the smart ptr goes out of scope if(sd->GetPartnerID().HasContent()) { // ignore it if speed dial with the same partner id or URL is already loaded if (default_partner_id_speed_dials.Contains(sd->GetPartnerID().CStr()) || default_url_speed_dials.Contains(sd->GetURL().CStr())) continue; // ignore it for further checks if it's in the deleted list if(IsInDeletedList(sd->GetPartnerID())) continue; RETURN_IF_ERROR(default_partner_id_speed_dials.Add(sd->GetPartnerID().CStr(), sd.get())); DesktopSpeedDial* sd_ptr = sd.release(); // in auto hash now, so release RETURN_IF_ERROR(default_url_speed_dials.Add(sd_ptr->GetURL().CStr(), sd_ptr)); } } } } // read the regular sections OpString_list sections; RETURN_IF_LEAVE(sd_file.ReadAllSectionsL(sections)); OpString8 section_name; for(unsigned i = 0; i < sections.Count(); ++i) { RETURN_IF_ERROR(section_name.Set(sections[i])); if(!section_name.Compare(SPEEDDIAL_SECTION_STR, strlen(SPEEDDIAL_SECTION_STR))) { // this is speed dial section OpAutoPtr<DesktopSpeedDial> sd(OP_NEW(DesktopSpeedDial, ())); RETURN_OOM_IF_NULL(sd.get()); RETURN_IF_LEAVE(RETURN_IF_ERROR(sd->LoadL(sd_file, section_name))); if (sd->GetExtensionWUID().HasContent()) { if (!ExtensionUtils::IsExtensionRunning(sd->GetExtensionWUID())) { // in case extensions was not started, delete its entry from speeddial.ini prefs_changed = true; continue; } } RETURN_IF_ERROR(m_speed_dials.Add(sd.get())); sd->OnAdded(); DesktopSpeedDial *tmp_sd = sd.release(); // check if we need to replace or update anything if(merge_entries) { const OpStringC& partner_id = tmp_sd->GetPartnerID(); const OpStringC& url = tmp_sd->GetURL(); DesktopSpeedDial *partner_sd; // check if we have a match on partner id first if(partner_id.HasContent() && OpStatus::IsSuccess(default_partner_id_speed_dials.GetData(partner_id.CStr(), &partner_sd))) { if(tmp_sd->GetURL().Compare(partner_sd->GetURL())) { // If the url of a certain partner_id speed dial is different in the default speeddial.ini, // replace the users speed dial entry with the new one, regardless of the position // Keep the unique id unchanged to avoid adding duplicates in other browsers that will // get this change via Link tmp_sd->Set(*partner_sd, true); prefs_changed = true; } OpStatus::Ignore(default_url_speed_dials.Remove(url.CStr(), &partner_sd)); // We found it, remove it so it's not added at the end of the speed dials later if(OpStatus::IsSuccess(default_partner_id_speed_dials.Remove(partner_id.CStr(), &partner_sd))) { OP_DELETE(partner_sd); } } // if not, check if we have the same url in speed dial but without partner id else if(url.HasContent() && OpStatus::IsSuccess(default_url_speed_dials.GetData(url.CStr(), &partner_sd))) { // we have the same url in the user file, update its data instead (but keep the unique id unchanged) tmp_sd->Set(*partner_sd, true); prefs_changed = true; OpStatus::Ignore(default_url_speed_dials.Remove(url.CStr(), &partner_sd)); // We found it, remove it so it's not added at the end of the speed dials later if(OpStatus::IsSuccess(default_partner_id_speed_dials.Remove(partner_id.CStr(), &partner_sd))) { OP_DELETE(partner_sd); } } } // check if we have an ID and generate it if not if(tmp_sd->GetUniqueID().IsEmpty()) { RETURN_IF_ERROR(tmp_sd->GenerateIDIfNeeded(FALSE, TRUE, m_speed_dials.Find(tmp_sd) + 1)); prefs_changed = true; } } } // If a partner_id in the default speeddial doesn't exist in the user speeddial, // add it in the first available blank spot (usually at the end) if(add_extra_items) { for (StringHashIterator<DesktopSpeedDial> it(default_partner_id_speed_dials); it; it++) { DesktopSpeedDial* sd = it.GetData(); // ownership transferred to the m_speed_dials collection RETURN_IF_ERROR(m_speed_dials.Add(sd)); sd->OnAdded(); prefs_changed = true; if(sd->GetUniqueID().IsEmpty()) { RETURN_IF_ERROR(sd->GenerateIDIfNeeded(FALSE, TRUE, m_speed_dials.Find(sd) + 1)); } } } default_partner_id_speed_dials.RemoveAll(); return OpStatus::OK; } // Will return a list of the default URLs if the default speed dial ini file can be found. OP_STATUS SpeedDialManager::GetDefaultURLList(OpString_list& url_list, OpString_list& title_list) { // The lists should be empty when passed in OP_ASSERT(url_list.Count() == 0); OP_ASSERT(title_list.Count() == 0); // Get the default speed dial ini file OpFile default_file; RETURN_IF_ERROR(ResourceSetup::GetDefaultPrefsFile(SDM_SPEED_DIAL_FILENAME, default_file)); // Read the URLs, and add them to the string list PrefsFile default_prefs_file(PREFS_STD); /* Construct and load up the speeddial.ini pref file */ OP_STATUS status; TRAP(status, default_prefs_file.ConstructL(); default_prefs_file.SetFileL(&default_file); default_prefs_file.LoadAllL(); ); RETURN_IF_ERROR(status); /* Loop the sections */ UINT32 i; url_list.Resize(m_speed_dials.GetCount()); title_list.Resize(m_speed_dials.GetCount()); for (i = 1; i <= m_speed_dials.GetCount(); i++) { /* Sections are from 1 -> 10 */ OpString8 section_name; RETURN_IF_ERROR(section_name.AppendFormat(SPEEDDIAL_SECTION, i)); // Read the URL and title sections OpString url; OpString title; TRAP(status, url.Set(default_prefs_file.ReadStringL(section_name.CStr(), SPEEDDIAL_KEY_URL)); title.Set(default_prefs_file.ReadStringL(section_name.CStr(), SPEEDDIAL_KEY_TITLE)); ); // Add them to the list, but only if you both have title and URL if (url.HasContent() && title.HasContent()) { url_list.Item(i-1).Set(url); title_list.Item(i-1).Set(title); } } return OpStatus::OK; } OP_STATUS SpeedDialManager::LoadBackgroundImage(OpString& filename) { m_image_type = NONE; RETURN_IF_ERROR(m_background_image_name.Set(filename.CStr())); #ifdef SPEEDDIAL_SVG_SUPPORT if(uni_stristr(filename.CStr(), ".svg") != NULL) { m_svg_background.SetListener(this); RETURN_IF_ERROR(m_svg_background.LoadSVGImage(filename)); } else #endif // SPEEDDIAL_SVG_SUPPORT { RETURN_IF_ERROR(m_image_reader.Read(filename)); m_image_type = BITMAP; } UINT32 i; for(i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialBackgroundChanged(); } return OpStatus::OK; } void SpeedDialManager::OnColumnLayoutChanged() { for (UINT32 i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialColumnLayoutChanged(); } } void SpeedDialManager::SetBackgroundImageEnabled(bool enabled) { m_background_enabled = enabled; UINT32 i; for(i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialBackgroundChanged(); } } bool SpeedDialManager::HasBackgroundImage() { #ifdef SPEEDDIAL_SVG_SUPPORT if(m_image_type == SVG) { return m_background_enabled; } else #endif // SPEEDDIAL_SVG_SUPPORT if(m_image_type == BITMAP) { return m_background_enabled && !m_image_reader.GetImage().IsEmpty(); } return false; } Image SpeedDialManager::GetBackgroundImage(UINT32 width, UINT32 height) { #ifdef SPEEDDIAL_SVG_SUPPORT if(m_image_type == SVG) { return m_svg_background.GetImage(width, height); } else #endif // SPEEDDIAL_SVG_SUPPORT if (m_image_type == BITMAP) { return m_image_reader.GetImage(); } return Image(); } #ifdef SPEEDDIAL_SVG_SUPPORT void SpeedDialManager::OnImageLoaded() { UINT32 i; m_image_type = SVG; for(i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialBackgroundChanged(); } } #endif // SPEEDDIAL_SVG_SUPPORT void SpeedDialManager::StartConfiguring(const DesktopWindow& window) { for (UINT32 i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialConfigurationStarted(window); } } bool SpeedDialManager::SetThumbnailScale(double new_scale) { new_scale = MAX(MinimumZoomLevel, MIN(MaximumZoomLevel, new_scale)); if (m_scale == new_scale) return false; m_scale = new_scale; if (!m_automatic_scale) UpdateScale(); return true; } void SpeedDialManager::ChangeScaleByDelta(bool scale_up) { if (scale_up) SetThumbnailScale(m_scale + ScaleDelta); else SetThumbnailScale(m_scale - ScaleDelta); } void SpeedDialManager::SetAutomaticScale(bool is_automatic_scale) { if (m_automatic_scale != is_automatic_scale) { m_automatic_scale = is_automatic_scale; UpdateScale(); } } void SpeedDialManager::UpdateScale() { int prefs_scale = m_automatic_scale ? 0 : GetIntegerThumbnailScale(); TRAPD(err, g_pcui->WriteIntegerL(PrefsCollectionUI::SpeedDialZoomLevel, prefs_scale)); for (UINT32 i = 0; i < m_config_listeners.GetCount(); i++) { m_config_listeners.Get(i)->OnSpeedDialScaleChanged(); } if (!m_scaling) m_zoom_timer.Start(MILLISECONDS_TO_WAIT_WITH_RELOAD); } void SpeedDialManager::StartScaling() { OP_ASSERT(!m_scaling); m_scaling = true; } void SpeedDialManager::EndScaling() { OP_ASSERT(m_scaling); m_scaling = false; m_zoom_timer.Start(MILLISECONDS_TO_WAIT_WITH_RELOAD); } unsigned SpeedDialManager::GetThumbnailWidth() const { ThumbnailManager::ThumbnailSize size = g_thumbnail_manager->GetThumbnailSize(); return (m_scale * size.base_thumbnail_width); } unsigned SpeedDialManager::GetThumbnailHeight() const { ThumbnailManager::ThumbnailSize size = g_thumbnail_manager->GetThumbnailSize(); return (m_scale * size.base_thumbnail_height); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////// OP_STATUS SpeedDialManager::Save() { UINT32 i; OpFile speeddial_file; if(m_has_loaded_config == false) { OP_ASSERT(!"Save() called before Load(), data loss will occur if we continue with Save()"); return OpStatus::ERR_NOT_SUPPORTED; } RETURN_IF_LEAVE(g_pcfiles->GetFileL(PrefsCollectionFiles::SpeedDialFile, speeddial_file)); /* Construct and load up the speeddial.ini pref file */ PrefsFile sd_file(PREFS_STD); RETURN_IF_LEAVE( sd_file.ConstructL(); sd_file.SetFileL(&speeddial_file)); /* Kill all the sections in the speeddial.ini which will be replaced below */ RETURN_IF_LEAVE(sd_file.DeleteAllSectionsL()); if (m_force_reload) RETURN_IF_LEAVE(sd_file.WriteIntL(SPEEDDIAL_VERSION_SECTION, SPEEDDIAL_KEY_FORCE_RELOAD, 1)); // write out the deleted entries for(UINT32 n = 0; n < m_deleted_ids.GetCount(); n++) { RETURN_IF_LEAVE(sd_file.WriteStringL(UNI_L(SPEEDDIAL_DELETED_ITEMS_SECTION), *m_deleted_ids.Get(n), NULL)); } if(m_background_image_name.HasContent()) { RETURN_IF_LEAVE(sd_file.WriteStringL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGENAME, m_background_image_name.CStr())); const uni_char *layout_option = UNI_L("Crop"); switch(m_image_layout) { case OpImageBackground::STRETCH: { layout_option = UNI_L("Stretch"); } break; case OpImageBackground::TILE: { layout_option = UNI_L("Tile"); } break; case OpImageBackground::CENTER: { layout_option = UNI_L("Center"); } break; } RETURN_IF_LEAVE(sd_file.WriteStringL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGELAYOUT, layout_option)); } RETURN_IF_LEAVE(sd_file.WriteIntL(SPEEDDIAL_IMAGE_SECTION, SPEEDDIAL_KEY_IMAGE_ENABLED, IsBackgroundImageEnabled())); for (i = 1; i <= m_speed_dials.GetCount(); i++) { DesktopSpeedDial *sd = m_speed_dials.Get(i - 1); if(!sd->IsEmpty()) { OpString8 section_name; RETURN_IF_ERROR(section_name.AppendFormat(SPEEDDIAL_SECTION, i)); RETURN_IF_LEAVE(sd->SaveL(sd_file, section_name)); } } if(HasUIOpacity()) { RETURN_IF_LEAVE(sd_file.WriteIntL(SPEEDDIAL_UI_SECTION, SPEEDDIAL_UI_OPACITY, GetUIOpacity())); } /* Commit the speed dial file */ RETURN_IF_LEAVE(sd_file.CommitL()); return OpStatus::OK; } DesktopSpeedDial* SpeedDialManager::GetSpeedDialByID(const uni_char* unique_id) const { for (UINT32 i = 0; i < m_speed_dials.GetCount(); i++) { DesktopSpeedDial *sd = m_speed_dials.Get(i); if(!sd->IsEmpty() && !sd->GetUniqueID().Compare(unique_id)) { return sd; } } return NULL; } void SpeedDialManager::PrefChanged(OpPrefsCollection::Collections id, int pref, int newvalue) { if (id != OpPrefsCollection::UI) return; switch (pref) { case PrefsCollectionUI::SpeedDialState: case PrefsCollectionUI::ShowAddSpeedDialButton: g_application->SettingsChanged(SETTINGS_SPEED_DIAL); break; } } void SpeedDialManager::OnTimeOut(OpTimer* timer) { if (timer == &m_zoom_timer && !m_scaling) { ReloadAll(PurposeZoom); } } void SpeedDialManager::SetDirty( bool state ) { // should not get dirty before speeddial.ini is loaded OP_ASSERT(m_has_loaded_config || !state); if( m_is_dirty != state ) { m_is_dirty = state; if( m_is_dirty ) { // Start delayed save m_delayed_trigger.InvokeTrigger(); } else { // abort writing m_delayed_trigger.CancelTrigger(); } } } void SpeedDialManager::OnTrigger(OpDelayedTrigger* trigger) { OP_ASSERT(trigger == &m_delayed_trigger); if(OpStatus::IsSuccess(Save())) { m_is_dirty = false; } } void SpeedDialManager::NotifySpeedDialAdded(const DesktopSpeedDial& sd) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialAdded(sd); } void SpeedDialManager::NotifySpeedDialRemoving(const DesktopSpeedDial& sd) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialRemoving(sd); } void SpeedDialManager::NotifySpeedDialReplaced(const DesktopSpeedDial& old_sd, const DesktopSpeedDial& new_sd) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialReplaced(old_sd, new_sd); } void SpeedDialManager::NotifySpeedDialMoved(int from_pos, int to_pos) { const DesktopSpeedDial* from_sd = GetSpeedDial(from_pos); const DesktopSpeedDial* to_sd = GetSpeedDial(to_pos); for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialMoved(*from_sd, *to_sd); } void SpeedDialManager::NotifySpeedDialPartnerIDAdded(const uni_char* partner_id) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialPartnerIDAdded(partner_id); } void SpeedDialManager::NotifySpeedDialPartnerIDDeleted(const uni_char* partner_id) { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialPartnerIDDeleted(partner_id); } void SpeedDialManager::NotifySpeedDialsLoaded() { for (OpListenersIterator it(m_listeners); m_listeners.HasNext(it); ) m_listeners.GetNext(it)->OnSpeedDialsLoaded(); } unsigned SpeedDialManager::GetDefaultCellWidth() const { ThumbnailManager::ThumbnailSize size = g_thumbnail_manager->GetThumbnailSize(); return size.base_thumbnail_width; } void SpeedDialManager::GetMinimumAndMaximumCellSizes(unsigned& min_width, unsigned& min_height, unsigned& max_width, unsigned& max_height) const { ThumbnailManager::ThumbnailSize size = g_thumbnail_manager->GetThumbnailSize(); min_width = size.base_thumbnail_width * (m_automatic_scale ? MinimumZoomLevelForAutoZooming : MinimumZoomLevel); min_height = size.base_thumbnail_height * (m_automatic_scale ? MinimumZoomLevelForAutoZooming : MinimumZoomLevel); max_width = size.base_thumbnail_width * (m_automatic_scale ? MaximumZoomLevelForAutoZooming : MaximumZoomLevel); max_height = size.base_thumbnail_height * (m_automatic_scale ? MaximumZoomLevelForAutoZooming : MaximumZoomLevel); } INT32 SpeedDialManager::FindSpeedDialByWuid(const OpStringC& wuid) const { for (unsigned i = 0; i < m_speed_dials.GetCount(); ++i) { if (m_speed_dials.Get(i)->GetExtensionWUID() == wuid) { return i; } } return -1; } INT32 SpeedDialManager::FindSpeedDialByUrl(const OpStringC& url, bool include_display_url) const { int len_to_cmp = KAll; int len_of_doc_url = url.Length(); for(UINT32 i = 0; i < g_speeddial_manager->GetTotalCount(); i++) { const DesktopSpeedDial *entry = g_speeddial_manager->GetSpeedDial(i); if(entry && !entry->IsEmpty() && !entry->GetExtensionWUID().HasContent()) { // DSK-345498 int len_of_entry_url = entry->GetURL().Length(); if (abs(len_of_entry_url - len_of_doc_url ) == 1) { int min_len = min(len_of_entry_url, len_of_doc_url); if (entry->GetURL().DataPtr()[min_len] == UNI_L('/') || url.DataPtr()[min_len] == UNI_L('/')) len_to_cmp = min_len; } if (entry->GetURL().Compare(url, len_to_cmp) == 0) return i; else if (include_display_url && entry->GetDisplayURL().Compare(url) == 0) return i; } } return -1; } #ifdef SPEEDDIAL_SVG_SUPPORT SpeedDialSVGBackground::SpeedDialSVGBackground() : m_listener(NULL), m_window(NULL), m_windowcommander(NULL), m_width(1280), m_height(1024) { } SpeedDialSVGBackground::~SpeedDialSVGBackground() { if (m_windowcommander) // might not exist due to OOM in init { m_windowcommander->SetLoadingListener(NULL); m_windowcommander->OnUiWindowClosing(); g_windowCommanderManager->ReleaseWindowCommander(m_windowcommander); m_windowcommander = NULL; } OP_DELETE(m_window); } void SpeedDialSVGBackground::OnLoadingFinished(OpWindowCommander* commander, LoadingFinishStatus status) { if(status == OpLoadingListener::LOADING_SUCCESS) { if(m_listener) { m_listener->OnImageLoaded(); } } } Image SpeedDialSVGBackground::GetImage(UINT32 width, UINT32 height) { bool changed = m_width != width || m_height != height || m_dirty; if(!changed) { return m_image; } m_width = width; m_height = height; OpStatus::Ignore(WindowCommanderProxy::GetSVGImage(m_windowcommander, m_image, width, height)); m_dirty = false; return m_image; } OP_STATUS SpeedDialSVGBackground::LoadSVGImage(OpString& filename) { if(!m_windowcommander) { RETURN_IF_ERROR(g_windowCommanderManager->GetWindowCommander(&m_windowcommander)); } if(!m_window) { RETURN_IF_ERROR(OpWindow::Create(&m_window)); RETURN_IF_ERROR(m_window->Init(OpWindow::STYLE_DESKTOP, OpTypedObject::WINDOW_TYPE_UNKNOWN, NULL, NULL)); RETURN_IF_ERROR(m_windowcommander->OnUiWindowCreated(m_window)); m_windowcommander->SetLoadingListener(this); } m_dirty = true; m_windowcommander->OpenURL(filename.CStr(), FALSE); return OpStatus::OK; } #endif // SPEEDDIAL_SVG_SUPPORT #endif // SUPPORT_SPEED_DIAL
#include "ReconstructionError.h" #include <ComputerVisionLib/Common/EigenHelpers.h> Eigen::Array2Xd Cvl::ReconstructionError::project(Eigen::Affine3d const & modelView, CameraModel const & cameraModel, Eigen::Array2Xd const & srcPoints) { // Since we have only 2d template points points with with z=0, // we can skip the z rotation axis here. Eigen::Matrix3d planarModelView; planarModelView.col(0) = modelView.linear().col(0); planarModelView.col(1) = modelView.linear().col(1); planarModelView.col(2) = modelView.translation(); // transformation to normalized camera coordinates Eigen::Array2Xd normalizedCameraPoints = (planarModelView * srcPoints.matrix().colwise().homogeneous()).colwise().hnormalized(); return cameraModel.distortAndProject(normalizedCameraPoints); } Eigen::VectorXd Cvl::ReconstructionError::calculateDiff( Eigen::Affine3d const & modelView, CameraModel const & cameraModel, Eigen::Array2Xd const & srcPoints, Eigen::Array2Xd const & dstPoints) { // camera projection to image coordinates Eigen::Array2Xd estimatedPoints = project(modelView, cameraModel, srcPoints); // difference of estimated and measured points Eigen::Array2Xd diff = estimatedPoints - dstPoints; Eigen::Map<Eigen::VectorXd> diffMap(diff.data(), diff.size()); return diffMap; } Eigen::VectorXd Cvl::ReconstructionError::calculateDiff( Eigen::Matrix<double, 6, 1> const & modelViewParameter, CameraModel const & cameraModel, Eigen::Array2Xd const & srcPoints, Eigen::Array2Xd const & dstPoints) { return calculateDiff(createModelView(modelViewParameter), cameraModel, srcPoints, dstPoints); } double Cvl::ReconstructionError::calculateRMSE( Eigen::Affine3d const & modelView, CameraModel const & cameraModel, Eigen::Array2Xd const & srcPoints, Eigen::Array2Xd const & dstPoints) { return std::sqrt(calculateDiff(modelView, cameraModel, srcPoints, dstPoints).squaredNorm() / srcPoints.size()); }
result[0] = -c[1]; result[1] = c[0];
vector<int> Solution::subUnsort(vector<int> &A) { int start = -1, end = -1; vector<int> v(1, -1); int n = A.size(); for (int i = 0; i < n - 1; i++) { if (A[i] > A[i + 1]) { start = i; break; } } if (start == -1) return v; for (int i = n - 1; i > 0; i--) { if (A[i] < A[i - 1]) { end = i; break; } } int small = INT_MAX; int great = INT_MIN; for (int i = start; i <= end; i++) { small = min(small, A[i]); great = max(great, A[i]); } start = INT_MAX; end = INT_MIN; for (int i = 0; i < n; i++) { if (A[i] > small) { start = min(i, start); } if (A[n - 1 - i] < great) { end = max(n - 1 - i, end); } } v.clear(); v.push_back(start); v.push_back(end); return v; }
/** Interactive Graphics Spring '15 Assignment #2 Ping Pong 3D Authors: Barbara and Ivana **/ #ifndef App_h #define App_h #include <G3D/G3DAll.h> class App : public GApp { public: App(const GApp::Settings& settings = GApp::Settings()); virtual void onInit(); virtual void onUserInput(UserInput *uinput); virtual void onSimulation(RealTime rdt, SimTime sdt, SimTime idt); virtual void onGraphics3D(RenderDevice* rd, Array< shared_ptr<Surface> >& surface); // Use these functions to access the current state of the paddle! Vector3 getPaddlePosition() { return paddleFrame.translation; } Vector3 getPaddleNormal() { return Vector3(0,0,-1); } Vector3 getPaddleVelocity() { return paddleVel; } // Functions for collision detection. virtual void detectCollisionTable(); virtual void detectCollisionPaddle(); virtual void detectCollisionNet(); // Functions for detecting if the ball is within the table and net bounds bool isWithinTableBounds(); bool isWithinNetBounds(); virtual void game(RenderDevice* rd); // renders the ball virtual Vector3 updateBallPos(double time); // return ball position based on time // Reset the game virtual void resetBall(); virtual void resetCollisions(); virtual void resetMessage(); virtual void resetScores(); // Draw win/lose message on the screen virtual void drawMessage(RenderDevice* rd); protected: // Numerical constants static const double GRAVITY; static const double BALL_RADIUS; static const double PADDLE_RADIUS; static const double TABLE_FRICTION; static const double RESTITUTION; double time; // game time (slower than real time) Vector3 lastBallPos; // last ball position Vector3 ballPos; // current ball position Vector3 initBallVelocity; // intial ball velocity double x_pos; // the initial launch x position double y_pos; // the initial launch y position double z_pos; // the initial launch z position CoordinateFrame paddleFrame; // stores position and rotation data for the paddle.1 Vector3 paddleVel; // paddle's current velocity. bool serve; // is the ball in play bool tableCollision; // has the ball collided with the table bool paddleCollision; // has the ball collided with the table bool netCollision; // has the ball collided with the net bool netFlag; // check if the ball has hit the net for the first time Vector3 newPaddlePos; // the current paddle position Vector3 lastPaddlePos; // the last paddle position Cylinder paddlePosCylinder; // a cylinder between the last and the current paddle position int playerScore; // player/user's score int opponentScore; // opponent/computer's score String message; // win/lose message to be printed in the screen Color3 messageColor; }; #endif
#include <iostream> #include <iomanip> #include <string> #include <vector> #include <math.h> using namespace std; int task2() { int a, b, c; cout << "Enter value a, b, c: " << '\n'; cout << "a = "; cin >> a; cout << "\nb = "; cin >> b; cout << "\nc = "; cin >> c; double x; cout << "\nCaclutation: x = (à + b - c / à) + c * a * a - (a + b)\n"; x = (a + b - c / a) + c * a * a - (a + b); cout << "x = " << x << '\n'; return 0; }
#include <Arduino.h> #include <TM1638GS.h> // I/O pins on the Arduino connected to strobe, clock, data // (power should go to 3.3v and GND) //TM1638GS tm(0,2,14); // D3 D4 D5 WeMos D1R23 TM1638GS LedAndKey(5,6,7); // D5 D6 D7 Leonardo void doLEDs(uint8_t value); char string[] = "IP = 192.168.2.71"; int end = sizeof(string) - 8; char text[9] = " "; void setup() { LedAndKey.reset(); } void loop() { int x = 0; LedAndKey.displayText("AbCdEF"); LedAndKey.setColorLED(0, 1); LedAndKey.setColorLED(1, 2); LedAndKey.setColorLED(6, 2); LedAndKey.setColorLED(7, 1); delay(2000); LedAndKey.clearLEDs(); delay(1000); strcpy(string, "briGht"); const char* pos = string; LedAndKey.displayText(pos); x = 0; do { LedAndKey.setColorLED(x, 1); LedAndKey.setBrightness(x); LedAndKey.displayASCII(7, x+48); delay(500); x++; } while(x<8); LedAndKey.setBrightness(2); LedAndKey.clearLEDs(); LedAndKey.clear(); delay(1000); LedAndKey.displayHex(0, 8); LedAndKey.displayHex(1, 9); LedAndKey.displayHex(2, 10); LedAndKey.displayHex(3, 11); LedAndKey.displayHex(4, 12); LedAndKey.displayHex(5, 13); LedAndKey.displayHex(6, 14); LedAndKey.displayHex(7, 15); delay(2000); LedAndKey.clear(); delay(2000); x = 0; strcpy(string, "IP = 192.168.2.71"); while (x < end) { const char* pos = string + x; //display.setChars(pos, 0); LedAndKey.displayText(pos); if (x == 0) delay(1000); else delay(300); x++; } delay(3000); LedAndKey.clear(); delay(2000); LedAndKey.setColorLEDs(0xF0, 0x0F); //<-- Right half green, left half red delay(2000); LedAndKey.setColorLEDs(0x55, 0x00); //<-- Right half green, left half red delay(2000); LedAndKey.setColorLEDs(0x00, 0xAA); //<-- Right half green, left half red delay(2000); LedAndKey.clearLEDs(); x = 0; do { LedAndKey.setColorLED(x, 1); delay(150); LedAndKey.setColorLED(x, 0); x++; } while(x<8); do { x--; LedAndKey.setColorLED(x, 2); delay(150); LedAndKey.setColorLED(x, 0); } while(x != 0); x = 0; do { LedAndKey.setColorLED(x, 3); delay(150); LedAndKey.setColorLED(x, 0); x++; } while(x<8); strcpy(string, "buttons"); pos = string; LedAndKey.displayText(pos); //LedAndKey.displayText("buttons"); x = 0; do { uint8_t buttons = LedAndKey.readButtons(); doLEDs(buttons); x++; } while(x < 2000); // delay(2000); LedAndKey.clear(); delay(2000); } // scans the individual bits of value void doLEDs(uint8_t value) { for (uint8_t position = 0; position < 8; position++) { LedAndKey.setColorLED(position, value & 1); value = value >> 1; } }
/* * File: main.cpp * Author: Daniel Canales * * Created on July 23, 2014, 1:02 PM */ #include <cstdlib> #include <iostream> #include <cmath> using namespace std; /* * */ //functions void presentValue(float future, float intrest, float years); int main(int argc, char** argv) { //declare variables float intrest, future, years; //get inputs cout << "Please enter how many years you wish to save for" << endl; cin >> years; cout << "Please enter how much you would like to have in that account" << endl; cin >> future; cout << "What would be the intrest rate" << endl; cin >> intrest; presentValue(future,intrest,years); return 0; } void presentValue(float future, float intrest, float years) { intrest /= 100; int temp = pow((1+intrest),years); float present; present = future/temp; cout << "You will need to deposit $" << present << " now" << endl; }
#include "CERPCategory.h" #include "CCategoryFactory.h" #include "CMisc.h" #include "CClientLog.h" #include <QFile> CERPCategory::CERPCategory(QObject *parent) : CCategoryBase(parent) { } CERPCategory::~CERPCategory() { } QString CERPCategory::Category() const { return QString::fromLocal8Bit("ERP"); } //ERP类判断是否安装需要判断程序exe文件是否存在 bool CERPCategory::IsAppInstall(const SoftData& data) { if(data.mainExe.isEmpty()) { //主EXE没有配置,判断目标目录是否存在 return CMisc::IsFileExist(data.location); } QString mainPath = data.location + "/" + data.mainExe; //ClientLogger->AddLog(QString::fromLocal8Bit("判断本地软件路劲:%1 是否存在").arg(mainPath)); return CMisc::IsFileExist(mainPath); } //判断该类型中是否存在需要升级(安装)的软件 const QMap<QString, SoftData> CERPCategory::UpgradeSoftwareData() { QMap<QString, SoftData> srcData = GetData(); QMap<QString, SoftData> upgradeData; //本地没有任何品牌安装 if(GetLocalBrand().isEmpty()) { //本地没有品牌安装,那么就需要进行一次扫描,以确定本地 //是否存在已安装的软件,扫描出的列表可能含有多种品牌, //那么扫描结束后需要做进一步的处理 QMapIterator<QString, SoftData> iter(srcData); while(iter.hasNext()) { iter.next(); SoftData data = iter.value(); //此处的本地文件夹扫描,只是为了设置确定已安装的品牌 LocalInstall(data); if(data.state == SMonitor::Normal || data.state == SMonitor::Upgrade) { //本地数据已安装,则需要记录已经安装的品牌 SetLocalBrand(data.brand); } //本地扫描后,会有合法路径得出,所以这里要重新进行赋值 srcData.insert(data.name, data); } } QString brand = GetLocalBrand(); if(brand.isEmpty()) { //由于任何软件的安装都会改变本地安装brand, 扫描后本地未存在任何已安装 //的品牌,那么则表示为全新的环境,则服务器数据需要全部显示 QMapIterator<QString, SoftData> iter(srcData); while(iter.hasNext()) { iter.next(); SoftData data = iter.value(); //此处已经确定无任何品牌安装,所以无需再判断是否安装至本地 //LocalInstall(data); emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); upgradeData.insert(data.name, data); } } else { QMap<QString, SoftData> LocalData = CategoryFactory->LocalData().value(Category(), QMap<QString, SoftData> ()); QMapIterator<QString, SoftData> iter(srcData); while(iter.hasNext()) { iter.next(); SoftData data = iter.value(); if(data.brand == brand) //只显示已安装品牌的软件 { if(LocalData.contains(iter.key()))//本地数据包含 { const SoftData& lData = LocalData.value(iter.key()); if(CMisc::IsNeedUpdate(lData.version, data.version)) { //软件需要进行升级 data.state = SMonitor::Upgrade; emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); upgradeData.insert(data.name, data); } else {//无需升级,需要检查一下程序是否还存在 if(!LocalInstall(data)) {//已经不存在了 upgradeData.insert(data.name, data); emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); } else { if(data.version.isEmpty()) continue; //本地已安装,则需要比较版本号,判断是否需要进行升级 QString version = CMisc::GetVersionFileVersion(data.location); if(CMisc::IsNeedUpdate(version, data.version)) { //软件需要进行升级 data.state = SMonitor::Upgrade; upgradeData.insert(data.name, data); emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); } } } } else { //判断本地是否已经安装 if(LocalInstall(data)) { //本地已安装,则需要比较版本号,判断是否需要进行升级 QString version = CMisc::GetVersionFileVersion(data.location); if(CMisc::IsNeedUpdate(version, data.version)) { //软件需要进行升级 data.state = SMonitor::Upgrade; upgradeData.insert(data.name, data); emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端软件 [%1] 可更新至版本 [%2]") .arg(data.name).arg(data.version)); } else {//本地已安装,但是本地数据中不包含,那么也需要显示 data.state = SMonitor::Normal; upgradeData.insert(data.name, data); } } else { upgradeData.insert(data.name, data); emit MessageNotify(QDateTime::currentDateTime(), QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); ClientLogger->AddLog(QString::fromLocal8Bit("客户端可安装软件 [%1](版本[%2]),请及时安装") .arg(data.name).arg(data.version)); } } } } } return upgradeData; }
#include "Executable.h" #include "Execution.h" using namespace std; /*void FunctionCall::execute(Execution& ex) { list<shared_ptr<Value>> paramValues; for (auto& i : params) paramValues.push_back(i->evaluate(ex)); ex.callFunction(funIdent, paramValues, defaultReturnValue); } shared_ptr<Value> FunctionCall::evaluate(Execution& ex) { execute(ex); return ex.retrieveReturnValue(); } void AssignmentEx::execute(Execution& ex) { ex.assignValue(varIdent, valueToAssign->evaluate(ex)); } void ReturnEx::execute(Execution& ex) { ex.returnFromFunction(toReturn->evaluate(ex)); } void Conditional::execute(Execution& ex) { if (static_pointer_cast<Boolean>(condition->evaluate(ex))->isTrue()) ex.materialize(toDoIfTrue); else ex.materialize(toDoIfFalse); } void Looped::execute(Execution& ex) { if (static_pointer_cast<Boolean>(loopCondition->evaluate(ex))->isTrue()) { toRepeat.push_back(shared_ptr<Executable>(new Looped(loopCondition, toRepeat))); ex.materialize(toRepeat); } } void PrintEx::execute(Execution& ex) { for (auto& i : data) i->evaluate(ex)->print(); } void InputEx::execute(Execution& ex) { for (auto& i : vars) ex.getValue(i)->input(); } void VarDeclaration::execute(Execution& ex) { for(auto& i : varIdent) ex.addVariable(i, initValue); }*/
// Copyright (c) 1991-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _gp_Trsf_HeaderFile #define _gp_Trsf_HeaderFile #include <gp_TrsfForm.hxx> #include <gp_Mat.hxx> #include <gp_XYZ.hxx> #include <NCollection_Mat4.hxx> #include <Standard_OStream.hxx> #include <Standard_OutOfRange.hxx> #include <Standard_SStream.hxx> class gp_Pnt; class gp_Trsf2d; class gp_Ax1; class gp_Ax2; class gp_Quaternion; class gp_Ax3; class gp_Vec; // Avoid possible conflict with SetForm macro defined by windows.h #ifdef SetForm #undef SetForm #endif //! Defines a non-persistent transformation in 3D space. //! The following transformations are implemented : //! . Translation, Rotation, Scale //! . Symmetry with respect to a point, a line, a plane. //! Complex transformations can be obtained by combining the //! previous elementary transformations using the method //! Multiply. //! The transformations can be represented as follow : //! @code //! V1 V2 V3 T XYZ XYZ //! | a11 a12 a13 a14 | | x | | x'| //! | a21 a22 a23 a24 | | y | | y'| //! | a31 a32 a33 a34 | | z | = | z'| //! | 0 0 0 1 | | 1 | | 1 | //! @endcode //! where {V1, V2, V3} defines the vectorial part of the //! transformation and T defines the translation part of the //! transformation. //! This transformation never change the nature of the objects. class gp_Trsf { public: DEFINE_STANDARD_ALLOC //! Returns the identity transformation. gp_Trsf(); //! Creates a 3D transformation from the 2D transformation theT. //! The resulting transformation has a homogeneous //! vectorial part, V3, and a translation part, T3, built from theT: //! a11 a12 //! 0 a13 //! V3 = a21 a22 0 T3 //! = a23 //! 0 0 1. //! 0 //! It also has the same scale factor as theT. This //! guarantees (by projection) that the transformation //! which would be performed by theT in a plane (2D space) //! is performed by the resulting transformation in the xOy //! plane of the 3D space, (i.e. in the plane defined by the //! origin (0., 0., 0.) and the vectors DX (1., 0., 0.), and DY //! (0., 1., 0.)). The scale factor is applied to the entire space. Standard_EXPORT gp_Trsf (const gp_Trsf2d& theT); //! Makes the transformation into a symmetrical transformation. //! theP is the center of the symmetry. void SetMirror (const gp_Pnt& theP); //! Makes the transformation into a symmetrical transformation. //! theA1 is the center of the axial symmetry. Standard_EXPORT void SetMirror (const gp_Ax1& theA1); //! Makes the transformation into a symmetrical transformation. //! theA2 is the center of the planar symmetry //! and defines the plane of symmetry by its origin, "X //! Direction" and "Y Direction". Standard_EXPORT void SetMirror (const gp_Ax2& theA2); //! Changes the transformation into a rotation. //! theA1 is the rotation axis and theAng is the angular value of the //! rotation in radians. Standard_EXPORT void SetRotation (const gp_Ax1& theA1, const Standard_Real theAng); //! Changes the transformation into a rotation defined by quaternion. //! Note that rotation is performed around origin, i.e. //! no translation is involved. Standard_EXPORT void SetRotation (const gp_Quaternion& theR); //! Replaces the rotation part with specified quaternion. Standard_EXPORT void SetRotationPart (const gp_Quaternion& theR); //! Changes the transformation into a scale. //! theP is the center of the scale and theS is the scaling value. //! Raises ConstructionError If <theS> is null. Standard_EXPORT void SetScale (const gp_Pnt& theP, const Standard_Real theS); //! Modifies this transformation so that it transforms the //! coordinate system defined by theFromSystem1 into the //! one defined by theToSystem2. After this modification, this //! transformation transforms: //! - the origin of theFromSystem1 into the origin of theToSystem2, //! - the "X Direction" of theFromSystem1 into the "X //! Direction" of theToSystem2, //! - the "Y Direction" of theFromSystem1 into the "Y //! Direction" of theToSystem2, and //! - the "main Direction" of theFromSystem1 into the "main //! Direction" of theToSystem2. //! Warning //! When you know the coordinates of a point in one //! coordinate system and you want to express these //! coordinates in another one, do not use the //! transformation resulting from this function. Use the //! transformation that results from SetTransformation instead. //! SetDisplacement and SetTransformation create //! related transformations: the vectorial part of one is the //! inverse of the vectorial part of the other. Standard_EXPORT void SetDisplacement (const gp_Ax3& theFromSystem1, const gp_Ax3& theToSystem2); //! Modifies this transformation so that it transforms the //! coordinates of any point, (x, y, z), relative to a source //! coordinate system into the coordinates (x', y', z') which //! are relative to a target coordinate system, but which //! represent the same point //! The transformation is from the coordinate //! system "theFromSystem1" to the coordinate system "theToSystem2". //! Example : //! @code //! gp_Ax3 theFromSystem1, theToSystem2; //! double x1, y1, z1; // are the coordinates of a point in the local system theFromSystem1 //! double x2, y2, z2; // are the coordinates of a point in the local system theToSystem2 //! gp_Pnt P1 (x1, y1, z1) //! gp_Trsf T; //! T.SetTransformation (theFromSystem1, theToSystem2); //! gp_Pnt P2 = P1.Transformed (T); //! P2.Coord (x2, y2, z2); //! @endcode Standard_EXPORT void SetTransformation (const gp_Ax3& theFromSystem1, const gp_Ax3& theToSystem2); //! Modifies this transformation so that it transforms the //! coordinates of any point, (x, y, z), relative to a source //! coordinate system into the coordinates (x', y', z') which //! are relative to a target coordinate system, but which //! represent the same point //! The transformation is from the default coordinate system //! @code //! {P(0.,0.,0.), VX (1.,0.,0.), VY (0.,1.,0.), VZ (0., 0. ,1.) } //! @endcode //! to the local coordinate system defined with the Ax3 theToSystem. //! Use in the same way as the previous method. FromSystem1 is //! defaulted to the absolute coordinate system. Standard_EXPORT void SetTransformation (const gp_Ax3& theToSystem); //! Sets transformation by directly specified rotation and translation. Standard_EXPORT void SetTransformation (const gp_Quaternion& R, const gp_Vec& theT); //! Changes the transformation into a translation. //! theV is the vector of the translation. void SetTranslation (const gp_Vec& theV); //! Makes the transformation into a translation where the translation vector //! is the vector (theP1, theP2) defined from point theP1 to point theP2. void SetTranslation (const gp_Pnt& theP1, const gp_Pnt& theP2); //! Replaces the translation vector with the vector theV. Standard_EXPORT void SetTranslationPart (const gp_Vec& theV); //! Modifies the scale factor. //! Raises ConstructionError If theS is null. Standard_EXPORT void SetScaleFactor (const Standard_Real theS); void SetForm (const gp_TrsfForm theP) { shape = theP; } //! Sets the coefficients of the transformation. The //! transformation of the point x,y,z is the point //! x',y',z' with : //! @code //! x' = a11 x + a12 y + a13 z + a14 //! y' = a21 x + a22 y + a23 z + a24 //! z' = a31 x + a32 y + a33 z + a34 //! @endcode //! The method Value(i,j) will return aij. //! Raises ConstructionError if the determinant of the aij is null. //! The matrix is orthogonalized before future using. Standard_EXPORT void SetValues (const Standard_Real a11, const Standard_Real a12, const Standard_Real a13, const Standard_Real a14, const Standard_Real a21, const Standard_Real a22, const Standard_Real a23, const Standard_Real a24, const Standard_Real a31, const Standard_Real a32, const Standard_Real a33, const Standard_Real a34); //! Returns true if the determinant of the vectorial part of //! this transformation is negative. Standard_Boolean IsNegative() const { return (scale < 0.0); } //! Returns the nature of the transformation. It can be: an //! identity transformation, a rotation, a translation, a mirror //! transformation (relative to a point, an axis or a plane), a //! scaling transformation, or a compound transformation. gp_TrsfForm Form() const { return shape; } //! Returns the scale factor. Standard_Real ScaleFactor() const { return scale; } //! Returns the translation part of the transformation's matrix const gp_XYZ& TranslationPart() const { return loc; } //! Returns the boolean True if there is non-zero rotation. //! In the presence of rotation, the output parameters store the axis //! and the angle of rotation. The method always returns positive //! value "theAngle", i.e., 0. < theAngle <= PI. //! Note that this rotation is defined only by the vectorial part of //! the transformation; generally you would need to check also the //! translational part to obtain the axis (gp_Ax1) of rotation. Standard_EXPORT Standard_Boolean GetRotation (gp_XYZ& theAxis, Standard_Real& theAngle) const; //! Returns quaternion representing rotational part of the transformation. Standard_EXPORT gp_Quaternion GetRotation() const; //! Returns the vectorial part of the transformation. It is //! a 3*3 matrix which includes the scale factor. Standard_EXPORT gp_Mat VectorialPart() const; //! Computes the homogeneous vectorial part of the transformation. //! It is a 3*3 matrix which doesn't include the scale factor. //! In other words, the vectorial part of this transformation is equal //! to its homogeneous vectorial part, multiplied by the scale factor. //! The coefficients of this matrix must be multiplied by the //! scale factor to obtain the coefficients of the transformation. const gp_Mat& HVectorialPart() const { return matrix; } //! Returns the coefficients of the transformation's matrix. //! It is a 3 rows * 4 columns matrix. //! This coefficient includes the scale factor. //! Raises OutOfRanged if theRow < 1 or theRow > 3 or theCol < 1 or theCol > 4 Standard_Real Value (const Standard_Integer theRow, const Standard_Integer theCol) const; Standard_EXPORT void Invert(); //! Computes the reverse transformation //! Raises an exception if the matrix of the transformation //! is not inversible, it means that the scale factor is lower //! or equal to Resolution from package gp. //! Computes the transformation composed with T and <me>. //! In a C++ implementation you can also write Tcomposed = <me> * T. //! Example : //! @code //! gp_Trsf T1, T2, Tcomp; ............... //! Tcomp = T2.Multiplied(T1); // or (Tcomp = T2 * T1) //! gp_Pnt P1(10.,3.,4.); //! gp_Pnt P2 = P1.Transformed(Tcomp); // using Tcomp //! gp_Pnt P3 = P1.Transformed(T1); // using T1 then T2 //! P3.Transform(T2); // P3 = P2 !!! //! @endcode Standard_NODISCARD gp_Trsf Inverted() const { gp_Trsf aT = *this; aT.Invert(); return aT; } Standard_NODISCARD gp_Trsf Multiplied (const gp_Trsf& theT) const { gp_Trsf aTresult (*this); aTresult.Multiply (theT); return aTresult; } Standard_NODISCARD gp_Trsf operator * (const gp_Trsf& theT) const { return Multiplied (theT); } //! Computes the transformation composed with <me> and theT. //! <me> = <me> * theT Standard_EXPORT void Multiply (const gp_Trsf& theT); void operator *= (const gp_Trsf& theT) { Multiply (theT); } //! Computes the transformation composed with <me> and T. //! <me> = theT * <me> Standard_EXPORT void PreMultiply (const gp_Trsf& theT); Standard_EXPORT void Power (const Standard_Integer theN); //! Computes the following composition of transformations //! <me> * <me> * .......* <me>, theN time. //! if theN = 0 <me> = Identity //! if theN < 0 <me> = <me>.Inverse() *...........* <me>.Inverse(). //! //! Raises if theN < 0 and if the matrix of the transformation not //! inversible. Standard_NODISCARD gp_Trsf Powered (const Standard_Integer theN) const { gp_Trsf aT = *this; aT.Power (theN); return aT; } void Transforms (Standard_Real& theX, Standard_Real& theY, Standard_Real& theZ) const; //! Transformation of a triplet XYZ with a Trsf void Transforms (gp_XYZ& theCoord) const; //! Convert transformation to 4x4 matrix. template<class T> void GetMat4 (NCollection_Mat4<T>& theMat) const { if (shape == gp_Identity) { theMat.InitIdentity(); return; } theMat.SetValue (0, 0, static_cast<T> (Value (1, 1))); theMat.SetValue (0, 1, static_cast<T> (Value (1, 2))); theMat.SetValue (0, 2, static_cast<T> (Value (1, 3))); theMat.SetValue (0, 3, static_cast<T> (Value (1, 4))); theMat.SetValue (1, 0, static_cast<T> (Value (2, 1))); theMat.SetValue (1, 1, static_cast<T> (Value (2, 2))); theMat.SetValue (1, 2, static_cast<T> (Value (2, 3))); theMat.SetValue (1, 3, static_cast<T> (Value (2, 4))); theMat.SetValue (2, 0, static_cast<T> (Value (3, 1))); theMat.SetValue (2, 1, static_cast<T> (Value (3, 2))); theMat.SetValue (2, 2, static_cast<T> (Value (3, 3))); theMat.SetValue (2, 3, static_cast<T> (Value (3, 4))); theMat.SetValue (3, 0, static_cast<T> (0)); theMat.SetValue (3, 1, static_cast<T> (0)); theMat.SetValue (3, 2, static_cast<T> (0)); theMat.SetValue (3, 3, static_cast<T> (1)); } //! Dumps the content of me into the stream Standard_EXPORT void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const; //! Inits the content of me from the stream Standard_EXPORT Standard_Boolean InitFromJson (const Standard_SStream& theSStream, Standard_Integer& theStreamPos); friend class gp_GTrsf; protected: //! Makes orthogonalization of "matrix" Standard_EXPORT void Orthogonalize(); private: Standard_Real scale; gp_TrsfForm shape; gp_Mat matrix; gp_XYZ loc; }; #include <gp_Trsf2d.hxx> #include <gp_Vec.hxx> #include <gp_Pnt.hxx> //======================================================================= //function : gp_Trsf // purpose : //======================================================================= inline gp_Trsf::gp_Trsf () : scale (1.0), shape (gp_Identity), matrix (1, 0, 0, 0, 1, 0, 0, 0, 1), loc (0.0, 0.0, 0.0) {} //======================================================================= //function : SetMirror // purpose : //======================================================================= inline void gp_Trsf::SetMirror (const gp_Pnt& theP) { shape = gp_PntMirror; scale = -1.0; loc = theP.XYZ(); matrix.SetIdentity(); loc.Multiply (2.0); } //======================================================================= //function : SetTranslation // purpose : //======================================================================= inline void gp_Trsf::SetTranslation (const gp_Vec& theV) { shape = gp_Translation; scale = 1.; matrix.SetIdentity(); loc = theV.XYZ(); } //======================================================================= //function : SetTranslation // purpose : //======================================================================= inline void gp_Trsf::SetTranslation (const gp_Pnt& theP1, const gp_Pnt& theP2) { shape = gp_Translation; scale = 1.0; matrix.SetIdentity(); loc = (theP2.XYZ()).Subtracted (theP1.XYZ()); } //======================================================================= //function : Value // purpose : //======================================================================= inline Standard_Real gp_Trsf::Value (const Standard_Integer theRow, const Standard_Integer theCol) const { Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 3 || theCol < 1 || theCol > 4, " "); if (theCol < 4) { return scale * matrix.Value (theRow, theCol); } else { return loc.Coord (theRow); } } //======================================================================= //function : Transforms // purpose : //======================================================================= inline void gp_Trsf::Transforms (Standard_Real& theX, Standard_Real& theY, Standard_Real& theZ) const { gp_XYZ aTriplet (theX, theY, theZ); aTriplet.Multiply (matrix); if (scale != 1.0) { aTriplet.Multiply (scale); } aTriplet.Add (loc); theX = aTriplet.X(); theY = aTriplet.Y(); theZ = aTriplet.Z(); } //======================================================================= //function : Transforms // purpose : //======================================================================= inline void gp_Trsf::Transforms (gp_XYZ& theCoord) const { theCoord.Multiply (matrix); if (scale != 1.0) { theCoord.Multiply (scale); } theCoord.Add (loc); } #endif // _gp_Trsf_HeaderFile
/* @author: Niamh on 13/04/2018. * <mccallan-n2@ulster.ac.uk> * * @copyright Niamh McCallan 2018 * * @license Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * https://www.boost.org/LICENSE_1_0.txt) */ #ifndef DIABETES_H #define DIABETES_H #include <string> using namespace std; class diabetes { public: // Constructor with default values diabetes(string = "Not answered", string = "Not answered", string = "Not answered", string = "Not answered", string = "Not answered",string = "Not answered", string = "Not answered",string = "Not answered", string = "Not answered",string = "Not answered"); //setting functions for questions // set functions void setQ1Thirst(std::string); void setQ2Polyurea(std::string); void setQ3Polyphagia(std::string); void setQ4BlurredVision(std::string); void setQ5WeightLoss(std::string); void setQ6RecurrentInfections(std::string); void setQ7Tiredness(std::string); void setQ8Itchiness(std::string); void setQ9SlowHealing(std::string); void setQ10SkinCondition(std::string); //getting functions for questions string getQ1Thirst(); string getQ2Polyurea(); string getQ3Polyphagia(); string getQ4BlurredVision(); string getQ5WeightLoss(); string getQ6RecurrentInfections(); string getQ7Tiredness(); string getQ8Itchiness(); string getQ9SlowHealing(); string getQ10SkinCondition(); // member functions //member functions void displayQuestions();//display questions private: string Thirst; string Polyurea; string Polyphagia; string BlurredVision; string WeightLoss; string RecurrentInfections; string Tiredness; string Itchiness; string SlowHealing; string SkinCondition; }; #endif //DIABETES_H
#ifndef SRC_RETREIVE_H #define SRC_RETRIEVE_H /** * Return the index-th child reference if index is valid, NULL otherwise. */ template<class T> TrieNode<T> *TrieNode<T>::getChildAtIndex(int index) { if (index < 0 || index >= children.size()) { return NULL; } return children[index]; } /** * Update the index-th child reference if index is valid; do nothing otherwise. */ template<class T> void TrieNode<T>::setChildAtIndex(int index, TrieNode<T> *updatedChild) { if (index < 0 || index >= children.size()) { return; } children[index] = updatedChild; } /** * Return the index of the child with the given value. * If this node does not have any such children, then return -1. */ template<class T> int TrieNode<T>::getIndexOfChild(T value) { for (int i = 0; i < children.size(); i++) { if (children[i]->getValue() == value) { return i; } } return -1; } /** * Return child node with the given value or NULL if no such child exists. */ template<class T> TrieNode<T> *TrieNode<T>::operator[](T value) { int index = this->getIndexOfChild(value); if (index == -1) { return NULL; } return children[index]; } /** * Return true if this TrieNode has a child with the given value, false otherwise. */ template<class T> bool TrieNode<T>::hasChild(T value) { return (*this)[value] != NULL; } /** * Return true if this TrieNode has a child with the same value as possibleChild and * false otherwise. */ template<class T> bool TrieNode<T>::hasChild(TrieNode<T> *possibleChild) { return hasChild(possibleChild->getValue()); } #endif // SRC_RETRIEVE_H
#include <iostream> #include "Chaine.hpp" #include "Etudiant.hpp" #include "Enseignant.hpp" #include "EleveVacataire.hpp" using enseirb::Chaine; using enseirb::Personne; using enseirb::Etudiant; using enseirb::Enseignant; using enseirb::EleveVacataire; Chaine annexe(Chaine u, Chaine t) { return u + t; } void affiche(const Chaine &s){ std::cout << "AFFICHE <"; for(unsigned int i = 0; i < s.taille(); i++) std::cout << s[i]; std::cout << ">" << std::endl; } void afficheNom(const Personne &p){ affiche(p.nom()); } void test1(){ Chaine s("un texte long"); Chaine p("test"); //Chaine r = annexe(s, p); Chaine r(annexe(s, p)); affiche(r); } void test2(){ Chaine a("royce"); Chaine b("info"); Chaine c("cpp"); Etudiant Royce(a, b, c); afficheNom(Royce); Chaine d("Charlie"); Chaine e("Prof"); Enseignant Charlie(d, e, 2); affiche(Royce.nom()); affiche(Charlie.nom()); EleveVacataire Blah(a, b, c, e, 6); affiche(Blah.nom()); affiche(Blah.nom()); } int main(){ test1(); test2(); return 0; }
#include <iostream> #include <list> #include <ctime> #include "simulation.hpp" #include "rabbits.hpp" #include "mt19937ar.hpp" Simulation::Simulation( const unsigned long rabbitsNum, const int month, double survivalRateYoung, double survivalRateAdult ) : _month( month ), _rabbitsNum( rabbitsNum ), _survivalRateYoung( survivalRateYoung ), _survivalRateAdult( survivalRateAdult ) { // Allocation for the table of rabbits _population = new std::list<Rabbits*>*[ _month + 1 ]; // month m + 1 is a buffer for( int i = 0; i < _month; ++i ) _population[ i ] = new std::list<Rabbits*>; // Allocation for the pool of rabbits _pool = new Rabbits*[ _rabbitsNum ]; for( unsigned long i = 0; i < _rabbitsNum; ++i ) _pool[ i ] = new Rabbits( false, genrand_real2( ) >= 0.5 ); // This pointer points to the last unusued rabbit in the pool _pt = _pool + _rabbitsNum - 1; _newRabbits = 0; _file = NULL; } // Destructor Simulation::~Simulation( ) { // // std::cout << "Destroying the simulation" << std::endl; for( unsigned long i = 0; i < _rabbitsNum; ++i ) delete _pool[ i ]; delete[] _pool; for( int i = 0; i <= _month; ++i ) delete _population[ i ]; delete[] _population; // Attention ici, ne pas oublier les crochets apres le 'delete'. _pt = NULL; } // Initialise the _population matrix with an array given in parameter // num: the size of the int* array // init[month][number of rabbits this month] void Simulation::Start( const char * outputFileName, int time, int num, int * init[2] ) { clock_t startBegin; clock_t startEnd; _file = fopen( outputFileName, "w+"); startBegin = clock( ); if( init != NULL ) { for( int i = 0; i < num; ++i ) { for( int j = 0; j < init[ i ][ 1 ]; ++j ) { // First we determine if rabbits are mature or not if( init[ i ][ 0 ] >= 5 && init[ i ][ 0 ] < 8 ) { // 80% chance being mature between 5 and 8 month if( genrand_int32( ) % 10 > 1 ) (*_pt)->set_mature( true ); } // At the 8th month, all rabbits are matures else if( init[ i ][ 0 ] >= 8 ) (*_pt)->set_mature( true ); // If none of this cases, the rabbit is not mature else (*_pt)->set_mature( false ); // Finaly, rabbits are put in the right list and removed from the pool _population[ init[ i ][ 0 ] ]->push_back( *_pt ); *_pt = NULL; if( _pt > _pool ) --_pt; } } } else { for( int i = 0; i < num; ++i ) { // All rabbits have 8 months, and are mature so (*_pt)->set_mature( true ); // Rabbits are stored in the month 8 <=> block 7 ( _population[ 7 ] )->push_back( *_pt ); *_pt = NULL; if( _pt > _pool ) --_pt; // // std::cout << "A rabbit is created" << std::endl; } } // Simulation is launched when everything is ready std::cout << "Result " << MonthSimul( time ) << std::endl; startEnd = clock( ); fprintf( _file, "%ld\t%f\n", (long) ( startEnd - startBegin ), (double) ( startEnd - startBegin ) / CLOCKS_PER_SEC ); } // Empty the lists, all rabbits go back to the pool void Simulation::Stop( ) { // // std::cout << "Stopping the simulation" <<std::endl; for( int i = 0; i < _month; ++i ) { for( _it = _population[ i ]->begin( ); _it != _population[ i ]->end( ); ) { ++_pt; *_pt = *_it; _it = _population[ i ]->erase( _it ); } } fclose( _file ); } // Call the destructor // void Simulation::End( ) { ~Simulation( ); } // The simulation // time: the number of months the simulation has to last. Can end earlier if no rabbits are left in the pool. int Simulation::MonthSimul( int time ) { clock_t simulBegin = clock( ); clock_t simulEnd; int j = 0; // The current month unsigned long tmp = 0; unsigned long died = 0; // The number of rabbits which have died this month unsigned long newBorns = 0; unsigned long females = 0; unsigned long reproduction = 0; _newRabbits = 0; // This variable stores the number of rabbits which should be created when the simulation ends /**/ for( int i = 0; i < time; ++i ) { /** fprintf( _file, "%d\n", i ); died = 0; /**/ // std::cout<< "Month: " << i << std::endl; // At the last month, all living rabbits die. for( _it = _population[ _month - 1 ]->begin( ); _it != _population[ _month - 1 ]->end( ); ) { ++died; ++_pt; *_pt = *_it; _it = _population[ _month - 1 ]->erase( _it ); } /** fprintf( _file, "%d\t%ld\n", _month - 1, died ); died = 0; /**/ // Mature and old rabbits [9-132-240] for( j = _month ; j > 8; --j ) { // Move the lists to the left _population[ j ] = _population[ j - 1 ]; for( _it = _population[ j ]->begin( ); _it != _population[ j ]->end( ); ++_it ) { if( !death( j ) ) { if( (*_it)->get_sex( ) ) { ++females; if( genrand_real1( ) >= 0.60 ) { ++reproduction; tmp = (*_it)->reproduce( *_it ); newBorns += tmp; _newRabbits += tmp; } } ++_it; } else ++died; } /**/ fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size( ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0; /**/ } // Final deadline for maturity [8-8] _population[ j ] = _population[ j - 1 ]; // On decale les listes de lapins vers la gauche for( _it = _population[ j ]->begin( ); _it != _population[ j ]->end( ); ) { if( !death( j ) ) { if( !(*_it)->get_mature( ) ) { (*_it)->set_mature( true ); if( (*_it)->get_sex( ) ) { ++females; ++reproduction; tmp = (*_it)->reproduce( *_it ); newBorns += tmp; _newRabbits += tmp; } } else { if( (*_it)->get_sex( ) ) { ++females; if( genrand_real1( ) >= 0.60 ) { ++reproduction; tmp = (*_it)->reproduce( *_it ); newBorns += tmp; _newRabbits += tmp; } } } ++_it; } else ++died; } /**/ fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size( ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0; /**/ // Rabbits getting maturity [5-7] for( j = 7; j >= 5; --j ) { // On decale les listes de lapins vers la gauche _population[ j ] = _population[ j - 1 ]; for( _it = _population[ j ]->begin( ); _it != _population[ j ]->end( ); ++_it ) { if( !death( j ) ) { if( !(*_it)->get_mature( ) ) { if( genrand_real1( ) >= 0.2 ) { // 80% of becoming mature each month (*_it)->set_mature( true ); if( (*_it)->get_sex( ) ) { ++females; ++reproduction; // Females reproduce their first month of maturity tmp = (*_it)->reproduce( *_it ); newBorns += tmp; _newRabbits += tmp; } } } else { if( (*_it)->get_sex( ) ) { ++females; if( genrand_real1( ) >= 0.60 ) { ++reproduction; tmp = (*_it)->reproduce( *_it ); newBorns += tmp; _newRabbits += tmp; } } } ++_it; } else ++died; } /**/ fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size( ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0; /**/ } // Newly-born, young rabbits [1-4] for( j = 4; j > 0; --j ) { _population[ j ] = _population[ j - 1 ]; // On decale les listes de lapins vers la gauche for( _it = _population[ j ]->begin( ); _it != _population[ j ]->end( ); ) { if( !death( j ) ) { if( (*_it)->get_sex( ) ) { ++females; } ++_it; } else ++died; } /**/ fprintf( _file, "%d\t%ld\t%ld\t%ld\t%ld\t%ld\n", j, died, newBorns, _population[ j ]->size( ), females, reproduction ); died = 0; newBorns = 0; females = 0; reproduction = 0; /**/ } // Moving the dead 20 years old rabbits' list to the new born's list _population[ 0 ] = _population[ _month ]; _population[ _month ] = NULL; // std::cout << "Death of " << died << " rabbits" << std::endl; if( _pt - _pool < _newRabbits ) { // End of the simulation i = time; // std::cout<< "Still " << _pt - _pool << " rabbits staying versus " << _newRabbits << " rabbits to be born" << std::endl; } else { // std::cout<< "Still " << _pt - _pool << " rabbits" << std::endl; // std::cout<< "Birthing of " << _newRabbits << " rabbits" << std::endl; for( j = 0; j < _newRabbits; ++j ) { // // std::cout << "Birthing of a rabbit" << std::endl; // initialisation of the rabbits (*_pt)->set_sex( ( genrand_real2( ) >= 0.5 ) ); if( (*_pt)->get_sex( ) ) { ++females; } (*_pt)->set_mature( false ); (*_pt)->set_monthsPassed( 0 ); // Rabbits are being born _population[ 0 ]->push_back( *_pt ); *_pt = NULL; if( _pt > _pool ) --_pt; } _newRabbits = 0; /**/ fprintf( _file, "%d\t%d\t%d\t%ld\t%ld\t%d\n", 0, 0, 0, _population[ 0 ]->size( ), females, 0 ); females = 0; /**/ } /**/ } /**/ simulEnd = clock( ); fprintf( _file, "%ld\t%f\t", (long) ( simulEnd - simulBegin ), (double) ( simulEnd - simulBegin ) / CLOCKS_PER_SEC ); return _newRabbits; } void Simulation::reproduce( int month ) { int monthsPassed = ( (*_it)->get_monthsPassed( ) <= 2 )? (*_it)->get_monthsPassed( ): 0; if( (*_it)->get_sex( ) && genrand_real1( ) <= ( 0.30 + 0.30 * monthsPassed ) ) { ++_newRabbits; (*_it)->set_monthsPassed( 0 ); } else (*_it)->set_monthsPassed( monthsPassed + 1 ); } bool Simulation::death( int month ) { bool death = false; double hazard = genrand_real1( ); death = ( month < 132 && hazard > _survivalRateAdult ); death |= ( month >= 132 && hazard > ( _survivalRateAdult * ( 1.0 - ( month / _month ) ) ) ); death &= (*_it)->get_mature( ); death |= ( !(*_it)->get_mature( ) ) && ( hazard > _survivalRateYoung ); if( death ) { // // std::cout << "Death of a rabbit" << std::endl; ++_pt; *_pt = *_it; _it = _population[ month ]->erase( _it ); } return death; }
#pragma once //==================================================================== // DirectInput //==================================================================== #ifndef _BDIRECT_INPUT #define _BDIRECT_INPUT #include <dinput.h> namespace iberbar { #define BINPUT_LBTN 0 #define BINPUT_RBTN 1 #define BINPUT_MBTN 2 typedef void ( CALLBACK*PCallBackInputEvent )( bool bClicked, void* pParam, void* pUserContext ); class CDXInput { protected: IDirectInputDevice8* m_pKeyboardDevice; IDirectInputDevice8* m_pMouseDevice; CHAR m_KeyboardBuf[ 256 ]; DIMOUSESTATE m_MouseState; LPVOID m_pAnotherData; public: bool CreateInput( HINSTANCE hInstance, HWND hWnd, INT iMin=-100, INT iMax=100, INT iDeadZone=20 ); bool ReadKeyboard(); bool ReadMouse(); public: inline const CHAR* GetKeyboardBufPtr() const { return m_KeyboardBuf; } inline bool IsKeyPressed( INT iKey ) const { return ( ( m_KeyboardBuf[ iKey ] & 0x80 ) ? true : false ); } inline LONG GetMouseMoveX() const { return m_MouseState.lX; } inline LONG GetMouseMoveY() const { return m_MouseState.lY; } inline LONG GetMouseMoveZ() const { return m_MouseState.lZ; } bool IsLButtonPressed() const { return ( ( m_MouseState.rgbButtons[ 0 ] & 0x80 ) ? true : false ); } bool IsRButtonPressed() const { return ( ( m_MouseState.rgbButtons[ 1 ] & 0x80 ) ? true : false ); } bool IsMButtonPressed() const { return ( ( m_MouseState.rgbButtons[ 2 ] & 0x80 ) ? true : false ); } bool IsButtonPressed( BYTE btIndex ) const { if ( btIndex > 2 ) return false; return ( ( m_MouseState.rgbButtons[ btIndex ] & 0x80 ) ? true : false ); } public: void Release(); protected: bool CreateDirectInput( HINSTANCE hInstance ); bool CreateKeyboard( HWND hWnd ); bool CreateMouse( HWND hWnd ); private: static LPDIRECTINPUT8 s_pd3dInput; public: CDXInput( void ); ~CDXInput(); }; typedef CDXInput *LPBDIRECTINPUT; } #endif
/*nom : ramon mir * * data: 19 - 3 - 2021 * * el que fara aquesta problema 1 es que primer sensendra el led 1 * * * despres sensendran tots els led(led 1 led 2 led 3) * * * estaran ensesos 1 segon i s'apagaran en 0,5 segons. * * * y aixi tota la estona. * * */ const int ledPin1=4; const int ledPin2 =9; const int ledPin3= 10; void setup() { pinMode ( ledPin1 , OUTPUT ); pinMode ( ledPin2 , OUTPUT ); pinMode ( ledPin3 , OUTPUT ); } void loop() { digitalWrite ( ledPin3 ,HIGH ); delay(1000); digitalWrite ( ledPin1 ,LOW ); digitalWrite ( ledPin2 ,LOW ); digitalWrite ( ledPin3 ,LOW ); delay(1000); digitalWrite ( ledPin1 ,HIGH ); digitalWrite ( ledPin2 ,HIGH ); digitalWrite ( ledPin3 ,HIGH ); delay(500); }
#include <iostream> #include <vector> #include <fstream> using namespace std; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); string s1, s2; ifstream fin("levenshtein.in"); ofstream fout("levenshtein.out"); fin >> s1 >> s2; int l1 = s1.size(); int l2 = s2.size(); vector<vector<int>> d(l1 + 1, vector<int>(l2 + 1, 0)); for (int i = 1; i <= l2; i++) d[0][i] = i; for (int i = 1; i <= l1; i++) d[i][0] = i; for (int i = 1; i <= l1; i++) { for (int j = 1; j <= l2; j++) { if (s1[i - 1] == s2[j - 1]) { d[i][j] = d[i - 1][j - 1]; } else { d[i][j] = min(d[i - 1][j - 1] + 1, min(d[i - 1][j] + 1, d[i][j - 1] + 1)); } } } fout << d[l1][l2]; return 0; }
/* ============================================================================== blueprint_GenericEditor.cpp Created: 3 Nov 2019 4:47:39pm ============================================================================== */ #pragma once namespace blueprint { //============================================================================== BlueprintGenericEditor::BlueprintGenericEditor (juce::AudioProcessor* processor, const juce::String& code, juce::AudioProcessorValueTreeState* vts) : juce::AudioProcessorEditor(processor), valueTreeState(vts) { // Bind parameter listeners for (auto& p : processor->getParameters()) p->addListener(this); // Now we can provision the app root assignNewAppRoot(code); // If an error showed up, our appRoot is already gone if (appRoot) addAndMakeVisible(appRoot.get()); // Set an arbitrary size, should be overriden from outside the constructor setSize(400, 200); } BlueprintGenericEditor::BlueprintGenericEditor (juce::AudioProcessor* processor, const juce::File& bundle, juce::AudioProcessorValueTreeState* vts) : juce::AudioProcessorEditor(processor), valueTreeState(vts) { // Sanity check jassert (bundle.existsAsFile()); bundleFile = bundle; lastModifiedTime = bundleFile.getLastModificationTime(); // Bind parameter listeners for (auto& p : processor->getParameters()) p->addListener(this); // Now we can provision the app root assignNewAppRoot(bundle.loadFileAsString()); // If an error showed up, our appRoot is already gone if (appRoot) addAndMakeVisible(appRoot.get()); // Kick off the timer that polls for file changes startTimer(50); // Set an arbitrary size, should be overriden from outside the constructor setSize(400, 200); } BlueprintGenericEditor::~BlueprintGenericEditor() { stopTimer(); for (auto& p : processor.getParameters()) { p->removeListener(this); } } //============================================================================== void BlueprintGenericEditor::parameterValueChanged (int parameterIndex, float newValue) { Component::SafePointer<blueprint::ReactApplicationRoot> safeAppRoot (appRoot.get()); // Collect some information about the parameter to push into the engine const auto& p = processor.getParameters()[parameterIndex]; juce::String id = p->getName(100); if (auto* x = dynamic_cast<juce::AudioProcessorParameterWithID*>(p)) id = x->paramID; float defaultValue = p->getDefaultValue(); const juce::String stringValue = p->getText(newValue, 0); // Dispatch parameter value updates to the javascript engine at 30Hz throttleMap.throttle(parameterIndex, 1000.0 / 30.0, [=]() { juce::MessageManager::callAsync([=]() mutable { if (safeAppRoot) { safeAppRoot->dispatchEvent( "parameterValueChange", parameterIndex, id, defaultValue, newValue, stringValue ); } }); }); } void BlueprintGenericEditor::parameterGestureChanged (int parameterIndex, bool gestureIsStarting) { // We don't need to worry so much about throttling gesture events since they happen far // more slowly than value changes if (appRoot) { appRoot->dispatchEvent("parameterGestureChange", parameterIndex, gestureIsStarting); } } //============================================================================== void BlueprintGenericEditor::timerCallback() { auto lmt = bundleFile.getLastModificationTime(); if (lmt > lastModifiedTime) { // Sanity check... again jassert (bundleFile.existsAsFile()); // Remove and delete the current appRoot appRoot.reset(); // Then we assign a new one assignNewAppRoot(bundleFile.loadFileAsString()); // Add and set size, carefull if (appRoot) { addAndMakeVisible(appRoot.get()); appRoot->setBounds(getLocalBounds()); } lastModifiedTime = lmt; } } void BlueprintGenericEditor::resized() { // Evaluating the bundle in the app root might hit the error handler, which // deletes the appRoot, in turn alerting the parent component (this) to remove // its child and resize. So we're careful check the appRoot before doing anything if (appRoot) { appRoot->setBounds(getLocalBounds()); } } void BlueprintGenericEditor::paint(juce::Graphics& g) { g.fillAll(juce::Colours::transparentWhite); if (errorText) { g.fillAll(juce::Colour(0xffe14c37)); errorText->draw(g, getLocalBounds().toFloat().reduced(10.f)); } } void BlueprintGenericEditor::assignNewAppRoot(const juce::String& code) { // Assign a fresh appRoot appRoot = std::make_unique<ReactApplicationRoot>(); appRoot->engine.onUncaughtError = [this](const juce::String& msg, const juce::String& trace) { showError(trace); }; // If we have a valueTreeState, bind parameter methods to the new app root if (valueTreeState != nullptr) { appRoot->engine.registerNativeMethod( "beginParameterChangeGesture", [](void* stash, const juce::var::NativeFunctionArgs& args) { auto* state = reinterpret_cast<juce::AudioProcessorValueTreeState*>(stash); const juce::String& paramId = args.arguments[0].toString(); if (auto* parameter = state->getParameter(paramId)) parameter->beginChangeGesture(); return juce::var::undefined(); }, (void *) valueTreeState ); appRoot->engine.registerNativeMethod( "setParameterValueNotifyingHost", [](void* stash, const juce::var::NativeFunctionArgs& args) { auto* state = reinterpret_cast<juce::AudioProcessorValueTreeState*>(stash); const juce::String& paramId = args.arguments[0].toString(); const double value = args.arguments[1]; if (auto* parameter = state->getParameter(paramId)) parameter->setValueNotifyingHost(value); return juce::var::undefined(); }, (void *) valueTreeState ); appRoot->engine.registerNativeMethod( "endParameterChangeGesture", [](void* stash, const juce::var::NativeFunctionArgs& args) { auto* state = reinterpret_cast<juce::AudioProcessorValueTreeState*>(stash); const juce::String& paramId = args.arguments[0].toString(); if (auto* parameter = state->getParameter(paramId)) parameter->endChangeGesture(); return juce::var::undefined(); }, (void *) valueTreeState ); } // Now evaluate the code within the environment. We reset the error text ahead // of time, assuming the code will evaluate well errorText.reset(); appRoot->evaluate(code); // At this point the appRoot may have been removed due to an error evaluating // the bundle, so we check for that case and halt if necessary if (!appRoot) return; // By now, things look good, let's push current parameter values into // the bundle for (auto& p : processor.getParameters()) parameterValueChanged(p->getParameterIndex(), p->getValue()); } void BlueprintGenericEditor::showError(const juce::String& trace) { appRoot.reset(); errorText.reset(new juce::AttributedString(trace)); #if JUCE_WINDOWS errorText->setFont(juce::Font("Lucida Console", 18, juce::Font::FontStyleFlags::plain)); #elif JUCE_MAC errorText->setFont(juce::Font("Monaco", 18, juce::Font::FontStyleFlags::plain)); #else errorText->setFont(18); #endif repaint(); } }
#ifndef TREEFACE_PATH_GLYPH_H #define TREEFACE_PATH_GLYPH_H #include "treeface/base/Enums.h" #include "treeface/graphics/guts/Enums.h" #include "treeface/math/Vec2.h" #include "treeface/scene/Geometry.h" #include <treecore/Array.h> namespace treeface { struct PathGlyphArc { float center_x; float center_y; float angle; bool is_cclw; }; struct PathGlyphBessel3 { float ctrl_x; float ctrl_y; }; struct PathGlyphBessel4 { float ctrl1_x; float ctrl1_y; float ctrl2_x; float ctrl2_y; }; struct PathGlyph { explicit PathGlyph( const Vec2f& line_end ) : type( GLYPH_TYPE_LINE ) , end( line_end ) {} PathGlyph( const Vec2f& center, const Vec2f& end, float angle, bool is_cclw ) : type( GLYPH_TYPE_ARC ) , end( end ) , arc( PathGlyphArc { center.x, center.y, angle, is_cclw } ) {} PathGlyph( const Vec2f& ctrl, const Vec2f& end ) : type( GLYPH_TYPE_BESSEL3 ) , end( end ) , bessel3( PathGlyphBessel3 { ctrl.x, ctrl.y } ) {} PathGlyph( const Vec2f& ctrl1, const Vec2f& ctrl2, const Vec2f& end ) : type( GLYPH_TYPE_BESSEL4 ) , end( end ) , bessel4( PathGlyphBessel4 { ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y } ) {} void segment( const Vec2f& prev_end, Geometry::HostVertexCache& result_vertices ) const { switch (type) { case GLYPH_TYPE_ARC: segment_arc( prev_end, result_vertices ); break; case GLYPH_TYPE_BESSEL3: case GLYPH_TYPE_BESSEL4: segment_bessel( prev_end, result_vertices ); break; case GLYPH_TYPE_LINE: result_vertices.add( end ); break; default: abort(); } } void segment_arc( const Vec2f& prev_end, Geometry::HostVertexCache& result_vertices ) const; void segment_bessel( const Vec2f& prev_end, Geometry::HostVertexCache& result_vertices ) const; GlyphType type; Vec2f end; union { PathGlyphArc arc; PathGlyphBessel3 bessel3; PathGlyphBessel4 bessel4; }; }; } // namespace treeface #endif // TREEFACE_PATH_GLYPH_H
#include <QApplication> #include <QLabel> #include <QDialog> #include <QTimer> #include <QVBoxLayout> #include "window.h" #include "samdial.h" #include "samclock.h" int main( int argc, char* argv[] ) { QApplication app(argc, argv); QDialog *dialog = new QDialog( 0 ); QLabel* sam = new QLabel( dialog ); SamDial* dial = new SamDial( dialog ); sam->setText( "Sam" ); SamClock* clock = new SamClock( dialog ); Window* win = new Window( dialog ); QVBoxLayout* layout = new QVBoxLayout( dialog ); layout->addStretch(); layout->addWidget( sam, Qt::AlignCenter ); layout->addWidget( win, Qt::AlignCenter ); layout->addWidget( dial ); layout->addWidget( clock ); layout->addStretch(); QTimer* timer = new QTimer( dialog ); timer->setInterval( 1000 ); QObject::connect( timer, SIGNAL(timeout()), dial, SLOT(iterate())); timer->start(); dialog->show(); return app.exec(); }
/** * created: 2013-4-8 14:53 * filename: FKSyncObjLock * author: FreeKnight * Copyright (C): * purpose: */ //------------------------------------------------------------------------ #include <wchar.h> #include "../Include/FKSyncObjLock.h" #include "../Include/FKError.h" #include "../Include/FKThread.h" #include "../Include/Dump/FKDumpErrorBase.h" #include "../Include/FKTimeMonitor.h" //------------------------------------------------------------------------ CLD_CCriticalSection::CLD_CCriticalSection() { InitializeCriticalSectionAndSpinCount( &m_csAccess,4000); } //------------------------------------------------------------------------ CLD_CCriticalSection::~CLD_CCriticalSection() { DeleteCriticalSection( &m_csAccess ); } //------------------------------------------------------------------------ void CLD_CCriticalSection::Lock() { EnterCriticalSection( &m_csAccess ); } //------------------------------------------------------------------------ void CLD_CCriticalSection::Unlock() { LeaveCriticalSection( &m_csAccess ); } //------------------------------------------------------------------------ CLD_CMutex::CLD_CMutex( char *pName ) { m_hMutex=NULL; m_boCreate=false; if (pName){ open(pName); } } //------------------------------------------------------------------------ CLD_CMutex::~CLD_CMutex() { close(); } //------------------------------------------------------------------------ bool CLD_CMutex::open( char *pName ) { if (m_hMutex == NULL) { m_hMutex=::OpenMutex(MUTEX_ALL_ACCESS, FALSE, pName); if (m_hMutex == NULL) { m_hMutex = CreateMutex( NULL, FALSE, pName ); if ( m_hMutex == NULL ) { throw CLDError( "CLD_CMutex::CLD_CMutex() ´´½¨Ê§°Ü" ); } m_boCreate=true; } return true; } return false; } //------------------------------------------------------------------------ void CLD_CMutex::close() { if (m_hMutex != NULL){ CloseHandle( m_hMutex ); m_hMutex=NULL; } m_boCreate=false; } //------------------------------------------------------------------------ void CLD_CMutex::Lock( int nTimeWait) { if (m_hMutex) { WaitForSingleObject( m_hMutex, nTimeWait ); } } //------------------------------------------------------------------------ void CLD_CMutex::Unlock() { if (m_hMutex) { ReleaseMutex( m_hMutex ); } } //------------------------------------------------------------------------
#include <iostream> using namespace std; void swap1(int a, int b) { int c; c = a; a = b; b = c; } void swap2(int &a, int &b) { int c; c = a; a = b; b = c; } void swap3(int *a, int *b) { int c; c = *a; *a = *b; *b = c; } int main() { int a[5] = {1,2,3,4,5}; int *p = (int *)(&a + 1); cout << *(a + 1) << endl << *(p - 1) << endl; }
#include <algorithm> #include <iostream> #include <iomanip> #include <cassert> #include <vector> #include <cmath> #include <deque> using std::vector; using std::pair; class UF { int *id, cnt, *sz; public: // Create an empty union find data structure with N isolated sets. UF(int N) { cnt = N; id = new int[N]; sz = new int[N]; for (int i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } } ~UF() { delete[] id; delete[] sz; } // Return the id of component corresponding to object p. int find(int p) { int root = p; while (root != id[root]) root = id[root]; while (p != root) { int newp = id[p]; id[p] = root; p = newp; } return root; } // Replace sets containing x and y with their union. void merge(int x, int y) { int i = find(x); int j = find(y); if (i == j) return; // make smaller root point to larger one if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } cnt--; } // Are objects x and y in the same set? bool connected(int x, int y) { return find(x) == find(y); } // Return the number of disjoint sets. int count() { return cnt; } }; struct EdgeCost { int u, v; long double cost; }; double clustering(vector<int> x, vector<int> y, int k) { auto cost = [&](const int& l, const int&r) { long double dx = x[l] - x[r]; long double dy = y[l] - y[r]; return std::sqrt(dx*dx + dy*dy); }; auto at = [&](int xx, int yy) { return yy*x.size() + xx; }; auto visited = std::vector<int>(x.size() * x.size(), 0); auto E = std::deque<EdgeCost>(); for (int i = 0; i < x.size(); ++i) { for (int j = 0; j < x.size(); ++j) { if (i == j) continue; if ((visited[at(i, j)] == 1) || (visited[at(j, i)] == 1)) continue; visited[at(i, j)] = visited[at(j, i)] = 1; E.push_back({ i, j, cost(i, j)}); } } std::sort(std::begin(E), std::end(E), [](const EdgeCost& l, const EdgeCost& r) {return l.cost < r.cost; }); auto sets = UF(x.size()); EdgeCost last; while (sets.count() > k) { last = E.front(); E.pop_front(); if (sets.connected(last.u, last.v)) continue; sets.merge(last.u, last.v); } while (E.size() > 0) { last = E.front(); E.pop_front(); if (!sets.connected(last.u, last.v)) break; } return last.cost; } void run(std::istream& in, std::ostream& out) { size_t n; int k; in >> n; vector<int> x(n), y(n); for (size_t i = 0; i < n; i++) { in >> x[i] >> y[i]; } in >> k; out << std::setprecision(10) << clustering(x, y, k) << std::endl; } #ifdef UNITTESTS #define CATCH_CONFIG_MAIN #include "../../catch.hpp" void test(const std::string &instr, const std::string& expectedOut) { auto in = std::stringstream{ instr }; auto actualOut = std::stringstream(); run(in, actualOut); REQUIRE(expectedOut == actualOut.str()); } TEST_CASE("","") { test(R"(12 7 6 4 3 5 1 1 7 2 7 5 7 3 3 7 8 2 8 4 4 6 7 2 6 3)",R"(2.828427125 )"); } #else int main() { run(std::cin, std::cout); return 0; } #endif
#include "SaveDataManager.h" #include "sqlite3.h" /************************************************************************/ /* 数据库校验 */ /************************************************************************/ //整数 int getIntFromTable(char * szItemName, int n_column, char ** column_value, char ** column_name) { for (int i = 0; i < n_column; i++) { if (strcmp(column_name[i],szItemName)==0)//比较 { return atoi(column_value[i]); } } log("Can't Find int [%s]",szItemName); return 0; } //小数 float getFloatFromTable(char * szItemName, int n_column, char ** column_value, char ** column_name) { for(int i=0;i<n_column;i++) { if(strcmp(column_name[i],szItemName)==0) { return atof(column_value[i]); } } log("Can't Find float [%s]",szItemName); return 0; } //字符串 string getStringFromTable( char * szItemName, int n_column, char ** column_value, char ** column_name) { for(int i=0;i<n_column;i++) { if(strcmp(column_name[i],szItemName)==0) { return column_value[i]; } } log("Can't Find string [%s]",szItemName); return NULL; } static SaveDataManager * g_pSaveDataManager=NULL; SaveDataManager::SaveDataManager() { } SaveDataManager * SaveDataManager::getInstance() { if(g_pSaveDataManager==NULL) { g_pSaveDataManager = new SaveDataManager(); } return g_pSaveDataManager; } void SaveDataManager::releaseData() { } void SaveDataManager::initBasicData() { do { //读取用户信息 readSaveUserFromDB(); //读取服务器信息 readSaveServerFromDB(); return ; } while (false); log("Fun SaveDataManager::initBasicData Error!"); } bool SaveDataManager::setSaveUserInfo(tagSaveUserInfo UserInfo) { char *szErrMsg = NULL; do { char szSQLCmd[NAME_LEN] = {0}; sqlite3 *pDB = NULL; int result = sqlite3_open(getSaveDBName().c_str(), &pDB); CC_BREAK_IF(result!=SQLITE_OK); CC_BREAK_IF(pDB==NULL); sprintf(szSQLCmd,"update t_user_info set s_open_id='%s',s_username='%s',s_password='%s'",UserInfo.strOpenID.c_str(),UserInfo.strUserName.c_str(),UserInfo.strPassWord.c_str()); CC_BREAK_IF(sqlite3_exec(pDB,szSQLCmd,NULL, NULL, &szErrMsg )!=SQLITE_OK); sqlite3_close(pDB); g_pSaveDataManager->m_SaveUserInfo = UserInfo; return true; } while (false); log("CNFSaveDataManager::SetSaveUserInfo Run Error! Msg=%s",szErrMsg); return false; } bool SaveDataManager::getSaveUserInfo( tagSaveUserInfo &UserInfo ) { UserInfo = m_SaveUserInfo; return true; } bool SaveDataManager::readSaveUserFromDB() { char *szErrMsg=NULL; do { sqlite3 *pDB=NULL; CC_BREAK_IF(sqlite3_open(getSaveDBName().c_str(),&pDB)!=SQLITE_OK); CC_BREAK_IF(pDB==NULL); CC_BREAK_IF(sqlite3_exec(pDB,"SELECT * from t_user_info",SaveDataManager::loadSaveUserCallBack, NULL, &szErrMsg )!=SQLITE_OK); sqlite3_close(pDB); return true; } while (false); log("SaveDataManager::readSaveUserFromDB Run Error! Msg=%s ",szErrMsg); return false; } int SaveDataManager::loadSaveUserCallBack( void * para, int n_column, char ** column_value, char ** column_name ) { if (g_pSaveDataManager==NULL) { g_pSaveDataManager = new SaveDataManager(); } tagSaveUserInfo Info; Info.strOpenID = getStringFromTable("s_open_id",n_column,column_value,column_name); Info.strUserName = getStringFromTable("s_username",n_column,column_value,column_name); Info.strPassWord = getStringFromTable("s_password",n_column,column_value,column_name); g_pSaveDataManager->m_SaveUserInfo = Info; return 0; } bool SaveDataManager::setSaveServerInfo(tagSaveServerInfo ServerInfo) { char *szErrMsg=NULL; do { char szSQLCmd[NAME_LEN]={0}; sqlite3 *pDB = NULL; CC_BREAK_IF(sqlite3_open(getSaveDBName().c_str(), &pDB)!=SQLITE_OK); CC_BREAK_IF(pDB==NULL); sprintf(szSQLCmd,"update t_server_info set s_server_id=%d,s_server_name='%s'",ServerInfo.nServerID,ServerInfo.strServerName.c_str()); CC_BREAK_IF(sqlite3_exec(pDB,szSQLCmd,NULL, NULL, &szErrMsg )!=SQLITE_OK); sqlite3_close(pDB); g_pSaveDataManager->m_SaveServerInfo = ServerInfo; return true; } while (false); log("SaveDataManager::setSaveServerInfo Run Error! Msg=%s",szErrMsg); return false; } bool SaveDataManager::getSaveServerInfo(tagSaveServerInfo &ServerInfo) { ServerInfo = m_SaveServerInfo; return true; } bool SaveDataManager::readSaveServerFromDB() { char *szErrMsg=NULL; do { sqlite3 *pDB=NULL; CC_BREAK_IF(sqlite3_open(getSaveDBName().c_str(),&pDB)!=SQLITE_OK); CC_BREAK_IF(pDB==NULL); CC_BREAK_IF(sqlite3_exec(pDB,"SELECT * from t_server_info",SaveDataManager::loadSaveServerCallBack, NULL, &szErrMsg )!=SQLITE_OK); sqlite3_close(pDB); return true; } while (false); log("SaveDataManager::readSaveServerFromDB Run Error! Msg=%s ",szErrMsg); return false; } int SaveDataManager::loadSaveServerCallBack( void * para, int n_column, char ** column_value, char ** column_name ) { if (g_pSaveDataManager==NULL) { g_pSaveDataManager = new SaveDataManager(); } tagSaveServerInfo Info; Info.nServerID = getIntFromTable("s_server_id",n_column,column_value,column_name); Info.strServerName = getStringFromTable("s_server_name",n_column,column_value,column_name); g_pSaveDataManager->m_SaveServerInfo = Info; return 0; } //this->execTable("insert into t_user_info(s_username,s_password) values('123456x','123456x')"); bool SaveDataManager::execTable(std::string sql)// { char *szErrMsg=NULL; do { sqlite3 *pdb=NULL;//1 //std::string path= FileUtils::getInstance()->getWritablePath()+"save.db";//2 int result; result=sqlite3_open(getSaveDBName().c_str(),&pdb);//3 if(result!=SQLITE_OK) { log("open database failed, number%d",result); } result=sqlite3_exec(pdb,sql.c_str(),NULL,NULL,&szErrMsg);//1 if(result!=SQLITE_OK) log("create table failed"); return true; } while (false); log("SaveDataManager::execTable Run Error! Msg=%s ",szErrMsg); return false; }
/* ** EPITECH PROJECT, 2018 ** cpp_indie_studio ** File description: ** Math.cpp */ #include "Math.hpp" size_t Math::roundUp(size_t numToRound, size_t multiple) { return ((numToRound + multiple - 1) / multiple) * multiple; } size_t Math::manhattanDistance(Point const & from, Point const & to) { int x1 = from.getX(); int x2 = to.getX(); int y1 = from.getY(); int y2 = to.getY(); int absX = x1 > x2 ? x1 - x2 : x2 - x1; int absY = y1 > y2 ? y1 - y2 : y2 - y1; return absX + absY; } int Math::randomNumberBetween(int min, int max) { return rand() % (max - min + 1) + min; }
// Copyright (c) 2013 Nick Porcino, All rights reserved. // License is MIT: http://opensource.org/licenses/MIT #ifndef LAB_INTVAROBJ_H #define LAB_INTVAROBJ_H #include "LandruVM/VarObj.h" namespace Landru { class IntVarObj : public Landru::VarObj { public: IntVarObj(const char* name); virtual ~IntVarObj(); virtual void Update(float /*elapsedTime*/) { } VAROBJ_FACTORY(int, IntVarObj) static std::unique_ptr<VarObj> createInt(int value); int value() const { return v; } void set(int val) { v = val; } private: int v; LANDRU_DECL_BINDING_BEGIN LANDRU_DECL_BINDING(add) LANDRU_DECL_BINDING(set) LANDRU_DECL_BINDING(range) LANDRU_DECL_BINDING_END }; } #endif
#ifndef _DUCK_H_ #define _DUCK_H_ #include"Animal.hpp" #include<iostream> using namespace std; class Duck : public Animal //add public { public: Duck(); Duck(string name, char mark, int* pattern, int size, int position); //~Dog(); virtual void showExcitement() const; }; #endif
#include "../../gl_framework.h" using namespace glmock; extern "C" { #undef glUniform1fv void CALL_CONV glUniform1fv(GLint location, GLsizei count, const GLfloat* value) { } DLL_EXPORT PFNGLUNIFORM1FVPROC __glewUniform1fv = &glUniform1fv; }
/***************************************************************************************** * * * owl * * * * Copyright (c) 2014 Jonas Strandstedt * * * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * * software and associated documentation files (the "Software"), to deal in the Software * * without restriction, including without limitation the rights to use, copy, modify, * * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * * permit persons to whom the Software is furnished to do so, subject to the following * * conditions: * * * * The above copyright notice and this permission notice shall be included in all copies * * or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF * * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ****************************************************************************************/ #include <owl/signal/signal.h> #include <signal.h> #ifdef __WIN32__ #ifndef SIGHUP #define SIGHUP 1 #endif #ifndef SIGQUIT #define SIGQUIT 3 #endif #ifndef SIGKILL #define SIGKILL 9 #endif #ifndef SIGSTOP #define SIGSTOP 23 #endif #ifndef SIGTSTP #define SIGTSTP 20 #endif #endif namespace { const std::string _loggerCat = "SignalHandler"; } namespace owl { void owl_signal_handler(int signo) { owl::SignalHandler::ref().call(signo); } SignalHandler::SignalHandler() { for (auto &c: _callbacks) { c = nullptr; } } SignalHandler::~SignalHandler() { } int SignalHandler::signalnumber (Signal s) { switch (s) { case Signal::Hangup: return SIGHUP; case Signal::Abort: return SIGABRT; case Signal::Quit: return SIGQUIT; case Signal::IllegalInstruction: return SIGILL; case Signal::Interrupt: return SIGINT; case Signal::Kill: return SIGKILL; case Signal::Terminate: return SIGTERM; case Signal::Stop: return SIGSTOP; case Signal::TTYStop: return SIGTSTP; default: return 0; } } int SignalHandler::numberToSignalPosition (int signo) { switch (signo) { case SIGHUP: return 0; case SIGABRT: return 1; case SIGQUIT: return 2; case SIGILL: return 3; case SIGINT: return 4; case SIGKILL: return 5; case SIGTERM: return 6; case SIGSTOP: return 7; case SIGTSTP: return 8; default: return -1; } } void SignalHandler::setCallback(int s, SignalCallback callback) { void (*c)(int) = owl_signal_handler; if(callback == nullptr) c = SIG_DFL; _lock.lock(); for (int i = 0; i < SignalHandler::NumberOfCallbacks; ++i) { int no = 1 << i; if(s & no) { int signr = signalnumber(static_cast<Signal>(no)); if(signr > 0) { _callbacks[i] = callback; signal(signr, c); } } } _lock.unlock(); } std::string SignalHandler::toString(Signal signal) { switch(signal) { case Signal::Hangup: return "Hangup"; case Signal::Abort: return "Abort"; case Signal::Quit: return "Quit"; case Signal::IllegalInstruction: return "IllegalInstruction"; case Signal::Interrupt: return "Interrupt"; case Signal::Kill: return "Kill"; case Signal::Terminate: return "Terminate"; case Signal::Stop: return "Stop"; case Signal::TTYStop: return "TTYStop"; default: return "Unknown"; break; } } std::string SignalHandler::toString(int signal) { switch(signal) { case SIGHUP : return toString(Signal::Hangup); case SIGABRT : return toString(Signal::Abort); case SIGQUIT : return toString(Signal::Quit); case SIGILL : return toString(Signal::IllegalInstruction); case SIGINT : return toString(Signal::Interrupt); case SIGKILL : return toString(Signal::Kill); case SIGTERM : return toString(Signal::Terminate); case SIGSTOP : return toString(Signal::Stop); case SIGTSTP : return toString(Signal::TTYStop); default: return "Unknown"; break; } } void SignalHandler::call(int signo) { int callbackpos = numberToSignalPosition(signo); if(callbackpos < 0) return; _lock.lock(); if(_callbacks[callbackpos] != nullptr) _callbacks[callbackpos](static_cast<Signal>(1<<callbackpos)); _lock.unlock(); } }
#ifndef _Stack_H #define _Stack_H #include <iostream> using namespace std; class Stack{ private: int size; int* data; int top; public: Stack(int i=1); void push(int value); int pop(); void clear(); bool isEmpty(); ~Stack(); }; void menu(); #endif
#ifndef STORAGE_BACKEND_SIMPLEDB_HH #define STORAGE_BACKEND_SIMPLEDB_HH #include "storage/backend.hh" #include "net/simpledb.hh" class SimpleDBStorageBackend : public StorageBackend { private: SimpleDB client_; public: SimpleDBStorageBackend(SimpleDBClientConfig& config) : client_(config) {} void put(const std::vector<storage::PutRequest>& requests, const PutCallback & success_callback = [](const storage::PutRequest&){}) override; void get(const std::vector<storage::GetRequest>& requests, const GetCallback & success_callback = [](const storage::GetRequest&){}) override; }; #endif /* STORAGE_BACKEND_SIMPLEDB_HH */
// // Copyright (c) 2002 David Gould // #ifndef BASICLOCATORMANIP_H #define BASICLOCATORMANIP_H #include <maya/MString.h> #include <maya/MTypeId.h> #include <maya/MPlug.h> #include <maya/MVector.h> #include <maya/M3dView.h> #include <maya/MMatrix.h> #include <maya/MDistance.h> #include <maya/MPxManipContainer.h> #include <maya/MFnDistanceManip.h> #include <maya/MManipData.h> #include <math.h> class BasicLocatorManip : public MPxManipContainer { public: virtual MStatus createChildren(); virtual MStatus connectToDependNode(const MObject & node); virtual void draw(M3dView & view, const MDagPath & path, M3dView::DisplayStyle style, M3dView::DisplayStatus status); static void * creator(); MManipData startPointCallback(unsigned index) const; MManipData sideDirectionCallback(unsigned index) const; MManipData backDirectionCallback(unsigned index) const; MVector nodeTranslation() const; MVector worldOffset(MVector vect) const; static const MTypeId typeId; static const MString typeName; MManipData centerPointCallback(unsigned index) const; // Paths to child manipulators MDagPath xWidthDagPath; MDagPath zWidthDagPath; MDagPath typeDagPath; // Object that the manipulator will be operating on MObject targetObj; }; #endif
/* * Platform Specification Implementation * Nana C++ Library(http://www.nanapro.org) * Copyright(C) 2003-2015 Jinhao(cnjinhao@hotmail.com) * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) * * @file: _GUI/PlatformSpec.cpp * * This file provides basis class and data structrue that required by _GUI */ #include <_/PlatformSpecSelector.h> #if defined(NANA_WINDOWS) #include <shellapi.h> #include <stdexcept> #if defined(_MSC_VER) #include <VersionHelpers.h> #endif // _MSVC namespace _G { DrawableImplType::DrawableImplType () { pen.handle = nullptr; pen.color = 0xffffffff; pen.style = -1; pen.width = -1; brush.handle = nullptr; brush.style = BrushSpec::Solid; brush.color = 0xffffffff; round_region.handle = nullptr; round_region.radius_x = round_region.radius_y = 0; string.tab_length = 4; string.tab_pixels = 0; string.whitespace_pixels = 0; } DrawableImplType::~DrawableImplType () { ::DeleteDC (context); ::DeleteObject (pixmap); ::DeleteObject (pen.handle); ::DeleteObject (brush.handle); ::DeleteObject (round_region.handle); } void DrawableImplType::fgcolor (const ::_GUI::color& clr) { set_text_color (clr); } unsigned DrawableImplType::get_color () const { return color_; } unsigned DrawableImplType::get_text_color () const { return text_color_; } void DrawableImplType::set_color (const ::_GUI::color& clr) { color_ = (clr.px_color ().value & 0xFFFFFF); } void DrawableImplType::set_text_color (const ::_GUI::color& clr) { auto rgb = (clr.px_color ().value & 0xFFFFFF); if (text_color_ != rgb) { ::SetTextColor (context, NANA_RGB(rgb)); text_color_ = rgb; } } void DrawableImplType::update_pen () { if (pen.color != color_) { pen.handle = ::CreatePen (PS_SOLID, 1, NANA_RGB(color_)); ::DeleteObject (::SelectObject (context, pen.handle)); pen.color = color_; } } void DrawableImplType::update_brush () { if (brush.color != color_) brush.set (context, brush.style, color_); } void DrawableImplType::PenSpec::set (HDC context, int style, int width, unsigned clr) { if (this->color != clr || this->width != width || this->style != style) { this->color = clr; this->width = width; this->style = style; this->handle = ::CreatePen (style, width, NANA_RGB(clr)); ::DeleteObject (::SelectObject (context, this->handle)); } } void DrawableImplType::BrushSpec::set (HDC context, DrawableImplType::BrushSpec::t style, unsigned rgb) { if (this->color != rgb || this->style != style) { this->color = rgb; this->style = style; switch (style) { case BrushSpec::HatchBDiagonal: this->handle = ::CreateHatchBrush (HS_BDIAGONAL, NANA_RGB(rgb)); break; case BrushSpec::Solid: default: this->style = BrushSpec::Solid; this->handle = ::CreateSolidBrush (NANA_RGB(color)); break; } ::DeleteObject (::SelectObject (context, this->handle)); } } void DrawableImplType::RoundRegionSpec::set (const _GUI::rectangle& r, unsigned radius_x, unsigned radius_y) { if (this->r != r || this->radius_x != radius_x || this->radius_y != radius_y) { if (handle) ::DeleteObject (this->handle); this->r = r; this->radius_x = radius_x; this->radius_y = radius_y; handle = ::CreateRoundRectRgn (r.x, r.y, r.x + static_cast<int> (r.width) + 1, r.y + static_cast<int> (r.height) + 1, static_cast<int> (radius_x + 1), static_cast<int> (radius_y + 1)); } } //struct FontTag::deleter void FontTag::deleter::operator() (const FontTag* tag) const { if (tag && tag->handle) ::DeleteObject (tag->handle); delete tag; } //< struct FontTag::deleter //class PlatformSpec PlatformSpec::co_initializer::co_initializer () : ole32_ (::LoadLibrary (L"OLE32.DLL")) { if (ole32_) { typedef HRESULT (__stdcall *CoInitializeEx_t) (LPVOID, DWORD); CoInitializeEx_t fn_init = reinterpret_cast<CoInitializeEx_t> (::GetProcAddress (ole32_, "CoInitializeEx")); if (0 == fn_init) { ::FreeLibrary (ole32_); ole32_ = 0; throw std::runtime_error ("Nana.PlatformSpec.Co_initializer: Can't locate the CoInitializeEx()."); } else fn_init (0, COINIT_APARTMENTTHREADED | /*COINIT_DISABLE_OLE1DDE =*/0x4); } else throw std::runtime_error ("Nana.PlatformSpec.Co_initializer: No Ole32.DLL Loaded."); } PlatformSpec::co_initializer::~co_initializer () { if (ole32_) { typedef void (__stdcall *CoUninitialize_t) (void); CoUninitialize_t fn_unin = reinterpret_cast<CoUninitialize_t> (::GetProcAddress (ole32_, "CoUninitialize")); if (fn_unin) fn_unin (); ::FreeLibrary (ole32_); } } PlatformSpec::PlatformSpec () { //Create default font object. NONCLIENTMETRICS metrics = {}; metrics.cbSize = sizeof metrics; #if(WINVER >= 0x0600) #if defined(NANA_MINGW) OSVERSIONINFO osvi = {}; osvi.dwOSVersionInfoSize = sizeof(osvi); ::GetVersionEx(&osvi); if (osvi.dwMajorVersion < 6) metrics.cbSize -= sizeof(metrics.iPaddedBorderWidth); #else if (!IsWindowsVistaOrGreater ()) metrics.cbSize -= sizeof(metrics.iPaddedBorderWidth); #endif #endif ::SystemParametersInfo (SPI_GETNONCLIENTMETRICS, sizeof metrics, &metrics, 0); def_font_ptr_ = make_native_font (to_UTF8 (metrics.lfMessageFont.lfFaceName).c_str (), font_size_to_height (9), 400, false, false, false); } const PlatformSpec::font_ptr_t& PlatformSpec::default_native_font () const { return def_font_ptr_; } void PlatformSpec::default_native_font (const font_ptr_t& fp) { def_font_ptr_ = fp; } unsigned PlatformSpec::font_size_to_height (unsigned size) const { HDC hdc = ::GetDC (0); size = ::MulDiv (int (size), ::GetDeviceCaps (hdc, LOGPIXELSY), 72); ::ReleaseDC (0, hdc); return size; } unsigned PlatformSpec::font_height_to_size (unsigned height) const { HDC hdc = ::GetDC (0); unsigned pixels = ::GetDeviceCaps (hdc, LOGPIXELSY); ::ReleaseDC (0, hdc); height = static_cast<unsigned> (static_cast<long long> (72) * height / pixels); return height; } PlatformSpec::font_ptr_t PlatformSpec::make_native_font (const char* name, unsigned height, unsigned weight, bool italic, bool underline, bool strike_out) { ::LOGFONT logfont; memset (&logfont, 0, sizeof logfont); if (name && *name) std::wcscpy (logfont.lfFaceName, to_wstring (name).c_str ()); else std::wcscpy (logfont.lfFaceName, def_font_ptr_->name.c_str ()); logfont.lfCharSet = DEFAULT_CHARSET; HDC hdc = ::GetDC (0); logfont.lfHeight = -static_cast<int> (height); ::ReleaseDC (0, hdc); logfont.lfWidth = 0; logfont.lfWeight = weight; logfont.lfQuality = PROOF_QUALITY; logfont.lfPitchAndFamily = FIXED_PITCH; logfont.lfItalic = italic; logfont.lfUnderline = underline; logfont.lfStrikeOut = strike_out; HFONT result = ::CreateFontIndirect (&logfont); if (result) { FontTag* impl = new FontTag; impl->name = logfont.lfFaceName; impl->height = height; impl->weight = weight; impl->italic = italic; impl->underline = underline; impl->strikeout = strike_out; impl->handle = result; return std::shared_ptr<FontTag> (impl, FontTag::deleter ()); } return nullptr; } PlatformSpec& PlatformSpec::instance () { static PlatformSpec object; return object; } void PlatformSpec::keep_window_icon (native_window_type wd, const Paint::Image& sml_icon, const Paint::Image& big_icon) { auto& icons = iconbase_[wd]; icons.sml_icon = sml_icon; icons.big_icon = big_icon; } void PlatformSpec::release_window_icon (native_window_type wd) { iconbase_.erase (wd); } } //< namespace _ #endif //NANA_WINDOWS
#include <SimpleTimer.h> #include <WiFi.h> #include <HTTPClient.h> #include <ArduinoJson.h> #include <SPI.h> #include <MD_Parola.h> #include <MD_MAX72xx.h> #include <time.h> #include <sys/time.h> #include <OneWire.h> #include <DallasTemperature.h> #include <PubSubClient.h> #include <aREST.h> #include "soc/timer_group_struct.h" #include "soc/timer_group_reg.h" typedef enum{ buzzer_on_alarm=0, buzzer_on_hour, buzzer_off, buzzer_stb, buzzer_check }ST_buzzer; typedef enum{ printing=0, print_error, print_stb, print_error_wifi }ST_print; typedef enum{ request, checking, stb }ST_request; typedef enum{ p_push, p_check, p_time }ST_boton; typedef enum{ menu_stb, menu_hora, menu_alarma }ST_menu; typedef enum{ conect, check_reconect, reconect, check }ST_wifi; enum{ T_PrintHour=0, T_PrintWeather, T_B1, T_B2, T_RequestWeather, T_RequestHour, T_RequestUbidotsTemperatura, T_Reconect, T_ControlCharge, T_buzzer, TIMERS, }; ST_request hour=request, weather=stb, ambiente=stb; ST_print tiempo=printing, clime=print_stb; ST_boton P1=p_check, P2=p_check; ST_wifi wifi=check; ST_buzzer buzzer=buzzer_check; ST_menu menu = menu_stb; const char ssid[]= "FAMILIA LONDONO"; const char password[]= "12624025"; char* device_id = "reloj1"; char * key = "821famk4b2t1q2el"; const char *ntpServer = "horalegal.inm.gov.co"; const long gmtOffset_sec = -18000; const int daylightOffset_sec = 0; #define HARDWARE_TYPE MD_MAX72XX::FC16_HW #define MAX_DEVICES 4 #define CS_PIN 2 #define CLK_PIN 18 #define DATA_PIN 23 #define B_1 21 #define B_2 19 #define buzzer_pin 15 #define ADC 35 #define SENSOR 22 #define FULL_CHARGE 4 #define CHARGING 5 double tem_amb; bool trigger_hora = true; int tem_amb_int,temperature = 0; char tem[200]; char alar[200]; char hora[20]; int channel=0; uint16_t v=50; struct tm timeinfo; int h=0,m=0,s=0,mo=0; uint8_t espera_wifi = 0; int h_alarm=100,m_alarm=100, ind_alarma = 0, stb_alarma = 0; uint16_t triger_alarm = 0,triger_hour = 0; volatile uint32_t timers[TIMERS]; volatile String data_clima; const char* w; const char* al; const char* ho; uint8_t degC[] = { 6, 3, 3, 56, 68, 68, 68 }; //caracter °c uint8_t alarm_yes[] = { 5, 0, 60, 20, 60, 0}; // caracter alarma on uint8_t alarm_no[] = { 5, 255, 195, 235, 195, 255}; // caracter alarma off TaskHandle_t Task1; TaskHandle_t Task2; TaskHandle_t Task3; WiFiClient espClient; PubSubClient client(espClient); aREST rest = aREST(client); SimpleTimer timer, timer2; MD_Parola P = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES); OneWire OneWireObject(SENSOR); DallasTemperature sensorDS18B20(&OneWireObject); String serie2; HTTPClient http3; StaticJsonDocument<1000> doc3; String serie; HTTPClient http2; StaticJsonDocument<1000> doc2; String serie3; HTTPClient http4; StaticJsonDocument<1000> doc4; void loop1(void *parameter); void loop2(void *parameter); void loop3(void *parameter); void conectarWifi(); void digitalClockDisplay(); void Tiempo_timer(); void process_buzzer(); void process_requestHour(); void process_requestWeather(); void process_printHour(); void process_printWeather(); void process_boton1(); void process_boton2(); void process_SendUbidotsTemperatura(); void process_reconnect(); int controlAlarma(String hora_alarma); void callback(char* topic, byte* payload, unsigned int length); void setup() { Serial.begin(115200); pinMode(B_1, INPUT); pinMode(B_2, INPUT); pinMode(FULL_CHARGE, INPUT); pinMode(CHARGING, INPUT); pinMode(2, OUTPUT); client.setCallback(callback); rest.function("alarma",controlAlarma); rest.set_id(device_id); rest.set_name("esp32"); P.begin(); P.setIntensity(0); P.addChar('#', alarm_yes); P.addChar('!', alarm_no); sensorDS18B20.begin(); timer.setInterval(1); timer2.setInterval(1000); ledcSetup(0,3500,8); ledcAttachPin(buzzer_pin,0); conectarWifi(); xTaskCreatePinnedToCore(loop1,"Task_1",5120,NULL,1,&Task1,0); xTaskCreatePinnedToCore(loop2,"Task_2",6144,NULL,1,&Task2,1); xTaskCreatePinnedToCore(loop3,"Task_3",5120,NULL,1,&Task3,0); } void loop() { Tiempo_timer(); //timers digitalClockDisplay(); //conteo reloj interno process_printHour(); process_boton1(); process_boton2(); process_printWeather(); } void loop1(void *parameter){ for(;;){ TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_feed = 1; TIMERG0.wdt_wprotect = 0; rest.handle(client); process_requestHour(); process_requestWeather(); //process_SendUbidotsTemperatura(); } vTaskDelay(10); } void loop2(void *parameter){ for(;;){ TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_feed = 1; TIMERG0.wdt_wprotect = 0; process_reconnect(); } vTaskDelay(10); } void loop3(void *parameter){ for(;;){ TIMERG0.wdt_wprotect = TIMG_WDT_WKEY_VALUE; TIMERG0.wdt_feed = 1; TIMERG0.wdt_wprotect = 0; process_buzzer(); } vTaskDelay(10); } void Tiempo_timer(){ uint16_t i; if(timer.isReady()){ for(i=0;i<=TIMERS;i++){ if(timers[i]!=0){ timers[i]--; } } timer.reset(); } } void conectarWifi(){ WiFi.begin(ssid, password); Serial.print("Conecting to: "); Serial.println(ssid); while(WiFi.status() != WL_CONNECTED){ Serial.print("."); delay(1000); espera_wifi++; Serial.println(espera_wifi); if(espera_wifi == 60){ break; } } Serial.println(F("WiFi connected")); Serial.print(F("IP address: ")); Serial.println(WiFi.localIP()); configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); } void digitalClockDisplay() { if(menu == menu_stb){ if(timer2.isReady()){ s = s+1; if(s==60){ m=m+1; s=0; } if(m==60){ h=h+1; m=0; } if(h==24){ h=0; } timer2.reset(); } } } void process_requestHour(){ switch(hour){ case stb: //do nothing break; case checking: timers[T_RequestHour]=300000; hour=request; break; case request: if(timers[T_RequestHour]==0){ if(!getLocalTime(&timeinfo)){ //error al sincronizar la hora return; } Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); h=timeinfo.tm_hour; m=timeinfo.tm_min; s=timeinfo.tm_sec; mo=timeinfo.tm_mon; hour=stb; } break; } } void process_requestWeather(){ switch(weather){ case stb: timers[T_RequestWeather]=60000; weather=request; break; case request: if(timers[T_RequestWeather]==0){ if(WiFi.status() == WL_CONNECTED){ HTTPClient http; http.begin("http://api.openweathermap.org/data/2.5/weather?q=Bogota&units=metric&lang=es&appid=d212d43340e59e9c201119a4fdae37c6"); int httpCode = http.GET(); if(httpCode > 0){ String payloads = http.getString(); StaticJsonDocument<1000> doc; deserializeJson(doc, payloads); const char* clima = doc["weather"][0]["main"]; temperature = doc["main"]["temp"]; sensorDS18B20.requestTemperatures(); tem_amb_int = sensorDS18B20.getTempCByIndex(0); P.addChar('$', degC); sprintf(tem," T:%d$ C:%s TA:%d$ ",temperature,clima,tem_amb_int); w = tem; } http.end(); }else if(WiFi.status() == WL_DISCONNECTED){ tiempo=print_stb; clime=print_error_wifi; } weather=stb; } break; } } void process_printHour(){ switch(tiempo){ case printing: if(P.displayAnimate()){ if((m==0 && s==0) && (h!=22 && h!=23 && h!=0 && h!=1 && h!=2 && h!=3 && h!=4 && h!=5) && triger_alarm==0){ triger_hour = 1; }else{ triger_hour = 0; } if(h == h_alarm && m == m_alarm && s==0 && stb_alarma == 0){ stb_alarma = 1; } if(h == h_alarm && m == m_alarm && s>=0 && triger_alarm==0 && stb_alarma == 1){ triger_alarm = 1; }else if(m != m_alarm){ stb_alarma = 0; triger_alarm = 0; } if(h<10 && m<10){ if(ind_alarma == 1){ sprintf(hora, "0%d:0%d!", h, m); }else if(ind_alarma == 0){ sprintf(hora, "0%d:0%d#", h, m); } }else if(h>9 && m>9){ if(ind_alarma == 1){ sprintf(hora, "%d:%d!", h, m); }else if(ind_alarma == 0){ sprintf(hora, "%d:%d#", h, m); } }else if(h<10 && m>9){ if(ind_alarma == 1){ sprintf(hora, "0%d:%d!", h, m); }else if(ind_alarma == 0){ sprintf(hora, "0%d:%d#", h, m); } }else if(h>9 && m<10){ if(ind_alarma == 1){ sprintf(hora, "%d:0%d!", h, m); }else if(ind_alarma == 0){ sprintf(hora, "%d:0%d#", h, m); } } ho=hora; P.setTextAlignment(PA_CENTER); P.write(ho); } break; case print_stb: tiempo=printing; break; case print_error: //no necesario break; } } void process_printWeather(){ switch(clime){ case printing: P.displayText(w, PA_CENTER, v, 100, PA_SCROLL_LEFT, PA_SCROLL_LEFT); P.displayAnimate(); clime=print_stb; break; case print_error: if(h_alarm == 100 && m_alarm == 100){ sprintf(alar," Alarma desactivada "); al = alar; }else{ sprintf(alar," Alarma activa: %d:%d",h_alarm,m_alarm); al = alar; } P.displayText(al, PA_CENTER, v, 100, PA_SCROLL_LEFT, PA_SCROLL_LEFT); P.displayAnimate(); clime=print_stb; break; case print_error_wifi: P.displayText("No hay conexion wifi", PA_CENTER, v, 100, PA_SCROLL_LEFT, PA_SCROLL_LEFT); P.displayAnimate(); clime=print_stb; case print_stb: //do nothing break; } } void process_boton1(){ int val=digitalRead(B_1); if(menu == menu_stb){ switch(P1){ case p_check: if(val == 1){ timers[T_B1] = 2500; P1 = p_push; Serial.println("1 pulsado"); } break; case p_time: if(timers[T_B1] == 0){ P1 = p_check; } break; case p_push: if(timers[T_B1] >= 2400){ //antirrebote Serial.print("*"); }else if(timers[T_B1] < 2400 && timers[T_B1] > 0){ Serial.print("_"); if(val == 1){ //do nothing }else if(val == 0){ Serial.println("soltado"); if(stb_alarma == 1){ ledcWriteTone(0,0); triger_alarm = 0; stb_alarma = 0; timers[T_B1]=200; P1=p_time; }else{ tiempo=print_stb; clime=printing; timers[T_B1]=9000; P1=p_time; timers[T_B2]=9000; P2=p_time; } } }else if(timers[T_B1] == 0 ){ hour = stb; menu = menu_hora; timers[T_B1] == 1500; P1 = p_time; ledcWriteTone(0,4000); Serial.println("modo hora"); } break; } }else{ switch(P1){ case p_check: if(val == 1){ timers[T_B1] = 2500; P1 = p_push; Serial.println("1 pulsado en modo"); } break; case p_time: if(timers[T_B1] == 0){ P1 = p_check; ledcWriteTone(0,0); } break; case p_push: if(timers[T_B1] >= 2400){ //antirrebote }else if(timers[T_B1] < 2400 && timers[T_B1] > 0){ if(val == 1){ //do nothing }else if(val == 0){ Serial.println("1 soltado en modo"); if(menu == menu_hora){ if(trigger_hora == true){ h++; if(h == 24){ h=0; } }else{ m++; if(m == 60){ m=0; } } } timers[T_B1]=200; P1=p_time; } }else if(timers[T_B1] == 0 ){ if(trigger_hora == false){ trigger_hora = true; menu = menu_stb; hour = checking; timers[T_B1] == 1500; P1 = p_time; ledcWriteTone(0,4000); }else{ trigger_hora = false; timers[T_B1] == 1500; P1 = p_time; ledcWriteTone(0,4000); } } break; } } } void process_boton2(){ int val2=digitalRead(B_2); switch(P2){ case p_check: if(val2 == 1){ timers[T_B2] = 2500; P2 = p_push; Serial.println("2 pulsado"); } break; case p_time: if(timers[T_B2] == 0){ P2 = p_check; } break; case p_push: if(timers[T_B2] >= 2400){ //antirrebote }else if(timers[T_B2] < 2400 && timers[T_B2] > 0){ if(val2 == 1){ //do nothing }else if(val2 == 0){ if(stb_alarma == 1){ ledcWriteTone(0,0); triger_alarm = 0; stb_alarma = 0; timers[T_B2]=200; P2=p_time; }else{ tiempo=print_stb; clime=print_error; timers[T_B2]=7000; P2=p_time; timers[T_B1]=7000; P1=p_time; } } }else if(timers[T_B2] == 0 ){ menu = menu_alarma; Serial.println("modo alarma"); } break; } } void process_reconnect() { switch(wifi){ case conect: configTime(gmtOffset_sec, daylightOffset_sec, ntpServer); wifi=check; break; case check_reconect: if(timers[T_Reconect] == 0){ if(WiFi.status() == WL_CONNECTED){ wifi=conect; Serial.println("Wifi conectado"); }else{ wifi=reconect; } } break; case check: if(WiFi.status() == WL_DISCONNECTED){ wifi=reconect; Serial.println("WiFi desconectado"); } break; case reconect: WiFi.begin(ssid, password); Serial.println("Reconectado..."); timers[T_Reconect]=10000; wifi=check_reconect; break; } } void process_SendUbidotsTemperatura(){ switch(ambiente){ case request: if(timers[T_RequestUbidotsTemperatura]==0){ if(WiFi.status() == WL_CONNECTED){ sensorDS18B20.requestTemperatures(); tem_amb = sensorDS18B20.getTempCByIndex(0); http3.begin("https://your-clock.herokuapp.com/api/datos"); http3.addHeader("Content-Type", "application/json"); serie2=""; doc3["temp_amb"]=tem_amb; doc3["temp_local"]=temperature; serializeJson(doc3, serie2); Serial.println(serie2); int code = http3.POST(serie2); if(code > 0){ Serial.println("OK"); }else{ Serial.println("Error en HTTP request"); } http3.end(); } ambiente=stb; } break; case stb: timers[T_RequestUbidotsTemperatura]=20000; ambiente=request; break; } } void process_buzzer(){ switch(buzzer){ case buzzer_on_alarm: if(timers[T_buzzer]>=1000 && timers[T_buzzer]<=2000){ ledcWriteTone(0,4000); }else if(timers[T_buzzer]>0 && timers[T_buzzer]<1000){ ledcWriteTone(0,0); }else if(timers[T_buzzer]==0){ buzzer = buzzer_check; } break; case buzzer_on_hour: ledcWriteTone(0,4000); buzzer = buzzer_check; break; case buzzer_off: ledcWriteTone(0,0); buzzer = buzzer_check; break; case buzzer_stb: break; case buzzer_check: if(triger_alarm == 0 && triger_hour == 0){ buzzer = buzzer_off; }else if(triger_alarm == 1 && triger_hour == 0){ buzzer = buzzer_on_alarm; timers[T_buzzer]=2000; }else if(triger_alarm == 0 && triger_hour == 1){ buzzer = buzzer_on_hour; }else if(triger_alarm == 1 && triger_hour == 1){ buzzer = buzzer_on_alarm; timers[T_buzzer]=2000; } break; } } int controlAlarma(String hora_alarma){ int aux_alarma = hora_alarma.toInt(); if(aux_alarma == 0){ h_alarm = 0; m_alarm = 0; ind_alarma = 1; }else if(aux_alarma >= 1 && aux_alarma <=59){ h_alarm = 0; m_alarm = aux_alarma; ind_alarma = 1; }else if(aux_alarma >=100 && aux_alarma <=2359){ h_alarm = (aux_alarma / 100); m_alarm = aux_alarma - (h_alarm * 100); ind_alarma = 1; }else{ h_alarm = 100; m_alarm = 100; ind_alarma = 0; } return 1; } void callback(char* topic, byte* payload, unsigned int length) { rest.handle_callback(client, topic, payload, length); }
#include "aePlatformMath.h" namespace aeEngineSDK { /*************************************************************************************************/ /* Common use math constants /*************************************************************************************************/ const float aePlatformMath::SMALL_NUMBER = 1.e-8f; /// "Small number" definition const float aePlatformMath::KIND_OF_SMALL_NUMBER = 1.e-4f; /// "Kinda small number" definition const float aePlatformMath::BIG_NUMBER = 3.4e+38f; /// "Big number" definition const float aePlatformMath::KIND_OF_BIG_NUMBER = 3.4e+19f; /// "Kinda big number" definition const float aePlatformMath::EULER = aePlatformMath::Exp(1.0f); /// Euler–Mascheroni constant const float aePlatformMath::INV_EULER = 1.0f/aePlatformMath::Exp(1.0f); /// Inverse Euler–Mascheroni constant const float aePlatformMath::PI = aePlatformMath::ArcTan(1.0f) * 4.0f; /// PI constant const float aePlatformMath::INV_PI = 0.25f / (aePlatformMath::ArcTan(1.0f)); /// Inverse of PI (1/PI) const float aePlatformMath::ONE_QUARTER_PI = aePlatformMath::ArcTan(1.0f); /// One quarter PI const float aePlatformMath::THREE_QUARTER_PI = aePlatformMath::ArcTan(1.0f)*3.0f; /// Three quarter PI const float aePlatformMath::HALF_PI = aePlatformMath::ArcTan(1.0f) * 2.0f; /// Half PI const float aePlatformMath::TWICE_PI = aePlatformMath::ArcTan(1.0f) * 8.0f; /// Twice PI const float aePlatformMath::MAX_FLOAT = NumericLimits<float>::max(); /// Max value of a float const float aePlatformMath::MIN_FLOAT = NumericLimits<float>::min(); /// Min value of a float const float aePlatformMath::LOW_FLOAT = NumericLimits<float>::lowest(); /// Lowest value of a float const float aePlatformMath::FLOAT_DELTA = 0.00001f; /// Magic number used for math precision const float aePlatformMath::FLOAT_EPSILON = NumericLimits<float>::epsilon(); const float aePlatformMath::FLOAT_NAN = NumericLimits<float>::quiet_NaN(); const float aePlatformMath::FLOAT_INFINITY = NumericLimits<float>::infinity(); const float aePlatformMath::FLOAT_ROUND_ERROR = NumericLimits<float>::round_error(); const float aePlatformMath::FLOAT_DENORM_MIN = NumericLimits<float>::denorm_min(); const double aePlatformMath::MAX_DOUBLE = NumericLimits<double>::max(); /// Max value of a double const double aePlatformMath::MIN_DOUBLE = NumericLimits<double>::min(); /// Min value of a double const double aePlatformMath::LOW_DOUBLE = NumericLimits<double>::lowest(); /// Lowest value of a double const double aePlatformMath::DOUBLE_DELTA = 0.00001; /// Magic number used for math precision const double aePlatformMath::DOUBLE_EPSILON = NumericLimits<double>::epsilon(); const double aePlatformMath::DOUBLE_NAN = NumericLimits<double>::quiet_NaN(); const double aePlatformMath::DOUBLE_INFINITY = NumericLimits<double>::infinity(); const double aePlatformMath::DOUBLE_ROUND_ERROR = NumericLimits<double>::round_error(); const double aePlatformMath::DOUBLE_DENORM_MIN = NumericLimits<double>::denorm_min(); /*************************************************************************************************/ /* Fast math functions using Taylor series /*************************************************************************************************/ float aePlatformMath::FastSin(const float& Value) { float Result = Value; float f = Value*Value*Value; Result -= f * 0.166666667f; f *= Value*Value; return Result += f * 0.008333333f; /*return Value - ((Value*Value*Value) * 0.166666667f) + ((Value*Value*Value*Value*Value) * 0.008333333f);*/ } float aePlatformMath::FastCos(const float& Value) { float Result = 1.0f; float f1 = Value*Value; Result -= f1 * 0.5f; float f2 = f1 * f1; Result += f2 * 0.041666667f; f2 *= f1; Result -= f2 * 0.001388889f; f2 *= f1; return Result += f2 * 0.000024801f; /*return 1.0f - (Value*Value*0.5f) + ((Value*Value*Value*Value) * 0.041666667f) - ((Value*Value*Value*Value*Value*Value) * 0.001388889f) + ((Value*Value*Value*Value*Value*Value*Value*Value)* 0.000024801f);*/ } float aePlatformMath::FastTan(const float& Value) { float Result = Value; float f1 = Value*Value*Value; Result += f1 * 0.333333333f; float f2 = Value*Value; f1 *= f2; Result += f1 * 0.133333333f; f1 *= f2; return Result += f1 * 0.053968253f; /*return Value + ((Value*Value*Value) * 0.333333333f) + ((Value*Value*Value*Value*Value)*0.133333333f) + ((Value*Value*Value*Value*Value*Value*Value)*0.053968253f);*/ } float aePlatformMath::FastCot(const float& Value) { float Result = 1.0f / Value; float f1 = Value; Result -= f1 * 0.333333333f; float f2 = f1 * f1 * f1; f1 *= f1; Result -= f2 * 0.022222222f; f2 *= f1; Result -= f2 * 0.002116402f; f2 *= f1; return Result -= f2 * 0.000211640f; /*return 1.0f / Value - (Value * 0.333333333f) - ((Value*Value*Value) * 0.022222222f) - ((Value*Value*Value*Value*Value) * 0.002116402f) - ((Value*Value*Value*Value*Value*Value*Value) * 0.000211640f);*/ } float aePlatformMath::FastSec(const float& Value) { float Result = 1.0f; float f1 = Value*Value; Result += f1 * 0.5f; float f2 = f1 * f1; Result += f2 * 0.208333333f; f2 *= f1; Result += f2 * 0.084722222f; f2 *= f1; return Result += f2 * 0.034350198f; /*return 1.0f + (Value*Value*0.5f) + ((Value*Value*Value*Value) * 0.208333333f) + ((Value*Value*Value*Value*Value*Value) * 0.084722222f) + ((Value*Value*Value*Value*Value*Value*Value*Value) * 0.034350198f);*/ } float aePlatformMath::FastCsc(const float& Value) { float Result = 1.0f / Value; float f1 = Value; Result += f1 * 0.166666667f; f1 *= f1; float f2 = f1 * Value; Result += f2 * 0.019444444f; f2 *= f1; Result += f2 * 0.002050264f; f2 *= f1; return Result += f2 * 0.000209987f; /*return 1.0f / Value + (Value * 0.166666667f) + ((Value*Value*Value) * 0.019444444f) + ((Value*Value*Value*Value*Value) * 0.002050264f) + ((Value*Value*Value*Value*Value*Value*Value) * 0.000209987f);*/ } float aePlatformMath::FastArcSin(const float& Value) { float Result = Value; float f2 = Value*Value; float f1 = Value*f2; Result += f1 * 0.166666667f; f1 *= f2; Result += f1 * 0.075f; f1 *= f2; Result += f1 * 0.044642857f; f1 *= f2; return Result += f1 * 0.030381944f; /*return Value + ((Value*Value*Value) * 0.166666667f) + ((Value*Value*Value*Value*Value) * 0.075f) + ((Value*Value*Value*Value*Value*Value*Value) * 0.044642857f) + ((Value*Value*Value*Value*Value*Value*Value*Value*Value) * 0.030381944f);*/ } float aePlatformMath::FastArcCos(const float& Value) { float Result = Value; float f2 = Value*Value; float f1 = Value*f2; Result += f1 * 0.166666667f; f1 *= f2; Result += f1 * 0.075f; f1 *= f2; Result += f1 * 0.044642857f; f1 *= f2; Result += f1 * 0.030381944f; return HALF_PI - Result; /*return HALF_PI - (Value + ((Value*Value*Value) * 0.166666667f) + ((Value*Value*Value*Value*Value) * 0.075f) + ((Value*Value*Value*Value*Value*Value*Value) * 0.044642857f) + ((Value*Value*Value*Value*Value*Value*Value*Value*Value) * 0.030381944f));*/ } float aePlatformMath::FastArcTan(const float& Value) { float Result = Value; float f2 = Value*Value; float f1 = Value*f2; Result -= f1 * 0.333333333f; f1 *= f2; Result += f1 * 0.2f; f1 *= f2; Result -= f1 * 0.142857142f; f1 *= f2; return Result += f1 * 0.111111111f; /*return Value - ((Value*Value*Value) *0.333333333f) + (Value*Value*Value*Value*Value*0.2f) - ((Value*Value*Value*Value*Value*Value*Value) *0.142857142f) + (Value*Value*Value*Value*Value*Value*Value*Value*Value*0.111111111f);*/ } float aePlatformMath::FastArcTan2(const float & Y, const float & X) { float r, angle; float abs_y = ((((*(uint32*)&Y) >= (uint32)0x80000000)) ? -Y : Y) + 1e-10f; // kludge to prevent 0/0 condition if (X < 0.0f) { r = (X + abs_y) / (abs_y - X); angle = THREE_QUARTER_PI; } else { r = (X - abs_y) / (X + abs_y); angle = ONE_QUARTER_PI; } angle += (0.1963f * r * r - 0.9817f) * r; if (Y < 0.0f) return(-angle); // negate if in quad III or IV else return(angle); /*if (X == 0.0f) { if (Y > 0.0f) return HALF_PI; return (Y == 0.0f) ? 0.0f : -HALF_PI; } float atan; float z = Y / X; if (/ *Abs(z) < 1.0f* / z < 1.0f && z > -1.0f) { atan = z / (1.0f + 0.28f*z*z); if (X < 0.0f) { return (Y < 0.0f) ? atan - PI : atan + PI; } } else { atan = HALF_PI - z / (z*z + 0.28f); if (Y < 0.0f) return atan - PI; } return atan;*/ } }
#include <bits/stdc++.h> using namespace std; // Cell Class class Cell { private: int x, y; public: Cell(const int &x, const int &y) { this->x = x; this->y = y; } void setCoordinates(const vector<int> &p) { this->x = p[0]; this->y = p[1]; } vector<int> getCoordinates() { return {x, y}; } }; // Game Class class Game { private: int n; char player, opponent; vector<vector<char>> board; const int INF = (int)1e5; public: Game(vector<vector<char>> board, char player, char opponent) { this->n = 3; this->board.resize(n, vector<char>(n, 0)); for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { this->board[i][j] = board[i][j]; } } this->player = player; this->opponent = opponent; } // check if the current player wins/loses/draw. int evaluate() { // check status for rows. for(int i = 0 ; i < n ; ++i) { if(board[i][0] == board[i][1] && board[i][1] == board[i][2]) { if(board[i][0] == player) { return 10; } if(board[i][0] == player) { return -10; } } } // check status for columns. for(int i = 0 ; i < n ; ++i) { if(board[0][i] == board[1][i] && board[1][i] == board[2][i]) { if(board[0][i] == player) { return 10; } if(board[0][i] == player) { return -10; } } } // check for top-left to bottom-right diagonal. if(board[0][0] == board[1][1] && board[1][1] == board[2][2]) { if(board[1][1] == player) { return +10; } else { return -10; } } // check for top-right to bottom-left diagonal. if(board[0][2] == board[1][1] && board[1][1] == board[2][0]) { if(board[1][1] == player) { return +10; } else { return -10; } } // in case of DRAW. return 0; } // check if the board is filled. bool isMovesLeft() { for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { if(board[i][j] == '.') return true; } } return false; } // This will return the best possible move for the player. void miniMaxAlgorithm() { int bestValue = -INF; Cell bestMove(-1, -1); // Traverse all cells, evaluate minimax function for all empty cells. And // return the cell with optimal value. for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { // if cell is empty. if(board[i][j] == '.') { board[i][j] = player; int currValue = minimizer(0, -INF, INF); board[i][j] = '.'; // update best move. if(bestValue < currValue) { bestValue = currValue; bestMove.setCoordinates({i, j}); } } } } vector<int> currCoordinates = bestMove.getCoordinates(); board[currCoordinates[0]][currCoordinates[1]] = player; } int maximizer(int level, int alpha, int beta) { // evaluate score based on current board. int score = evaluate(); // if maximizer has won/lost return evaluated score. if(score == 10 || score == -10) { return score; } // if no moves are left then there is draw return 0 score. if(!isMovesLeft()) { return 0; } int bestScore = -INF; for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { if(board[i][j] == '.') { board[i][j] = player; bestScore = max(bestScore, minimizer(level+1, alpha, beta)-level); alpha = max(bestScore, alpha); board[i][j] = '.'; if(alpha >= beta) { return alpha; } } } } return bestScore; } int minimizer(int level, int alpha, int beta) { // evaluate score based on current board. int score = evaluate(); // if maximizer has won/lost return evaluated score. if(score == 10 || score == -10) { return score; } // if no moves are left then there is draw return 0 score. if(!isMovesLeft()) { return 0; } int bestScore = INF; for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { if(board[i][j] == '.') { board[i][j] = opponent; bestScore = min(bestScore, maximizer(level+1, alpha, beta)+level); beta = min(beta, bestScore); board[i][j] = '.'; if(alpha >= beta) { return beta; } } } } return bestScore; } // print the board. void print() { for(int i = 0 ; i < n ; ++i) { for(int j = 0 ; j < n ; ++j) { cout << board[i][j] << ' '; } cout << '\n'; } } }; int32_t main() { // taking input vector<vector<char>> board(3, vector<char>(3)); for(int i = 0 ; i < 3 ; ++i) { for(int j = 0 ; j < 3 ; ++j) { cin >> board[i][j]; } } char player; cin >> player; char opponent = (player == 'x') ? 'o' : 'x'; // initialize board Game g(board, player, opponent); g.miniMaxAlgorithm(); g.print(); return 0; }
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} int main() { ll X, Y, A, B, C; cin >> X >> Y >> A >> B >> C; vector<ll> p(A); vector<ll> q(B); vector<ll> r(C); rep(i, A) { cin >> p[i]; } rep(i, B) { cin >> q[i]; } rep(i, C) { cin >> r[i]; } sort(p.begin(), p.end(), greater<ll>()); sort(q.begin(), q.end(), greater<ll>()); sort(r.begin(), r.end(), greater<ll>()); vector<ll> pd(p.begin(), p.begin()+X); vector<ll> qd(q.begin(), q.begin()+Y); vector<ll> pqd; rep(i, pd.size()){ pqd.push_back(pd[i]); } rep(i, qd.size()){ pqd.push_back(qd[i]); } sort(pqd.begin(), pqd.end(), greater<ll>()); vector<ll> sum; sum.push_back(0); ll tmp = 0; rep(i, pqd.size()){ tmp += pqd[i]; sum.push_back(tmp); } //cout << pqd.size() << sum.size() <<endl; ll total_max = sum[pqd.size()]; ll r_sum = 0; rep(i, r.size()){ r_sum += r[i]; if (i >= X + Y) break; ll total = r_sum + sum[X + Y - 1 - i]; total_max = max(total_max, total); } cout << total_max << endl; }
// // Created on 05.03.18. // // // Code translated to C++ from the original: https://github.com/eXascaleInfolab/cdrec // #include "CDMissingValueRecovery.h" #include "../Stats/Correlation.h" #include <iostream> namespace Algorithms { CDMissingValueRecovery::CDMissingValueRecovery(arma::mat &src, uint64_t maxIterations, double eps) : matrix(src), cd(src, src.n_cols - 1), k(src.n_cols - 1), cm(src), maxIterations(maxIterations), //defaults are hardcoded in CDMVR.h epsPrecision(eps), missingBlocks(std::vector<MissingBlock>()), disableCaching(false) { } uint64_t CDMissingValueRecovery::getReduction() { return k; } void CDMissingValueRecovery::setReduction(uint64_t k) { this->k = k; cd.truncation = k; } void CDMissingValueRecovery::addMissingBlock(uint64_t col, uint64_t start, uint64_t size) { missingBlocks.emplace_back(MissingBlock(col, start, size, matrix)); } void CDMissingValueRecovery::addMissingBlock(MissingBlock mb) { missingBlocks.emplace_back(mb); } void CDMissingValueRecovery::autoDetectMissingBlocks(double val) { for (uint64_t j = 0; j < matrix.n_cols; ++j) { bool missingBlock = false; uint64_t start = 0; for (uint64_t i = 0; i < matrix.n_rows; ++i) { if ((std::isnan(val) && std::isnan(matrix.at(i, j))) || (!std::isnan(val) && matrix.at(i, j) == val)) { if (!missingBlock) { missingBlock = true; start = i; } } else { if (missingBlock) { //finalize block missingBlock = false; addMissingBlock(j, start, i - start); } } } if (missingBlock) { addMissingBlock(j, start, matrix.n_rows - start); } } } // // Algorithm // void CDMissingValueRecovery::decomposeOnly() { this->cd.performDecomposition(nullptr); } void CDMissingValueRecovery::increment(const std::vector<double> &vec) { cd.increment(vec); if (useNormalization && false) // not implemented { uint64_t lastIdx = matrix.n_rows - 1; const std::vector<double> &mean = cm.getMean(); const std::vector<double> &stddev = cm.getStddev(); for (uint64_t j = 0; j < matrix.n_cols; ++j) { matrix.at(lastIdx, j) = (matrix.at(lastIdx, j) - mean[j]) / stddev[j]; } } } void CDMissingValueRecovery::increment(const arma::vec &vec) { cd.increment(vec); if (useNormalization && false) // not implemented { uint64_t lastIdx = matrix.n_rows - 1; const std::vector<double> &mean = cm.getMean(); const std::vector<double> &stddev = cm.getStddev(); for (uint64_t j = 0; j < matrix.n_cols; ++j) { matrix.at(lastIdx, j) = (matrix.at(lastIdx, j) - mean[j]) / stddev[j]; } } } #define RECOVERY_VERBOSE_ uint64_t CDMissingValueRecovery::performRecovery(bool determineReduction /*= false*/) { uint64_t totalMBSize = 0; for (auto mblock : missingBlocks) { totalMBSize += mblock.blockSize; } interpolate(); uint64_t iter = 0; double delta = 99.0; if (useNormalization) { cm.normalizeMatrix(); } if (determineReduction) { this->determineReduction(); } auto centroidValues = std::vector<double>(); while (++iter <= maxIterations && delta >= epsPrecision) { if (disableCaching) { cd.resetSignVectors(); } this->cd.performDecomposition(&centroidValues); const arma::mat &L = cd.getLoad(); const arma::mat &R = cd.getRel(); arma::mat recover = L * R.t(); delta = 0.0; for (auto mblock : missingBlocks) { for (uint64_t i = mblock.startingIndex; i < mblock.startingIndex + mblock.blockSize; ++i) { double diff = matrix.at(i, mblock.column) - recover.at(i, mblock.column); delta += fabs(diff); matrix.at(i, mblock.column) = recover.at(i, mblock.column); recover.at(i, mblock.column) = 0.0; } } delta = delta / (double)totalMBSize; #ifdef RECOVERY_VERBOSE lastrecon -= recover; delta = arma::norm(lastrecon) / std::sqrt((double)lastrecon.n_rows); lastrecon = recover; std::cout << "delta_" << iter << " =" << delta << std::endl << std::endl; #endif } if (useNormalization) { cm.deNormalizeMatrix(); } lastIterations = iter - 1; std::cout << "recovery performed in " << lastIterations << " iterations " << std::endl; // when the recovery is done, we need to clean up some stuff missingBlocks.clear(); return iter - 1; } void CDMissingValueRecovery::interpolate() { // init missing blocks for (auto mblock : missingBlocks) { // linear interpolation double val1 = NAN, val2 = NAN; if (mblock.startingIndex > 0) { val1 = matrix.at(mblock.startingIndex - 1, mblock.column); } if (mblock.startingIndex + mblock.blockSize < matrix.n_rows) { val2 = matrix.at(mblock.startingIndex + mblock.blockSize, mblock.column); } double step; // fallback case - no 2nd value for interpolation if (std::isnan(val1) && std::isnan(val2)) { val1 = 0.0; step = 0; } else if (std::isnan(val1)) // start block is missing { val1 = val2; step = 0; } else if (std::isnan(val2)) // end block is missing { step = 0; } else { step = (val2 - val1) / (double)(mblock.blockSize + 1); } for (uint64_t i = 0; i < mblock.blockSize; ++i) { matrix.at(mblock.startingIndex + i, mblock.column) = val1 + step * (double)(i + 1); } } } void CDMissingValueRecovery::determineReduction() { // step 1 - do full CD to determine rank std::vector<double> centroidValues = std::vector<double>(); centroidValues.reserve(matrix.n_cols); cd.truncation = matrix.n_cols; cd.performDecomposition(&centroidValues, true); uint64_t rank = centroidValues.size(); double squaresum = 0.0; std::cout << "CValues (rank=" << rank << "): "; for (auto &a : centroidValues) { a /= (double)matrix.n_rows; squaresum += a * a; std::cout << a << " "; } std::cout << std::endl; // step 2 [ALT] - entropy std::vector<double> relContribution = std::vector<double>(); relContribution.reserve(rank); for (auto a : centroidValues) { relContribution.emplace_back(a * a / squaresum); } double entropy = 0.0; for (auto a : relContribution) { entropy += a * std::log(a); } entropy /= -std::log(rank); uint64_t red; double contributionSum = relContribution[0]; for (red = 1; red < rank - 1; ++red) { if (contributionSum >= entropy) { break; } contributionSum += relContribution[red]; } std::cout << "Auto-reduction [entropy] detected as: " << red << " in [1..." << rank - 1 << "]," << std::endl << "with sum(contrib)=" << contributionSum << " entropy=" << entropy << std::endl << std::endl; // cleanup - we will have less dimensions later cd.destroyDecomposition(); setReduction(red); } // simplistic API void CDMissingValueRecovery::RecoverMatrix(arma::mat &matrix, uint64_t k, double eps) { CDMissingValueRecovery rmv(matrix, 100, eps); rmv.setReduction(k); rmv.autoDetectMissingBlocks(); rmv.performRecovery(k == 0); } } // namespace Algorithms
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2007-2016 Hartmut Kaiser // Copyright (c) 2008-2009 Chirag Dekate, Anshul Tandon // Copyright (c) 2012-2013 Thomas Heller // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //////////////////////////////////////////////////////////////////////////////// #pragma once #include <pika/config.hpp> #include <pika/assert.hpp> #include <pika/errors/error_code.hpp> #include <pika/topology/cpu_mask.hpp> #include <cstddef> #include <cstdint> #include <string> #include <vector> namespace pika::detail { enum distribution_type { compact = 0x01, scatter = 0x02, balanced = 0x04, numa_balanced = 0x08 }; using mappings_type = distribution_type; PIKA_EXPORT void parse_mappings( std::string const& spec, mappings_type& mappings, error_code& ec = throws); PIKA_EXPORT void parse_affinity_options(std::string const& spec, std::vector<threads::detail::mask_type>& affinities, std::size_t used_cores, std::size_t max_cores, std::size_t num_threads, std::vector<std::size_t>& num_pus, bool use_process_mask, error_code& ec = throws); } // namespace pika::detail
// // Moto.cpp // Apuntadores // // Created by Daniel on 22/09/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include "Moto.h" std::ostream & operator << (std::ostream & os, Moto & moto){ return os << "Soy una Moto"<<std::endl; } void Moto::Corre(){ std::cout<<"La moto corre\n"; }
/* Pin toggling via interrupts Put a button on PB2 and an LED on PB4 */ #include "avr/interrupt.h" #define LED PB4 void setup() { // set up PB2 to detect falling edges GIMSK |= (1<<6); // INT0 bit MCUCR |= 0b10; // falling edge sei(); // enables interrupts pinMode(LED, OUTPUT); } void loop() { } ISR(INT0_vect) { static volatile int on = false; on = 1 - on; digitalWrite(LED, on); }
#include <cstdio> #define ElementType int #define do_question(func_question) \ printf("%s:\n", #func_question); \ func_question() #define printList(list) \ printf("%s (%d):\n", #list, list.len); \ listPrint(list) struct ListNode { ElementType data; ListNode *next; }; struct LinkList { ListNode *head; int len; }; LinkList newLinkList() { LinkList list; list.len = 0; list.head = new ListNode(); list.head->next = NULL; return list; } LinkList *newNoHeadLinkList() { LinkList *list = new LinkList(); list->len = 0; list->head = NULL; return list; } // insert element to index i (1<=i<=list.len) bool listInsert(LinkList &list, int i, ElementType e) { if (i < 1) return false; ListNode *p = list.head; int k = 0; while (p && k < i - 1) { p = p->next; k++; } if (!p) return false; ListNode *newNode = new ListNode(); newNode->data = e; newNode->next = p->next; p->next = newNode; list.len++; return true; } // remove element at i (1<=i<=list.len) bool listRemoveAt(LinkList &list, int i) { if (i < 1) return false; ListNode *p = list.head; int k = 0; while (p->next && k < i - 1) { p = p->next; k++; } if (!p->next) return false; ListNode *s = p->next; p->next = s->next; delete s; list.len--; return true; } void listAppend(LinkList &list, LinkList list2) { ListNode *p = list.head; while (p->next) { p = p->next; } p->next = list2.head->next; list.len += list2.len; } void listDistinct(LinkList &list) { ListNode *p = list.head->next, *tmp; int cnt = 0; while (p) { if (p->next == NULL) { break; } if (p->data == p->next->data) { tmp = p->next; p->next = tmp->next; delete tmp; cnt++; continue; } p = p->next; } list.len -= cnt; } void mergeOrderList(LinkList &la, LinkList &lb) { ListNode *p1 = la.head->next; ListNode *p2 = lb.head->next; ListNode *last = la.head; while (p1 && p2) { if (p1->data < p2->data) { last->next = p1; last = p1; p1 = p1->next; } else { last->next = p2; last = p2; p2 = p2->next; } } last->next = (p1 == NULL) ? p2 : p1; la.len = la.len + lb.len; delete lb.head; } void listPrint(LinkList list) { ListNode *p = list.head->next; while (p) { printf("%d->", p->data); p = p->next; } printf("NULL\n"); } void noHeadLinkListRemoveAll(ListNode *&node, ElementType data) { // 此处*&node意为指针变量的引用 // 也就是说指针变量的地址可以被修改 // node是上一个节点的next变量 // 将next的地址修改为next->next既 node=node->next // 即可完成删除操作 // if(node==NULL) return; // noHeadLinkListRemoveAll(node->next,data); // ListNode *s = node->next; // if (s&&s->data==data){ // node->next=s->next; // delete s; // } ListNode *p; if (node == NULL) return; if (node->data == data) { p = node; node = node->next; delete p; noHeadLinkListRemoveAll(node, data); } else { noHeadLinkListRemoveAll(node->next, data); } } void listRemoveAll(LinkList &list, ElementType data) { ListNode *p = list.head; ListNode *tmp; int cnt = 0; while (p && p->next) { if (p->next->data == data) { tmp = p->next; p->next = tmp->next; delete tmp; cnt++; } p = p->next; } list.len -= cnt; } void listReverse(LinkList &list) { ListNode *p = list.head->next; ListNode *tmp; list.head->next = NULL; while (p) { tmp = p; p = p->next; tmp->next = list.head->next; list.head->next = tmp; } // way2: // ListNode *tmp,*last=NULL; // while(p){ // tmp=p->next; // p->next=last; // last=p; // p=tmp; // } // list.head->next=last; } void q1() { ListNode *first = new ListNode(); first->data = 2; ListNode *p = first; for (int i = 0; i < 10; i++) { ListNode *newNode = new ListNode(); newNode->data = i % 3; newNode->next = NULL; p->next = newNode; p = newNode; } p = first; noHeadLinkListRemoveAll(p, 0); p = first; while (p) { printf("%d->", p->data); p = p->next; } printf("NULL\n"); } void q2() { LinkList list = newLinkList(); for (int i = 1; i <= 10; i++) { listInsert(list, i, i % 3); } printList(list); listRemoveAll(list, 1); printList(list); } // 反转链表 void q5() { LinkList list = newLinkList(); for (int i = 1; i <= 10; i++) { listInsert(list, i, i); } printList(list); listReverse(list); printList(list); } // 寻找第一个公共元素 void q8() { LinkList list3 = newLinkList(); for (int i = 1; i <= 5; i++) { listInsert(list3, i, 10 + i); } printList(list3); LinkList list1 = newLinkList(); for (int i = 1; i <= 2; i++) { listInsert(list1, i, i); } listAppend(list1, list3); printList(list1); LinkList list2 = newLinkList(); for (int i = 1; i <= 5; i++) { listInsert(list2, i, i * 2); } listAppend(list2, list3); printList(list2); // 寻找第一个相同元素 ListNode *longList = list1.head->next; ListNode *shortList = list2.head->next; int distance = list1.len - list2.len; if (list2.len > list1.len) { longList = list2.head->next; shortList = list1.head->next; distance = -distance; } while (distance--) longList = longList->next; while (longList) { if (longList == shortList) { break; } longList = longList->next; shortList = shortList->next; } if (longList != NULL) { printf("first common element: %p %d\n", longList, longList->data); return; } printf("first common element (none)"); } // 递增输出并删除 void q9() { LinkList list = newLinkList(); for (int i = 1; i <= 5; i++) { listInsert(list, i, i * 2); } printList(list); ListNode *p = list.head, *minpre = list.head; while (list.head->next != NULL) { p = list.head; minpre = list.head; while (p->next) { if (p->next->data < minpre->next->data) { minpre = p; } p = p->next; } if (minpre->next != NULL) { printf("%d ", minpre->next->data); ListNode *tmp = minpre->next; minpre->next = tmp->next; delete tmp; } } printf("\n"); } // 有序去重 void q12() { LinkList list = newLinkList(); for (int i = 1; i <= 10; i++) { listInsert(list, i, i / 3); } printList(list); listDistinct(list); printList(list); } // 合并有序链表 void q13() { LinkList listA = newLinkList(); LinkList listB = newLinkList(); for (int i = 1; i <= 5; i++) { listInsert(listA, i, i * 2 - 1); } for (int i = 1; i <= 3; i++) { listInsert(listB, i, i * 2); } printList(listA); printList(listB); mergeOrderList(listA, listB); printList(listA); } // 求有序链表交集 void q15() { LinkList listA = newLinkList(); LinkList listB = newLinkList(); for (int i = 1; i <= 5; i++) { listInsert(listA, i, i); } for (int i = 1; i <= 7; i++) { listInsert(listB, i, i+3); } //listInsert(listB, 1,); printList(listA); printList(listB); ListNode *pa=listA.head; ListNode *pb=listB.head->next; listA.len=0; while(pa->next&&pb){ if(pa->next->data>pb->data){ pb=pb->next; }else if(pa->next->data<pb->data){ ListNode *tmp=pa->next; pa->next=tmp->next; delete tmp; }else{ pa=pa->next; pb=pb->next; listA.len++; } } if (pb==NULL) { pa->next=NULL; } // free掉A和B printList(listA); } int findLastK(ListNode *list,int k){ ListNode *p1=list->next,*p2=list->next; while(p2&&k>0){ p2=p2->next; k--; } if(k!=0) return 0; while(p2){ p1=p1->next; p2=p2->next; } printf(": %d\n",p1->data); return 1; } // 求倒数第K个元素 void q21(){ LinkList list = newLinkList(); for (int i = 1; i <= 10; i++) { listInsert(list, i, i); } for(int k = 1; k <= 15; k++) { printf("find last %d result %d\n",k,findLastK(list.head,k)); } } int main(int argc, char const *argv[]) { LinkList list = newLinkList(); for (int i = 1; i <= 10; i++) { listInsert(list, i, i * 2); } printList(list); listRemoveAt(list, 10); printList(list); do_question(q1); do_question(q2); do_question(q5); do_question(q8); do_question(q9); do_question(q12); do_question(q13); do_question(q15); do_question(q21); return 0; }
// Created on: 1993-02-19 // Created by: Remi LEQUETTE // Copyright (c) 1993-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepAdaptor_Curve_HeaderFile #define _BRepAdaptor_Curve_HeaderFile #include <Adaptor3d_CurveOnSurface.hxx> #include <gp_Trsf.hxx> #include <GeomAdaptor_Curve.hxx> #include <TopoDS_Edge.hxx> #include <Adaptor3d_Curve.hxx> #include <Standard_Real.hxx> #include <GeomAbs_Shape.hxx> #include <Standard_Integer.hxx> #include <TColStd_Array1OfReal.hxx> #include <GeomAbs_CurveType.hxx> class TopoDS_Face; class Adaptor3d_CurveOnSurface; class gp_Pnt; class gp_Vec; class gp_Lin; class gp_Circ; class gp_Elips; class gp_Hypr; class gp_Parab; class Geom_BezierCurve; class Geom_BSplineCurve; class Geom_OffsetCurve; DEFINE_STANDARD_HANDLE(BRepAdaptor_Curve, Adaptor3d_Curve) //! The Curve from BRepAdaptor allows to use an Edge //! of the BRep topology like a 3D curve. //! //! It has the methods the class Curve from Adaptor3d. //! //! It is created or Initialized with an Edge. It //! takes into account local coordinate systems. If //! the Edge has a 3D curve it is use with priority. //! If the edge has no 3D curve one of the curves on //! surface is used. It is possible to enforce using a //! curve on surface by creating or initialising with //! an Edge and a Face. class BRepAdaptor_Curve : public Adaptor3d_Curve { DEFINE_STANDARD_RTTIEXT(BRepAdaptor_Curve, Adaptor3d_Curve) public: //! Creates an undefined Curve with no Edge loaded. Standard_EXPORT BRepAdaptor_Curve(); //! Creates a Curve to access the geometry of edge //! <E>. Standard_EXPORT BRepAdaptor_Curve(const TopoDS_Edge& E); //! Creates a Curve to access the geometry of edge //! <E>. The geometry will be computed using the //! parametric curve of <E> on the face <F>. An Error //! is raised if the edge does not have a pcurve on //! the face. Standard_EXPORT BRepAdaptor_Curve(const TopoDS_Edge& E, const TopoDS_Face& F); //! Shallow copy of adaptor Standard_EXPORT virtual Handle(Adaptor3d_Curve) ShallowCopy() const Standard_OVERRIDE; //! Reset currently loaded curve (undone Load()). Standard_EXPORT void Reset(); //! Sets the Curve <me> to access the geometry of //! edge <E>. Standard_EXPORT void Initialize (const TopoDS_Edge& E); //! Sets the Curve <me> to access the geometry of //! edge <E>. The geometry will be computed using the //! parametric curve of <E> on the face <F>. An Error //! is raised if the edge does not have a pcurve on //! the face. Standard_EXPORT void Initialize (const TopoDS_Edge& E, const TopoDS_Face& F); //! Returns the coordinate system of the curve. Standard_EXPORT const gp_Trsf& Trsf() const; //! Returns True if the edge geometry is computed from //! a 3D curve. Standard_EXPORT Standard_Boolean Is3DCurve() const; //! Returns True if the edge geometry is computed from //! a pcurve on a surface. Standard_EXPORT Standard_Boolean IsCurveOnSurface() const; //! Returns the Curve of the edge. Standard_EXPORT const GeomAdaptor_Curve& Curve() const; //! Returns the CurveOnSurface of the edge. Standard_EXPORT const Adaptor3d_CurveOnSurface& CurveOnSurface() const; //! Returns the edge. Standard_EXPORT const TopoDS_Edge& Edge() const; //! Returns the edge tolerance. Standard_EXPORT Standard_Real Tolerance() const; Standard_EXPORT Standard_Real FirstParameter() const Standard_OVERRIDE; Standard_EXPORT Standard_Real LastParameter() const Standard_OVERRIDE; Standard_EXPORT GeomAbs_Shape Continuity() const Standard_OVERRIDE; //! Returns the number of intervals for continuity //! <S>. May be one if Continuity(me) >= <S> Standard_EXPORT Standard_Integer NbIntervals (const GeomAbs_Shape S) const Standard_OVERRIDE; //! Stores in <T> the parameters bounding the intervals //! of continuity <S>. //! //! The array must provide enough room to accommodate //! for the parameters. i.e. T.Length() > NbIntervals() Standard_EXPORT void Intervals (TColStd_Array1OfReal& T, const GeomAbs_Shape S) const Standard_OVERRIDE; //! Returns a curve equivalent of <me> between //! parameters <First> and <Last>. <Tol> is used to //! test for 3d points confusion. //! If <First> >= <Last> Standard_EXPORT Handle(Adaptor3d_Curve) Trim (const Standard_Real First, const Standard_Real Last, const Standard_Real Tol) const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsClosed() const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsPeriodic() const Standard_OVERRIDE; Standard_EXPORT Standard_Real Period() const Standard_OVERRIDE; //! Computes the point of parameter U on the curve Standard_EXPORT gp_Pnt Value (const Standard_Real U) const Standard_OVERRIDE; //! Computes the point of parameter U. Standard_EXPORT void D0 (const Standard_Real U, gp_Pnt& P) const Standard_OVERRIDE; //! Computes the point of parameter U on the curve //! with its first derivative. //! Raised if the continuity of the current interval //! is not C1. Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt& P, gp_Vec& V) const Standard_OVERRIDE; //! Returns the point P of parameter U, the first and second //! derivatives V1 and V2. //! Raised if the continuity of the current interval //! is not C2. Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2) const Standard_OVERRIDE; //! Returns the point P of parameter U, the first, the second //! and the third derivative. //! Raised if the continuity of the current interval //! is not C3. Standard_EXPORT void D3 (const Standard_Real U, gp_Pnt& P, gp_Vec& V1, gp_Vec& V2, gp_Vec& V3) const Standard_OVERRIDE; //! The returned vector gives the value of the derivative for the //! order of derivation N. //! Raised if the continuity of the current interval //! is not CN. //! Raised if N < 1. Standard_EXPORT gp_Vec DN (const Standard_Real U, const Standard_Integer N) const Standard_OVERRIDE; //! returns the parametric resolution Standard_EXPORT Standard_Real Resolution (const Standard_Real R3d) const Standard_OVERRIDE; Standard_EXPORT GeomAbs_CurveType GetType() const Standard_OVERRIDE; Standard_EXPORT gp_Lin Line() const Standard_OVERRIDE; Standard_EXPORT gp_Circ Circle() const Standard_OVERRIDE; Standard_EXPORT gp_Elips Ellipse() const Standard_OVERRIDE; Standard_EXPORT gp_Hypr Hyperbola() const Standard_OVERRIDE; Standard_EXPORT gp_Parab Parabola() const Standard_OVERRIDE; Standard_EXPORT Standard_Integer Degree() const Standard_OVERRIDE; Standard_EXPORT Standard_Boolean IsRational() const Standard_OVERRIDE; Standard_EXPORT Standard_Integer NbPoles() const Standard_OVERRIDE; Standard_EXPORT Standard_Integer NbKnots() const Standard_OVERRIDE; //! Warning: //! This will make a copy of the Bezier Curve since it applies to it myTsrf. //! Be careful when using this method. Standard_EXPORT Handle(Geom_BezierCurve) Bezier() const Standard_OVERRIDE; //! Warning: //! This will make a copy of the BSpline Curve since it applies to it myTsrf. //! Be careful when using this method. Standard_EXPORT Handle(Geom_BSplineCurve) BSpline() const Standard_OVERRIDE; Standard_EXPORT Handle(Geom_OffsetCurve) OffsetCurve() const Standard_OVERRIDE; private: gp_Trsf myTrsf; GeomAdaptor_Curve myCurve; Handle(Adaptor3d_CurveOnSurface) myConSurf; TopoDS_Edge myEdge; }; #endif // _BRepAdaptor_Curve_HeaderFile
#pragma once #include <Windows.h> #include <time.h> #include <string> //HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam void OnClose(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); void OnCreate(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); void OnKeyDown(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); void CALLBACK TimerProc_move(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime); void CALLBACK TimerProc_show(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime); void DrawTable(HWND); void ShowFood(HWND hWnd, struct food *f);
#include "Passenger.h" Passenger::Passenger(int _arrive, int _board, int _luggage, int _security, string _vip, string _online){ this->arrive = _arrive; this->board = _board; this->luggage = _luggage; this->security = _security; this->vip = _vip; this->online = _online; this->lastTime = _arrive; } Passenger::Passenger(const Passenger& passenger){ this->arrive = passenger.arrive; this->board = passenger.board; this->luggage = passenger.luggage; this->security = passenger.security; this->vip = passenger.vip; this->online = passenger.online; this->lastTime = passenger.lastTime; } Passenger& Passenger::operator=(const Passenger& passenger){ this->arrive = passenger.arrive; this->board = passenger.board; this->luggage = passenger.luggage; this->security = passenger.security; this->vip = passenger.vip; this->online = passenger.online; this->lastTime = passenger.lastTime; return *this; }