blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7a3e3e372484fd4a5fb5e673854c0aac602ce59b | 6fe9140244dae1db54abe5bf0ed2026748948803 | /4_course/2_week_suffix_arrays/4_suffix_array/main.cpp | dab5ff3563cd8354da7eceda12af0b18db60019d | [
"Unlicense"
] | permissive | chom125/Algorithms-UCSanDiego | f4c93aab1950a29e50dc39e50b45e976cf613a84 | 09d433a1cbc00dc8d913ece8716ac539b81340cd | refs/heads/master | 2022-11-18T20:06:54.829653 | 2020-07-04T21:48:15 | 2020-07-04T21:48:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | cpp | main.cpp | /**
*
* C++ implementation of Burrows Wheeler Transform to trivially create a Suffix Array in O(N^2) time
*
* (c) Copyright 2019 Clayton J. Wong ( http://www.claytonjwong.com )
*
**/
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
//#define OUTPUT_CYCLIC_ROTATIONS__THE_BURROWS_WHEELER_TRANSFORM_MATRIX
//#define OUTPUT_BURROWS_WHEELER_TRANSFORM
#define OUTPUT_SUFFIX_ARRAY_INDEXES
using namespace std;
using Strings = vector< string >;
using Indexes = vector< size_t >;
int main() {
Strings S;
string text; cin >> text;
const auto N = text.size();
for( auto i{ 0 }; i < N; ++i ){
rotate( text.begin(), text.begin()+1, text.end() );
S.push_back( text );
}
sort( S.begin(), S.end() );
#ifdef OUTPUT_CYCLIC_ROTATIONS__THE_BURROWS_WHEELER_TRANSFORM_MATRIX
copy( S.begin(), S.end(), ostream_iterator< string >( cout, "\n" ) );
#endif
#ifdef OUTPUT_BURROWS_WHEELER_TRANSFORM
Strings T( N );
transform( S.begin(), S.end(), T.begin(), []( const auto& str ){ return str.back(); });
ostringstream os; copy( T.begin(), T.end(), ostream_iterator< string >( os, "" ) );
cout << endl << os.str() << endl;
#endif
#ifdef OUTPUT_SUFFIX_ARRAY_INDEXES
Indexes I( N );
transform( S.begin(), S.end(), I.begin(),
[]( const auto& line ){ return line.size() - line.find( '$' ) - 1; }); // -1 for 0-based indexing
copy( I.begin(), I.end(), ostream_iterator< int >( cout, " " ) );
#endif
return 0;
}
|
6858c7063f0bf45aa857defd1162313c4d408c0d | 02d7168b4d4b93e97cb0fa7cf98da42515e9f0a6 | /6 高级IO/relayer/main.cpp | 02a31ee4cf228cb0dfa5e45cbd685f7fae43a29e | [] | no_license | acptek/APUE-NOTE | 82ea4868d976dd27adb3af08d1d8d05b1d0d4d62 | a00b59574d4302438f1be4d93983810d560f98c9 | refs/heads/master | 2022-11-20T22:32:16.525271 | 2020-07-30T13:20:11 | 2020-07-30T13:20:11 | 278,355,275 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,165 | cpp | main.cpp | #include <bits/stdc++.h>
#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include "relayer.h"
#define TTY1 "/dev/tty11"
#define TTY2 "/dev/tty12"
#define TTY3 "/dev/tty10"
#define TTY4 "/dev/tty9"
int main() {
int fd1, fd2;
fd1 = open(TTY1, O_RDWR);
if(fd1 < 0){
perror("open()");
exit(1);
}
write(fd1, "TTY1\n", 5);
fd2 = open(TTY2, O_RDWR|O_NONBLOCK);
if(fd1 < 0) {
perror("open()");
exit(1);
}
write(fd2, "TTY2\n", 5);
int job1 = rel_addjob(fd1, fd2);
if(job1 < 0){
fprintf(stderr, "rel_addjob:%s\n", strerror(-job1));
exit(1);
}
int fd3 = open(TTY3, O_RDWR);
if(fd3 < 0){
perror("open()");
exit(1);
}
write(fd3, "TTY3\n", 5);
int fd4 = open(TTY4, O_RDWR);
if(fd4 < 0){
perror("open()");
exit(1);
}
write(fd4, "TTY4\n", 5);
int job2 = rel_addjob(fd3, fd4);
if(job2 < 0){
fprintf(stderr, "rel_addjob:%s\n", strerror(-job2));
exit(1);
}
while (1){
pause();
}
close(fd1);
close(fd2);
close(fd3);
close(fd4);
return 0;
}
|
bc7e9007ddcbcf55b4afa1cf6cb505c194619b82 | 875316d92f1cf2c63b30b9d310825ceb9e564e36 | /src/main.cpp | 44dde78cc888bb07b025394914dfebec8afa6c41 | [] | no_license | anasmatic/CarND-Term2-project4-PID-Control | bddb52b6babcc869c79f7edf0e6f69e5c0765157 | f366bd20fd59120c34d398f40193555d8827f86c | refs/heads/master | 2021-09-22T08:56:19.893741 | 2018-09-06T17:27:09 | 2018-09-06T17:27:09 | 111,207,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,197 | cpp | main.cpp | #include <uWS/uWS.h>
#include <iostream>
#include "json.hpp"
#include "PID.h"
#include <math.h>
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
double kp = 0.12, ki = 0, kd = 3;//manually tuned parameters, will be used on initial state
double p[] = { 0.12,0,3 };
double pd[] = { 1,0,15 };
double throttle = 0.4;
int count = 0;
double tolerance = 0.1;
int n = 5; //steps to publish next new error in twiddle
int i = 0;//iterate over p and/or pd param
void next_i() {
i++;
if (i == 3)i = 0;//out of index, reset to 0
if (i == 1) i = 2;//skip ki
}
bool isUsingTwiddle = true;//default
bool flag_to_1st_step = true;//flag to twiddle first step
bool flag_to_else = false;//flag to 2nd stage in twiddle second step
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
std::string hasData(std::string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_last_of("]");
if (found_null != std::string::npos) {
return "";
}
else if (b1 != std::string::npos && b2 != std::string::npos) {
return s.substr(b1, b2 - b1 + 1);
}
return "";
}
int main(int argc, char *argv[])
{
uWS::Hub h;
PID pid;
// TODO: Initialize the pid variable.
//by experment,
//the more Kp , the more car swings after turn, wee, wee, wee, wee !
// but the least, the less the car will turn on prober time
//for testing
double err = 0;
double best_err = 1000;
if (argc > 1) {
for (int i = 1; i < argc; i++) {
//int i = 1;
if (strcmp(argv[i],"t") == 0) {
std::cout << "set t" << std::endl;
i++;tolerance = atof(argv[i]);
}
if (strcmp(argv[i],"n") == 0) {
isUsingTwiddle = true;
std::cout << "set n" << std::endl;
i++;n = atoi(argv[i]);
}
if (strcmp(argv[i],"p") == 0) {
std::cout << "set p" << std::endl;
i++;p[0] = atof(argv[i]);
i++; p[1] = atof(argv[i]);
i++; p[2] = atof(argv[i]);
}
if (strcmp(argv[i],"d") == 0) {
std::cout << "set d" << std::endl;
i++; pd[0] = atof(argv[i]);
i++; pd[1] = atof(argv[i]);
i++; pd[2] = atof(argv[i]);
}
if (strcmp(argv[i],"x") == 0) {
i++; kp = atof(argv[1]);
i++; ki = atof(argv[2]);
i++; kd = atof(argv[3]);
}
if (strcmp(argv[i], "s") == 0) {
std::cout << "set s" << std::endl;
i++; throttle = atof(argv[i]);
}
}
}
std::cout << "n:" << n << std::endl;
std::cout << "speed:" << throttle << std::endl;
std::cout << "tolerance:" << tolerance << std::endl;
std::cout << "p:" << p[0] << ", " << p[1] << ", " << p[2] << std::endl;
std::cout << "pd:" << pd[0] << ", " << pd[1] << ", " << pd[2] << std::endl;
std::cout << "kp:" << kp << ", ki:" << ki<< ", kd:" << kd << std::endl;
//pid.Init(0.15, 0, -3.0);
pid.Init(kp, ki, kd);
h.onMessage([&pid, &err, &best_err](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2')
{
auto s = hasData(std::string(data).substr(0, length));
if (s != "") {
auto j = json::parse(s);
std::string event = j[0].get<std::string>();
if (event == "telemetry") {
// j[1] is the data JSON object
double cte = std::stod(j[1]["cte"].get<std::string>());
double speed = std::stod(j[1]["speed"].get<std::string>());
double angle = std::stod(j[1]["steering_angle"].get<std::string>());
double steer_value;
pid.UpdateError(cte);
steer_value = pid.TotalError();
if (isUsingTwiddle) {
double sum_pd = pd[0] + pd[1] + pd[2];
if (sum_pd > tolerance)//if true we keep doing the twiddle ~(1)
{
count++;
err += (cte*cte) / count; //keep error total error updated
//initial step, upon car engien start
if (count == n) {//do this step if only #n step has passed
best_err = err;//save it as initial best_error
err = 1000;//reset new_error
}
//now we twiddle until sum_pd > tolerance
else if (count > n && count % n == 0) {//do this step if only #n step has passed
//******** this is the first step of twiddle *********
//it has flag_to_1st_step ,
//this flag is true by default, and true after every loop is done
if (flag_to_1st_step) {
p[i] += pd[i];//change params
flag_to_1st_step = false;//set false to skip if param index didn't change
}//else loop anothe #n and check again
else {
//******** this is the second step of twiddle *********
//this step starts with check and pd edit, then after #n loops in contine to else lines
if (!flag_to_else && err < best_err) {//
best_err = err;
pd[i] *= 1.1;
next_i();//now lets check next param. and "continue" next loop iteration
flag_to_1st_step = true;
}
else {//this is 2nd stage of twiddle 2nd step,
//stage 2 starts with a reset to p , then loop #n steps
if (flag_to_else == false) {
p[i] -= 2 * pd[i];
flag_to_else = true;//means next time skip here ang go directly to elseif
//then loop another #n, then check again, but remember to start from elseif next time
}
// after #n loops check again
else if (flag_to_else) {
if (err < best_err) {
best_err = err;
pd[i] *= 1.1;
}
else {
p[i] += pd[i];
pd[i] *= 0.9;
}
flag_to_else = false;//rest the flag, we are done with else
next_i();//now lets check next param
flag_to_1st_step = true;
}
}
}
// std::cout << " 2 - best_err:" << best_err << " vs err:" << err << std::endl;
// std::cout << " new " << p[0] << "," << p[1] << "," << p[2] << std::endl;
// std::cout << "______________ sum dp" << sum_pd << std::endl;
count = n;//reset count , not to 0 , but to #n
err = 0;//reset new_error
}//end else if
pid.Init(p[0], p[1], p[2]);//then update the kp ki kd params
}//else just update stearing using the same Kp Ki Kd, we should be stable now with good error
else {
isUsingTwiddle = false;
std::cout << "_______ Twiddle Stopped" << p[0] << "," << p[1] << "," << p[2] << std::endl;
}
}
std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl;
json msgJson;
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = throttle;//0.3;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
//std::cout << msg << std::endl;
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
}
else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
|
218e2a24f2c8dc97ad7dbf21812f4c4369876390 | d49ae2df9af2b69024070858ff7d251702ad0a2e | /SkillEditor/EffectCommonWindow.h | 83103364f9b3b0c0a6c2185f53ec8c03cccf3a98 | [] | no_license | xiaoxiaoyi/DataEditor | 4a9701a01e012a53585a22df7c140ca1a40d46da | bbf0f4bb94f826e2acce4da4ef569613be96625d | refs/heads/master | 2021-01-21T16:00:29.948354 | 2013-08-11T14:16:00 | 2013-08-11T14:16:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 574 | h | EffectCommonWindow.h | #pragma once
#include "ToolDef.h"
USE_NS_AC
// EffectCommonWindow 对话框
class EffectCommonWindow : public CDialog
{
DECLARE_DYNAMIC(EffectCommonWindow)
public:
EffectCommonWindow(CWnd* pParent = NULL); // 标准构造函数
virtual ~EffectCommonWindow();
// 对话框数据
enum { IDD = IDD_DIALOG_EFFECTCOMMON };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
public:
void OnLoadFromDB(MapCNameToValueT& mapValues);
void OnSaveToDB(MapCNameToValueT& mapValues);
};
|
d77b2ce56df8b20f7737d556f9f6f9d7c726ff62 | c7ad1dd84604e275ebfc5a7e354b23ceb598fca5 | /include/objects/trackmgr/displaytrack_client.hpp | 6b144d8cf59202a1afb3af8bfa6e34991ccb378c | [] | no_license | svn2github/ncbi_tk | fc8cfcb75dfd79840e420162a8ae867826a3d922 | c9580988f9e5f7c770316163adbec8b7a40f89ca | refs/heads/master | 2023-09-03T12:30:52.531638 | 2017-05-15T14:17:27 | 2017-05-15T14:17:27 | 60,197,012 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,844 | hpp | displaytrack_client.hpp | #ifndef OBJECTS_TRACKMGR_GRIDCLI__DISPLAY_TRACK_CLIENT_HPP
#define OBJECTS_TRACKMGR_GRIDCLI__DISPLAY_TRACK_CLIENT_HPP
/* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Peter Meric
*
* File Description: NetSchedule grid client for TrackManager display-track request/reply
*
*/
/// @file tmgr_displaytrack_client.hpp
/// NetSchedule grid client for TrackManager display-track request/reply
#include <objects/trackmgr/gridrpcclient.hpp>
#include <connect/ncbi_http_session.hpp>
#include <serial/rpcbase.hpp>
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(objects)
class CTMgr_DisplayTrackRequest;
class CTMgr_DisplayTrackReply;
END_SCOPE(objects)
class CTMS_DisplayTrack_Client : private CGridRPCBaseClient<CAsnBinCompressed>
{
private:
using TBaseClient = CGridRPCBaseClient<ncbi::CAsnBinCompressed>;
struct HttpService
{
explicit HttpService(const string& svc)
: service(svc)
{
}
string service;
};
public:
using TRequest = objects::CTMgr_DisplayTrackRequest;
using TReply = objects::CTMgr_DisplayTrackReply;
using TRequestCRef = CConstRef<TRequest>;
using TReplyRef = CRef<TReply>;
public:
CTMS_DisplayTrack_Client(const string& NS_service,
const string& NS_queue,
const string& client_name,
const string& NC_registry_section
);
CTMS_DisplayTrack_Client(const string& NS_registry_section = "netschedule_api",
const string& NC_registry_section = kEmptyStr
);
CTMS_DisplayTrack_Client(CTMS_DisplayTrack_Client&& c)
: TBaseClient(move(c)),
m_Http_svc(move(c.m_Http_svc)),
m_Http_session(move(c.m_Http_session)),
m_Rpc_client(move(c.m_Rpc_client))
{
}
virtual ~CTMS_DisplayTrack_Client() = default;
static CTMS_DisplayTrack_Client CreateServiceClient(const string& http_svc = "TMS_DisplayTracks");
TReplyRef Fetch(const TRequest& request) const;
bool FetchRawStream(CNcbiIstream& requeststr, CNcbiOstream& replystr) const;
protected:
CTMS_DisplayTrack_Client(CTMS_DisplayTrack_Client&) = delete;
CTMS_DisplayTrack_Client(const HttpService&& http_svc);
TReplyRef x_HttpFetch(const TRequest& request) const;
protected:
CUrl m_Http_svc;
mutable CRef<CHttpSession> m_Http_session;
using TRPCBaseClient = CGridRPCHttpClient<TRequest, TReply>;
mutable CRef<TRPCBaseClient> m_Rpc_client;
};
END_NCBI_SCOPE
#endif // OBJECTS_TRACKMGR_GRIDCLI__DISPLAY_TRACK_CLIENT_HPP
|
3e5bb7c22de331f7ab9346557c253c4e44559ba3 | 7feafc361420ba68c0df24840e62d18ccfdf11ef | /programing fun/(B)c++ file practice(Bengali Book)/use of setf-function(HP)(PAGE-316).cpp | e207d57fdb1913651bd712c8e901d660a2977db7 | [] | no_license | omarKaushru/Numb-UV-Life-activites | b7e94645c9bbc52317fcb80cd6c83e95793fcefb | 63a74e875edee6dc5cfe77439247172da009f2c5 | refs/heads/master | 2022-12-05T11:34:12.142216 | 2020-09-01T18:19:41 | 2020-09-01T18:19:41 | 292,070,016 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 604 | cpp | use of setf-function(HP)(PAGE-316).cpp | #include<iostream>
#include<conio.h>
using namespace std;
int main(){
double number;
cout<<"Enter number";
cin>>number;
cout<<"default output of input number is :"<<number<<endl;
cout.setf(ios::showpoint|ios::showpos);
cout<<"After setting showpoint and showpos :"<<number<<endl;
cout.unsetf(ios::showpoint);
cout<<"After clearing showpoint :"<<number<<endl;
cout.setf(ios::hex|ios::showbase);
cout<<"Number in Hexa "<<number<<endl;
//cout<<"Number in Octal "<<oct<<number<<endl;
//cout<<"Number in Decimal "<<dec<<number;
getch();
}
|
8eb52cb5a9a0867a3d45afa49830bdd5dfbcbece | f6244209f8ecff355822843f64d6368281266143 | /167.h | 9261376d7d5cbf08898d1f09d71a4c373cc9ee67 | [] | no_license | seesealonely/old-leetcode | 5711fc0d583ca15c14cb8fb3a241e860e6d6fcd4 | 28e4bc6e28ba8c36e90a05a6214c7c716fe03431 | refs/heads/master | 2022-04-26T10:18:43.770677 | 2020-04-28T21:20:35 | 2020-04-28T21:20:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 588 | h | 167.h | #include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int>& numbers, int target) {
for(int begin=0;begin<numbers.size()-1;begin++)
{
int subbegin=begin+1,subend=numbers.size()-1,minus=target-numbers[begin],mid;
while(subbegin<=subend)
{
mid=(subbegin+subend)/2;
if(numbers[mid]>minus) subend=mid-1;
else if(numbers[mid]<minus) subbegin=mid+1;
else
{
vector<int> res;
res.push_back(begin+1);
res.push_back(mid+1);
return res;
}
}
}
return {};
}
};
|
02e1a1cc41069083ccfcbb9f23d9a7560a298ae8 | 18ee6ed195e5b94dbb3bf04aec5a5d76c37bb385 | /C:C++/C++/Projects/1.ShapeClock/Rectangle.cpp | a195c7a03bec546d8e6e7b07e12a9720117081ec | [] | no_license | brycexu/UndergraduateProjects | b4a092a74b9b97d07e4e36785d5b69f48882a071 | 9ef1dc8de251b02497aa35691c2879169571ef9e | refs/heads/master | 2022-12-21T20:49:08.047921 | 2019-06-13T07:42:58 | 2019-06-13T07:42:58 | 168,340,769 | 0 | 1 | null | 2022-12-16T06:56:44 | 2019-01-30T12:39:50 | Jupyter Notebook | UTF-8 | C++ | false | false | 308 | cpp | Rectangle.cpp | #include "Rectangle.h"
#include"acllib.h"
Rectangle::Rectangle(int x, int y, int width, int height):CShape(x,y,width,height)
{
}
Rectangle::~Rectangle()
{
}
void Rectangle::DrawShape()
{
setPenColor(BLACK);
setPenWidth(2);
setBrushColor(WHITE);
rectangle(x, y,x+ width,y+ height);
} |
330071f3c2fabd0bd1ac275935c0b2742cd2139b | 50eb6a64e33cd5a561b85acc94614334ac4aec66 | /CatalanitzadorPerAlWindows/Applications/MSOffice.cpp | ecd594880e60a62e5c775586d60c7ac67ec48045 | [] | no_license | Softcatala/Catalanitzador | 4024fc98b85047e4fefc2123ac98b53fcf3774e1 | 9466d699f6b25c45d16331057f8b454dcc2ae812 | refs/heads/master | 2021-12-23T06:19:34.760551 | 2021-12-11T14:43:06 | 2021-12-11T14:43:06 | 2,496,055 | 11 | 1 | null | 2020-06-24T10:31:54 | 2011-10-01T18:44:34 | C++ | ISO-8859-10 | C++ | false | false | 19,426 | cpp | MSOffice.cpp | /*
* Copyright (C) 2014-2018 Jordi Mas i Hernāndez <jmas@softcatala.org>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*/
#include "stdafx.h"
#include "MSOffice.h"
#include "ConfigureLocaleAction.h"
#include "Runner.h"
#include "ConfigurationInstance.h"
#include "LogExtractor.h"
#include <algorithm>
#include <map>
using namespace std;
#define TIMER_ID 2016
static map <int, MSOffice*> s_timersIDsToObjs;
#define CATALAN_LCID L"1027" // 0x403
#define VALENCIAN_LCID L"2051" // 0x803
#define CATALAN_PRIMARY_LCID 0x03
#define OFFICE2016_LAP_LANG L"ca-ES"
#define OFFICE2016_LAPKEY L"SOFTWARE\\Microsoft\\Office\\16.0\\Common\\LanguageResources"
MSOffice::RegKeyVersion MSOffice::RegKeys2003 =
{
L"11.0",
L"SOFTWARE\\Microsoft\\Office\\11.0\\Common\\LanguageResources\\ParentFallback",
true
};
MSOffice::RegKeyVersion MSOffice::RegKeys2007 =
{
L"12.0",
L"SOFTWARE\\Microsoft\\Office\\12.0\\Common\\LanguageResources\\InstalledUIs",
false
};
MSOffice::RegKeyVersion MSOffice::RegKeys2010 =
{
L"14.0",
L"SOFTWARE\\Microsoft\\Office\\14.0\\Common\\LanguageResources\\InstalledUIs",
false
};
MSOffice::RegKeyVersion MSOffice::RegKeys2013 =
{
L"15.0",
L"SOFTWARE\\Microsoft\\Office\\15.0\\Common\\LanguageResources\\InstalledUIs",
false
};
MSOffice::RegKeyVersion MSOffice::RegKeys2016 =
{
L"16.0",
L"SOFTWARE\\Microsoft\\Office\\16.0\\Common\\LanguageResources\\InstalledUIs",
false
};
MSOffice::MSOffice(IOSVersion* OSVersion, IRegistry* registry, IWin32I18N* win32I18N, IRunner* runner, MSOfficeVersion version)
{
m_registry = registry;
m_OSVersion = OSVersion;
m_runner = runner;
m_win32I18N = win32I18N;
m_MSVersion = version;
m_dialectalVariant = false;
m_szFullFilename[0] = NULL;
m_szTempPath2003[0] = NULL;
m_szFilename[0] = NULL;
GetTempPath(MAX_PATH, m_szTempPath);
m_nTimerID = 0;
}
MSOffice::~MSOffice()
{
if (m_szFullFilename[0] != NULL && GetFileAttributes(m_szFullFilename) != INVALID_FILE_ATTRIBUTES)
{
DeleteFile(m_szFullFilename);
}
if (m_msiexecLog.empty() == false && GetFileAttributes(m_msiexecLog.c_str()) != INVALID_FILE_ATTRIBUTES)
{
DeleteFile(m_msiexecLog.c_str());
}
_removeOffice2003TempFiles();
_stopTimer();
}
const wchar_t* MSOffice::GetVersion()
{
switch (m_MSVersion)
{
case MSOffice2003:
return L"2003";
case MSOffice2007:
return L"2007";
case MSOffice2010:
return L"2010";
case MSOffice2010_64:
return L"2010_64bits";
case MSOffice2013:
return L"2013";
case MSOffice2013_64:
return L"2013_64bits";
case MSOffice2016:
return L"2016";
case MSOffice2016_64:
return L"2016_64bits";
default:
return L"";
}
}
// This deletes the contents of the extracted CAB file for MS Office 2003
void MSOffice::_removeOffice2003TempFiles()
{
if (m_MSVersion != MSOffice2003 || m_szTempPath2003[0] == NULL)
return;
wchar_t szFile[MAX_PATH];
wchar_t* files[] = {L"DW20.ADM_1027", L"DWINTL20.DLL_0001_1027", L"LIP.MSI",
L"lip.xml", L"OSE.EXE", L"SETUP.CHM_1027", L"SETUP.EXE", L"SETUP.INI", L"lip1027.cab",
NULL};
for(int i = 0; files[i] != NULL; i++)
{
wcscpy_s(szFile, m_szTempPath2003);
wcscat_s(szFile, L"\\");
wcscat_s(szFile, files[i]);
if (DeleteFile(szFile) == FALSE)
{
g_log.Log(L"MSOffice::_removeOffice2003TempFiles. Cannot delete '%s'", (wchar_t *) szFile);
}
}
RemoveDirectory(m_szTempPath2003);
}
bool MSOffice::_isOffice2016LangAccessoryPackInstalled()
{
if (m_MSVersion != MSOffice2016_64 && m_MSVersion != MSOffice2016)
{
return false;
}
wstring location;
_getSHGetFolderPath(location);
location += L"\\Microsoft Office\\root\\Office16\\1027\\WWINTL.DLL";
bool bFound = GetFileAttributes(location.c_str()) != INVALID_FILE_ATTRIBUTES;
g_log.Log(L"MSOffice::_isOffice2016LangAccessoryPackInstalled. Found: %u", (wchar_t *) bFound);
return bFound;
}
void MSOffice::_getSHGetFolderPath(wstring& folder)
{
wchar_t szProgFolder[MAX_PATH];
if (m_MSVersion == MSOffice2016_64)
{
// Due to WOW all calls always report the "Program Files (x86)" path. Need to look to this environment variable
ExpandEnvironmentStrings(L"%ProgramW6432%", szProgFolder, ARRAYSIZE(szProgFolder));
}
else
{
SHGetFolderPath(NULL, CSIDL_PROGRAM_FILES|CSIDL_FLAG_CREATE, NULL, 0, szProgFolder);
}
folder = szProgFolder;
}
bool MSOffice::IsLangPackInstalled()
{
bool isInstalled = false;
RegKeyVersion regkeys = _getRegKeys();
bool b64bits = (m_MSVersion == MSOffice2010_64 || m_MSVersion == MSOffice2013_64 || m_MSVersion == MSOffice2016_64);
if (_isOffice2016LangAccessoryPackInstalled())
{
g_log.Log(L"MSOffice::IsLangPackInstalled(Accessory) (%s) 64 bits %u, installed 1", (wchar_t *) GetVersion(),
(wchar_t*) b64bits);
return true;
}
if (b64bits ? m_registry->OpenKeyNoWOWRedirect(HKEY_LOCAL_MACHINE, regkeys.InstalledLangMapKey, false) :
m_registry->OpenKey(HKEY_LOCAL_MACHINE, regkeys.InstalledLangMapKey, false))
{
m_installedLangPackCode.empty();
if (regkeys.InstalledLangMapKeyIsDWord)
{
DWORD dwValue;
if (m_registry->GetDWORD(CATALAN_LCID, &dwValue))
{
m_installedLangPackCode = CATALAN_LCID;
}
else
{
if (m_registry->GetDWORD(VALENCIAN_LCID, &dwValue))
{
m_installedLangPackCode = VALENCIAN_LCID;
}
}
}
else
{
wchar_t szValue[1024];
if (m_registry->GetString(CATALAN_LCID, szValue, sizeof (szValue)))
{
if (wcslen (szValue) > 0)
{
m_installedLangPackCode = CATALAN_LCID;
}
}
if (m_registry->GetString(VALENCIAN_LCID, szValue, sizeof (szValue)))
{
if (wcslen (szValue) > 0)
{
m_installedLangPackCode = VALENCIAN_LCID;
}
}
}
if (m_installedLangPackCode.size() > 0)
isInstalled = true;
m_registry->Close();
}
g_log.Log(L"MSOffice::IsLangPackInstalled (%s) 64 bits %u, installed %u", (wchar_t *) GetVersion(),
(wchar_t*) b64bits, (wchar_t *)isInstalled);
return isInstalled;
}
#define UNDEFINED_LCID -1
void MSOffice::_readDefaultLanguageForOffice2016LangAccessoryPack(bool& isCatalanSetAsDefaultLanguage, bool& followSystemUIOff)
{
isCatalanSetAsDefaultLanguage = false;
followSystemUIOff = false;
if (m_registry->OpenKey(HKEY_CURRENT_USER, OFFICE2016_LAPKEY, false))
{
wstring value;
wchar_t szValue[2048] = L"";
if (m_registry->GetString(L"UILanguageTag", szValue, sizeof(szValue)))
{
value = szValue;
std::transform(value.begin(), value.end(), value.begin(), ::tolower);
isCatalanSetAsDefaultLanguage = (value.compare(L"ca-es") == 0 || value.compare(L"ca-es-valencia") == 0);
g_log.Log(L"MSOffice::_readDefaultLanguageForOffice2016LangAccessoryPack. UILanguageTag: %s, default %u", (wchar_t* )szValue, (wchar_t* )isCatalanSetAsDefaultLanguage);
}
// If FollowSystemUI is true Office uses Windows's language pack language to decide which language to use
DWORD follow = -1;
if (m_registry->GetDWORD(L"FollowSystemUILanguage", &follow))
{
if (follow == 0)
{
followSystemUIOff = true;
}
}
m_registry->Close();
}
g_log.Log(L"MSOffice::_readDefaultLanguageForOffice2016LangAccessoryPack. isCatalanSetAsDefaultLanguage: %x, FollowSystemUIOff %u",
(wchar_t* )isCatalanSetAsDefaultLanguage, (wchar_t* )followSystemUIOff);
}
void MSOffice::_readDefaultLanguage(bool& isCatalanSetAsDefaultLanguage, bool& followSystemUIOff)
{
wchar_t szKeyName [1024];
swprintf_s(szKeyName, L"Software\\Microsoft\\Office\\%s\\Common\\LanguageResources", _getRegKeys().VersionNumber);
if (m_registry->OpenKey(HKEY_CURRENT_USER, szKeyName, false))
{
DWORD lcid = UNDEFINED_LCID;
if (m_registry->GetDWORD(L"UILanguage", &lcid))
{
if (lcid == _wtoi(VALENCIAN_LCID) || lcid == _wtoi(CATALAN_LCID))
isCatalanSetAsDefaultLanguage = true;
}
// If FollowSystemUI is true Office uses Windows's language pack language to decide which language to use
if (m_MSVersion == MSOffice2003)
{
followSystemUIOff = (lcid == 0 ? false : true);
}
else
{
wstring value;
wchar_t szValue[2048];
if (m_registry->GetString(L"FollowSystemUI", szValue, sizeof(szValue)))
{
value = szValue;
std::transform(value.begin(), value.end(), value.begin(), ::tolower);
if (value.compare(L"off") == 0)
followSystemUIOff = true;
}
}
m_registry->Close();
}
g_log.Log(L"MSOffice::_readDefaultLanguage. isCatalanSetAsDefaultLanguage: %x, FollowSystemUIOff %u",
(wchar_t* )isCatalanSetAsDefaultLanguage, (wchar_t* )followSystemUIOff);
}
bool MSOffice::IsDefaultLanguage()
{
// TODO: No language detection for Office 2016
if (m_MSVersion == MSOffice2016_64 || m_MSVersion == MSOffice2016)
{
g_log.Log(L"MSOffice::SetDefaultLanguage. No changes in Office 2016");
return true;
}
ConfigureLocaleAction configureLocaleAction((IOSVersion*) NULL, m_registry, (IRunner*)NULL);
bool isDefaultLanguage = false;
bool isCatalanSetAsDefaultLanguage = false;
bool followSystemUIOff = false;
_readDefaultLanguage(isCatalanSetAsDefaultLanguage, followSystemUIOff);
if (followSystemUIOff)
{
if (isCatalanSetAsDefaultLanguage)
isDefaultLanguage = true;
}
else
{
if (m_win32I18N->GetUserDefaultUILanguage() == CATALAN_PRIMARY_LCID)
isDefaultLanguage = true;
}
g_log.Log(L"MSOffice::IsDefaultLanguage (%s) returns '%u'", (wchar_t*) GetVersion(), (wchar_t*) isDefaultLanguage);
return isDefaultLanguage;
}
void MSOffice::SetDefaultLanguage()
{
// TODO: No language setting for Office 2016
if (m_MSVersion == MSOffice2016_64 || m_MSVersion == MSOffice2016)
{
g_log.Log(L"MSOffice::SetDefaultLanguage. No changes in Office 2016");
return;
}
_setDefaultLanguage();
}
// We install the LIP instead of the LAP then if we call this function is the case
// that the LAP was installed but the language was not selected
void MSOffice::_setDefaultLanguageForOffice2016LangAccessoryPack()
{
BOOL bSetKey = FALSE;
if (m_registry->OpenKey(HKEY_CURRENT_USER, OFFICE2016_LAPKEY, true))
{
bSetKey = m_registry->SetString(L"UILanguageTag", L"ca-es");
// This key setting tells Office do not use the same language that the Windows UI to determine the Office Language
// and use the specified language instead
m_registry->SetDWORD(L"FollowSystemUILanguage", 0);
m_registry->Close();
}
g_log.Log(L"MSOffice::_setDefaultLanguageForOffice2016LangAccessoryPack (%s), set UILanguage %u", (wchar_t*) GetVersion(), (wchar_t *) bSetKey);
}
void MSOffice::_setDefaultLanguage()
{
BOOL bSetKey = FALSE;
wchar_t szKeyName [1024];
int lcid = 0;
swprintf_s(szKeyName, L"Software\\Microsoft\\Office\\%s\\Common\\LanguageResources", _getRegKeys().VersionNumber);
if (m_registry->OpenKey(HKEY_CURRENT_USER, szKeyName, true))
{
// Always set the language to match the installed langpack
// GetUseDialectalVariant is only used as guidance when installing a language pack, when setting the language
// of already existing installation we use the already existing language pack (ca or va) independely of what
// the user has selected
if (m_packageCodeToSet.size() > 0)
{
lcid = _wtoi(m_packageCodeToSet.c_str());
}
else
{
lcid = _wtoi(m_installedLangPackCode.c_str());
}
bSetKey = m_registry->SetDWORD(L"UILanguage", lcid);
// This key setting tells Office do not use the same language that the Windows UI to determine the Office Language
// and use the specified language instead
if (m_MSVersion != MSOffice2003)
{
m_registry->SetString(L"FollowSystemUI", L"Off");
}
m_registry->Close();
}
g_log.Log(L"MSOffice::SetDefaultLanguage (%s), set UILanguage %u, lcid %u", (wchar_t*) GetVersion(), (wchar_t *) bSetKey, (wchar_t *) lcid);
}
MSOffice::RegKeyVersion MSOffice::_getRegKeys()
{
switch (m_MSVersion)
{
case MSOffice2003:
return RegKeys2003;
case MSOffice2007:
return RegKeys2007;
case MSOffice2010:
case MSOffice2010_64:
return RegKeys2010;
case MSOffice2013:
case MSOffice2013_64:
return RegKeys2013;
case MSOffice2016:
case MSOffice2016_64:
default:
return RegKeys2016;
}
}
wchar_t* MSOffice::_getDownloadID()
{
switch (m_MSVersion)
{
case MSOffice2003:
m_packageCodeToSet = CATALAN_LCID;
return L"2003";
case MSOffice2007:
m_packageCodeToSet = CATALAN_LCID;
return L"2007";
case MSOffice2010:
m_packageCodeToSet = CATALAN_LCID;
return L"2010_32";
case MSOffice2010_64:
m_packageCodeToSet = CATALAN_LCID;
return L"2010_64";
case MSOffice2013:
if (GetUseDialectalVariant())
{
m_packageCodeToSet = VALENCIAN_LCID;
return L"2013_va_32";
}
else
{
m_packageCodeToSet = CATALAN_LCID;
return L"2013_ca_32";
}
case MSOffice2013_64:
if (GetUseDialectalVariant())
{
m_packageCodeToSet = VALENCIAN_LCID;
return L"2013_va_64";
}
else
{
m_packageCodeToSet = CATALAN_LCID;
return L"2013_ca_64";
}
case MSOffice2016:
m_packageCodeToSet = CATALAN_LCID;
return L"2016_ca_32";
case MSOffice2016_64:
m_packageCodeToSet = CATALAN_LCID;
return L"2016_ca_64";
default:
return L"";
}
}
bool MSOffice::_extractCabFile(wchar_t * file, wchar_t * path)
{
Runner runnerCab;
wchar_t szParams[MAX_PATH];
wchar_t szApp[MAX_PATH];
GetSystemDirectory(szApp, MAX_PATH);
wcscat_s(szApp, L"\\expand.exe ");
swprintf_s (szParams, L" %s %s -f:*", file, path);
g_log.Log(L"MSOffice::_extractCabFile '%s' with params '%s'", szApp, szParams);
runnerCab.Execute(szApp, szParams);
runnerCab.WaitUntilFinished();
return true;
}
void MSOffice::_startTimer()
{
m_nTimerID = SetTimer(NULL, TIMER_ID, 500, _timerProc);
s_timersIDsToObjs[m_nTimerID] = this;
g_log.Log(L"MSOffice::startTimer");
}
void MSOffice::_stopTimer()
{
if (m_nTimerID == 0)
return;
KillTimer(NULL, m_nTimerID);
s_timersIDsToObjs.erase(m_nTimerID);
m_nTimerID = 0;
g_log.Log(L"MSOffice::stopTimer");
}
VOID CALLBACK MSOffice::_timerProc(HWND hWndTimer, UINT uMsg, UINT_PTR idEvent, DWORD dwTime)
{
HWND hWnd;
map<int, MSOffice*>::iterator it;
MSOffice* obj;
it = s_timersIDsToObjs.find(idEvent);
if (it == s_timersIDsToObjs.end())
return;
obj = it->second;
// Splash screen
hWnd = FindWindowEx(NULL, NULL, L"Click2RunSplashScreen", NULL);
while (hWnd)
{
wchar_t szText[2048];
GetWindowText(hWnd, szText, sizeof(szText));
// Once we send the first HIDE we could stop here, by doing obj->Stop(), however it is necessary continuing sending HIDE in Adobe case
ShowWindow(hWnd, SW_HIDE);
hWnd = FindWindowEx(NULL, hWnd, L"Click2RunSplashScreen", NULL);
}
// installer screen
hWnd = FindWindowEx(NULL, NULL, L"Click2RunSetupUIClass", NULL);
while (hWnd)
{
wchar_t szText[2048];
GetWindowText(hWnd, szText, sizeof(szText));
// Once we send the first HIDE we could stop here, by doing obj->Stop(), however it is necessary continuing sending HIDE in Adobe case
ShowWindow(hWnd, SW_HIDE);
hWnd = FindWindowEx(NULL, hWnd, L"Click2RunSetupUIClass", NULL);
}
}
void MSOffice::Execute()
{
wchar_t szParams[MAX_PATH] = L"";
wchar_t szApp[MAX_PATH] = L"";
switch (m_MSVersion)
{
case MSOffice2016_64:
case MSOffice2016:
wcscpy_s(szApp, m_szFullFilename);
_startTimer();
break;
case MSOffice2013_64:
case MSOffice2013:
case MSOffice2010_64:
case MSOffice2010:
{
wchar_t logFile[MAX_PATH];
wcscpy_s(szApp, m_szFullFilename);
wcscpy_s(szParams, L" /passive /norestart /quiet");
// We need temporary unique files for the logs since we can execute several MS instances
GetTempFileName(m_szTempPath, L"mslog", 0, logFile);
wcscat_s(szParams, L" /log:");
wcscat_s(szParams, logFile);
m_msiexecLog = logFile;
break;
}
case MSOffice2007:
{
wcscpy_s(szApp, m_szFullFilename);
wcscpy_s(szParams, L" /quiet");
break;
}
case MSOffice2003:
{
wchar_t szMSI[MAX_PATH];
// Unique temporary file (needs to create it)
GetTempFileName(m_szTempPath, L"CAT", 0, m_szTempPath2003);
DeleteFile(m_szTempPath2003);
if (CreateDirectory(m_szTempPath2003, NULL) == FALSE)
{
g_log.Log(L"MSOffice::Execute. Cannot create temp directory '%s'", m_szTempPath2003);
break;
}
_extractCabFile(m_szFullFilename, m_szTempPath2003);
GetSystemDirectory(szApp, MAX_PATH);
wcscat_s(szApp, L"\\msiexec.exe ");
wcscpy_s(szMSI, m_szTempPath2003);
wcscat_s(szMSI, L"\\");
wcscat_s(szMSI, L"lip.msi");
wcscpy_s(szParams, L" /i ");
wcscat_s(szParams, szMSI);
wcscat_s(szParams, L" /qn");
break;
}
default:
break;
}
g_log.Log(L"MSOffice::Execute (%s) '%s' with params '%s'", (wchar_t*) GetVersion(), szApp, szParams);
m_runner->Execute(szApp, szParams);
SetStatus(InProgress);
}
void MSOffice::AddDownloads(MultipleDownloads& multipleDownloads)
{
ConfigurationFileActionDownload downloadVersion;
downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(_getID(),
wstring(_getDownloadID()));
wcscpy_s(m_szFilename, downloadVersion.GetFilename().c_str());
wcscpy_s(m_szFullFilename, m_szTempPath);
wcscat_s(m_szFullFilename, m_szFilename);
multipleDownloads.AddDownload(downloadVersion, m_szFullFilename);
}
#define LINES_TODUMP 7
#define KEYWORD_TOSEARCH L"Error"
void MSOffice::DumpLogOnError()
{
if (m_msiexecLog.empty() == true)
return;
LogExtractor logExtractor(m_msiexecLog, LINES_TODUMP);
logExtractor.SetExtractLastOccurrence(true);
logExtractor.SetFileIsUnicode(false);
logExtractor.ExtractLogFragmentForKeyword(KEYWORD_TOSEARCH);
logExtractor.DumpLines();
}
bool MSOffice::IsLangPackAvailable()
{
bool isLangPackAvailable;
ConfigurationFileActionDownload downloadVersion;
downloadVersion = ConfigurationInstance::Get().GetRemote().GetDownloadForActionID(_getID(),
wstring(_getDownloadID()));
isLangPackAvailable = downloadVersion.IsUsable();
g_log.Log(L"MSOffice::IsLangPackAvailable (%s) available %u", (wchar_t *) GetVersion(), (wchar_t *)isLangPackAvailable);
return isLangPackAvailable;
}
bool MSOffice::IsNeed()
{
assert(false);
return false;
}
void MSOffice::Complete()
{
if (IsLangPackInstalled())
{
SetDefaultLanguage();
SetStatus(Successful);
}
if (IsLangPackAvailable() && IsLangPackInstalled() == false)
{
SetStatus(FinishedWithError);
DumpLogOnError();
}
g_log.Log(L"MSOffice::Complete. (%s) is '%s'", (wchar_t *)GetVersion(), GetStatus() == Successful ? L"Successful" : L"FinishedWithError");
}
void MSOffice::CheckPrerequirements(Action * action)
{
if (IsLangPackInstalled())
{
if (IsDefaultLanguage())
{
SetStatus(AlreadyApplied);
}
}
else
{
if (IsLangPackAvailable() == false)
{
SetStatus(CannotBeApplied);
return;
}
}
SetStatus(status);
g_log.Log(L"MSOffice::CheckPrerequirements. (%s) status '%u'", (wchar_t *)GetVersion(), (wchar_t *) GetStatus());
}
|
f491f9ce2fbe4ddce4a73260dbc8aed866fac565 | cd4587f46b5f1393e46459c7b7959455a847c0db | /source/geometry/src/GateGenericRepeaterMessenger.cc | 451118ea97e1dd0c81984818d493bcafc8f58cb2 | [] | no_license | lynch829/Gate | 8072e7e30d855b15a9152a5884fc1357c07539bc | 02754973dbaeca343a7c3b9402521f45c05e9ccf | refs/heads/develop | 2021-01-24T20:13:11.821931 | 2016-07-12T11:23:15 | 2016-07-12T11:23:15 | 66,326,268 | 1 | 0 | null | 2016-08-23T02:33:29 | 2016-08-23T02:33:29 | null | UTF-8 | C++ | false | false | 2,198 | cc | GateGenericRepeaterMessenger.cc | /*----------------------
Copyright (C): OpenGATE Collaboration
This software is distributed under the terms
of the GNU Lesser General Public Licence (LGPL)
See GATE/LICENSE.txt for further details
----------------------*/
#include "GateGenericRepeaterMessenger.hh"
#include "GateGenericRepeater.hh"
#include "G4UIdirectory.hh"
#include "G4UIcmdWithAString.hh"
#include "G4UIcmdWithAnInteger.hh"
#include "G4UIcmdWithADoubleAndUnit.hh"
#include "G4UIcmdWith3VectorAndUnit.hh"
#include "G4UIcmdWithoutParameter.hh"
#include "G4UIcmdWithABool.hh"
//--------------------------------------------------------------------------------------------
GateGenericRepeaterMessenger::GateGenericRepeaterMessenger(GateGenericRepeater* itsRepeater)
:GateObjectRepeaterMessenger(itsRepeater) {
G4String cmdName;
cmdName = GetDirectoryName()+"setPlacementsFilename";
mFileCmd = new G4UIcmdWithAString(cmdName,this);
mFileCmd->SetGuidance("Set a filename with a list of 3D translations and rotations.");
cmdName = GetDirectoryName()+"useRelativeTranslation";
mRelativeTransCmd = new G4UIcmdWithABool(cmdName,this);
mRelativeTransCmd->SetGuidance("If true, translation are relative to the initial translation.");
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
GateGenericRepeaterMessenger::~GateGenericRepeaterMessenger() {
delete mFileCmd;
delete mRelativeTransCmd;
}
//--------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------
void GateGenericRepeaterMessenger::SetNewValue(G4UIcommand* command,G4String newValue)
{
if (command == mFileCmd) GetGenericRepeater()->SetPlacementsFilename(newValue);
else if (command == mRelativeTransCmd) GetGenericRepeater()->EnableRelativeTranslation(mRelativeTransCmd->GetNewBoolValue(newValue));
else GateObjectRepeaterMessenger::SetNewValue(command,newValue);
}
//--------------------------------------------------------------------------------------------
|
3a09f011455a4c046afb536ea510224abe81b972 | 1f290d3ddcaf70de1c99576e9da42535b5a29e89 | /Assignment2/Vstack.h | be24a14f0f4ff196ff2bcb6c7d6a88a433e4c2c3 | [] | no_license | octavio1594/Advanced-Level-Course-Work | 3e075b687b8cbff3dac721773627cbe3e9c7c6f7 | 598c7b0bd7aa3f4f3df22d50e37a2363bbe2f7f0 | refs/heads/master | 2021-01-19T09:21:08.380493 | 2017-02-23T20:26:11 | 2017-02-23T20:26:11 | 82,099,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,347 | h | Vstack.h |
// =======================================================
// HW#: HW1P1 stack
// Your name: Octavio Cea
// Compiler: g++
// File type: headher file Vstack.h
//=======================================================
//----- Globally setting up the aliases ----------------
#include <vector>
#include<iostream>
using namespace std;
class stack
{
private: // to be hidden from the client
vector<int> V; // el is a vector of el_t's
public: // prototypes to be used by the client
// Note that no parameter variables are given
// exception handling classes
class Overflow{}; // thrown when the stack overflows
class Underflow{}; // thrown when the stack underflows
stack(); // constructor to create an object
~stack(); // destructor to destroy an object
// PURPOSE: if not full, enters an element at the top;
// otherwise throws an exception - Overflow
// PARAMETER: pass the element to be pushed
void push(int);
// PURPOSE: if not empty, removes and gives back the top element;
// otherwise throws an exception - Underflow
// PARAMETER: provide variable to receive the popped element (pass by ref)
void pop(int&);
// PURPOSE: if not empty, gives the top element without removing it;
// otherwise, throws an exception - Underflow
// PARAMETER: provide variable to receive the top element (pass by ref)
void topElem(int&);
// You must add good comments for each function - See Notes1B
//PURPOSE: checks the top of the stack and returns true if it is empty,
// if it is not empty then it returns false. (if top is empty, top = -1)
bool isEmpty();
//PURPOSE: If this function returns true,it throws the exception Overflow
// if it returns false, it adds an element to el and it increments top by 1.
bool isFull();
//PURPOSE: This function calls isEmpty and if isEmpty returns true,
// displayAll displays [ empty ]. to the screen, if isEmpty returns false,
// displayAll displays the elements in the stack vertically.
void displayAll();
//PURPOSE: This function pops all the elements from the stack until it
// is empty if it is not empty yet.
void clearIt();
};
// Note: semicolon is needed at the end of the header file
|
2c868ff58ada91606563d5e07e1dfe239a933716 | 8888fb4af4000f02903299bda0ecc954c402452a | /BOJ/6064.cpp | 786ca50bc7058560a060685110fbbf20300a1041 | [
"MIT"
] | permissive | ReinforceIII/Algorithm | 48122e826c60a433cdfb5bb1283db3b3d1be64d1 | 355f6e19f8deb6a76f82f5283d7c1987acd699a6 | refs/heads/master | 2020-07-26T03:57:36.567702 | 2019-09-16T11:46:02 | 2019-09-16T11:46:02 | 208,526,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 686 | cpp | 6064.cpp | /* 6064 카잉달력 */
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
using namespace std;
int gcd(int a, int b) {
if(b == 0) return a;
else return gcd(b, a%b);
}
int lcm(int a, int b) {
return a*b /gcd(a,b);
}
int main() {
int t;
cin>>t;
while(t--) {
int M,N,x,y;
cin>>M>>N>>x>>y;
int last = lcm(M,N);
int result = -1;
int now = x;
do {
if (now%N == y) {
result = now;
break;
} else now+=M;
} while(now <= last);
now = y;
do {
if(now%M == x) {
result = now;
break;
} else now+=N;
} while(now<= last);
cout<<result<<"\n";
}
return 0;
} |
935b277b1e0db9a973c1397070a14cdd7731214c | c220f55c8b671a7b51f0d10837270dab65c6f8ea | /Source/Library.Shared/Runtime/Attribute.h | ec4a4cbad93b794bb654245f75397060a617b7e7 | [] | no_license | PlatoManchi/NoobEngine | 6fd4a95f4985f2722a6216be7aa2e35ee7d073cc | b6211fa46fe0ce89c76b970d719ca4f517e37d4f | refs/heads/master | 2021-01-11T17:28:35.961322 | 2017-08-22T20:45:18 | 2017-08-22T20:45:18 | 79,780,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,519 | h | Attribute.h | #pragma once
#include "RTTI.h"
#include "Datum.h"
#include "Scope.h"
#include "Container/Hashmap.h"
namespace NoobEngine
{
namespace Runtime
{
class Attribute abstract : public Scope
{
RTTI_DECLARATIONS(Attribute, Scope)
public:
/**
@brief Default constructor.
*/
Attribute();
/**
@brief Copy constructor that takes the attribute as parameter and deep copy everything.
@param pOther The attribute that should be copied.
@see Attribute()
*/
Attribute(const Attribute& pOther);
/**
@brief Deep copy all content from passed attribute into current attribute
@param pOther The attribute from which copy should be made
@see operator=()
*/
Attribute& operator=(const Attribute& pOther);
/**
@brief Move semantics. Steals the data from passed attribute and nullify the passed attribute.
@param pOther Attribute from which to steal the data.
*/
Attribute(const Attribute&& pOther);
/**
@brief Move semantics. Steal the data from passed attribute and nullify the passed attribute.
@param pOther Attribute from which to steal the data.
*/
Attribute& operator=(const Attribute&& pOther);
/**
@brief Standard destructor
*/
virtual ~Attribute();
/**
@brief Checks if the attribute is prescribed and if yes then return true else false.
@param pKey String that holds the key for the attribute.
@return Boolean which is true if pKey is key of prescribed attribute else false.
@see IsAuxiliaryAttribute()
@see IsAttribute()
*/
bool IsPrescribedAttribute(const std::string& pKey) const;
/**
@brief Checks if the attribute is auxiliary and if yes then return true else false.
@param pKey String that holds the key for the attribute.
@return Boolean which is true if pKey is key of auxiliary attribute else false.
@see AppendAuxiliaryAttribute()
@see IsPrescribedAttribute()
@see IsAttribute()
*/
bool IsAuxiliaryAttribute(const std::string& pKey) const;
/**
@brief Checks if there is attribute with key and return true if present else false.
@param pKey String that holds the key for the attribute.
@return Boolean which is true if pKey is a key to attribute else false.
@see IsAuxiliaryAttribute()
@see IsPrescribedAttribute()
*/
bool IsAttribute(const std::string& pKey) const;
/**
@brief Adds an auxiliary attribute to the attribute
@param pKey The key to be used for the attribute
@return Reference to datum that is appended
*/
Datum& AppendAuxiliaryAttribute(const std::string& pKey);
/**
@brief Appends a nested scope to the current scope.
@details This will adopt the scope as a prescribed scope. Will throw exception if key already exists.
@param pKey string that holds value of key.
@param pValue Reference to scope that has to be adopted.
*/
void AppendNestedScope(const std::string& pKey, Scope& pValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, int32_t pInitialValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, float pInitialValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, std::string& pInitialValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, glm::vec4& pInitialValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, glm::mat4x4& pInitialValue);
/**
@brief Add the attribute as internal attribute and initialize that value with the value sent.
@param pKey String that holds that value of key.
@param pInitialValue The initial value of the attribute.
@return Reference to the datum
*/
Datum& AddInternalAttribute(const std::string& pKey, RTTI* pInitialValue);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, int32_t* pValue, uint32_t pSize = 1);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, float* pValue, uint32_t pSize = 1);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, std::string* pValue, uint32_t pSize = 1);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, glm::vec4* pValue, uint32_t pSize = 1);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, glm::mat4x4* pValue, uint32_t pSize = 1);
/**
@brief Add the attribute as external attribute.
@param pKey String that holds that value of key.
@param pValue The value to hold.
@return Reference to the datum
*/
Datum& AddExternalAttribute(const std::string& pKey, RTTI** pValue, uint32_t pSize = 1);
protected:
/**
@brief Add prescribed attribute
@param pKey The key to be used for the attribute
@return Reference to datum that is appended. If key already exists returns existing datum else creates new datum.
*/
Datum& AppendPrescribedAttribute(const std::string& pKey);
/**
@brief Populate all the initial prescribed and auxiliary attributes.
@details This function has to be called in all child class constructors. Failing to do so will leads to unexpected behavior.
*/
void Populate();
private:
static uint32_t mObjCount;
/**
Static HashMap that holds the prescribed attribute list of all the class that will extend Attribute
*/
static Container::Hashmap<uint64_t, Container::Vector<std::string>> sAttributeList;
};
}
} |
4ead1422896a707a9865ffa3a9176d0ed3d960b8 | 7f86d6422cb359aa46842d5e6c22385d4a0ff4ad | /source/play_state.hpp | bbb0091e8c2e22ba47f3e1c7b13f3e886cc1d48f | [] | no_license | tomgalvin594/Struct | e6d0b65a710ba5ded170fbff030e1407d1c55183 | 1b0dfd212f9a549884e1a59ba3c8e1aefb90f3aa | refs/heads/master | 2021-01-10T02:42:02.877494 | 2015-05-24T01:15:38 | 2015-05-24T01:15:38 | 36,150,161 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,072 | hpp | play_state.hpp | #ifndef PLAY_STATE_HPP
#define PLAY_STATE_HPP
#include <vector>
#include <string>
#include <fstream>
#include <SFML/Audio.hpp>
#include <Box2D/Box2D.h>
#include "random.hpp"
#include "state.hpp"
#include "button.hpp"
#include "loading_bar.hpp"
#include "animation.hpp"
#include "block.hpp"
#include "query_callback.hpp"
class Play_State : public State
{
public:
Play_State(std::shared_ptr<b2World> world,
std::shared_ptr<Asset_Manager> asset_manager);
~Play_State();
void handle_events(sf::Event &event, std::shared_ptr<sf::RenderWindow> window);
void update(double delta);
void render(std::shared_ptr<sf::RenderWindow> window);
//read data from a file and build the level from that data
void load_level();
//create an explosion
void explode();
//destroy the splinters from the world
void cleanup();
private:
std::shared_ptr<b2World> m_world = nullptr;
//store all the block objects
std::vector<std::unique_ptr<Block>> m_all_blocks;
//store all the shadow sprites(to guide the player)
std::vector<sf::Sprite> m_shadow_sprites;
//sound
sf::SoundBuffer m_buffer_1;
sf::SoundBuffer m_buffer_2;
sf::Sound m_explosion_snd;
sf::Sound m_click_snd;
//store the created bodies for explosion
std::vector<b2Body*> m_splinters;
std::unique_ptr<Button> m_pause_button = nullptr;
std::unique_ptr<Loading_Bar> m_time_bar = nullptr;
std::unique_ptr<Loading_Bar> m_comp_bar = nullptr;
std::unique_ptr<Animation> m_explosion = nullptr;
sf::RectangleShape m_top_rect;
sf::RectangleShape m_bottom_rect;
sf::Clock m_clock;
double m_elapsed_time = 0.0;
double m_level_time = 25.0; //seconds
double m_current_time = 0.0;
unsigned int m_total_blocks = 0;
unsigned int m_current_blocks = 0;
b2Body *m_ground_body = nullptr;
b2Body *m_top_body = nullptr;
b2Body *m_left_body = nullptr;
b2Body *m_right_body = nullptr;
sf::Sprite m_ground_spt;
unsigned int m_level_index = 1;
b2MouseJoint *m_mouse_joint = nullptr;
double m_last_explosion = 0.0;
unsigned int m_explosion_count = 0;
//true to get player input and start play
bool m_play = false;
sf::Music m_music;
//sf::Text fps;
};
#endif // PLAY_STATE_HPP
|
12865f5ef776cceca2ed3230466f3acffe79b0b2 | 4bf637918b726280534d034aff883c1e220262db | /Player.h | 60d8656a5c02263771724c5fc32cbe6e6d86b107 | [] | no_license | AbdullahYasserK/sfml.AB | 06baaa5c57cc6dd6d64143a441361d37612226b5 | 07c34c8cb6b2eda59f5f434d6bc0a28d01a2d9e0 | refs/heads/main | 2023-05-07T09:49:55.315548 | 2021-06-01T14:02:57 | 2021-06-01T14:02:57 | 372,850,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | Player.h | #pragma once
#include <SFML/Graphics.hpp>
#include "Animation.h"
using namespace sf;
class Player
{
public :
Player(Texture* texture, Vector2u imageCount, float switchTime, float speed);
~Player();
void update(float deltatime);
void draw(RenderWindow& window);
private :
RectangleShape body;
Animation animation;
unsigned int row;
float speed;
bool faceRight;
};
|
068ecaf774fd8e13dfba1171a0aac837a2752f25 | f7a4c1351175677c3cc89078fcfcb8bba38bd0cf | /3. 수학 관련/3-5 조합.cpp | 3647779a0117b79b57dcc608ad97ebb894873e0d | [] | no_license | ltnscp9028/dimigoAlgorithm | 8842ed19b8d2c4392f310fe413f849c3224a88aa | e9c79052d9638cfd5b30d77c3325ba885d8c117e | refs/heads/master | 2022-11-26T11:15:15.227526 | 2020-08-02T14:26:19 | 2020-08-02T14:26:19 | 280,155,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | cpp | 3-5 조합.cpp | #include <bits/stdc++.h>
using namespace std;
int n,k,i;
vector<int>v,vv;
int main() {
for(cin>>n>>k,v.resize(n);i<n;i++)cin>>v[i];
for(i=0;i<k;i++)vv.push_back(1);
for(i=0;i<n-k;i++)vv.push_back(0);
sort(vv.begin(),vv.end());
i=0;
do{
i++;
}while(next_permutation(vv.begin(),vv.end()));
cout<<i;
} |
b76a5d69e40482db5988be07cf0c72e3e7aa0815 | 1a72e26a84acb12a3f8b3a25b7e4f8f3eede9e3f | /src/pwm.h | 4bdbfb7ec3c96ff9625500d255661f9a9cdb159c | [] | no_license | kennethabarr/transcpp | efed6777bbd88ff0b2579ac5f7d3ca9831a674e0 | 9813b9a2bc666cd3f001bc56590ba7fb8fef58f7 | refs/heads/master | 2021-01-11T03:55:49.894022 | 2016-04-18T15:58:44 | 2016-04-18T15:58:44 | 47,208,942 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,926 | h | pwm.h | #ifndef PWM_H
#define PWM_H
#include "utils.h"
#include "parameter.h"
#include "mode.h"
#include <boost/property_tree/xml_parser.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/version.hpp>
#include <vector>
using namespace std;
using boost::property_tree::ptree;
/* there are more ways to express binding preferences than a PWM,
so this is going to have to expand. It could expand to include dinucleotide
preferences, but also more complex rules, like the periodic diculcleotide
preferences of a nulceosome. What they all have in common is that they can
score a sequences, and that score can be converted to an affinity using exp */
/* there are several ways we specify pwm information:
PCM, or Position Count Matrix, contains the counts of
observed bases at each position
PFM, or Position Frequency Matrix, contains the
probablity of a base at each position
PSSM, the Position Specific Scoring Matrix, contains
the log-likelihood of each base at each position,
taking into account the background model
BEM, the Binding Energy Model, contains what can be
interpreted as the ddG for a substitution of each
base at each position, in the case where lambda=kT
THIS MODE HAS BEEN REMOVED! The conversion of PSSM to BEM
is lossy and I decided there was no real benefit to using
BEM over PSSM. BEMs can still be entered, but they are scored
as PSSMs with a maxscore of 0
*/
/* there are several ways to express binding preferences. We can convert between
some, not others */
enum pwm_types { PCM = 0, PFM = 1, PSSM = 2, BEM = 3, HEIJDEN2012 = 4};
/* struct holding the score of a TF over sequence */
struct TFscore
{
//TF* tf;
vector<double> fscore;
vector<double> rscore;
vector<double> mscore;
double maxscore;
};
class PWM
{
private:
mode_ptr mode;
string source;
int input_type; // the type of binding preference initially specified
double gc; // gc content used as background model
string tfname; // the tfname so we know what to move in parameters
// pwm specific parameters
bool is_pwm; // is this even a pwm
pwm_param_ptr mat; // the actual matrix
vector<int> consensus; // the consensus sequence
vector<double> position_counts;
vector<double> s2p; // convert scores to pvalues
double pseudo; // pseudo count if PCM
// nucleosome binding parameters
bool is_periodic; // uses periodic dinuc binding from van der Heijden 2012
double plength; // the length of sequence to scan over (use 147 or 146 for octamer, 74 for tetramer)
double_param_ptr period; // the period of dinuc (10-11)
double_param_ptr beta; // the strengh of preference for dinucs
double maxscore; // the maximum score
// private methods
void subscore(const vector<int> & s, double * out);
double score_dyad(int first, int second, double position);
public:
// constructors
PWM();
PWM(mode_ptr mode);
PWM(vector<vector<double> >& t, int type, mode_ptr mode);
// setters
void setSource(string source) { this->source = source; }
void setGC(double gc);
void setPseudo(double pseudo);
void setTFName(string tfname) { this->tfname = tfname; }
void setMode(mode_ptr mode) { this->mode = mode; }
void setPWM(vector<vector<double> >& t, int type); // use default gc=0.25, pseudo=1
void setPWM(vector<vector<double> >& t, int type, double gc, double pseudo);
// getters
const string& getSource() { return source; }
double getGC() { return gc; }
double getPseudo() { return pseudo; }
double getMaxScore() { return maxscore; }
int length() { return mat->getValue().size(); }
int getInputType() { return input_type; }
vector<int>& getConsensus() { return consensus; }
vector<vector<double> >& getPWM(); // efficient, return reference to pwm
vector<vector<double> > getPWM(int type); // return a copy, for conveneince, not inner loop
pwm_param_ptr getPWMParam() { return mat; }
void getParameters(param_ptr_vector&);
void getAllParameters(param_ptr_vector&);
// forward converstions
void PCM2PFM();
void PFM2PSSM();
// reverse conversions (dont touch the actual matrix since PSSMs are always used internally)
void PFM2PCM(vector<vector<double> >& t);
void PSSM2PFM(vector<vector<double> >& t);
// methods
void setNscore();
void calc_max_score();
double pval2score(double pval); // returns the threshold that would yeild a given p-value
double score2pval(double score); // returns the pvalue of a given score
void score(const vector<int>& s, TFscore &t);
//size_t getSize();
//void serialize(void *buf) const;
//void deserialize(void const *buf);
//void print(ostream& os, int precision);
void read(ptree& pt);
void write(ptree& pt);
};
#endif
|
541d3ddf2863b03d6457b08ce6326ce883f44eb1 | 6fbf3695707248bfb00e3f8c4a0f9adf5d8a3d4c | /java/jniutil/include/jvm/array.hpp | c2db6f6c69c9024d4c032e24ea6ba8dcb8cbd79b | [] | no_license | ochafik/cppjvm | c554a2f224178bc3280f03919aff9287bd912024 | e1feb48eee3396d3a5ecb539de467c0a8643cba0 | refs/heads/master | 2020-12-25T16:02:38.582622 | 2011-11-17T00:11:35 | 2011-11-17T00:11:35 | 2,790,123 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,003 | hpp | array.hpp | #ifndef JVM_ARRAY_INCLUDED
#define JVM_ARRAY_INCLUDED
#include <jvm/virtual_machine.hpp>
#include <jvm/object.hpp>
namespace jvm
{
/* A traits class allows us to abstract over the inconsistencies in the
JNI APIs. The general traits for any type T are assumed to work on
the CppWrap-generated wrappers for any Java class, and so they use
the APIs for dealing with Object[] arrays.
*/
template <class T>
struct array_traits
{
typedef jobjectArray array_type; // The JNI array type
typedef T accessor_base_type; // Base for type to return from operator[]
// Allocate an array (we assume we can get the jclass from T)
static array_type alloc(JNIEnv *e, jsize n)
{ return e->NewObjectArray(e, n, T::get_class(), 0); }
// We assume a method T::get_impl() to obtain local reference jobjects
static void put(JNIEnv *e, array_type a, jsize p, const T *b, jsize c)
{
// There are no APIs for bulk operations on object arrays, so we simulate them
for (jsize n = 0; n < c; n++)
e->SetObjectArrayElement(a, p + n, b[n].get_impl());
}
// We assume a method T::put_impl() to store the references
static void get(JNIEnv *e, array_type a, jsize p, T *b, jsize c)
{
for (jsize n = 0; n < c; n++)
b[n].put_impl(e->GetObjectArrayElement(a, p + n));
}
};
/* Then we define specialised traits for the primitive types, which are
somewhat simpler. They all follow an identical pattern so we can use
a macro to declare them.
*/
template <class T>
class primitive_accessor
{
T val;
public:
void put_impl(T o)
{ val = o; }
operator T()
{ return val; }
};
#define DECLARE_JARRAY_TRAITS(ELEM, FNAME) \
template <> \
struct array_traits<ELEM> \
{ \
typedef ELEM ## Array array_type; \
typedef primitive_accessor<ELEM> accessor_base_type; \
static array_type alloc(JNIEnv *e, jsize n) \
{ return e->New ## FNAME ## Array(n); } \
static void put(JNIEnv *e, array_type a, jsize p, const ELEM *b, jsize c) \
{ e->Set ## FNAME ## ArrayRegion(a, p, c, b); } \
static void get(JNIEnv *e, array_type a, jsize p, ELEM *b, jsize c) \
{ e->Get ## FNAME ## ArrayRegion(a, p, c, b); } \
}
DECLARE_JARRAY_TRAITS(jbyte, Byte);
DECLARE_JARRAY_TRAITS(jchar, Char);
DECLARE_JARRAY_TRAITS(jboolean, Boolean);
DECLARE_JARRAY_TRAITS(jshort, Short);
DECLARE_JARRAY_TRAITS(jint, Int);
DECLARE_JARRAY_TRAITS(jlong, Long);
DECLARE_JARRAY_TRAITS(jfloat, Float);
DECLARE_JARRAY_TRAITS(jdouble, Double);
template <class T>
class array : public object
{
public:
typedef typename array_traits<T>::array_type array_type;
typedef typename array_traits<T>::accessor_base_type accessor_base_type;
array() {}
explicit array(jobject ar)
: object(ar) {}
explicit array(jsize length)
{ new_(length); }
void new_(jsize length)
{ put_impl(array_traits<T>::alloc(global_vm().env(), length)); }
jsize length() const
{ return global_vm().env()->GetArrayLength((array_type)get_impl()); }
void put(int p, const T *v, size_t c = 1) const
{ array_traits<T>::put(global_vm().env(), (array_type)get_impl(), p, v, c); }
void get(int p, T *v, size_t c = 1) const
{ array_traits<T>::get(global_vm().env(), (array_type)get_impl(), p, v, c); }
class accessor_ : public accessor_base_type
{
const array<T> &data_;
jsize index_;
public:
accessor_(const array<T> &array, jsize index)
: data_(array), index_(index)
{
T v;
array.get(index, &v);
accessor_base_type::put_impl(v);
}
accessor_ &operator=(const T &v)
{
accessor_base_type::put_impl(v);
data_.put(index_, &v);
return *this;
}
};
accessor_ operator[](jlong index) const
{ return accessor_(*this, index); }
accessor_ operator[](int index) const // VC++2008 needs this when using int literals
{ return accessor_(*this, index); }
};
}
#endif
|
d8b6d22f0a80d0059daf991335bbc85f4b5bffbd | 052b567e55fc5d9e1415351008ae7a0b1b4317db | /09/test_std_literals.cpp | c200a25f9862b013b1de8863cbaa87e70b3ac46c | [
"Unlicense"
] | permissive | caijw/geek_time_cpp | 75fbee65412b6176f16ce48ad8f6c9b4e7b92894 | 746cd3bd15a511dc41130632563f66a475a756f5 | refs/heads/master | 2022-12-07T00:09:52.727994 | 2020-09-02T17:46:58 | 2020-09-02T17:46:58 | 280,107,476 | 0 | 0 | Unlicense | 2020-07-16T09:09:22 | 2020-07-16T09:09:21 | null | UTF-8 | C++ | false | false | 409 | cpp | test_std_literals.cpp | #include <chrono> // std::chrono::milliseconds
#include <complex> // std::complex
#include <iostream> // std::cout/endl
#include <string> // std::string
#include <thread> // std::this_thread
using namespace std;
int main()
{
cout << "i * i = " << 1i * 1i << endl;
cout << "Waiting for 500ms" << endl;
this_thread::sleep_for(500ms);
cout << "Hello world"s.substr(0, 5) << endl;
}
|
3be5f62dfd38499b65c17dbc85f1af2b05c9bd80 | 1dc1550c1345e4bb31fd45b06020d139404b8bea | /PointCloudClassifier/PCLVisualizer/GeneratedFiles/Release/moc_ThreadCalcPointCloudMsg.cpp | 8f1cc85a4c0abc8a5119c0dc4a7b7266bd29d5b2 | [] | no_license | jonhzy/PointCloudClassifier | 0a09c2725d1e13b1e7a8bf895b639fa530b8bf91 | ee96469cbfac32753a241cb96b733f1d857a5e1b | refs/heads/master | 2020-09-27T19:59:46.403302 | 2018-10-08T09:12:19 | 2018-10-08T09:12:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,514 | cpp | moc_ThreadCalcPointCloudMsg.cpp | /****************************************************************************
** Meta object code from reading C++ file 'ThreadCalcPointCloudMsg.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.7.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../ThreadCalcPointCloudMsg.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ThreadCalcPointCloudMsg.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.7.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_ThreadCalcPointCloudMsg_t {
QByteArrayData data[4];
char stringdata0[56];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ThreadCalcPointCloudMsg_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ThreadCalcPointCloudMsg_t qt_meta_stringdata_ThreadCalcPointCloudMsg = {
{
QT_MOC_LITERAL(0, 0, 23), // "ThreadCalcPointCloudMsg"
QT_MOC_LITERAL(1, 24, 9), // "submitMsg"
QT_MOC_LITERAL(2, 34, 0), // ""
QT_MOC_LITERAL(3, 35, 20) // "std::vector<QString>"
},
"ThreadCalcPointCloudMsg\0submitMsg\0\0"
"std::vector<QString>"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ThreadCalcPointCloudMsg[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void, 0x80000000 | 3, 2,
0 // eod
};
void ThreadCalcPointCloudMsg::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
ThreadCalcPointCloudMsg *_t = static_cast<ThreadCalcPointCloudMsg *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->submitMsg((*reinterpret_cast< std::vector<QString>(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (ThreadCalcPointCloudMsg::*_t)(std::vector<QString> );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&ThreadCalcPointCloudMsg::submitMsg)) {
*result = 0;
return;
}
}
}
}
const QMetaObject ThreadCalcPointCloudMsg::staticMetaObject = {
{ &QThread::staticMetaObject, qt_meta_stringdata_ThreadCalcPointCloudMsg.data,
qt_meta_data_ThreadCalcPointCloudMsg, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *ThreadCalcPointCloudMsg::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ThreadCalcPointCloudMsg::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_ThreadCalcPointCloudMsg.stringdata0))
return static_cast<void*>(const_cast< ThreadCalcPointCloudMsg*>(this));
return QThread::qt_metacast(_clname);
}
int ThreadCalcPointCloudMsg::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QThread::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
// SIGNAL 0
void ThreadCalcPointCloudMsg::submitMsg(std::vector<QString> _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
QT_END_MOC_NAMESPACE
|
8553250b87125533abd042f329e13deee96c0aec | 2cff35be91152bbbf21ff8735482aee759caa865 | /XiaoMi_Login/HttpsClient.h | 91247288007ad8870f4b5a36e1264fb799a920db | [] | no_license | asdlei99/Study_XiaoMi_Login | 67f2fef019515f5b5e0d63d749a80247700155bd | 9faf4f091babeb5bed1f59674ef1b2904d54d29f | refs/heads/master | 2022-01-25T19:15:13.228577 | 2018-12-06T10:34:27 | 2018-12-06T10:34:27 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,205 | h | HttpsClient.h | #pragma once
#include "WtlString.h"
#ifdef __cplusplus
extern "C"
{
#endif // __cplusplus
#include <openssl/ssl.h>
#include <openssl/err.h>
#ifdef __cplusplus
}
#endif // __cplusplus
#include <string>
#include <vector>
#include <map>
enum HttpStatusCode
{
/* 1xx Infomational */
HttpStatusContinue = 100,
HttpStatusSwichingProtocols = 101,
/* 2xx Succesful */
HttpStatusOk = 200,
HttpStatsuCreated = 201,
HttpStatusAccepted = 202,
HttpStatusNonAuthorizedInformation = 203,
HttpStatusNoContent = 204,
HttpStatusResetContent = 205,
HttpStatusPartialContent = 206,
/* 3xx Redirection */
HttpStatusMultipleChoices = 300,
HttpStatusMovedPermanetly = 301,
HttpStatusFound = 302,
HttpStatusSeeOther = 303,
HttpStatusNotModified = 304,
HttpStatusUseProxy = 305,
HttpStatusTemporaryRedirection = 307,
/* 4xx Client Error */
HttpStatusBadRequest = 400,
HttpStatusUnauthorized = 401,
HttpStatusPaymentRequired = 402,
HttpStatusForbidden = 403,
HttpStatusNotFound = 404,
HttpStatusMethodNotAllowed = 405,
HttpStatusNotAcceptable = 406,
HttpStatusProxyAuthenticationRequired = 407,
HttpStatusRequestTimeOut = 408,
HttpStatusConflict = 409,
HttpStatusGone = 410,
HttpStatusLengthRequired = 411,
HttpStatusProconditionFailed = 412,
HttpStatusRequestEntityTooLarge = 413,
HttpStatusRequestURITooLarge = 414,
HttpStatusUnsupportedMediaType = 415,
HttpStatusRequestedRangeNotSatisfiable = 416,
HttpStatusExpectationFailed = 417,
/* 5xx Server Error */
HttpStatusInternalServerError = 500,
HttpStatusNotImplemented = 501,
HttpStatusBadGateway = 502,
HttpStatusServiceUnavaliable = 503,
HttpStatusGatewayTimeOut = 504,
HttpStatusHttpVersionNotSupported = 505
};
class HttpsClient
{
public:
HttpsClient();
//!清理打开的句柄
~HttpsClient();
BOOL LogoutOfServer();
BOOL ConnectToServer(const CString strServerUrl, const int nPort);
void CloseServer();
BOOL SslGetCipherAndCertification();
int GetHttpStatusCode();
public:
typedef std::map<std::string, std::string> CookieContainer;
typedef std::map<std::string, std::string>::iterator CookieIt;
CookieContainer m_vCookie;
std::string m_strHeader;
std::string m_strGetResult;
int m_nStatusCode; // Http返回值
bool socketHttps(std::string host, std::string request);
bool ExtractCookie();
bool postData(std::string host, std::string path, std::string post_content = "");
bool getData(std::string host, std::string pathAndparameter);
bool getDataWithParam(std::string host, std::string path, std::string get_content = "");
void SetCookie(std::string &strCookie);
// 获取请求的结果
std::string GetLastRequestResult();
protected:
// 初始化winSocket环境
BOOL InitializeSocketContext();
// 原生socket连接
BOOL SocketConnect();
// SSL通信初始化
BOOL InitializeSslContext();
// SSL绑定原生socket,并连接服务器
BOOL SslConnect();
private:
SSL *m_ssl;
SSL_CTX *m_sslCtx;
long m_socketClient;
CString cstrServerUrl;
int m_nServerPort;
CString cstrUserName;
CString cstrPassWord;
CString m_cstrCookieUid;
SOCKADDR_IN m_socketAddrClient;
const SSL_METHOD* m_sslMethod;
char * m_cstrSslSubject;
char* m_cstrSslIssuer;
};
|
c375dcdf7a1e9fb8ed30311b0ff528f1a33d7949 | 250de1f388e705db9ad2bb0433648d003381fa9c | /codeforces/676div2/a4temp.cpp | 2313559691763f1a8335deab3451f7fe4f087769 | [] | no_license | parthsarthiprasad/Competitive_Programming | a13e82886a6576b3b1ba137278ada9582d64bfda | 1efaf0820be119f367b082f606ebf56a6f15564f | refs/heads/master | 2023-04-11T14:15:55.200053 | 2021-04-14T09:19:09 | 2021-04-14T09:19:09 | 254,834,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | a4temp.cpp | #include <bits/stdc++.h>
using namespace std;
void fn(vector<long long> a,long long & op){
if(a.size()==0) return;
if(a.size()==1) return;
if(a.size()==2){
op+=a[0]+a[1];
return;
}
int n=a.size();
for(int i=0;i<n-1;i++){
op=op+a[i]+a[i+1];
vector<long long> rectemp;
for(int j=0;j<i;j++) rectemp.push_back(a[j]);
rectemp.push_back(a[i]+a[i+1]);
for(int j=i+2;j<n;j++) rectemp.push_back(a[j]);
for(int i=0;i<rectemp.size();i++){
cout<<rectemp[i]<<" ";
}
cout<<endl;
fn(rectemp,op);
}
return;
}
long long NOR(int x){
if(x==0) return 1;
long long op=1;
for(int i=1;i<=x;i++) op=op*i;
return op;
}
int main(){
int t;
cin>>t;
int ttno=1;
while(t--){
int n;
cin>>n;
vector<long long> a(n);
for(int i=0;i<n;i++) cin>>a[i];
long long op=0;
fn(a,op);
long long nr=NOR(n-1);
cout<<"Case #"<<ttno<<": "<<setprecision(6)<<(float)op/nr<<endl;
ttno++;
}
return 0;
} |
35460ac28ec0824aeedff5002c51aeacff9b52d5 | f4fa1a469cc3c8e84993901fa3d0bba65d30e38b | /include/nexus/global/context.hpp | dda955dd04e5df5c16cfda75a5045c20257c7789 | [
"BSL-1.0"
] | permissive | cbodley/nexus | ebae21b7616dbc2803c6e5addf89aa44474ae28b | d1d8486f713fd089917331239d755932c7c8ed8e | refs/heads/master | 2022-07-28T10:01:26.819330 | 2022-07-18T13:08:24 | 2022-07-18T13:08:29 | 179,001,824 | 47 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 1,454 | hpp | context.hpp | #pragma once
#include <utility>
#include <nexus/global/error.hpp>
namespace nexus::global {
class context;
namespace detail {
context init(int flags, error_code& ec);
} // namespace detail
/// a context object representing the global initialization of the nexus
/// QUIC/HTTP library, and its consequent global cleanup on destruction
class context {
friend context detail::init(int flags, error_code& ec);
using cleanup_fn = void (*)();
cleanup_fn cleanup;
context(cleanup_fn cleanup) noexcept : cleanup(cleanup) {}
public:
/// construct an uninitialized context
context() noexcept : cleanup(nullptr) {}
/// move construct, claiming ownership of another context's cleanup
context(context&& o) noexcept : cleanup(std::exchange(o.cleanup, nullptr)) {}
/// move assign, swapping ownership with another context
context& operator=(context&& o) noexcept {
std::swap(cleanup, o.cleanup);
return *this;
}
/// perform global shutdown if initialized
~context() {
if (cleanup) {
shutdown();
}
}
/// return true if the context represents successful initialization
operator bool() const { return cleanup; }
/// enable log output to stderr, where the log level is one of:
/// emerg, alert, crit, error, warn, notice, info, debug
void log_to_stderr(const char* level);
/// perform global shutdown of an initialized context
void shutdown() {
cleanup();
}
};
} // namespace nexus::global
|
fe0b327a14b0520349e0f4a8597e41d65e1036d0 | 2683ec53321b09c5380b4fdd6dae18bfabbf2940 | /ProModbusMd/ProModbusVd/ViceTemporaryFunction.h | 2c1588c464d98348d756ba79d14a456954286ae1 | [] | no_license | Cillebokin/ProModbusForMvc | 8135f1ccb1361ba14e4fab876ad10b06f1f203cf | cafe8285afc4b8afde57b9f870695fe378b45c39 | refs/heads/main | 2023-07-22T06:09:25.731934 | 2021-08-31T02:00:46 | 2021-08-31T02:00:46 | 401,541,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | ViceTemporaryFunction.h | #ifndef _VICE_TEMPORARY_FUNCTION_H_
#define _VICE_TEMPORARY_FUNCTION_H_
#include <windows.h>
#define VICE_NO_MIN 1
#define VICE_NO_MAX 247
#define READ_COIL_NUM_MAX 2000
#define READ_REGI_NUM_MAX 125
#define WRITE_COIL_NUM_MAX 1968
#define WRITE_REGI_NUM_MAX 123
#define BEGIN_ADDR 0x0000
#define END_ADDR 0x270F
enum RetCodeMeanAnalyse{CodeAnalyseSuc = 0, CodeMessNotEnoughLong = -1, CodeProtocolNotTrue = -2, CodeHeadAfterByteNotTrue = -3, CodeViceNoNotTrue = -4, CodeCantReadFunc = -5, CodeErrorOne = -6, CodeErrorTwoOrThree = -7, CodeBeginAddrErr = -8, CodeReadCoilNumErr = -9, CodeReadRegiNumErr = -10, CodeWriteCoilNumErr = -11, CodeWriteRegiNumErr = -12, CodeAddrAndCountNotTrue = -13, Code01ReqLenNotTrue = -14, Code03ReqLenNotTrue = -15, Code0FReqLenNotTrue = -16, Code10ReqLenNotTrue = -17, Code0FByteNotTrue = -18, Code10ByteNotTrue = -19, CodeCrcError = -20};
class ClaTempFuncVice
{
public:
static unsigned short FunCombineTwoChar(byte preNum, byte afterNum);
private:
};
#endif _TEMPORARY_FUNCTION_H_ |
6df1a4b75315943d22c93d62263927d5d3801343 | 7708ce22c1c0c3e2c45f306813bd11d8a550e5ed | /GE_2_ECM/ControlSystem.cpp | bece81298d7916a8eb3a5091d059f51d07ce3ec7 | [] | no_license | BlueSully/GE_2_ECM | d4f91ddc9792bf00615f0dbdc8c8ec64e6d56512 | feaf70268bf694e3a52baaab2449abf729927bd5 | refs/heads/master | 2020-05-23T10:20:30.130867 | 2017-02-02T15:18:26 | 2017-02-02T15:18:26 | 80,423,332 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | cpp | ControlSystem.cpp | #include "ControlSystem.h"
ControlSystem::ControlSystem()
{
}
ControlSystem::~ControlSystem()
{
}
void ControlSystem::addEntity(Entity & e)
{
entities.push_back(&e);
}
void ControlSystem::update()
{
SDL_Event evt;
for (size_t i = 0; i < entities.size(); i++)
{
int speed = entities[i]->getComponent<ControlComponent>()->getSpeed();
while (SDL_PollEvent(&evt))
{
if (evt.type == SDL_KEYDOWN)
{
//Select surfaces based on key press
switch (evt.key.keysym.sym)
{
case SDLK_UP:
entities[i]->getComponent<PositionComponent>()->setY(entities[i]->getComponent<PositionComponent>()->getY() - speed);
break;
case SDLK_DOWN:
entities[i]->getComponent<PositionComponent>()->setY(entities[i]->getComponent<PositionComponent>()->getY() + speed);
break;
case SDLK_LEFT:
entities[i]->getComponent<PositionComponent>()->setX(entities[i]->getComponent<PositionComponent>()->getX() - speed);
break;
case SDLK_RIGHT:
entities[i]->getComponent<PositionComponent>()->setX(entities[i]->getComponent<PositionComponent>()->getX() + speed);
break;
default:
break;
}
}
}
}
}
|
0fe9e2cb333edac2ad165556d6d02f66010f0b1d | 2be2c3dfc55405c64fb78607ea90548966a90349 | /actor.h | 176474e8340e2992b5028c1c15c6040f68aef6f1 | [] | no_license | vladanghelache/Tema_3_POO | cef916a2e9a2e3601830394490dfd0dcff8450d2 | 04e1aa8444cdbaf9dc47057c9e3d23c35722b7fa | refs/heads/master | 2022-07-21T17:57:30.162008 | 2020-05-20T13:19:11 | 2020-05-20T13:19:11 | 265,570,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | h | actor.h | #ifndef ACTOR_H_INCLUDED
#define ACTOR_H_INCLUDED
#include "persoana.h"
class actor: public persoana{
bool actor_principal;
public:
actor();
actor(std::string,std::string,std::string,float,bool);
unsigned get_procent_bonus()const;
bool get_actor_principal()const;
friend std::istream &operator>> (std::istream&,actor&);
void afisare();
friend void n_actori(std::vector<actor*>&,int);
};
#endif // ACTOR_H_INCLUDED
|
ee3112e14b7ec5b116f1ed83097ef1c89ee6d596 | 7579d827cb7b50b438dfd9ef6fa80ba2797848c9 | /sources/plug_wx/src/luna/bind_wxDialogLayoutAdapter.cpp | 799c7f682c18b8e3befbf905baa65a72223f61c1 | [] | no_license | roche-emmanuel/sgt | 809d00b056e36b7799bbb438b8099e3036377377 | ee3a550f6172c7d14179d9d171e0124306495e45 | refs/heads/master | 2021-05-01T12:51:39.983104 | 2014-09-08T03:35:15 | 2014-09-08T03:35:15 | 79,538,908 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,792 | cpp | bind_wxDialogLayoutAdapter.cpp | #include <plug_common.h>
#include <luna/wrappers/wrapper_wxDialogLayoutAdapter.h>
class luna_wrapper_wxDialogLayoutAdapter {
public:
typedef Luna< wxDialogLayoutAdapter > luna_t;
inline static bool _lg_typecheck_getTable(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
return true;
}
static int _bind_getTable(lua_State *L) {
if (!_lg_typecheck_getTable(L)) {
luaL_error(L, "luna typecheck failed in getTable function, expected prototype:\ngetTable(). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
wxDialogLayoutAdapter* self=(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call getTable()");
}
luna_wrapper_base* wrapper = luna_caster<wxDialogLayoutAdapter,luna_wrapper_base>::cast(self); //dynamic_cast<luna_wrapper_base*>(self);
if(wrapper) {
CHECK_RET(wrapper->pushTable(),0,"Cannot push table from value wrapper.");
return 1;
}
return 0;
}
inline static bool _lg_typecheck___eq(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( !Luna<void>::has_uniqueid(L,1,64729109) ) return false;
return true;
}
static int _bind___eq(lua_State *L) {
if (!_lg_typecheck___eq(L)) {
luaL_error(L, "luna typecheck failed in __eq function, expected prototype:\n__eq(wxDialogLayoutAdapter*). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
wxDialogLayoutAdapter* rhs =(Luna< wxDialogLayoutAdapter >::check(L,2));
wxDialogLayoutAdapter* self=(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call __eq(...)");
}
lua_pushboolean(L,self==rhs?1:0);
return 1;
}
inline static bool _lg_typecheck_fromVoid(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( !Luna<void>::has_uniqueid(L,1,3625364) ) return false;
return true;
}
static int _bind_fromVoid(lua_State *L) {
if (!_lg_typecheck_fromVoid(L)) {
luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nfromVoid(void*). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
wxDialogLayoutAdapter* self= (wxDialogLayoutAdapter*)(Luna< void >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call fromVoid(...)");
}
Luna< wxDialogLayoutAdapter >::push(L,self,false);
return 1;
}
inline static bool _lg_typecheck_asVoid(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( !Luna<void>::has_uniqueid(L,1,64729109) ) return false;
return true;
}
static int _bind_asVoid(lua_State *L) {
if (!_lg_typecheck_asVoid(L)) {
luaL_error(L, "luna typecheck failed in fromVoid function, expected prototype:\nasVoid(). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
void* self= (void*)(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call asVoid(...)");
}
Luna< void >::push(L,self,false);
return 1;
}
// Base class dynamic cast support:
inline static bool _lg_typecheck_dynCast(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( lua_type(L,2)!=LUA_TSTRING ) return false;
return true;
}
static int _bind_dynCast(lua_State *L) {
if (!_lg_typecheck_dynCast(L)) {
luaL_error(L, "luna typecheck failed in dynCast function, expected prototype:\ndynCast(const std::string &). Got arguments:\n%s",luna_dumpStack(L).c_str());
}
std::string name(lua_tostring(L,2),lua_objlen(L,2));
wxDialogLayoutAdapter* self=(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call dynCast(...)");
}
static LunaConverterMap& converters = luna_getConverterMap("wxDialogLayoutAdapter");
return luna_dynamicCast(L,converters,"wxDialogLayoutAdapter",name);
}
// Constructor checkers:
inline static bool _lg_typecheck_ctor(lua_State *L) {
if( lua_gettop(L)!=1 ) return false;
if( lua_istable(L,1)==0 ) return false;
return true;
}
// Function checkers:
inline static bool _lg_typecheck_CanDoLayoutAdaptation(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,56813631)) ) return false;
return true;
}
inline static bool _lg_typecheck_DoLayoutAdaptation(lua_State *L) {
if( lua_gettop(L)!=2 ) return false;
if( (lua_isnil(L,2)==0 && !Luna<void>::has_uniqueid(L,2,56813631)) ) return false;
return true;
}
// Operator checkers:
// (found 0 valid operators)
// Constructor binds:
// wxDialogLayoutAdapter::wxDialogLayoutAdapter(lua_Table * data)
static wxDialogLayoutAdapter* _bind_ctor(lua_State *L) {
if (!_lg_typecheck_ctor(L)) {
luaL_error(L, "luna typecheck failed in wxDialogLayoutAdapter::wxDialogLayoutAdapter(lua_Table * data) function, expected prototype:\nwxDialogLayoutAdapter::wxDialogLayoutAdapter(lua_Table * data)\nClass arguments details:\n\n%s",luna_dumpStack(L).c_str());
}
return new wrapper_wxDialogLayoutAdapter(L,NULL);
}
// Function binds:
// bool wxDialogLayoutAdapter::CanDoLayoutAdaptation(wxDialog * dialog)
static int _bind_CanDoLayoutAdaptation(lua_State *L) {
if (!_lg_typecheck_CanDoLayoutAdaptation(L)) {
luaL_error(L, "luna typecheck failed in bool wxDialogLayoutAdapter::CanDoLayoutAdaptation(wxDialog * dialog) function, expected prototype:\nbool wxDialogLayoutAdapter::CanDoLayoutAdaptation(wxDialog * dialog)\nClass arguments details:\narg 1 ID = 56813631\n\n%s",luna_dumpStack(L).c_str());
}
wxDialog* dialog=(Luna< wxObject >::checkSubType< wxDialog >(L,2));
wxDialogLayoutAdapter* self=(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call bool wxDialogLayoutAdapter::CanDoLayoutAdaptation(wxDialog *). Got : '%s'\n%s",typeid(Luna< wxDialogLayoutAdapter >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
bool lret = self->CanDoLayoutAdaptation(dialog);
lua_pushboolean(L,lret?1:0);
return 1;
}
// bool wxDialogLayoutAdapter::DoLayoutAdaptation(wxDialog * dialog)
static int _bind_DoLayoutAdaptation(lua_State *L) {
if (!_lg_typecheck_DoLayoutAdaptation(L)) {
luaL_error(L, "luna typecheck failed in bool wxDialogLayoutAdapter::DoLayoutAdaptation(wxDialog * dialog) function, expected prototype:\nbool wxDialogLayoutAdapter::DoLayoutAdaptation(wxDialog * dialog)\nClass arguments details:\narg 1 ID = 56813631\n\n%s",luna_dumpStack(L).c_str());
}
wxDialog* dialog=(Luna< wxObject >::checkSubType< wxDialog >(L,2));
wxDialogLayoutAdapter* self=(Luna< wxDialogLayoutAdapter >::check(L,1));
if(!self) {
luaL_error(L, "Invalid object in function call bool wxDialogLayoutAdapter::DoLayoutAdaptation(wxDialog *). Got : '%s'\n%s",typeid(Luna< wxDialogLayoutAdapter >::check(L,1)).name(),luna_dumpStack(L).c_str());
}
bool lret = self->DoLayoutAdaptation(dialog);
lua_pushboolean(L,lret?1:0);
return 1;
}
// Operator binds:
};
wxDialogLayoutAdapter* LunaTraits< wxDialogLayoutAdapter >::_bind_ctor(lua_State *L) {
return luna_wrapper_wxDialogLayoutAdapter::_bind_ctor(L);
// Note that this class is abstract (only lua wrappers can be created).
// Abstract methods:
// bool wxDialogLayoutAdapter::CanDoLayoutAdaptation(wxDialog * dialog)
// bool wxDialogLayoutAdapter::DoLayoutAdaptation(wxDialog * dialog)
}
void LunaTraits< wxDialogLayoutAdapter >::_bind_dtor(wxDialogLayoutAdapter* obj) {
delete obj;
}
const char LunaTraits< wxDialogLayoutAdapter >::className[] = "wxDialogLayoutAdapter";
const char LunaTraits< wxDialogLayoutAdapter >::fullName[] = "wxDialogLayoutAdapter";
const char LunaTraits< wxDialogLayoutAdapter >::moduleName[] = "wx";
const char* LunaTraits< wxDialogLayoutAdapter >::parents[] = {0};
const int LunaTraits< wxDialogLayoutAdapter >::hash = 64729109;
const int LunaTraits< wxDialogLayoutAdapter >::uniqueIDs[] = {64729109,0};
luna_RegType LunaTraits< wxDialogLayoutAdapter >::methods[] = {
{"CanDoLayoutAdaptation", &luna_wrapper_wxDialogLayoutAdapter::_bind_CanDoLayoutAdaptation},
{"DoLayoutAdaptation", &luna_wrapper_wxDialogLayoutAdapter::_bind_DoLayoutAdaptation},
{"dynCast", &luna_wrapper_wxDialogLayoutAdapter::_bind_dynCast},
{"__eq", &luna_wrapper_wxDialogLayoutAdapter::_bind___eq},
{"fromVoid", &luna_wrapper_wxDialogLayoutAdapter::_bind_fromVoid},
{"asVoid", &luna_wrapper_wxDialogLayoutAdapter::_bind_asVoid},
{"getTable", &luna_wrapper_wxDialogLayoutAdapter::_bind_getTable},
{0,0}
};
luna_ConverterType LunaTraits< wxDialogLayoutAdapter >::converters[] = {
{0,0}
};
luna_RegEnumType LunaTraits< wxDialogLayoutAdapter >::enumValues[] = {
{0,0}
};
|
a0920e65fe46fa86c2db66d336f51c01a3a08ef9 | 2ff61cbabab9b036e2e8e64bcfc3b64db6cdfaf1 | /Framework/playership.h | f2a4f41421d3d59a0cc34f2de018e3e2c08f6ea1 | [] | no_license | KretschmarHockey/US-Space-Force-Game | f52f8aae096ee4926a7d0f072588508774b0c7de | e01589f4761807ce0978034947dc7f50f7513264 | refs/heads/master | 2020-12-10T22:15:33.993211 | 2020-01-14T01:09:57 | 2020-01-14T01:09:57 | 233,727,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 683 | h | playership.h | #include "entity.h"
#ifndef __PLAYERSHIP_H__
#define __PLAYERSHIP_H__
enum Direction { LEFT, RIGHT };
class Playership : public Entity
{
// Methods
public:
Playership();
~Playership();
void Process(float deltaTime);
virtual void Draw(BackBuffer& backBuffer);
void SetDirection(Direction direction);
Direction GetDirection();
void SetInvincibility(bool invincible);
bool IsInvincible();
void SetInvincibleTimer(float timer);
float m_fInvincibilityTimer;
private:
Playership(const Playership& playership);
Playership& operator=(const Playership& playership);
// Members
protected:
Direction m_dDirection;
bool m_bInvincibility;
};
#endif // __PLAYERSHIP_H__
|
96e3b45b0f4791940e1f4369744d05b88ade4457 | 03128da170ceb04c7ceb776cfd920bf74fd23a89 | /common/shader_program.hpp | 73aed4d8f3a6d8cd7ca2143de17151e41ff9cd99 | [] | no_license | averne/learnopengl | 1038cfb1a20859d176f6f3ad78ddc99b24c31afe | d97abad951eadba1aee9ba9079d4bf1eafe4603f | refs/heads/master | 2020-07-01T23:22:42.348855 | 2019-08-26T08:17:31 | 2019-08-26T08:17:31 | 201,340,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,413 | hpp | shader_program.hpp | #pragma once
#include <string>
#include <iostream>
#include <algorithm>
#include <initializer_list>
#include <type_traits>
#include <utility>
#include <stdexcept>
#include <map>
#include <glad/glad.h>
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "shader.hpp"
#include "object.hpp"
class ShaderProgram: public GlObject {
public:
ShaderProgram(): GlObject(glCreateProgram()) {
if (!get_handle())
throw std::runtime_error("Could not create Buffer object");
}
template <typename ...Shaders>
ShaderProgram(Shaders &&...shaders): ShaderProgram() {
set_shaders(std::forward<Shaders>(shaders)...);
if (!link()) {
print_log();
throw std::runtime_error("Could not link shader program");
}
}
~ShaderProgram() {
glDeleteProgram(get_handle());
}
template <typename ...Shaders>
void set_shaders(Shaders &&...shaders) const {
(glAttachShader(get_handle(), shaders.get_handle()), ...);
}
GLint link() const {
GLint rc;
glLinkProgram(get_handle());
glGetProgramiv(get_handle(), GL_LINK_STATUS, &rc);
if (rc); // delete shaders
return rc;
}
void use() const {
glUseProgram(get_handle());
}
static void unuse() {
glUseProgram(0);
}
inline void bind() const { use(); }
inline static void unbind() { unuse(); }
inline GLint get_uniform_loc(const std::string &name) {
auto it = this->uniform_loc_cache.find(name);
if (it != this->uniform_loc_cache.end())
return it->second;
GLint loc = glGetUniformLocation(get_handle(), name.c_str());
if (loc == -1)
std::cout << "Could not find uniform " << name << '\n';
this->uniform_loc_cache[name] = loc;
return loc;
}
template <typename T>
void set_value(GLint loc, const T &val) const {
if constexpr (std::is_same_v<T, GLboolean> || std::is_same_v<T, GLint>)
glUniform1i(loc, (int)val);
else if constexpr (std::is_same_v<T, GLfloat>)
glUniform1f(loc, val);
else if constexpr (std::is_same_v<T, glm::vec2>)
glUniform2fv(loc, 1, glm::value_ptr(val));
else if constexpr (std::is_same_v<T, glm::vec3>)
glUniform3fv(loc, 1, glm::value_ptr(val));
else if constexpr (std::is_same_v<T, glm::vec4>)
glUniform4fv(loc, 1, glm::value_ptr(val));
else if constexpr (std::is_same_v<T, glm::mat2>)
glUniformMatrix2fv(loc, 1, GL_FALSE, glm::value_ptr(val));
else if constexpr (std::is_same_v<T, glm::mat3>)
glUniformMatrix3fv(loc, 1, GL_FALSE, glm::value_ptr(val));
else if constexpr (std::is_same_v<T, glm::mat4>)
glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(val));
else
throw std::invalid_argument("Invalid argument for ShaderProgram::set_value");
}
void set_value(GLint loc, float val_1, float val_2) const {
glUniform2f(loc, val_1, val_2);
}
void set_value(GLint loc, float val_1, float val_2, float val_3) const {
glUniform3f(loc, val_1, val_2, val_3);
}
void set_value(GLint loc, float val_1, float val_2, float val_3, float val_4) const {
glUniform4f(loc, val_1, val_2, val_3, val_4);
}
template <typename ...Args>
void set_value(const std::string &name, Args &&...args) {
set_value(get_uniform_loc(name), std::forward<Args>(args)...);
}
std::string get_log() const {
std::string str(0x200, 0);
glGetProgramInfoLog(get_handle(), str.size(), nullptr, (char *)str.data());
return str;
}
void print_log() const {
std::cout << get_log() << '\n';
}
private:
struct Comp {
bool operator()(const std::string &s1, const std::string &s2) const {
return strcmp(s1.c_str(), s2.c_str()) < 0;
}
};
std::map<std::string, GLint, Comp> uniform_loc_cache;
};
|
1c08e278683fed03653f3305e75ce28e6ff58d96 | 107790ec592154927ff1a1f57bb018b2c02a85d5 | /atmega328p/dist/main.ino | d978fc774a465158c14bf969522d8dbf4f8fa745 | [] | no_license | misiewiczp/arc | 9be3f4d11225ad37ff6d117d049e09123f78c75a | 855a9f7b20373cfa1aea8f5509c121080818abea | refs/heads/master | 2020-03-27T22:42:47.817746 | 2019-11-30T16:23:43 | 2019-11-30T16:23:43 | 147,254,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,679 | ino | main.ino | #include <SPI.h>
#include "../pwm_read/proto.h"
#define MISO_PIN 12
#define BUF_SIZE SPI_COMMAND_LEN
#define ULTRASOUND_SPEED_2 (29<<1)
volatile int val = 0;
volatile spi_command buf;
void initMeasure()
{
PORTC &= ~(1<<PC5);
delayMicroseconds(2);
PORTC |= (1<<PC5);
delayMicroseconds(10);
PORTC &= ~(1<<PC5);
}
void setup() {
DDRC |= (1<<PC5); // DIST - TRIGGER
DDRD &= ~(1<<PD1); // DIST - ECHO
DDRD |= (1<<PD7); // LED
DDRB |= (1<<PB4); // MISO
PCMSK2 |= (1<<PCINT17);
PCICR |= (1<<PCIE2);
// turn on SPI in slave mode
SPCR |= bit(SPE);
// turn on interrupts
SPCR |= bit(SPIE);
}
volatile long timer = 0;
volatile int cnt = 0;
void loop() {
if (timer == 0)
initMeasure();
delay(10); // shorter than maximum time of over 50ms
}
ISR(PCINT2_vect)
{
if (PIND & (1<<PD1)) {
timer = micros();
} else
if (timer != 0) {
int tmp_val = (int)(micros()-timer);
if (tmp_val >= ULTRASOUND_SPEED_2) {
val = tmp_val;
cnt++;
}
timer = 0;
}
if (val > 0 && val <= 30*ULTRASOUND_SPEED_2)
PORTD |= (1<<PD7); // LED ON
else
PORTD &= ~(1<<PD7); // LED OFF
}
volatile int position = -1;
ISR (SPI_STC_vect)
{
byte c = SPDR;
if (c == REQ_RC) // starting new sequence?
{
buf.rc.motor = val/ULTRASOUND_SPEED_2; // /2 - two directions, /29 - 1 cm = 29 micorseconds ~ 34 cm = 1 milisecond
buf.rc.servo = cnt;
buf.rc.motor_off = 0;
buf.rc.servo_off = 0;
position = 0;
SPDR = 100; // ACK
return;
} else if (c == 0)
{
if (position >= 0 && position < BUF_SIZE)
{
SPDR = buf.cval[position];
position++;
return;
}
}
SPDR = 101;
}
|
5c5b9c5b57929684036931cba847827aa93cd8fa | 627157a23a44a38852c3e146efb8fd993f6c4128 | /3389.cpp | 0e8208657511bcd503979d88d984f49260320f36 | [] | no_license | hsh778205/luogu_code | e598fd87896a61ea6c75e3c918885bd00ea6933b | 5280e8d5cae5d5ac51cb9dbbe2a69fd8a8c3595a | refs/heads/master | 2021-07-21T12:24:37.708033 | 2021-03-30T06:29:21 | 2021-03-30T06:29:21 | 247,858,584 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,706 | cpp | 3389.cpp | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<queue>
#include<vector>
#include<limits.h>
#define IL inline
#define re register
#define LL long long
#define ULL unsigned long long
#ifdef TH
#define debug printf("Now is %d\n",__LINE__);
#else
#define debug
#endif
using namespace std;
template<class T>inline void read(T&x)
{
char ch=getchar();
int fu;
while(!isdigit(ch)&&ch!='-') ch=getchar();
if(ch=='-') fu=-1,ch=getchar();
x=ch-'0';ch=getchar();
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
x*=fu;
}
inline int read()
{
int x=0,fu=1;
char ch=getchar();
while(!isdigit(ch)&&ch!='-') ch=getchar();
if(ch=='-') fu=-1,ch=getchar();
x=ch-'0';ch=getchar();
while(isdigit(ch)){x=x*10+ch-'0';ch=getchar();}
return x*fu;
}
int G[55];
template<class T>inline void write(T x)
{
int g=0;
if(x<0) x=-x,putchar('-');
do{G[++g]=x%10;x/=10;}while(x);
for(int i=g;i>=1;--i)putchar('0'+G[i]);putchar('\n');
}
#define N 110
//bool book[N];
double a[N][N];
int n;
void Guess()
{
for(int i=1;i<=n;i++)
{
//let a[i][i] max
//find a[mx][i] in [i,n]
int mx=i;
for(int j=i+1;j<=n;j++)
{
if(fabs(a[j][i])>fabs(a[mx][i])) mx=j;
}
//swap(a[i],a[mx])
for(int j=1;j<=n+1;j++)
{
swap(a[i][j],a[mx][j]);
}
if(!a[i][i])
{
cout<<"No Solution"<<endl;
exit(0);
}
for(int j=1;j<=n;j++)
{
if(i==j) continue;
for(int k=i+1;k<=n+1;k++)
{
a[j][k]-=a[i][k]*a[j][i]/a[i][i];
}
}
}
for(int i=1;i<=n;i++)
{
printf("%.2lf\n",a[i][n+1]/a[i][i]);
}
}
int main()
{
n=read();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n+1;j++)
{
cin>>a[i][j];
}
}
Guess();
return 0;
}
|
bcc7d1024e3aaf99dbd7ca06b316c37d71295c72 | 9c079c10fb9f90ff15181b3bdd50ea0435fbc0cd | /Stl/vec.cpp | 132aabc6d422dd8754474c1057c7d92b869fcdc0 | [] | no_license | shihab122/Competitive-Programming | 73d5bd89a97f28c8358796367277c9234caaa9a4 | 37b94d267fa03edf02110fd930fb9d80fbbe6552 | refs/heads/master | 2023-04-02T20:57:50.685625 | 2023-03-25T09:47:13 | 2023-03-25T09:47:13 | 148,019,792 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | cpp | vec.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
vector<int>v(10,1);
v.resize(15);
//v.pop_back();
int t=v.back();
cout<<t<<endl;
for(int i=0;i<v.size();i++) cout<<v[i]<<endl;
return 0;
}
|
9d1b2df6f556a7f4ba0a5a23a0aece37285424e1 | 17212fa4fbc1025514d52db359097c119521912d | /include/mckl/core/matrix.hpp | 32149be5eca72fc3724602b4baaaecfad1f4d883 | [
"BSD-2-Clause"
] | permissive | zhouyan/MCKL | d2c6d609f3576243ea9dfa30c227568b9b1b73c4 | 1d03eb5a879e47e268efc73b1d433611e64307b3 | refs/heads/master | 2020-04-15T14:03:53.579628 | 2020-03-12T13:52:18 | 2020-03-12T13:52:18 | 58,975,768 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 24,290 | hpp | matrix.hpp | //============================================================================
// MCKL/include/mckl/core/matrix.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2018, Yan Zhou
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_CORE_MATRIX_HPP
#define MCKL_CORE_MATRIX_HPP
#include <mckl/internal/common.hpp>
#include <mckl/core/is_equal.hpp>
#include <mckl/core/iterator.hpp>
namespace mckl {
/// \brief Matrix container
/// \ingroup Core
///
/// \tparam T The value type
/// \tparam Layout The storage layout, either RowMajor or ColMajor
/// \tparam Alloc The allocator type
template <typename T, MatrixLayout Layout = ColMajor,
typename Alloc = Allocator<T>>
class Matrix
{
using layout_dispatch = std::integral_constant<MatrixLayout, Layout>;
using row_major = std::integral_constant<MatrixLayout, RowMajor>;
using col_major = std::integral_constant<MatrixLayout, ColMajor>;
Vector<T, Alloc> data_;
public:
using value_type = T;
using allocator_type = Alloc;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = value_type &;
using const_reference = const value_type &;
using pointer = value_type *;
using const_pointer = const value_type *;
using iterator = pointer;
using const_iterator = const_pointer;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
using row_iterator =
std::conditional_t<Layout == RowMajor, pointer, StepIterator<pointer>>;
using const_row_iterator = std::conditional_t<Layout == RowMajor,
const_pointer, StepIterator<const_pointer>>;
using reverse_row_iterator = std::reverse_iterator<row_iterator>;
using const_reverse_row_iterator =
std::reverse_iterator<const_row_iterator>;
using col_iterator =
std::conditional_t<Layout == ColMajor, pointer, StepIterator<pointer>>;
using const_col_iterator = std::conditional_t<Layout == ColMajor,
const_pointer, StepIterator<const_pointer>>;
using reverse_col_iterator = std::reverse_iterator<col_iterator>;
using const_reverse_col_iterator =
std::reverse_iterator<const_col_iterator>;
using row_range = Range<row_iterator>;
using const_row_range = Range<const_row_iterator>;
using reverse_row_range = Range<reverse_row_iterator>;
using const_reverse_row_range = Range<const_reverse_row_iterator>;
using col_range = Range<col_iterator>;
using const_col_range = Range<const_col_iterator>;
using reverse_col_range = Range<reverse_col_iterator>;
using const_reverse_col_range = Range<const_reverse_col_iterator>;
using transpose_type =
Matrix<T, Layout == RowMajor ? ColMajor : RowMajor, Alloc>;
/// \brief Construct an empty matrix
Matrix() noexcept(
std::is_nothrow_default_constructible<Vector<T, Alloc>>::value)
: nrow_(0), ncol_(0)
{
}
/// \brief Construct an `nrow` by `ncol` matrix
Matrix(size_type nrow, size_type ncol)
: data_(nrow * ncol), nrow_(nrow), ncol_(ncol)
{
}
/// \brief Copy constructor
Matrix(const Matrix &) = default;
/// \brief Move constructor
Matrix(Matrix &&other) noexcept(
std::is_nothrow_move_constructible<Vector<T, Alloc>>::value)
: data_(std::move(other.data_)), nrow_(other.nrow_), ncol_(other.ncol_)
{
other.nrow_ = 0;
other.ncol_ = 0;
}
/// \brief Copy assignment operator
Matrix &operator=(const Matrix &) = default;
/// \brief Move assignment operator
Matrix &operator=(Matrix &&other) noexcept(
noexcept(data_.swap(other.data_)))
{
if (this != &other) {
data_.swap(other.data_);
std::swap(nrow_, other.nrow_);
std::swap(ncol_, other.ncol_);
}
return *this;
}
/// \brief Convert to a matrix with a different storage layout
explicit operator transpose_type() const
{
transpose_type mat(nrow_, ncol_);
if (Layout == RowMajor) {
for (size_type i = 0; i != nrow_; ++i) {
for (size_type j = 0; j != ncol_; ++j) {
mat(i, j) = operator()(i, j);
}
}
}
if (Layout == ColMajor) {
for (size_type j = 0; j != ncol_; ++j) {
for (size_type i = 0; i != nrow_; ++i) {
mat(i, j) = operator()(i, j);
}
}
}
return mat;
}
/// \brief Return the associated allocator
allocator_type get_allocator() const { return data_.get_allocator(); }
/// \brief Iterator to the upper left corner of the matrix
iterator begin() { return data(); }
/// \brief Iterator to the upper left corner of the matrix
const_iterator begin() const { return cbegin(); }
/// \brief Iterator to the upper left corner of the matrix
const_iterator cbegin() const { return data(); }
/// \brief Iterator to one pass the lower right corner of the matrix
iterator end() { return begin() + nrow_ * ncol_; }
/// \brief Iterator to one pass the lower right corner of the matrix
const_iterator end() const { return cend(); }
/// \brief Iterator to one pass the lower right corner of the matrix
const_iterator cend() const { return begin() + nrow_ * ncol_; }
/// \brief Iterator to the lower right corner of the matrix
reverse_iterator rbegin() { return reverse_iterator(end()); }
/// \brief Iterator to the lower right corner of the matrix
const_reverse_iterator rbegin() const { return crbegin(); }
/// \brief Iterator to the lower right corner of the matrix
const_reverse_iterator crbegin() const
{
return const_reverse_iterator(cend());
}
/// \brief Iterator one before the upper left corner of the matrix
reverse_iterator rend() { return reverse_iterator(begin()); }
/// \brief Iterator one before the upper left corner of the matrix
const_reverse_iterator rend() const { return crend(); }
/// \brief Iterator one before the upper left corner of the matrix
const_reverse_iterator crend() const
{
return const_reverse_iterator(cbegin());
}
/// \brief Iterator to the beginning of a row
row_iterator row_begin(size_type i)
{
return row_begin_dispatch(i, layout_dispatch());
}
/// \brief Iterator to the beginning of a row
const_row_iterator row_begin(size_type i) const { return row_cbegin(i); }
/// \brief Iterator to the beginning of a row
const_row_iterator row_cbegin(size_type i) const
{
return row_begin_dispatch(i, layout_dispatch());
}
/// \brief Iterator to one pass the end of a row
row_iterator row_end(size_type i) { return row_begin(i) + ncol_; }
/// \brief Iterator to one pass the end of a row
const_row_iterator row_end(size_type i) const { return row_cend(i); }
/// \brief Iterator to one pass the end of a row
const_row_iterator row_cend(size_type i) const
{
return row_cbegin(i) + ncol_;
}
/// \brief Iterator to the end of a row
reverse_row_iterator row_rbegin(size_type i)
{
return reverse_row_iterator(row_end(i));
}
/// \brief Iterator to the end of a row
const_reverse_row_iterator row_rbegin(size_type i) const
{
return row_crbegin(i);
}
/// \brief Iterator to the end of a row
const_reverse_row_iterator row_crbegin(size_type i) const
{
return const_reverse_row_iterator(row_cend(i));
}
/// \brief Iterator to one before the beginning of a row
reverse_row_iterator row_rend(size_type i)
{
return reverse_row_iterator(row_begin(i));
}
/// \brief Iterator to one before the beginning of a row
const_reverse_row_iterator row_rend(size_type i) const
{
return row_crend(i);
}
/// \brief Iterator to one before the beginning of a row
const_reverse_row_iterator row_crend(size_type i) const
{
return const_reverse_row_iterator(row_cbegin(i));
}
/// \brief Iterator to the beginning of a column
col_iterator col_begin(size_type i)
{
return col_begin_dispatch(i, layout_dispatch());
}
/// \brief Iterator to the beginning of a column
const_col_iterator col_begin(size_type j) const { return col_cbegin(j); }
/// \brief Iterator to the beginning of a column
const_col_iterator col_cbegin(size_type j) const
{
return col_begin_dispatch(j, layout_dispatch());
}
/// \brief Iterator to one pass the end of a column
col_iterator col_end(size_type j) { return col_begin(j) + nrow_; }
/// \brief Iterator to one pass the end of a column
const_col_iterator col_end(size_type j) const { return col_cend(j); }
/// \brief Iterator to one pass the end of a column
const_col_iterator col_cend(size_type j) const
{
return col_cbegin(j) + nrow_;
}
/// \brief Iterator to the end of a column
reverse_col_iterator col_rbegin(size_type j)
{
return reverse_col_iterator(col_end(j));
}
/// \brief Iterator to the end of a column
const_reverse_col_iterator col_rbegin(size_type j) const
{
return col_crbegin(j);
}
/// \brief Iterator to the end of a column
const_reverse_col_iterator col_crbegin(size_type j) const
{
return const_reverse_col_iterator(col_cend(j));
}
/// \brief Iterator to one before the beginning of a column
reverse_col_iterator col_rend(size_type j)
{
return reverse_col_iterator(col_begin(j));
}
/// \brief Iterator to one before the beginning of a column
const_reverse_col_iterator col_rend(size_type j) const
{
return col_crend(j);
}
/// \brief Iterator to one before the beginning of a column
const_reverse_col_iterator col_crend(size_type j) const
{
return const_reverse_col_iterator(col_cbegin(j));
}
/// \brief Range of a row
row_range row(size_type i) { return row_range(row_begin(i), row_end(i)); }
/// \brief Range of a row
const_row_range row(size_type i) const
{
return const_row_range(row_begin(i), row_end(i));
}
/// \brief Range of a row
const_row_range crow(size_type i) const
{
return const_row_range(row_cbegin(i), row_cend(i));
}
/// \brief Range of a row in reverse order
reverse_row_range rrow(size_type i)
{
return reverse_row_range(row_rbegin(i), row_rend(i));
}
/// \brief Range of a row in reverse order
const_reverse_row_range rrow(size_type i) const
{
return const_reverse_row_range(row_rbegin(i), row_rend(i));
}
/// \brief Range of a row in reverse order
const_reverse_row_range crrow(size_type i) const
{
return const_reverse_row_range(row_crbegin(i), row_crend(i));
}
/// \brief Range of a column
col_range col(size_type i) { return col_range(col_begin(i), col_end(i)); }
/// \brief Range of a column
const_col_range col(size_type i) const
{
return const_col_range(col_begin(i), col_end(i));
}
/// \brief Range of a column
const_col_range ccol(size_type i) const
{
return const_col_range(col_cbegin(i), col_cend(i));
}
/// \brief Range of a column in reverse order
reverse_col_range rcol(size_type i)
{
return reverse_col_range(col_rbegin(i), col_rend(i));
}
/// \brief Range of a column in reverse order
const_reverse_col_range rcol(size_type i) const
{
return const_reverse_col_range(col_rbegin(i), col_rend(i));
}
/// \brief Range of a column in reverse order
const_reverse_col_range crcol(size_type i) const
{
return const_reverse_col_range(col_crbegin(i), col_crend(i));
}
/// \brief Access an element in the matrix with bound checking
reference at(size_type i, size_type j)
{
runtime_assert<std::out_of_range>(
i < nrow_, "**Matrix::at** row index out of range");
runtime_assert<std::out_of_range>(
j < ncol_, "**Matrix::at** column index out of range");
return at_dispatch(i, j, layout_dispatch());
}
/// \brief Access an element in the matrix with bound checking
const_reference at(size_type i, size_type j) const
{
runtime_assert<std::out_of_range>(
i < nrow_, "**Matrix::at** row index out of range");
runtime_assert<std::out_of_range>(
j < ncol_, "**Matrix::at** column index out of range");
return at_dispatch(i, j, layout_dispatch());
}
/// \brief Access an element in the matrix
reference operator()(size_type i, size_type j)
{
return at_dispatch(i, j, layout_dispatch());
}
/// \brief Access an element in the matrix
const_reference operator()(size_type i, size_type j) const
{
return at_dispatch(i, j, layout_dispatch());
}
/// \brief Pointer to the upper left corner of the matrix
pointer data() { return data_.data(); }
/// \brief Pointer to the upper left corner of the matrix
const_pointer data() const { return data_.data(); }
/// \brief Pointer to the first element of a row
pointer row_data(size_type i)
{
return row_data_dispatch(i, layout_dispatch());
}
/// \brief Pointer to the first element of a row
const_pointer row_data(size_type i) const
{
return row_data_dispatch(i, layout_dispatch());
}
/// \brief The stride of row-wise access through `row_data()`
size_type row_stride() const
{
return row_stride_dispatch(layout_dispatch());
}
/// \brief Pointer to the beginning of a column
pointer col_data(size_type j)
{
return col_data_dispatch(j, layout_dispatch());
}
/// \brief Pointer to the beginning of a column
const_pointer col_data(size_type j) const
{
return col_data_dispatch(j, layout_dispatch());
}
/// \brief The stride size of column-wise access through `col_data()`
size_type col_stride() const
{
return col_stride_dispatch(layout_dispatch());
}
/// \brief The layout of the matrix
static constexpr MatrixLayout layout() { return Layout; }
/// \brief If the matrix is empty, i.e., `nrow() * ncol() == 0`
bool empty() const { return nrow_ == 0 || ncol_ == 0; }
/// \brief The number of rows
size_type nrow() const { return nrow_; }
/// \brief The number of columns
size_type ncol() const { return ncol_; }
/// \brief The number of elements in the leading dimension
size_type ldim() const { return ldim_dispatch(layout_dispatch()); }
/// \brief The total number of elements
size_type size() const { return nrow_ * ncol_; }
/// \brief Reserve storage space for the matrix
void reserve(size_type n, size_type m) { data_.reserve(n * m); }
/// \brief Resize the matrix
///
/// \details
/// Let the orignal be a \f$p\f$ by \f$q\f$ matrix and the new matrix be of
/// dimensions \f$s\f$ by \f$t\f$. Then the sub-matrix at the upper left
/// corner, of dimensions \f$n = \min\{p,s\}\f$ by \f$m = \min\{q,t\}\f$
/// has its original values.
void resize(size_type nrow, size_type ncol)
{
if (nrow * ncol == 0) {
data_.clear();
nrow_ = nrow;
ncol_ = ncol;
return;
}
if (nrow == nrow_ && ncol_ == ncol) {
return;
}
resize_dispatch(nrow, ncol, layout_dispatch());
}
/// \brief Release memory no longer needed
void shrink_to_fit() { data_.shrink_to_fit(); }
/// \brief Clear the matrix of all elements
void clear()
{
data_.clear();
nrow_ = 0;
ncol_ = 0;
}
/// \brief Insert a new row at the bottom
template <typename InputIter>
void push_back_row(InputIter first)
{
resize(nrow_ + 1, ncol_);
std::copy_n(first, ncol_, row_begin(nrow_ - 1));
}
/// \brief Insert a new coloumn at the right
template <typename InputIter>
void push_back_col(InputIter first)
{
resize(nrow_, ncol_ + 1);
std::copy_n(first, nrow_, col_begin(ncol_ - 1));
}
/// \brief Swap two matrices
void swap(Matrix &other) noexcept(noexcept(data_.swap(other.data_)))
{
std::swap(nrow_, other.nrow_);
std::swap(ncol_, other.ncol_);
data_.swap(other.data_);
}
/// \brief Swap two matrices
friend void swap(Matrix &m1, Matrix &m2) noexcept(noexcept(m1.swap(m2)))
{
m1.swap(m2);
}
/// \brief Compare equality
friend bool operator==(const Matrix &m1, const Matrix &m2)
{
if (m1.nrow_ != m2.nrow_) {
return false;
}
if (m1.ncol_ != m2.ncol_) {
return false;
}
return m1.data_ == m2.data_;
}
/// \brief Compare inequality
friend bool operator!=(const Matrix &m1, const Matrix &m2)
{
return !(m1 == m2);
}
/// \brief Compare equality
friend bool is_equal(const Matrix &m1, const Matrix &m2)
{
if (m1.nrow_ != m2.nrow_) {
return false;
}
if (m1.ncol_ != m2.ncol_) {
return false;
}
return is_equal(m1.data_, m2.data_);
}
private:
std::size_t nrow_;
std::size_t ncol_;
// Layout == RowMajor
size_type ldim_dispatch(row_major) const { return ncol_; }
pointer row_begin_dispatch(size_type i, row_major) { return row_data(i); }
const_pointer row_begin_dispatch(size_type i, row_major) const
{
return row_data(i);
}
StepIterator<pointer> col_begin_dispatch(size_type j, row_major)
{
return StepIterator<pointer>(
col_data(j), static_cast<difference_type>(col_stride()));
}
StepIterator<const_pointer> col_begin_dispatch(
size_type j, row_major) const
{
return StepIterator<const_pointer>(
col_data(j), static_cast<difference_type>(col_stride()));
}
reference at_dispatch(size_type i, size_type j, row_major)
{
return data_[i * ncol_ + j];
}
const_reference at_dispatch(size_type i, size_type j, row_major) const
{
return data_[i * ncol_ + j];
}
size_type row_stride_dispatch(row_major) const { return 1; }
pointer row_data_dispatch(size_type i, row_major)
{
return data() + i * ncol_;
}
const_pointer row_data_dispatch(size_type i, row_major) const
{
return data() + i * ncol_;
}
size_type col_stride_dispatch(row_major) const { return ncol_; }
pointer col_data_dispatch(size_type j, row_major) { return data() + j; }
const_pointer col_data_dispatch(size_type j, row_major) const
{
return data() + j;
}
void resize_dispatch(size_type nrow, size_type ncol, row_major)
{
if (ncol == ncol_) {
data_.resize(nrow * ncol);
nrow_ = nrow;
return;
}
Matrix tmp(nrow, ncol);
const size_type n = std::min(nrow, nrow_);
const size_type m = std::min(ncol, ncol_);
for (size_type i = 0; i != n; ++i) {
std::copy_n(row_data(i), m, tmp.row_data(i));
}
swap(tmp);
}
// Layout == ColMajor
size_type ldim_dispatch(col_major) const { return nrow_; }
StepIterator<pointer> row_begin_dispatch(size_type i, col_major)
{
return StepIterator<pointer>(
row_data(i), static_cast<difference_type>(row_stride()));
}
StepIterator<const_pointer> row_begin_dispatch(
size_type i, col_major) const
{
return StepIterator<const_pointer>(
row_data(i), static_cast<difference_type>(row_stride()));
}
pointer col_begin_dispatch(size_type j, col_major) { return col_data(j); }
const_pointer col_begin_dispatch(size_type j, col_major) const
{
return col_data(j);
}
reference at_dispatch(size_type i, size_type j, col_major)
{
return data_[j * nrow_ + i];
}
const_reference at_dispatch(size_type i, size_type j, col_major) const
{
return data_[j * nrow_ + i];
}
size_type row_stride_dispatch(col_major) const { return nrow_; }
pointer row_data_dispatch(size_type i, col_major) { return data() + i; }
const_pointer row_data_dispatch(size_type i, col_major) const
{
return data() + i;
}
size_type col_stride_dispatch(col_major) const { return 1; }
pointer col_data_dispatch(size_type j, col_major)
{
return data() + j * nrow_;
}
const_pointer col_data_dispatch(size_type j, col_major) const
{
return data() + j * nrow_;
}
void resize_dispatch(size_type nrow, size_type ncol, col_major)
{
if (nrow == nrow_) {
data_.resize(nrow * ncol);
ncol_ = ncol;
return;
}
Matrix tmp(nrow, ncol);
const size_type n = std::min(nrow, nrow_);
const size_type m = std::min(ncol, ncol_);
for (size_type i = 0; i != m; ++i) {
std::copy_n(col_data(i), n, tmp.col_data(i));
}
swap(tmp);
}
}; // class Matrix
/// \brief Output operator
template <typename CharT, typename Traits, typename T, MatrixLayout Layout,
typename Alloc>
inline std::basic_ostream<CharT, Traits> &operator<<(
std::basic_ostream<CharT, Traits> &os, const Matrix<T, Layout, Alloc> &mat)
{
if (!os) {
return os;
}
os << mat.nrow() << ' ' << mat.ncol();
if (!os) {
return os;
}
for (std::size_t j = 0; j != mat.ncol(); ++j) {
for (std::size_t i = 0; i != mat.nrow(); ++i) {
os << ' ' << mat(i, j);
}
}
return os;
}
/// \brief Input operator
template <typename CharT, typename Traits, typename T, MatrixLayout Layout,
typename Alloc>
inline std::basic_istream<CharT, Traits> &operator>>(
std::basic_istream<CharT, Traits> &is, Matrix<T, Layout, Alloc> &mat)
{
if (!is) {
return is;
}
std::size_t nrow = 0;
std::size_t ncol = 0;
is >> nrow >> std::ws >> ncol;
if (!is) {
return is;
}
Matrix<T, Layout, Alloc> tmp(nrow, ncol);
for (std::size_t j = 0; j != mat.ncol(); ++j) {
for (std::size_t i = 0; i != mat.nrow(); ++i) {
is >> std::ws >> tmp(i, j);
}
}
if (is) {
mat = std::move(tmp);
}
return is;
}
} // namespace mckl
#endif // MCKL_CORE_MATRIX_HPP
|
27ba6bd9cdd88724a92634c0dbaf2a1b52cdaa8f | 2981b933db2c279dde0081134c9fedc53ee08d1f | /ROTATION.cpp | 2ff106cd0c419f7a8b7eedc074bba1720e244dc3 | [] | no_license | gcnit/Competitive-Programming | 4a7a1adde5549cf5e1bd4917c9c8755ecb6a933a | 1482aec39a4dcf01f68229f4d517ba3851dadb46 | refs/heads/master | 2020-04-06T03:41:55.467473 | 2014-10-24T08:09:26 | 2014-10-24T08:09:26 | 25,677,951 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | ROTATION.cpp | #include<cstdio>
#define ll long long int
using namespace std;
int main()
{
ll n,m,i,x,d,y;
scanf("%lld %lld",&n,&m);
ll a[n+10];
char s[10];
for(i=1;i<=n;i++)
{
scanf("%lld",&a[i]);
}
x=0;
for(i=0;i<m;i++)
{
scanf("%s %lld",s,&d);
if(s[0]=='C')
x+=d;
else if(s[0]=='A')
x-=d;
else
{
y=((x+d)%n+n)%n;
if(!y) y+=n;
printf("%lld\n",a[y]);
}
}
return 0;
}
|
4aadd9aa2f5296853ee6f13fa00f1df9129234d8 | 2c82ed4682022dddeff70b7163993412101f002c | /project/test_makefile/test.cpp | 89b4c3080135d7b907ebb679cf27a8992134b916 | [] | no_license | wd-cell/Wproject | e06b848520effb349e283b6991b08f8b514441aa | 2477590566716c7fc5793ce45b60777985728ed7 | refs/heads/master | 2022-12-23T03:00:16.149054 | 2020-10-03T08:59:20 | 2020-10-03T08:59:20 | 287,028,051 | 1 | 0 | null | 2020-08-14T13:29:56 | 2020-08-12T13:58:11 | C++ | UTF-8 | C++ | false | false | 74 | cpp | test.cpp | #include "hello.h"
#include "bye.h"
int main(){
hello();
bye();
} |
406d3df2b86bf4885f879a2a89221f02be008e24 | cd45a5a20de51f9e2e829a027045e927e63e4c16 | /apps/vaporgui/VSection.h | 24b30a192f67032e4896ff927c5ed7cffbb7f158 | [] | no_license | StasJ/vapor-formatted | b98f55c6528827122bf191c72be5a2165253d1cc | 9fad47d88714ef835b78f6c1dd855d66b6aa90da | refs/heads/master | 2022-12-05T22:29:23.048696 | 2020-08-13T21:05:11 | 2020-08-13T21:05:11 | 287,616,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,162 | h | VSection.h | #pragma once
#include <QStackedWidget>
#include <QTabWidget>
#include <QVBoxLayout>
#include <string>
#include <QToolButton>
//! \class VSection
//! Represents a section/group to be used in the sidebar.
//! Provides a consistent layout which is not supposed to be changed
//! Provides a settings menu that is intended to provide extra options for the parameters that are
//! shown within this section, for example resetting to default values.
class VSection : public QTabWidget {
Q_OBJECT
class SettingsMenuButton;
public:
VSection(const std::string &title);
QVBoxLayout *layout() const;
void setMenu(QMenu *menu);
void setLayout(QLayout *layout) = delete;
int addTab(QWidget *page, const QString &label) = delete;
QWidget *widget(int index) const = delete;
void setCornerWidget(QWidget *widget, Qt::Corner corner) = delete;
QWidget *cornerWidget() const = delete;
private:
QWidget *_tab() const;
QString _createStylesheet() const;
};
class VSection::SettingsMenuButton : public QToolButton {
Q_OBJECT
public:
SettingsMenuButton();
protected:
void paintEvent(QPaintEvent *event);
};
|
4b80dd85215ce4dd564c75b84affb194d332e4d4 | cf11d33291d1aa0d20bbf14203a4b5bedb089ae9 | /hw5/g.cpp | a0cb4ca33e9c703aa3b9d84fb3ae28302bc547e0 | [] | no_license | HyeokyYun/2021-2_Computer-Vision | de059fd1cb457c3233e95d56323a29e5432bf811 | 6f3454417b8f6072a42782ecdd7661fda8e0f9e2 | refs/heads/master | 2023-08-27T10:36:45.513784 | 2021-11-10T09:36:45 | 2021-11-10T09:36:45 | 409,425,685 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,349 | cpp | g.cpp | #include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main()
{
Mat lena, colorful, balancing;
Mat lena_channels[3];
Mat colorful_channels[3];
Mat balancing_channels[3];
lena = imread("lena.png");
colorful = imread("colorful.jpg");
balancing = imread("balancing.jpg");
int key;
int row, col;
int total_B, total_G, total_R, average_B, average_G, average_R;
int hue;
//For gamma transformation
MatIterator_<uchar> it, end;
float gamma;
unsigned char pix[256]; //pixel type
while (1)
{
imshow("lena", lena);
imshow("colorful", colorful);
imshow("balancing", balancing);
key = waitKey();
switch (key)
{
// lena
case 110: //n: Negative transformation
cvtColor(lena, lena, CV_BGR2HSV);
split(lena, lena_channels);
for (row = 0; row < lena.rows; row++)
{
for (col = 0; col < lena.cols; col++)
{
lena_channels[2].at<uchar>(row, col) = 255 - lena_channels[2].at<uchar>(row, col);
}
}
merge(lena_channels, 3, lena);
cvtColor(lena, lena, CV_HSV2BGR);
break;
case 103: //g: gamma transformation
cvtColor(lena, lena, CV_BGR2HSV);
split(lena, lena_channels);
gamma = 2.5f;
for (int i = 0; i < 256; i++)
pix[i] = (uchar)(pow((float)(i / 255.0), gamma) * 255.0f); //pre compute possible case
for (it = lena_channels[2].begin<uchar>(), end = lena_channels[2].end<uchar>(); it != end; it++)
*it = pix[(*it)];
merge(lena_channels, 3, lena);
cvtColor(lena, lena, CV_HSV2BGR);
break;
case 104: //h: Histogram equalization
cvtColor(lena, lena, CV_BGR2HSV);
split(lena, lena_channels);
equalizeHist(lena_channels[2], lena_channels[2]); // equalize V of HSV
merge(lena_channels, 3, lena);
cvtColor(lena, lena, CV_HSV2BGR);
break;
// colorful
case 115: //s: Color Slicing
cvtColor(colorful, colorful, CV_BGR2HSV);
split(colorful, colorful_channels);
for (row = 0; row < colorful.rows; row++)
{
for (col = 0; col < colorful.cols; col++)
{
hue = colorful_channels[0].at<uchar>(row, col);
if (hue <= 9 || hue >= 23)
colorful_channels[1].at<uchar>(row, col) = 0;
}
}
merge(colorful_channels, 3, colorful);
cvtColor(colorful, colorful, CV_HSV2BGR);
break;
case 99: //c: Color Conversion
cvtColor(colorful, colorful, CV_BGR2HSV);
split(colorful, colorful_channels);
for (row = 0; row < colorful.rows; row++)
{
for (col = 0; col < colorful.cols; col++)
{
if (colorful_channels[0].at<uchar>(row, col) < 129)
colorful_channels[0].at<uchar>(row, col) = colorful_channels[0].at<uchar>(row, col) + 50;
else
colorful_channels[0].at<uchar>(row, col) = colorful_channels[0].at<uchar>(row, col) - 129;
}
}
merge(colorful_channels, 3, colorful);
cvtColor(colorful, colorful, CV_HSV2BGR);
break;
// balancing
case 97: //a: Average filtering
cvtColor(balancing, balancing, CV_BGR2HSV);
split(balancing, balancing_channels);
blur(balancing_channels[2], balancing_channels[2], Size(9, 9));
merge(balancing_channels, 3, balancing);
cvtColor(balancing, balancing, CV_HSV2BGR);
break;
case 119: //w: White balancing
total_B = 0;
total_G = 0;
total_R = 0;
for (row = 0; row < balancing.rows; row++)
{
for (col = 0; col < balancing.cols; col++)
{
total_B = total_B + balancing.at<Vec3b>(row, col)[0];
total_G = total_G + balancing.at<Vec3b>(row, col)[1];
total_R = total_R + balancing.at<Vec3b>(row, col)[2];
}
}
average_B = total_B / (balancing.rows * balancing.cols);
average_G = total_G / (balancing.rows * balancing.cols);
average_R = total_R / (balancing.rows * balancing.cols);
for (row = 0; row < balancing.rows; row++)
{
for (col = 0; col < balancing.cols; col++)
{
balancing.at<Vec3b>(row, col)[0] = balancing.at<Vec3b>(row, col)[0] * 128 / average_B;
balancing.at<Vec3b>(row, col)[1] = balancing.at<Vec3b>(row, col)[1] * 128 / average_G;
balancing.at<Vec3b>(row, col)[2] = balancing.at<Vec3b>(row, col)[2] * 128 / average_R;
}
}
break;
// reset
case 114: //r: reset all
lena = imread("lena.png");
colorful = imread("colorful.jpg");
balancing = imread("balancing.jpg");
break;
//exit
case 27: //esc
cout << "esc" << endl;
return 0;
}
}
} |
21f4990a899d4342eda3d8862ed58de8e4524335 | 76e33a3929e485f32e3a960874ffa782c5c13a43 | /Solution/HappyClinic/CreateUsers.h | e84773d9e032a3a550db49518a42ff92de85f62f | [] | no_license | LocoBukkake/HappyClinic-master | 94014b9baf064a05246085724dec78cdfebf6d02 | 23900c51aff7fe9f387d331570634a26473b5d81 | refs/heads/main | 2023-05-08T19:07:13.161005 | 2021-05-26T16:17:40 | 2021-05-26T16:17:40 | 371,097,986 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 594 | h | CreateUsers.h | #pragma once
#include "CreateUsers.g.h"
namespace winrt::HappyClinic::implementation
{
struct CreateUsers : CreateUsersT<CreateUsers>
{
CreateUsers();
int32_t MyProperty();
void MyProperty(int32_t value);
winrt::Windows::Foundation::IAsyncAction registerSubmitButton_Click(
winrt::Windows::Foundation::IInspectable const& sender,
winrt::Windows::UI::Xaml::RoutedEventArgs const& e);
};
}
namespace winrt::HappyClinic::factory_implementation
{
struct CreateUsers : CreateUsersT<CreateUsers, implementation::CreateUsers>
{
};
}
|
d17612e8b072f0ff3c337debf9dfd8a85924be46 | 4defc4ee020b1781e27e2f29efbc8c41a98afa7f | /OBE/MMITSS_OBE_MAP_SPAT_Receiver_Field/src/MMITSS_OBE_MAP_SPAT_Receiver_ASN.cpp | 4ba658fb335947218c3db54321f388b743530e8c | [
"Apache-2.0"
] | permissive | OSADP/MMITSS_AZ_FIELD | 6ec44a557bab83081e7d4ee9f2eb0c5ab64bc94c | b4c870061c518eddfa0152938ab60abc2a31023f | refs/heads/master | 2021-03-22T04:44:42.485482 | 2016-08-23T23:35:33 | 2016-08-23T23:35:33 | 39,451,330 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 35,403 | cpp | MMITSS_OBE_MAP_SPAT_Receiver_ASN.cpp | // Receive RNDF map, Request List and Signal status from RSU through DSRC
// Need "rsu_msg_transmitter" running in RSUs
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <iostream>
#include <string>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <sstream>
#include <istream>
#include "math.h"
#include <sys/time.h>
#include <iomanip>
#include "LinkedList.h"
#include <time.h>
#include "NMAP.h"
#include "geoCoord.h"
#include <asn_application.h>
#include <asn_internal.h>/* for _ASN_DEFAULT_STACK_MAX */
#include <SPAT.h>
#include <MAP.h>
#define MAX_BUFLEN_MAP 1999
#define NUM_MM_STS 8
#ifndef byte
#define byte char // needed if byte not defined
#endif
#define FLOAT2INT 10.0
using namespace std;
char logfilename[256] = "/nojournal/bin/log/obu_listener_V2_";
char recv_buf[MAX_BUFLEN_MAP];
//socket settings
//#define PORT 5799
#define PORT 15030
#define PORT_ART 15040
#define BROADCAST_ADDR "192.168.101.255"
#define numPhases 8
//*** The ACTIVE is for RNDF file. ***//
#define EV 1
#define TRANSIT 2
#define ACTIVE 1
#define LEAVE 0
#define NOT_ACTIVE -1
#ifndef UNIT_CHANGE_VALUE
#define UNIT_CHANGE_VALUE 1000000 // needed if byte not defined
#endif
int Global;
const long timeinterval=30; // For determining if the rndf entry is obsolete
char predir [64] = "/nojournal/bin/";
char rndf_file[128]="/nojournal/bin/RNDF.txt";
char active_rndf_file[128]="/nojournal/bin/ActiveRNDF.txt";
char signalfilename[128] = "/nojournal/bin/signal_status.txt";
char temp_log[1024];
char map_files[128]="/nojournal/bin/Intersection_maps.txt";
char active_map_file[64]="/nojournal/bin/ActiveMAP.txt";
char ART_File_Name[64]= "/nojournal/bin/psm.txt";
char tmp_log[512];
class Intersection_ID
{
public:
long ID;
long Time; //The time this map is received
};
LinkedList <Intersection_ID> Intersection_ID_list; //Stores the intersection ID of all intersections
double GetSeconds(); // Get the current time: seconds in float point number
char *GetDate(); // Get the current date as: "Sat May 20 15:21:51 2000"
void split(string &s1, string &s2, char delim);
void xTimeStamp( char * pc_TimeStamp_ );
int outputlog(char *output);
void printmap_to_file(MAP_t *MapType,char *filename);
int print_Sig_Status(SPAT_t *spatType, char *filename);
//int printspat(J2735SPATMsg_t *spat);
int FindActiveMap(); //find the active map id
int field_flag=0; //0: in the lab 1: in the field
//unpack ART message and save to requests_combined.txt
void Unpack_ART(byte* ablob, char * filename);
bool is_empty(std::ifstream& pFile);
void flipEndian (char *buf, int size) {
int start, end;
for (start = 0, end = size - 1; start < end; start++, end--) {
buf[start] = buf[start] ^ buf[end];
buf[end] = buf[start] ^ buf[end];
buf[start] = buf[start] ^ buf[end];
}
}
int active_map_id=0;
int main ( int argc, char* argv[] )
{
if (argc>=2) {sscanf(argv[1],"%d",&field_flag);}
//Struct for UDP socket timeout: 1s
struct timeval tv;
tv.tv_sec = 3;
tv.tv_usec = 0;
//Struct for UDP socket timeout: 1s
struct timeval tv_ART;
tv_ART.tv_sec = 0;
tv_ART.tv_usec = 10000;
int i,j;
//Init log file
//------log file name with Time stamp-----------------------//
char timestamp[128];
char tt[256];
char strbuf[256];
xTimeStamp(timestamp);
strcat(logfilename,timestamp);
strcat(logfilename,".log");
//------end log file name-----------------------------------//
//----init requests.txt and RNDF.txt-------------------------//
char temp2[64];
sprintf(temp2,"Num_req -1 0");
//--strcpy(tt,""); strcat(tt,predir); strcat(tt,"requests.txt");
fstream fs_req;
fs_req.open(ART_File_Name, ios::out | ios::trunc );
fs_req<<temp2;
fs_req.close();
//----Delete all old ***.rndf files----------//
system("\\rm -f /nojournal/bin/*.rndf");
fstream fs_rndf;
fs_rndf.open(rndf_file, ios::out | ios::trunc );
fs_rndf.close();
fstream fs_active_rndf;
fs_active_rndf.open(active_rndf_file, ios::out | ios::trunc );
fs_active_rndf.close();
//------------------------------------------------------//
fstream fs;
fs.open(logfilename, ios::out | ios::trunc );
fs << "obugid is running...." << GetDate();
cout << "obugid is running....\n";
int sockfd;
char pBuf[256];
char sendMSG[256];
struct sockaddr_in sendaddr;
struct sockaddr_in recvaddr;
int numbytes;
int numbytes_ART;
int addr_len;
int broadcast=1;
if((sockfd = socket(PF_INET,SOCK_DGRAM,0)) == -1)
{
perror("sockfd");
exit(1);
}
//Setup time out
if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {
perror("Error");
}
if((setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,
&broadcast,sizeof broadcast)) == -1)
{
perror("setsockopt - SO_SOCKET ");
exit(1);
}
sendaddr.sin_family = AF_INET;
sendaddr.sin_port = htons(PORT);
sendaddr.sin_addr.s_addr = INADDR_ANY;//inet_addr(BROADCAST_ADDR) ; //INADDR_BROADCAST;
memset(sendaddr.sin_zero,'\0',sizeof sendaddr.sin_zero);
if(bind(sockfd, (struct sockaddr*) &sendaddr, sizeof sendaddr) == -1)
{
perror("bind");
exit(1);
}
addr_len = sizeof ( sendaddr );
int sockfd_ART;
struct sockaddr_in sendaddr_ART;
if((sockfd_ART = socket(PF_INET,SOCK_DGRAM,0)) == -1)
{
perror("sockfd");
exit(1);
}
//Setup time out
if (setsockopt(sockfd_ART, SOL_SOCKET, SO_RCVTIMEO,&tv_ART,sizeof(tv_ART)) < 0) {
perror("Error");
}
sendaddr_ART.sin_family = AF_INET;
sendaddr_ART.sin_port = htons(PORT_ART);
sendaddr_ART.sin_addr.s_addr = INADDR_ANY;//inet_addr(BROADCAST_ADDR) ; //INADDR_BROADCAST;
memset(sendaddr_ART.sin_zero,'\0',sizeof sendaddr_ART.sin_zero);
if(bind(sockfd_ART, (struct sockaddr*) &sendaddr_ART, sizeof sendaddr_ART) == -1)
{
perror("bind");
exit(1);
}
int ret;
int count=0;
while ( true )
{
//Find active map
active_map_id=FindActiveMap();
cout<<"Active map is: "<<active_map_id<<endl;
int flag_map=0;
//cout<<"Receive the data from RSU"<<endl;
// -------------------------Receive the data from RSU-------------------------//
numbytes = recvfrom(sockfd, recv_buf, sizeof recv_buf, 0,(struct sockaddr *)&sendaddr, (socklen_t *)&addr_len);
if(numbytes>=0)
{
cout<<"Received data number: "<<count++<<endl;
}
SPAT_t * spatType_decode=0;
spatType_decode=(SPAT_t *)calloc(1,sizeof(SPAT_t));
asn_dec_rval_t rval;
rval=ber_decode(0, &asn_DEF_SPAT,(void **)&spatType_decode, recv_buf, MAX_BUFLEN_MAP);
if ( rval.code==RC_OK)
{
printf("SPAT: Decode Sucess\n");
// printspat(&spat);
//print signal status
flag_map=0;
//get intersection id
unsigned char ByteA=spatType_decode->intersections.list.array[0]->id.buf[0];
unsigned char ByteB=spatType_decode->intersections.list.array[0]->id.buf[1];
int intersection_id= (int) (((ByteB << 8) + (ByteA)));
if (intersection_id==active_map_id)
print_Sig_Status(spatType_decode,signalfilename); //need to be changed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
if (Intersection_ID_list.ListSize()==1)
print_Sig_Status(spatType_decode,signalfilename); //need to be changed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
else
{
printf("SPAT: Decode Failure\n");
flag_map=1;
}
if(flag_map==1 && numbytes>=0) //Received MAP Message, not a SPAT
{
//sprintf(temp_log,"Received MAP Message size %d\n",numbytes);
//outputlog(temp_log); cout<<temp_log;
MAP_t * Map_decoder=0;
Map_decoder=(MAP_t *)calloc(1,sizeof(MAP_t));
int decode_map_flag=0; //indicate whether the map message is decoded successfully
//~ for(int ii=0;ii<MAX_BUFLEN_MAP;ii++)
//~ {
//~ printf("%2x ",(unsigned char)recv_buf[ii]);
//~ if(ii%16==15 && ii>0){
//~ printf("\n");}
//~ }
// Calculating the length of the message taking the 2nd and 3rd bytes of the buffer. (after 0th and 1st bytes)
//numbytes = *(int *)(recv_buf);
//flipEndian ((char *)(&numbytes), 4);
//numbytes &= 0xFFFF;
//numbytes += 4;
sprintf(temp_log,"Parsing MAP Message size %d\n",numbytes);
outputlog(temp_log); cout<<temp_log;
asn_dec_rval_t rval;
rval=ber_decode(0, &asn_DEF_MAP,(void **)&Map_decoder, recv_buf, numbytes);
if (rval.code==RC_OK) {
printf("MAP: Decode Success!\n");
decode_map_flag=1;
} else {
printf("MAP: Decode Failure\n");
decode_map_flag=0;
}
if(decode_map_flag==1) //only decode map successfully
{
int found=0;
//printmap(&j2735_map);
//get intersection id
unsigned char ByteA=Map_decoder->intersections.list.array[0]->id.buf[0];
unsigned char ByteB=Map_decoder->intersections.list.array[0]->id.buf[1];
int intersection_id= (int) (((ByteB << 8) + (ByteA)));
//Determine whether this is a new MAP
Intersection_ID_list.Reset();
while(!Intersection_ID_list.EndOfList())
{
if (Intersection_ID_list.Data().ID==intersection_id) //old map
{
found=1;
Intersection_ID_list.Data().Time=GetSeconds();
cout<<"This is not a new map!"<<endl;
break;
}
Intersection_ID_list.Next();
}
if(found==0) //This is a new map!!
{
//Add new map;
Intersection_ID tmp_Inter;
tmp_Inter.ID=intersection_id;
tmp_Inter.Time=GetSeconds();
Intersection_ID_list.InsertRear(tmp_Inter);
cout<<"Add new MAP!!!!"<<endl;
//Write the map structure to a text file
//Create the new map_file Name;
char map_file_name[128]="/nojournal/bin/Intersection_MAP_";
char tmp[16];
sprintf(tmp,"%d",intersection_id);
strcat(map_file_name,tmp);
strcat(map_file_name,".nmap");
cout<<"Intersection map name: "<<map_file_name<<endl;
printmap_to_file(Map_decoder,map_file_name); //Create a map description file. need to be changed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
//Delete the MAP if we didn't receive for 5 seconds
long current_time=GetSeconds();
Intersection_ID_list.Reset();
while(!Intersection_ID_list.EndOfList())
{
if (current_time-Intersection_ID_list.Data().Time>5)
Intersection_ID_list.DeleteAt();
Intersection_ID_list.Next();
}
cout<<"The current map list size is:"<<Intersection_ID_list.ListSize()<<endl;
//Write current map list to Intersection_maps.txt
fstream fs;
fs.open(map_files, ios::out);
if (!fs || !fs.good())
{
cout << "could not open file!\n";
}
Intersection_ID_list.Reset();
while(!Intersection_ID_list.EndOfList())
{
sprintf(tmp_log,"%d %ld -1\n",Intersection_ID_list.Data().ID,Intersection_ID_list.Data().Time);
fs<<tmp_log;
Intersection_ID_list.Next();
}
fs.close();
}
}
numbytes_ART = recvfrom(sockfd_ART, recv_buf, sizeof recv_buf, 0,(struct sockaddr *)&sendaddr_ART, (socklen_t *)&addr_len);
//cout<<"numbytes_ART "<<numbytes_ART<<endl;
if (numbytes_ART>0) //Received ART message
{
cout<<"Received ART Message!"<<endl;
//unpack received ART message and write to the file if the id is matched to the active map id.
Unpack_ART(recv_buf,ART_File_Name);
}
if (numbytes<0) //Didn't receive anything for 3 seconds
{
memset(&recv_buf[0], 0, sizeof(recv_buf)); //clear the buf if nothing received
Intersection_ID_list.ClearList(); //Clear the map list
fstream fs; //Clear the Intersection_maps.txt file
fs.open(map_files, ios::out|ios::trunc);
fs.close();
//clear the active_map.txt file
fs.open(active_map_file, ios::out|ios::trunc);
fs.close();
//clear the signal_status file if there is no active map
//ifstream f_active_map;
//f_active_map.open(active_map_file,ios::in);
//if(is_empty(f_active_map))
//{
fstream f_signal_status_file;
f_signal_status_file.open(signalfilename,ios::out|ios::trunc);
f_signal_status_file.close();
//Clear the request combined file
fstream req_com_file;
req_com_file.open(ART_File_Name,ios::out|ios::trunc);
req_com_file.close();
//}
//f_active_map.close();
}
}//while(true)
close(sockfd);
return 0;
}
bool is_empty(std::ifstream& pFile)
{
return pFile.peek() == std::ifstream::traits_type::eof();
}
void xTimeStamp( char * pc_TimeStamp_ )
{
struct tm * ps_Time;
time_t i_CurrentTime;
char ac_TmpStr[256];
i_CurrentTime = time(NULL);
ps_Time = localtime( &i_CurrentTime );
//year
sprintf(ac_TmpStr, "%d", ps_Time->tm_year + 1900);
strcpy(pc_TimeStamp_, ac_TmpStr);
//month
sprintf(ac_TmpStr, "_%d", ps_Time->tm_mon + 1 );
strcat(pc_TimeStamp_, ac_TmpStr);
//day
sprintf(ac_TmpStr, "_%d", ps_Time->tm_mday );
strcat(pc_TimeStamp_, ac_TmpStr);
//hour
sprintf(ac_TmpStr, "_%d", ps_Time->tm_hour );
strcat(pc_TimeStamp_, ac_TmpStr);
//min
sprintf(ac_TmpStr, "_%d", ps_Time->tm_min );
strcat(pc_TimeStamp_, ac_TmpStr);
//sec
sprintf(ac_TmpStr, "_%d", ps_Time->tm_sec );
strcat(pc_TimeStamp_, ac_TmpStr);
}
int outputlog(char *output)
{
FILE * stream = fopen( logfilename, "r" );
fseek( stream, 0L, SEEK_END );
long endPos = ftell( stream );
fclose( stream );
fstream fs;
if (endPos <1000000)
fs.open(logfilename, ios::out | ios::app);
else
fs.open(logfilename, ios::out | ios::trunc);
if (!fs || !fs.good())
{
cout << "could not open file!\n";
return -1;
}
fs << output;
if (fs.fail())
{
cout << "failed to append to file!\n";
return -1;
}
return 1;
}
void split(string &s1, string &s2, char delim)
{
size_t i;
i=s1.find_first_of(delim);
s2.append(s1, i+1, s1.size());
s1.erase(i, s1.size());
}
double GetSeconds()
{
struct timeval tv_tt;
gettimeofday(&tv_tt, NULL);
return (tv_tt.tv_sec+tv_tt.tv_usec/1.0e6);
}
char *GetDate()
{
time_t rawtime;
time ( &rawtime );
return ctime(&rawtime);
}
void printmap_to_file(MAP_t *MapType,char *filename)
{
int i,j,k,l;
char log[128];
fstream fs;
fs.open(filename, ios::out);
if (!fs || !fs.good())
{
cout << "could not open file!\n";
}
fs<<"MAP_Name\t"<< "Gaisy_Gav.nmap"<<endl;
fs<<"RSU_ID\t"<< "Gaisy_Gav"<<endl;
//Do intersection ID
unsigned char ByteA=MapType->intersections.list.array[0]->id.buf[0];
unsigned char ByteB=MapType->intersections.list.array[0]->id.buf[1];
int intersection_id= (int) (((ByteB << 8) + (ByteA)));
fs<<"IntersectionID\t"<<intersection_id<<endl;
fs<<"Intersection_attributes\t"<<"00110011"<<endl;
//Do reference Point
double latitude= (double)(MapType->intersections.list.array[0]->refPoint->lat)/UNIT_CHANGE_VALUE;
double longitude= (double) (MapType->intersections.list.array[0]->refPoint->Long)/UNIT_CHANGE_VALUE;
ByteA=MapType->intersections.list.array[0]->refPoint->elevation->buf[0];
ByteB=MapType->intersections.list.array[0]->refPoint->elevation->buf[1];
printf("%x %x ",ByteA,ByteB);
unsigned short elevation= (int) ((((ByteB+1) << 8) + (ByteA)));
sprintf(log,"Reference_point\t %lf %lf %d\n",latitude,longitude,elevation);
//init geo coord
geoCoord geoPoint;
double g_long, g_lat, g_altitude ;
double x_grid, y_grid, z_grid ;
double ecef_x,ecef_y,ecef_z;
//Important!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
//Note the rectangular coordinate system: local_x is N(+) S(-) side, and local_y is E(+) W(-) side
//This is relative distance to the ref point!!!!
//local z can be considered as 0 because no elevation change.
double local_x,local_y,local_z;
geoPoint.init(longitude, latitude, elevation/10);
fs<<log;
fs<<"No_Approach\t"<<"8"<<endl;
cout<<"Num_approaches "<<MapType->intersections.list.array[0]->approaches.list.count<<endl;
int missing_approach=0;
//find missing approach: for T intersections
if(MapType->intersections.list.array[0]->approaches.list.count<4) //There is missing approaches
{
for(i=0;i<MapType->intersections.list.array[0]->approaches.list.count;i++)
{
if(*MapType->intersections.list.array[0]->approaches.list.array[i]->approach->id!=i*2+1)
{
missing_approach=i*2+1;
break;
}
}
if(missing_approach==0) //less than 4 approaches, but here missing approach is zero, which means missing the last approach!!!!!!!!!!
{
missing_approach=7;
}
}
cout<<"Missing approach is:"<<missing_approach<<endl;
//Do each Approach
for(i=0;i<MapType->intersections.list.array[0]->approaches.list.count;i++) //There are only 4 approaches in J2735 MAP
{
int approach_id=*MapType->intersections.list.array[0]->approaches.list.array[i]->approach->id;
//add missing approach information to the map file here
if(missing_approach==i*2+1)
{
sprintf(log,"Approach\t %d\n",i*2+1);
fs<<log;
sprintf(log,"Approach_type\t 0\n");
fs<<log;
sprintf(log,"No_lane\t 0\n");
fs<<log;
fs<<"end_approach"<<endl;
sprintf(log,"Approach\t %d\n",i*2+2);
fs<<log;
sprintf(log,"Approach_type\t 0\n");
fs<<log;
sprintf(log,"No_lane\t 0\n");
fs<<log;
fs<<"end_approach"<<endl;
}
//Ingress lanes Odd Approaches
sprintf(log,"Approach\t %d\n",approach_id);
fs<<log;
sprintf(log,"Approach_type\t 1\n");
fs<<log;
int lane_no=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.count;
sprintf(log,"No_lane\t %d\n",lane_no);
cout<<"No of Lane is: "<<lane_no<<endl;
fs<<log;
//Do each ingress lane
for(j=0;j<lane_no;j++)
{
sprintf(log,"Lane\t %d.%d\n",approach_id,j+1);
fs<<log;
//Do lane ID;
ByteA=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneNumber.buf[0];
ByteB=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneNumber.buf[1];
unsigned short Lane_ID= (int) (((ByteB << 8) + (ByteA)));
sprintf(log,"Lane_ID\t %d\n",Lane_ID);
fs<<log;
sprintf(log,"Lane_type\t 1\n");
fs<<log;
if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==2)
sprintf(log,"Lane_attributes\t 0000000000100010\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==4)
sprintf(log,"Lane_attributes\t 000000000010100\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==8)
sprintf(log,"Lane_attributes\t 0000000000101000\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==6)
sprintf(log,"Lane_attributes\t 000000000010110\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==12)
sprintf(log,"Lane_attributes\t 0000000000101100\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==10)
sprintf(log,"Lane_attributes\t 0000000000101010\n");
else if (MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneAttributes==14)
sprintf(log,"Lane_attributes\t 0000000000101110\n");
else
sprintf(log,"Lane_attributes\t 0000000000100000\n"); //No movement avaialbe
fs<<log;
sprintf(log,"Lane_width\t %d\n",*MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->laneWidth);
fs<<log;
int num_way_points=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.count;
sprintf(log,"No_nodes\t %d\n",num_way_points);
fs<<log;
//do lane nodes
for(k=0;k<num_way_points;k++)
{
//transfer from local coordinates to GPS coordinates
unsigned char B0,B1,B2,B3;
B0=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[0];
B1=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[1];
B2=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[2];
B3=MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[3];
sprintf(tmp_log,"%x %x %x %x\n",MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[0],
MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[1],
MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[2],
MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[3]);
cout<<tmp_log;
int N_Offset_int, E_Offset_int;
N_Offset_int=(int)B0;
N_Offset_int=(N_Offset_int<<8)+(int)B1;
E_Offset_int=(int)B2;
E_Offset_int=(E_Offset_int<<8)+(int)B3;
sprintf(tmp_log,"N_Offset %d E_offset %d\n",N_Offset_int,E_Offset_int);
cout<<tmp_log;
double N_Offset=(double)(N_Offset_int-32768)/10;
double E_Offset=(double)(E_Offset_int-32768)/10;
geoPoint.local2ecef(N_Offset, E_Offset, elevation/10, &x_grid, &y_grid, &z_grid) ; // Third argument z=0.0 for vissim
geoPoint.ecef2lla(x_grid, y_grid, z_grid, &g_long, &g_lat, &g_altitude) ;
sprintf(log,"%d.%d.%d\t %lf %lf\n",approach_id,j+1,k+1,g_lat,g_long);
fs<<log;
}
//do connection lanes - only for approaching lanes
unsigned char C[4];
C[0]= MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->connectsTo->buf[0];
C[1]= MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->connectsTo->buf[1];
C[2]= MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->connectsTo->buf[2];
C[3]= MapType->intersections.list.array[0]->approaches.list.array[i]->approach->drivingLanes.list.array[j]->connectsTo->buf[3];
//No. of connection lane
int conn_lane_no=(int)C[0];
sprintf(log,"No_Conn_lane\t %d\n",conn_lane_no);
fs<<log;
for(int l=0;l<conn_lane_no;l++)
{
//printf("Connection lane: %d",mapdata->approaches[i].ingress_lanes[j].connects_to_lanes[l]);
int ten,one; //two digits of the connection lane
ten= (int) (C[l+1]/10);
one= C[l+1]%10;
sprintf(log,"%d.%d\t 0\n",ten,one); //THe movement manuevue is missing in the J2735 MAP, put 0
fs<<log;
}
fs<<"end_lane"<<endl;
}
fs<<"end_approach"<<endl;
//Do each egress lane
sprintf(log,"Approach\t %d\n",(*MapType->intersections.list.array[0]->approaches.list.array[i]->approach->id)+1);
fs<<log;
sprintf(log,"Approach_type\t 2\n");
fs<<log;
int lane_no_egress=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.count;
sprintf(log,"No_lane\t %d\n",lane_no_egress);
fs<<log;
for(j=0;j<lane_no_egress;j++)
{
sprintf(log,"Lane\t %d.%d\n",approach_id+1,j+1);
fs<<log;
//Do lane ID;
ByteA=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->laneNumber.buf[0];
ByteB=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->laneNumber.buf[1];
unsigned short Lane_ID_Egress= (int) (((ByteB << 8) + (ByteA)));
sprintf(log,"Lane_ID\t %d\n",Lane_ID_Egress);
fs<<log;
sprintf(log,"Lane_type\t 1\n");
fs<<log;
sprintf(log,"Lane_attributes\t 0000000001100011\n");
fs<<log;
sprintf(log,"Lane_width\t %d\n",*MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->laneWidth);
fs<<log;
int num_way_points_egress=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->nodeList.list.count;
sprintf(log,"No_nodes\t %d\n",num_way_points_egress);
fs<<log;
//do lane nodes
for(k=0;k<num_way_points_egress;k++)
{
//transfer from local coordinates to GPS coordinates
unsigned char B0,B1,B2,B3;
B0=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[0];
B1=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[1];
B2=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[2];
B3=MapType->intersections.list.array[0]->approaches.list.array[i]->egress->drivingLanes.list.array[j]->nodeList.list.array[k]->buf[3];
int N_Offset_int, E_Offset_int;
N_Offset_int=(int)B0;
N_Offset_int=(N_Offset_int<<8)+(int)B1;
E_Offset_int=(int)B2;
E_Offset_int=(E_Offset_int<<8)+(int)B3;
double N_Offset= (double)(N_Offset_int-32768)/10;
double E_Offset= (double)(E_Offset_int-32768)/10;
geoPoint.local2ecef(N_Offset, E_Offset, elevation/10, &x_grid, &y_grid, &z_grid) ; // Third argument z=0.0 for vissim
geoPoint.ecef2lla(x_grid, y_grid, z_grid, &g_long, &g_lat, &g_altitude) ;
sprintf(log,"%d.%d.%d\t %lf %lf\n",approach_id+1,j+1,k+1,g_lat,g_long);
fs<<log;
}
//do connection lanes
sprintf(log,"No_Conn_lane\t 0\n");
fs<<log;
fs<<"end_lane"<<endl;
}
fs<<"end_approach"<<endl;
}
if(MapType->intersections.list.array[0]->approaches.list.count<4 && missing_approach==7)
{
sprintf(log,"Approach\t %d\n",7);
fs<<log;
sprintf(log,"Approach_type\t 0\n");
fs<<log;
sprintf(log,"No_lane\t 0\n");
fs<<log;
fs<<"end_approach"<<endl;
sprintf(log,"Approach\t %d\n",8);
fs<<log;
sprintf(log,"Approach_type\t 0\n");
fs<<log;
sprintf(log,"No_lane\t 0\n");
fs<<log;
fs<<"end_approach"<<endl;
}
fs<<"end_map";
fs.close();
}
int print_Sig_Status(SPAT_t *spatType,char *filename)
{
fstream fs;
fs.open(filename, ios::out);
if (!fs || !fs.good())
{
cout << "could not open file!\n";
exit(0);
}
//get intersection id
unsigned char ByteA=spatType->intersections.list.array[0]->id.buf[0];
unsigned char ByteB=spatType->intersections.list.array[0]->id.buf[1];
int intersection_id= (int) (((ByteB << 8) + (ByteA)));
fs<<intersection_id<<" Signal_status ";
int i;
//printf("The signal status are:\n");
for(i=0;i<NUM_MM_STS;i++)
{
if(*spatType->intersections.list.array[0]->states.list.array[i]->currState == 0)
{
//printf("N/A ");
fs<<"0 ";
}
if(*spatType->intersections.list.array[0]->states.list.array[i]->currState & (1<<0))
{
//printf("G ");
fs<<"3 ";
}
if(*spatType->intersections.list.array[0]->states.list.array[i]->currState & (1<<1))
{
//printf("Y ");
fs<<"4 ";
}
if(*spatType->intersections.list.array[0]->states.list.array[i]->currState & (1<<2))
{
//printf("R ");
fs<<"1 ";
}
}
//printf("\n");
//printf("The Ped signal status are:\n");
//for(i=0;i<NUM_MM_STS;i++)
//{
//if (mm_st[i].ped_state==J2735SPAT_PED_WALK)
//printf("W ");
//if (mm_st[i].ped_state==J2735SPAT_PED_CAUTION)
//printf("F ");
//if (mm_st[i].ped_state==J2735SPAT_PED_STOP)
//printf("D ");
//if (mm_st[i].ped_state==J2735SPAT_PED_UNAVAILABLE)
//printf("N/A ");
//}
//printf("\n");
//printf("The Ped Remaining time are:\n");
//for(i=0;i<NUM_MM_STS;i++)
//{
//printf("%d ",mm_st[i].next_time_remaining);
//}
//printf("\n");
return 0;
}
int gettimestamp(uint64_t *seconds, uint64_t *microsecs)
{
struct timeval tv;
gettimeofday(&tv, 0);
*seconds = tv.tv_sec;
*microsecs = tv.tv_usec;
return 0;
}
void Unpack_ART(byte* ablob, char *filename)
{
int intersection_id;
int i;
int offset=0;
unsigned short tempUShort; // temp values to hold data in final format
long tempLong;
float tempfloat;
unsigned char byteA; // force to unsigned this time,
unsigned char byteB; // we do not want a bunch of sign extension
unsigned char byteC; // math mucking up our combine logic
unsigned char byteD;
//Intersection ID;
byteA = ablob[offset+0];
byteB = ablob[offset+1];
byteC = ablob[offset+2];
byteD = ablob[offset+3];
intersection_id = (unsigned long)((byteA << 24) + (byteB << 16) + (byteC << 8) + (byteD));
offset = offset + 4;
if (intersection_id==active_map_id) //only write the request table from the active map to the file
{
fstream fs;
fs.open(filename, ios::out);
if (!fs || !fs.good())
{
cout << "could not open file!\n";
exit(0);
}
sprintf(temp_log,"Received ART!\n");
outputlog(temp_log);
//Number of Requests
byteA = ablob[offset+0];
byteB = ablob[offset+1];
int NumReq = (int)(((byteA << 8) + (byteB))); // in fact unsigned
offset = offset + 2;
fs<<"Num_req "<<NumReq<<endl;
//cout<<"The number of requests is: "<<NumReq<<endl;
sprintf(temp_log,"The number of requests is %d\n",NumReq);
outputlog(temp_log); cout<<temp_log;
//Do Active Request Table
for (i=0;i<NumReq;i++)
{
//Do Veh_ID
byteA = ablob[offset+0];
byteB = ablob[offset+1];
byteC = ablob[offset+2];
byteD = ablob[offset+3];
tempLong = (unsigned long)((byteA << 24) + (byteB << 16) + (byteC << 8) + (byteD));
offset = offset + 4;
fs<<tempLong<<" ";
//Do Veh_Class
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//Do ETA
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
tempfloat=tempUShort/FLOAT2INT;
offset = offset + 2;
fs<<setprecision(3)<<tempfloat<<" ";
//Do phase
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//Do Tq
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
tempfloat=tempUShort/FLOAT2INT;
offset = offset + 2;
fs<<setprecision(3)<<tempfloat<<" ";
//Do abs_time
byteA = ablob[offset+0];
byteB = ablob[offset+1];
byteC = ablob[offset+2];
byteD = ablob[offset+3];
tempLong = (unsigned long)((byteA << 24) + (byteB << 16) + (byteC << 8) + (byteD));
offset = offset + 4;
fs<<tempLong<<" ";
sprintf(temp_log,"Absolute time is %ld\n",tempLong);
outputlog(temp_log);
//Do split phase
// byteA = ablob[offset+0];
// byteB = ablob[offset+1];
// tempUShort= (int)(((byteA << 8) + (byteB)));
// offset = offset + 2;
// fs<<tempUShort<<" ";
//Do inlane
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//Do outlane
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do shour
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do smin
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do ssec
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do ehour
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do emin
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do esec
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort<<" ";
//do veh states
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
//fs<<tempUShort<<" ";
if(tempUShort==1)
//fs<<"Approaching ";
fs<<"1 ";
else if(tempUShort==2)
//fs<<"Leaving ";
fs<<"2 ";
else if(tempUShort==3)
//fs<<"InQueue ";
fs<<"3 ";
else
//fs<<"N/A ";
fs<<"0 ";
//do request sequence
byteA = ablob[offset+0];
byteB = ablob[offset+1];
tempUShort= (int)(((byteA << 8) + (byteB)));
offset = offset + 2;
fs<<tempUShort;
sprintf(temp_log,"Sequence is %d\n",tempUShort);
outputlog(temp_log);
if(i<NumReq-1)
fs<<endl;
}
fs.close();
}
}
int FindActiveMap()
{
int active_id=0;
char temp[128];
ifstream f_active_map;
f_active_map.open(active_map_file,ios::in);
if(!is_empty(f_active_map)) //if not empty, read the active map id
{
string temp_string;
getline(f_active_map,temp_string);
if(temp_string.size()!=0)
{
char tmp[128];
//cout<<temp_string<<endl;
strcpy(tmp,temp_string.c_str());
sscanf(tmp,"%*d %d %*d",&active_id);
// cout<<"active id is:"<<active_id<<endl;
}
else
{
sprintf(temp,"Reading active map file error!\n");
cout<<temp<<endl;
outputlog(temp);
exit(0);
}
}
else //if the file is empty
{
if(field_flag==1) //in the field, request gps location, not done yet!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
{
//gps_init ();
//savari_gps_read(&gps, gps_handle);
//savari_gps_close(gps_handle);
}
}
f_active_map.close();
return active_id;
}
|
fc487cb5c11dd0a82faac231b40400b4a7184126 | d1ea3d1c729b701c1e5f974e310a54e3d73d3da5 | /208A - Dubstep.cpp | 602d07059669e690c66c2e3826b9bd0d5bfcfb64 | [] | no_license | subhamsagar524/DSA | 61c22f6fbc52c405b2c4732800cafcf8def15f52 | c54da3d621e2174706c4b178f5842c56e8657852 | refs/heads/master | 2022-12-26T20:08:49.256932 | 2020-09-18T18:02:30 | 2020-09-18T18:02:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | 208A - Dubstep.cpp | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string input;
cin >> input;
for(int i = 0; i < input.length(); i++)
{
string temp = input.substr(i, 3);
if(temp == "WUB")
for(int j = 0; j < 3; j++)
input[i+j] = ' ';
}
stringstream ss(input);
string word, result;
while(ss >> word)
{
if(!result.empty())
result += ' ';
result += word;
}
cout << result << endl;
return 0;
} |
f760c6d0cb215b00760e76afc5a958b24b50866e | 36e73dc3889c970df6e6bf9df8a2b8fd92c52737 | /hw3/cave_main.cpp | 2b85c8dd6f52d3724ee641464cee550bee83ec30 | [] | no_license | guswns3396/CSCI104 | 82536507c99c2e1932bec2331f82d07d0afbddc9 | a8b22351fb6b797d2bbb00f82b8aa71e16e0a332 | refs/heads/master | 2022-07-09T09:57:39.570112 | 2020-05-18T03:19:41 | 2020-05-18T03:19:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | cave_main.cpp | #include "cave.h"
#include <iostream>
using namespace std;
int main(int argc, char* argv[]){
// check for valid input
if(argc < 2){
cout << "Must provide an input file" << endl;
return 0;
}
ifstream in(argv[1]);
if(in.fail()){
cout << "Failed to open file" << endl;
return 0;
}
cout << cave(in) << endl;
return 0;
} |
e806f7c73b3bd85fc6f4c724150ff206ed7fc7f1 | 39499f41104be148fd795eb4e1efae5d198bea5b | /Maze/src/Engine/Application.cpp | a5f7d3ff98611655cab3286ce18247efeb237b06 | [] | no_license | Superseth794/Maze | f16c5001851e6dbdbd9901db004f19d3b5be35bd | 26d3275c65976d0468fa8d616d89c0554f14a723 | refs/heads/master | 2022-02-03T05:52:45.224029 | 2022-01-22T15:00:41 | 2022-01-22T15:00:41 | 238,751,429 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | cpp | Application.cpp | //
// Application.cpp
// Maze
//
// Created by Jaraxus on 13/09/2021.
//
#include "../../include/Engine/Application.hpp"
mz::Application::Application(unsigned width, unsigned height, std::string title) :
Application(sf::VideoMode(width, height), std::move(title))
{
}
mz::Application::Application(sf::VideoMode mode, std::string title, sf::Uint32 style, sf::ContextSettings const& settings) :
m_gameScene(mode.width, mode.height),
m_lastFrameTime(getCurrentFrameTime()),
m_title(std::move(title)),
m_window(mode, m_title, style, settings)
{
m_window.setFramerateLimit(60);
}
void mz::Application::run() {
while (runOnce());
}
bool mz::Application::runOnce() {
if (m_exiting) {
// clear gameScene
return true;
}
std::uint64_t currentFrameTime = getCurrentFrameTime();
std::uint64_t deltaTime = m_lastFrameTime - currentFrameTime;
m_lastFrameTime = currentFrameTime;
// handle events
m_gameScene.update(deltaTime);
m_window.clear();
m_gameScene.display(m_window);
m_window.display();
return !m_exiting; // check gameScene
}
|
c46e9be24359322dff09fc8b560b14123ac95bc9 | 45204a8651d27a9837989eac7381bbe79d613033 | /test20160312/network.cpp | 44bfdcf795734497edc3e6cb8128d67387acc108 | [] | no_license | gdjs2/Test | 34638c1ed3c4f3be99fe7ce2c340787a82b4b332 | 943fcc6b2358c6492ca055cf2991d873939fbf31 | refs/heads/test20160312 | 2021-01-10T11:17:08.963574 | 2016-03-13T10:48:06 | 2016-03-13T10:48:06 | 53,779,823 | 0 | 0 | null | 2016-03-14T10:47:32 | 2016-03-13T10:43:12 | C++ | UTF-8 | C++ | false | false | 3,431 | cpp | network.cpp | #include <cstdio>
#include <queue>
#include <memory.h>
#define mem(x, y) memset(x, y, sizeof(x))
typedef long long ll;
const int Maxn = 1100;
const ll oo = 0x3f3f3f3f3f3f3f3f * 1LL;
ll n, m;
ll min(ll a, ll b)
{
return a < b ? a : b;
}
ll read()
{
ll x = 0; char c = getchar();
while(c < '0' || c > '9') c = getchar();
while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
return x;
}
namespace Map
{
ll fir[Maxn], nxt[Maxn*200], to[Maxn*200], cnt = 0, dist[Maxn*200];
void add(ll a, ll b, ll c)
{
nxt[++cnt] = fir[a];
fir[a] = cnt;
to[cnt] = b;
dist[cnt] = c;
}
bool inq[Maxn];
void dijk(ll *d, ll s)
{
d[s] = 0;
std::queue<ll> q;
q.push(s);
while(!q.empty())
{
ll now = q.front(); q.pop();
for(ll i = fir[now]; i; i = nxt[i])
if(d[to[i]] > d[now]+dist[i])
{
d[to[i]] = d[now]+dist[i];
if(!inq[to[i]]) q.push(to[i]);
}
}
}
}
namespace Flow
{
ll level[Maxn], iter[Maxn];
ll fir[Maxn], nxt[Maxn*200], to[Maxn*200], cap[Maxn*200], cnt = 0;
ll find(ll x)
{
return x&1 ? x+1 : x-1;
}
void add(ll a, ll b, ll c)
{
nxt[++cnt] = fir[a];
fir[a] = cnt;
to[cnt] = b;
cap[cnt] = c;
return;
}
void bfs(ll s)
{
std::queue<ll> q;
q.push(s);
while(!q.empty())
{
ll now = q.front(); q.pop();
for(ll i = fir[now]; i; i = nxt[i])
if(cap[i] > 0 && level[to[i]] == -1)
{
level[to[i]] = level[now]+1;
q.push(to[i]);
}
}
}
ll dfs(ll s, ll e, ll f)
{
if(s == e) return f;
for(ll& i = iter[s]; i; i = nxt[i])
if(cap[i] && level[to[i]] > level[s])
{
ll fl = dfs(to[i], e, min(f, cap[i]));
if(fl)
{
cap[i] -= fl;
cap[find(i)] += fl;
return fl;
}
}
return 0;
}
ll maxflow(ll s, ll e)
{
ll flow = 0;
for(;;)
{
mem(level, -1);
level[0] = 1;
bfs(0);
if(level[e] == -1) return flow;
for(ll i = s; i <= e; ++i) iter[i] = fir[i];
ll f;
while(f = dfs(s, e, oo)) flow += f;
}
return 0;
}
}
ll f[Maxn], d[Maxn];
int main()
{
freopen("network.in", "r", stdin);
freopen("network.out", "w", stdout);
n = read(); m = read();
for(ll i = 1; i <= m; ++i)
{
ll a = read(), b = read(), c = read();
Map::add(a, b, c); Map::add(b, a, c);
}
mem(f, 0x3f); mem(d, 0x3f);
Map::dijk(f, 1); Map::dijk(d, n);
for(int i = 1; i <= n; ++i)
for(ll j = Map::fir[i]; j; j = Map::nxt[j])
if(f[i] + d[Map::to[j]] + Map::dist[j] == f[n]) Flow::add(i+n, Map::to[j], oo), Flow::add(Map::to[j], i+n, 0);// printf("%d %d\n", i, Map::to[j]);
for(int i = 1; i <= n; ++i)
{
ll c = read();
(i==1||i==n) ? c = oo : 1 ;
Flow::add(i, i+n, c);
Flow::add(i+n, i, 0);
}
Flow::add(0, 1, oo); Flow::add(1, 0, 0);
Flow::add(2*n, 2*n+1, oo); Flow::add(2*n+1, 2*n, 0);
printf("%lld\n", Flow::maxflow(0, 2*n+1));
return 0;
}
|
dfd188ccee5cc332ad5e0e1e14c517e12de5c291 | 08cac4e3def118b1bc46048808500ffd38b1fe1c | /Project2/Source.cpp | 3d63e4a410d16ab74b91557a1a88f4f99f460d2d | [] | no_license | suelemsk/program | 29b7a3a4bfa858270b817ac936ff946f802d1dc6 | d8115d9fb1ba40ee848e59e182f0b0a4d103a448 | refs/heads/master | 2016-08-03T14:39:34.104765 | 2015-08-28T01:05:23 | 2015-08-28T01:05:23 | 41,517,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | Source.cpp | #include <iostream>
#define NUMERO_MAX_SIZE 5
int main()
{
int* ap[ NUMERO_MAX_SIZE ];
int numeros[NUMERO_MAX_SIZE] = { 11, 12, 13, 14, 15 };
int i, j;
for (int i = 0, j = 4; i < NUMERO_MAX_SIZE; i++, j--)
{
ap[j]= &numeros[i];
}
for (int i = 0; i < NUMERO_MAX_SIZE; i++)
{
std::cout << *(*(ap + i))
<< std::endl;
}
system("pause");
return 0;
} |
0ed0ffd981854d7664783980928001b03f5858af | 4a0a1ac87d2fc37f77e92cf7c0b2000716af1765 | /aq-sequential.cpp | e44c5800bcd2b306af7657fd050706db93ab3cc3 | [] | no_license | FluffyPinata/AQIntegration | ecb86f7d812f731221a9732ee09f94e638c89848 | 530e7db3367e991b9a396aff0da0d2e075977871 | refs/heads/main | 2023-03-31T15:00:00.738579 | 2020-12-06T18:13:08 | 2020-12-06T18:13:08 | 312,894,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,829 | cpp | aq-sequential.cpp | #include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <omp.h>
#include <stack>
#include <time.h>
#include <cstdlib>
#include <iomanip>
#include <cmath>
#include <stdio.h>
#include <unistd.h>
#include <bits/stdc++.h>
using namespace std;
double f1(double x){
double result = (4 * pow(x, 6) - 2 * pow(x, 3) + (7 * x) - 4);
return result;
}
double f2(double x){
double result = cos(x) - (3 / pow(x, 5));
return result;
}
double f3(double x){
double result = exp(x) + 1 / (pow(x, 2) + 1);
return result;
}
double integralF1(double a, double b){
double integral;
integral = (((4 * pow(b, 7)) / 7) - ((2 * pow(b, 4)) / 4) + ((7 * pow(b, 2)) / 2) - 4 * b)
- (((4 * pow(a, 7)) / 7) - ((2 * pow(a, 4)) / 4) + ((7 * pow(a, 2)) / 2) - 4 * a);
return integral;
}
double integralF2(double a, double b){
double integral;
integral = (sin(b) + (3 / (4 * pow(b, 4)))) - (sin(a) + (3 / (4 * pow(a, 4))));
return integral;
}
double integralF3(double a, double b){
double integral;
integral = (exp(b) + atan(b)) - (exp(a) + atan(a));
return integral;
}
double SimpsonsRule(double a, double b, int func){
double integral = 0.0;
double c = (a + b) / 2;
if (func == 1){
integral = ((b - a) * (f1(a) + 4 * f1(c) + f1(b))) / 6;
}
else if (func == 2){
integral = ((b - a) * (f2(a) + 4 * f2(c) + f2(b))) / 6;
}
else if (func == 3){
integral = ((b - a) * (f3(a) + 4 * f3(c) + f3(b))) / 6;
}
return integral;
}
double getError(double val1, double val2){
return (abs((val1 - val2) / val1));
}
double AdaptiveQuadrature(double lower, double upper, double error, int func){
double simpsons = SimpsonsRule(lower, upper, func);
double actual;
if (func == 1){
actual = integralF1(lower, upper);
}
else if (func == 2){
actual = integralF2(lower, upper);
}
else if (func == 3){
actual = integralF3(lower, upper);
}
double integral = 0.0;
if (getError(actual, simpsons) > error){
double midpoint = (upper + lower) / 2;
integral += AdaptiveQuadrature(lower, midpoint, error, func);
integral += AdaptiveQuadrature(midpoint, upper, error, func);
}
else{
integral += simpsons;
}
return integral;
}
int main()
{
double approxf1, approxf2, approxf3, actualf1, actualf2, actualf3, error1, error2, error3, runtime;
//runtime = clock()/(double)CLOCKS_PER_SEC;
runtime = omp_get_wtime();
approxf1 = AdaptiveQuadrature(0, 10, 0.02, 1);
approxf2 = AdaptiveQuadrature(1, 8, 0.02, 2);
approxf3 = AdaptiveQuadrature(0, 10, 0.02, 3);
actualf1 = integralF1(0, 10);
actualf2 = integralF2(1, 8);
actualf3 = integralF3(0, 10);
error1 = getError(actualf1, approxf1);
error2 = getError(actualf2, approxf2);
error3 = getError(actualf3, approxf3);
runtime = omp_get_wtime() - runtime;
//runtime = (clock()/(double)CLOCKS_PER_SEC ) - runtime;
cout << "Approximate integral of f(x) = 4x^6 - 2x^3 + 7x - 4 from 0 to 10: " << approxf1 << endl;
cout << "Actual integral of f(x) = 4x^6 - 2x^3 + 7x - 4 from 0 to 10: " << actualf1 << endl;
cout << "Error: " << error1 << "\n\n";
cout << "Approximated f(x) = cos(x) - 3x^-5 from 1 to 8: " << approxf2 << endl;
cout << "Actual f(x) = cos(x) - 3x^-5 from 1 to 8: " << actualf2 << endl;
cout << "Error: " << error2 << "\n\n";
cout << "Approximated f(x) = e^x + 1 / (x^2 + 1) from 0 to 10: " << approxf3 << endl;
cout << "Actual f(x) = e^x + 1 / (x^2 + 1) from 0 to 10: " << actualf3 << endl;
cout << "Error: " << error3 << "\n\n";
cout << "Program runs in " << setiosflags(ios::fixed) << setprecision(8) << runtime << " seconds\n";
return 0;
} |
a80538d36dd0cf9399df0841825bc4eca52aabe1 | fca768a2ae424b436fadf529733bd2de317d2398 | /CPPQTDatabaseTest/MainWindow.h | b495ff909adc35a7f4eb010932bd0382994f613a | [] | no_license | DodgeeSoftware/CPPQTDatabaseTest | 98b255c50f01e7cb292ce3bc266242c1ccfa519a | d671b236423ea508100166255e2790da98fd4ff8 | refs/heads/master | 2021-09-20T02:33:49.051487 | 2018-08-02T09:25:29 | 2018-08-02T09:25:29 | 139,801,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | h | MainWindow.h | /* SimpleDatabase Application Using Qt, MySQL and C++
(c) Dodgee Software 2018
Youtube: https://youtube.com/dodgeesoftware */
#pragma once
// C++ Includes
#include <iostream>
// Qt Includes
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMessagebox.h>
// Window Includes
#include "AddNewCustomerWindow.h"
#include "CustomerWindow.h"
#include "FindCustomerWindow.h"
#include "RemoveCustomerWindow.h"
#include "ShowCustomersWindow.h"
#include "GeneratedFiles/ui_MainWindow.h"
/* The Main Window class is the container for
our main applicaiton window. It inherits
from QMainWindow */
class MainWindow : public QMainWindow
{
/* BoilerPlate Macro required
because the base Object implements
a QObject*/
Q_OBJECT
// *****************************
// * CONSTRUCTORS / DESTRUCTOR *
// *****************************
public:
// Constructor
MainWindow(QWidget *parent = Q_NULLPTR);
// Destructor
virtual ~MainWindow();
protected:
// Members and Methods
// ***********
// * WINDOWS *
// ***********
public:
// Members and Methods
protected:
// AddNewCustomerWindow
AddNewCustomerWindow addNewCustomerWindow;
// CustomerWindow
CustomerWindow customerWindow;
// FindCustomerWindow
FindCustomerWindow findCustomerWindow;
// RemoveCustomerWindow
RemoveCustomerWindow removeCustomerWindow;
// ShowCustomersWindow
ShowCustomersWindow showCustomersWindow;
protected:
Ui::MainWindowClass* pMainWindowClass;
// *********
// * SLOTS *
// *********
public slots:
// Add Customer Button Released Slot
void addCustomerButtonReleasedSlot();
// Find Customer Button Released Slot
void findCustomerButtonReleasedSlot();
// Remove Customer Button Release Slot
void removeCustomerButtonReleasedSlot();
// Show Customer Button Release Slot
void showCustomersButtonReleasedSlot();
// Quit Button Release Slot
void quitButtonReleasedSlot();
// About Button Released Slot
void aboutButtonReleasedSlot();
protected:
// Members and Methods
};
|
2023388f014d0149f1b100d2e5fba6c79546c943 | 4703ab4f910e6af3f8d935b69e35b4da7defabf7 | /nauEngine/nauUtilities/src/nauVector3.cpp | 91a7fd2d4cd7e70440b841bc35c14d10b5e89821 | [] | no_license | USwampertor/NautilusEngine | 6ae96839086832cd9490afe237dc987015fa105f | df027468b4f58691b3b5f4866190ce395dab3d5a | refs/heads/master | 2021-06-07T12:11:09.162039 | 2018-10-01T23:05:38 | 2018-10-01T23:05:38 | 148,564,586 | 1 | 0 | null | null | null | null | BIG5 | C++ | false | false | 6,160 | cpp | nauVector3.cpp | /*||偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|*/
/**
* @file nauVector3.cpp
* @author Marco "Swampy" Millan
* @date 2018/09/27 2018
* @brief the nauVector3 member definition
*
*/
/*||偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|偽院|*/
#include "nauVector3.h"
namespace nauEngineSDK {
/**
* Method Implementation
*/
nauVector3::nauVector3(float nx, float ny, float nz) : x(nx), y(ny), z(nz) {}
float&
nauVector3::operator[](uint32 index) {
return (&x)[index];
}
float
nauVector3::operator[](uint32 index) const {
return (&x)[index];
}
FORCEINLINE nauVector3
nauVector3::operator+(const nauVector3& v) const {
return nauVector3(x + v.x, y + v.y, z + v.z);
}
FORCEINLINE nauVector3
nauVector3::operator-(const nauVector3& v) const {
return nauVector3(x - v.x, y - v.y, z - v.z);
}
FORCEINLINE nauVector3
nauVector3::operator*(const nauVector3& v) const {
return nauVector3(x * v.x, y * v.y, z * v.z);
}
FORCEINLINE nauVector3
nauVector3::operator/(const nauVector3& v) const {
return nauVector3(x / v.x, y / v.y, z / v.z);
}
FORCEINLINE nauVector3
nauVector3::operator+(float plus) const {
return nauVector3(x + plus, y + plus, z + plus);
}
FORCEINLINE nauVector3
nauVector3::operator-(float minus) const {
return nauVector3(x - minus, y - minus, y - minus);
}
FORCEINLINE nauVector3
nauVector3::operator*(float times) const {
return nauVector3(x * times, y * times, z * times);
}
FORCEINLINE nauVector3
nauVector3::operator/(float under) const {
return nauVector3(x / under, y / under, z / under);
}
FORCEINLINE float
nauVector3::operator|(const nauVector3 v) const {
return x * v.x + y * v.y + z * v.z;
}
FORCEINLINE float
nauVector3::operator^(const nauVector3 v) const {
return x * v.x - y * v.y - z * v.z;
}
bool
nauVector3::operator==(const nauVector3& v) const {
return x == v.x && y == v.y && z == v.z;
}
bool
nauVector3::operator!=(const nauVector3& v) const {
return x != v.x || y != v.y || z == v.z;
}
bool
nauVector3::operator<(const nauVector3& v) const {
return x < v.x && y < v.y && z < v.z;
}
bool
nauVector3::operator>(const nauVector3& v) const {
return x > v.x && y > v.y && z > v.z;
}
bool
nauVector3::operator<=(const nauVector3& v) const {
return x <= v.x && y <= v.y && z <= v.z;
}
bool
nauVector3::operator>=(const nauVector3& v) const {
return x >= v.x && y >= v.y && z >= v.z;
}
FORCEINLINE nauVector3
nauVector3::operator-() const {
return nauVector3(-x, -y, -z);
}
nauVector3&
nauVector3::operator+=(const nauVector3& v) {
x += v.x;
y += v.y;
z += v.z;
return *this;
}
nauVector3&
nauVector3::operator-=(const nauVector3& v) {
x -= v.x;
y -= v.y;
z -= v.z;
return *this;
}
nauVector3&
nauVector3::operator*=(const nauVector3& v) {
x *= v.x;
y *= v.y;
z *= v.z;
return *this;
}
nauVector3&
nauVector3::operator/=(const nauVector3& v) {
x /= v.x;
y /= v.y;
z /= v.z;
return *this;
}
nauVector3&
nauVector3::operator*=(float scale) {
x *= scale;
y *= scale;
z *= scale;
return *this;
}
nauVector3&
nauVector3::operator/=(float scale) {
x /= scale;
y /= scale;
z /= scale;
return *this;
}
FORCEINLINE float
nauVector3::dot(const nauVector3& a, const nauVector3& b) {
return a | b;
}
FORCEINLINE float
nauVector3::cross(const nauVector3& a, const nauVector3& b) {
return a ^ b;
}
FORCEINLINE float
nauVector3::dotScale(const nauVector3& a, const nauVector3& b) {
return (a | b) / nauMath::sqr(a.magnitude());
}
float
nauVector3::sqrDistance(const nauVector3& a, const nauVector3& b) {
return nauMath::sqr(a.x - b.x) +
nauMath::sqr(a.y - b.y) +
nauMath::sqr(a.z - b.z);
}
FORCEINLINE float
nauVector3::distance(const nauVector3& a, const nauVector3& b) {
return
nauMath::sqrt(nauMath::sqr(a.x - b.x) +
nauMath::sqr(a.y - b.y) +
nauMath::sqr(a.z - b.z));
}
void
nauVector3::setValues(float newX, float newY, float newZ) {
x = newX;
y = newY;
z = newZ;
}
void
nauVector3::min(const nauVector3& v) {
if (v.x < x) x = v.x;
if (v.y < y) y = v.y;
if (v.z < z) z = v.z;
}
void
nauVector3::max(const nauVector3& v) {
if (v.x > x) x = v.x;
if (v.y > y) y = v.y;
if (v.z > z) z = v.z;
}
void
nauVector3::floor() {
x = nauMath::floor(x);
y = nauMath::floor(y);
z = nauMath::floor(z);
}
void
nauVector3::ceiling() {
x = nauMath::ceil(x);
y = nauMath::ceil(y);
z = nauMath::ceil(z);
}
void
nauVector3::round() {
x = nauMath::round(x);
y = nauMath::round(y);
z = nauMath::round(z);
}
void
nauVector3::roundHalf() {
x = nauMath::roundHalf(x);
y = nauMath::roundHalf(y);
z = nauMath::roundHalf(z);
}
float
nauVector3::getHighest() const {
return nauMath::max3(x, y, z);
}
float
nauVector3::getLowest() const {
return nauMath::min3(x, y, z);
}
float
nauVector3::magnitude() const {
return nauMath::sqrt(x * x + y * y + z * z);
}
float
nauVector3::sqrMagnitude() const {
return (x * x + y * y + z * z);
}
FORCEINLINE nauVector3
nauVector3::normalized() {
float unit = nauMath::invSqrt(x*x + y * y + z * z);
return nauVector3((x * unit), (y * unit), (z * unit));
}
void
nauVector3::normalize() const {
}
bool
nauVector3::isZero() const {
return 0.0f == x && 0.0f == y && 0.0f == z;
}
const nauVector3 nauVector3::ZERO = nauVector3(0.0f, 0.0f, 0.0f);
const nauVector3 nauVector3::ONES = nauVector3(1.0f, 1.0f, 1.0f);
const nauVector3 nauVector3::ONEX = nauVector3(1.0f, 0.0f, 0.0f);
const nauVector3 nauVector3::ONEY = nauVector3(0.0f, 1.0f, 0.0f);
const nauVector3 nauVector3::ONEZ = nauVector3(0.0f, 0.0f, 1.0f);
}
|
825ab7d1c04e878259a8c611916ecebbdff7bb40 | cf26fab850b5ae23bf614095362d92d711f1693b | /Yan-Zhenyu-lab06/Matrix.h | 1b78883c3b3247041f3dae82035c4d5ef9cf5e85 | [] | no_license | olveryu/CSCI1730-system-programming | 61d443bdeb77085ab782a60a70748e7cf2356ebd | f3b6ea8db13dbafa0a8f30d6d35ae598dc0cfb3e | refs/heads/master | 2021-07-12T02:30:41.143961 | 2017-10-12T21:48:19 | 2017-10-12T21:48:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,809 | h | Matrix.h |
#ifndef MATRIX_H
#define MATRIX_H
#include <string>
#include <iostream>
#include <initializer_list>
using std::initializer_list;
using std::ostream;
typedef unsigned int uint;
typedef initializer_list<initializer_list<double>> i_list;
namespace MatrixProject{
/**
* the Matrix class stores and operates on numeric matrixs of
*element type double.
*/
class Matrix{
/**1st Dimenstion length of the vector*/
uint rows;
/**1st Dimenstion length of the vector*/
uint cols;
/**2 Dimenstion array*/
double ** matrix = nullptr;
public:
/**
* Constructs a new matrix object. Each element is initialized to 0.
* @param rows: 1st dimention
* @param cols: 2nd dimention
*/
Matrix(uint rows, uint cols);
/**
* Constructs a new matrix object from an i_list list.
* @param list: i_list list
*/
Matrix(const i_list & list);
/**
* Construct a new matrix object as a copy of another matrix object.
* @param m: matrix to copy
*/
Matrix(const Matrix & m);
/**
* Destructs the matrix object.
*/
~Matrix();
/**
* Returns the sum of this `matrix` and some scaler `s`.
* @param s: scaler to add
*/
Matrix add(double s) const;
/**
* Returns the sum of this `matrix` and another `matrix` of the same length.
* @param m: matrix to add
*/
Matrix add(const Matrix & m) const;
/**
* Returns the difference of this `matrix` and some scaler `s`.
* @param s: scaler to subtract
*/
Matrix subtract(double s) const;
/**
* Returns the difference of this `matrix` and another `matrix` of the same
* length.
* @param m: matrix to subtract
*/
Matrix subtract(const Matrix & m) const;
/**
* Returns the product of this `matrix` and some scaler `s`.
* @param s: scaler to multiply
*/
Matrix multiply(double s) const;
/**
* Returns the product of this `matrix` and another `matrix` of the same
* length.
* @param m: matrix to multiply
*/
Matrix multiply(const Matrix & m) const;
/**
* Returns the quotient of this `matrix` and some scaler `s`.
* @param s: scaler to divide
*/
Matrix divide(double s) const;
/**
* return the transposition of the matrix
*/
Matrix t() const;
/**
* return the number of rows in the matrix
*/
const uint numRows() const;
/**
*return the number of cols in the martrix
*/
const uint numCols() const;
/**
* return the element which you can get or set the element
* @param m: row to the first dimension, col to the second dimention
*/
double & at(uint row, uint col);
/**
* return the element which you can get the element, This version is for const objects.
* @param m: row to the first dimension, col to the second dimention
*/
const double & at(uint row, uint col) const;
/**
* Copy assignment operator.
* @param m: matrix to copy
*/
Matrix & operator=(const Matrix & m);
/**
* Copy assignment operator.
* @param list: i_list to copy
*/
Matrix & operator=(const i_list & list);
/**
* Function Call at(row,col) Operator
*/
double & operator()(uint row, uint col);
/**
* Function addtion Operator
*/
Matrix operator+(const double s) const;
/**
* Function addtion Operator
*/
Matrix operator+(const Matrix & m) const;
/**
* Function minus Operator
*/
Matrix operator-(const double s) const;
/**
* Function minus Operator
*/
Matrix operator-(const Matrix & m) const;
/**
* Function mulitiplication Operator
*/
Matrix operator*(const double s) const;
/**
* Function multiplication Operator
*/
Matrix operator*(const Matrix & m) const;
/**
* Function division Operator
*/
Matrix operator/(const double s) const;
/**
* Function unary minus Operator: return the negation of the orginal matrix
*/
Matrix operator-() const;
};// Matrix
} // Matrix
/**
* Non-Member Arithmetic Operators for Scalers
*/
MatrixProject::Matrix operator+(const double s, const MatrixProject::Matrix & m);
MatrixProject::Matrix operator-(const double s, const MatrixProject::Matrix & m);
MatrixProject::Matrix operator*(const double s, const MatrixProject::Matrix & m);
MatrixProject::Matrix operator/(const double s, const MatrixProject::Matrix & m);
/**
* return the os of the matrix which print it out the whole matrix
* @param os: cout
* @param m : matrix
*/
ostream & operator <<(ostream & os, const MatrixProject::Matrix m);
#endif
|
3adf771423275b5f3731e29e42351075dddfacc7 | 823b41823eea7afb820fc19127282226b06fd8c5 | /Game.h | 94d81e9c3aa3830e6af6170d8352b23412b190e6 | [] | no_license | NickWils98/Roadfighter | 415dfe3d88165f7d3cda33d93c1a0e5cced65a9f | f0e031e1e152226f0d572f20ae0a7d01fefe5236 | refs/heads/master | 2020-04-11T10:21:24.932524 | 2018-12-14T20:07:19 | 2018-12-14T20:07:19 | 161,708,205 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 716 | h | Game.h | //
// Created by nick on 14.12.18.
//
#ifndef ROADFIGHTER_GAME_H
#define ROADFIGHTER_GAME_H
#include <SFML/Graphics.hpp>
#include <memory>
#include "World.h"
#include "PlayerCarSFML.h"
#include "Car.h"
#include "PlayerCar.h"
#include "Entity.h"
class Game {
public:
Game();
virtual ~Game();
void run();
void init();
void moveObjects();
void handleEvent();
void DrawBackground();
private:
sf::RenderWindow m_window;
std::shared_ptr<World> world;
sf::View view;
std::shared_ptr<PlayerCarSFML> player;
float deltaTime = 0;
std::vector<std::shared_ptr<sf::Texture>> textures = {};
std::vector<sf::Sprite>backgrounds = {};
};
#endif //ROADFIGHTER_GAME_H
|
be1ac939882f4c4efd076ab079a6a99b5def5de2 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_644_git-2.8.5.cpp | e575455786734ac0c51f27ea305ca1c72edea563 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 134 | cpp | git_repos_function_644_git-2.8.5.cpp | char *packet_read_line_buf(char **src, size_t *src_len, int *dst_len)
{
return packet_read_line_generic(-1, src, src_len, dst_len);
} |
702c69a3a7881bbdfeaea831fbd39a9db66a405b | 3a73f1d47b9d84c0f65da01812a978ea5e692a7e | /CodeVita 9/1.cpp | 48521b8dc21cdd44c25e53556b0932d61c6cbed0 | [] | no_license | pushpend3r/cpp | 6c010957f7a503fd9e13cfd22df06e6644f7816f | 45d465bd63c01359dfcfcabc725684b4de0608a9 | refs/heads/master | 2023-03-26T14:08:36.928690 | 2021-03-10T14:52:18 | 2021-03-10T14:52:18 | 280,484,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 598 | cpp | 1.cpp | #include <bits/stdc++.h>
using namespace std;
typedef unsigned long int ul;
ul n;
string g, b;
int main(void)
{
cin >> n;
cin >> b >> g;
queue<char> grooms;
for (auto &i : g)
{
grooms.push(i);
}
ul rejected = 0;
for (ul i = 1; i <= n; ++i)
{
while (grooms.front() != b[i - 1])
{
rejected++;
grooms.push(grooms.front());
grooms.pop();
if (rejected == grooms.size())
break;
}
if (grooms.front() == b[i - 1])
{
grooms.pop();
rejected = 0;
}
else
{
break;
}
}
cout << rejected;
} |
e27e277a171035d19db34f06e7d42d10a4b74d10 | 3f3d5fd1bf296d0bf0e01200fbb876c61197aca7 | /src/model/model/camera/cameracontroller.h | 42df3ad4d7be1bc29de0674e20285f6b698c97ce | [] | no_license | noodlecollie/calliper | f2299417bda8ec6c57eed08d8fdbae7a942c6267 | b23c945cdf24583a622a7b36954b6feb6314b018 | refs/heads/master | 2021-10-13T23:03:47.909959 | 2018-07-19T18:52:47 | 2018-07-19T18:52:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,711 | h | cameracontroller.h | #ifndef CAMERACONTROLLER_H
#define CAMERACONTROLLER_H
#include "model_global.h"
#include "scenecamera.h"
#include <QTimer>
#include <QObject>
namespace Model
{
class MODELSHARED_EXPORT CameraController : public QObject
{
Q_OBJECT
public:
CameraController(QObject* parent = 0);
SceneCamera* camera() const;
void setCamera(SceneCamera* camera);
float forwardSpeed() const;
void setForwardSpeed(float speed);
float strafeSpeed() const;
void setStrafeSpeed(float speed);
float verticalSpeed() const;
void setVerticalSpeed(float speed);
bool enabled() const;
void setEnabled(bool enabled);
signals:
void tickFinished();
public slots:
void moveForward(bool active);
void moveBackward(bool active);
void moveLeft(bool active);
void moveRight(bool active);
void moveUp(bool active);
void moveDown(bool active);
void clearMovement();
void addPitch(float pitch);
void addYaw(float yaw);
void addRoll(float roll);
private slots:
void tick();
private:
enum MovementState
{
PositiveMovement = 1,
NoMovement = 0,
NegativeMovement = -1,
};
static void modifyMovementState(MovementState& member, bool active);
SceneCamera* m_pCamera;
float m_flForwardSpeed;
float m_flStrafeSpeed;
float m_flVerticalSpeed;
MovementState m_iForwardState;
MovementState m_iStrafeState;
MovementState m_iVerticalState;
QTimer m_Timer;
};
}
#endif // CAMERACONTROLLER_H
|
4ad815efba5e9c66f80f8f26e3b2a862cb804c99 | 8ea1174292b3dfa8e3fb0e35b5fdadb939136231 | /Sources/Game/Collision/Collider.cpp | dd881cb42712ce02d009a923afb9d51bdfdbfa16 | [] | no_license | onievui/DuelWitch | 22f20ed0873c4027a9c479a7e6dfd163c5af55f4 | 0e1a7fc7a0d231e9fec287c60501e97c0873db9a | refs/heads/master | 2021-08-08T04:37:48.586341 | 2020-06-24T15:32:06 | 2020-06-24T15:32:06 | 194,236,085 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 823 | cpp | Collider.cpp | #include "Collider.h"
#include <Game\Object\Transform.h>
/// <summary>
/// コンストラクタ
/// </summary>
/// <param name="type">当たり判定の種類</param>
/// <param name="pTransform">姿勢クラスへのポインタ</param>
/// <param name="offset">座標のオフセット</param>
Collider::Collider(Type type, const Transform* pTransform, const DirectX::SimpleMath::Vector3& offset)
: m_type(type)
, m_pTransform(pTransform)
, m_offset(offset) {
}
/// <summary>
/// 実際の座標を取得する
/// </summary>
/// <returns>
/// 実際の座標を取得する
/// </returns>
DirectX::SimpleMath::Vector3 Collider::GetPos() const {
DirectX::SimpleMath::Vector3 offset = DirectX::SimpleMath::Vector3::Transform(m_offset, m_pTransform->GetRotation());
return m_pTransform->GetPosition() + offset;
}
|
a8cbdb75b0c3621fa6bc4da03f6bfefa7ec1aa44 | df7277d8f9d404a989ddea2467297fec1da80364 | /GRDialogBar.h | e617c3b450e299804775b8e2a4f7d0702a7ce501 | [
"Unlicense"
] | permissive | 15831944/Painter | 6b68cd029d0937b0e04f650de24af70986376216 | ab57f5d022c8b4ce8f9713cd7533fc87e5fafa3b | refs/heads/master | 2023-07-15T12:17:46.353736 | 2021-08-28T13:49:14 | 2021-08-28T13:49:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,333 | h | GRDialogBar.h | #pragma once
#include <GR/GRTypes.h>
#include "GRControlBar.h"
#include "GRMiniDockFrameWnd.h"
#include <vector>
class GRDialogBar : public GRControlBar
{
DECLARE_DYNAMIC(GRDialogBar)
public:
GRDialogBar();
virtual ~GRDialogBar();
virtual BOOL Create( CWnd* pParentWnd,
HWND hwndDialog,
DWORD dwControlStyles = GRCBS_FIXED_SIZE,
UINT nID = 0,
const GR::tChar* szTitle = NULL );
BOOL LoadToolBar( LPCTSTR lpszResourceName );
BOOL LoadToolBar( DWORD dwResourceID );
BOOL LoadBitmap( LPCTSTR lpszResourceName );
BOOL AddReplaceBitmap( HBITMAP hbmImageWell );
protected:
HWND m_hwndDialog;
bool m_Horizontal;
virtual CSize EstimateSize( GR::u32 dwSizingFlags );
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnPaint();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnGetMinMaxInfo(MINMAXINFO* lpMMI);
};
|
ce2b08017743decb4c20b2c65cf1882ed8b8fe81 | 9d195ee578eed18af2637f8bdd137e0f0caae193 | /MetroMiniABS2-bidir/MetroMiniABS2-bidir/ButtonLed_noled.cpp | 4af1c3bda96228e634365e157fa06d64bd7534c0 | [
"CC-BY-4.0"
] | permissive | RobertPHeller/RPi-RRCircuits | 2fb95c73bbeecae4b4752bd3b061f237a7584123 | 6fa701e34990625b82db688b9e106ff3f3864c45 | refs/heads/master | 2023-01-11T07:11:56.560499 | 2022-12-31T18:25:13 | 2022-12-31T18:25:13 | 76,808,345 | 17 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,369 | cpp | ButtonLed_noled.cpp | // -!- C++ -!- //////////////////////////////////////////////////////////////
//
// System :
// Module :
// Object Name : $RCSfile$
// Revision : $Revision$
// Date : $Date$
// Author : $Author$
// Created By : Robert Heller
// Created : Fri May 25 20:01:55 2018
// Last Modified : <180525.2006>
//
// Description
//
// Notes
//
// History
//
/////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2018 Robert Heller D/B/A Deepwoods Software
// 51 Locke Hill Road
// Wendell, MA 01379-9728
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//
//
//////////////////////////////////////////////////////////////////////////////
static const char rcsid[] = "@(#) : $Id$";
#include "ButtonLed_noled.h"
void ButtonLed_noled::init(uint8_t s) {
sense = s;
lastState=false; // start with led off
duration=lastDuration=0; // init durations
state=false; // start with button off
}
// state: F T T F
// lastState: F T T F
// returns: F T F F
void ButtonLed_noled::process() {
long now = millis();
int period = now & 0xFFE0; // each period is 32 ms
if(period != lastButtonPeriod) { // If we are in a new period
lastButtonPeriod = period; // .. remember it
pinMode(pin, INPUT); // .. change the pin to input..
digitalWrite(pin, HIGH); // .. and activate pull up
newState = (sense == digitalRead(pin)); // .. and read it, is the button up or down
pinMode(pin, OUTPUT); // .. return pin to output mode
digitalWrite(pin, ledState); // .. and make sure its showing its state
if(newState != lastState) { // ..if button changed then..
lastState = newState; // ....remember the button state
} else { // ..else its position is stable and so debounced
if(state != newState) { // ....But is it a new state?..
state = newState; // .....yes, so update
lastDuration = duration + 32; // and remember the duration of the last state
timeOfLastChange = now; // so we can calc duration
duration = 0; // start timing new state
} else { // .....no, the same state is continuing, so
duration = millis() - timeOfLastChange; // ......calculate its duration
}
}
}
return;
}
|
c5f5abf043abfdf6ec4553d92397caa117c132a5 | 77da8c47ac180754edfe06b0fa42fa6afb76d226 | /RobinHoodHashTable.h | 50020e016371adcb9a734119acd03c4a6c446633 | [] | no_license | xinyigu930/Programming-Abstractions | a8bf7331ae74c9b7a07ebc0218e8d637e40aa218 | 9e6078127404661863a209fb27f0a1be2a120f13 | refs/heads/main | 2023-03-30T07:24:40.138987 | 2021-03-22T17:27:24 | 2021-03-22T17:27:24 | 333,314,849 | 2 | 0 | null | 2021-02-07T22:50:45 | 2021-01-27T05:33:12 | C++ | UTF-8 | C++ | false | false | 3,148 | h | RobinHoodHashTable.h | #pragma once
#include "HashFunction.h"
#include "Demos/Utility.h"
#include "GUI/SimpleTest.h"
#include "GUI/MemoryDiagnostics.h"
#include <string>
class RobinHoodHashTable {
public:
/**
* Constructs a new Robin Hood hash table that uses the hash function given
* as the argument. (Note that the hash function lets you determine how
* many slots to use; you can get this by calling hashFn.numSlots().)
*/
RobinHoodHashTable(HashFunction<std::string> hashFn);
/**
* Cleans up all memory allocated by this hash table.
*/
~RobinHoodHashTable();
/**
* Returns whether the table is empty.
*/
bool isEmpty() const;
/**
* Returns the number of elements in the table.
*/
int size() const;
/**
* Inserts the specified element into this hash table. If the element already
* exists, this leaves the table unchanged. If there is no space in the table
* to insert an element - that is, every slot is full - this should return
* false to indicate that there is no more space.
*
* This function returns whether the element was inserted into the table.
*/
bool insert(const std::string& key);
/**
* Returns whether the specified key is contained in this hash tasble.
*/
bool contains(const std::string& key) const;
/**
* Removes the specified element from this hash table. If the element is not
* present in the hash table, this operation is a no-op.
*
* You should implement this operation using backward-shift deletion, as
* described in lecture.
*
* Returns true if the element was removed and false otherwise.
*/
bool remove(const std::string& key);
/**
* Prints out relevant information to assist with debugging.
*/
void printDebugInfo() const;
private:
/* Type representing a slot in the table. Full slots have their distances
* set to the distance from the home slot (measured by starting at that
* slot and walking forward, wrapping around the table if necessary). Empty
* slots have their distance set to the constant EMPTY_SLOT.
*
* Our tests expect the Slot type to look exactly like this; please do not
* modify this type.
*/
struct Slot {
std::string element;
int distance;
TRACK_ALLOCATIONS_OF(Slot);
};
/* Constant used to denote that a slot is empty. Distances can't be negative,
* so this can't be confused for a valid distance.
*/
static const int EMPTY_SLOT = -137;
/* Pointer to the elements. Our tests expect this field to be here, so please do
* not change this definition.
*/
Slot* elems = nullptr;
int allocatedSize;
int logicalSize;
HashFunction<std::string> Hash;
/* Finds the index of the element if the element is in the hashtable. */
int findElement (const std::string& key) const;
/* Internal shenanigans to make this play well with C++. */
DISALLOW_COPYING_OF(RobinHoodHashTable);
ALLOW_TEST_ACCESS();
MAKE_PRINTERS_FOR(Slot);
MAKE_COMPARATORS_FOR(Slot);
};
|
1236e54fce47c70764c2f071d4fe283bf9289d45 | 41a4e547077f4f21b77ea19c0c4f2640d8cf67c8 | /examples/inheritance.cpp | e01f307e33d4f955b9f2122f5a75cb9faf8bd9fc | [] | no_license | RahulRavishankar/Meta-Objects-in-Cpp | fcefd5c1d42f686349d2f26d54a0a4bad012d7a2 | 7707ca3144e5fb44b8388f19e039615f4cff27b7 | refs/heads/main | 2023-06-05T12:14:43.772029 | 2021-06-27T06:58:27 | 2021-06-27T06:58:27 | 380,671,138 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,106 | cpp | inheritance.cpp | #include <iostream>
#include <vector>
#include <list>
using namespace std;
#include "class_definition.h"
#include "object.h"
#include "attribute.h"
#include "value.h"
#include "type.h"
int main()
{
Type::init();
// Define a base class
ClassDef * product = new ClassDef(0, "Product");
product->addAttribute(Attribute("Product Number", Type::intT));
product->addAttribute(Attribute("Name", Type::stringT));
product->addAttribute(Attribute("Price", Type::doubleT));
product->addAttribute(Attribute("Weight", Type::doubleT));
// Create a list of attributes
list<Attribute> attrL;
attrL.push_back(Attribute("Author", Type::stringT));
attrL.push_back(Attribute("Title", Type::stringT));
attrL.push_back(Attribute("ISBN", Type::intT));
// Define a derived class with the above list of attributes
ClassDef * book = new ClassDef(product, "Book", attrL.begin(), attrL.end());
// Display the attributes of the derived class
cout<<"Class: Book\n";
ClassDef::AttrIterator a;
size_t idx;
for (a = book->attribBegin(), idx = 0;a != book->attribEnd(); ++a, ++idx)
{
string attr_name = (*a).getName();
int type_id = (*a).getType();
cout << attr_name << ": "<< type_id <<"\n";
}
cout<<"------------------------------------------------\n";
// Create a derived class object
Object * book_obj(book->newObject());
book_obj->setValue("Product Number", RealValue<int>(12345));
book_obj->setValue("Author", RealValue<string>("Robert Kanigel"));
book_obj->setValue("Title", RealValue<string>("The Man who knew Infinity"));
book_obj->setValue("Weight", RealValue<double>(150));
// Display the derived class object
cout<<"Object of Book: \n";
for (a = book_obj->instanceOf().attribBegin(), idx = 0;a != book_obj->instanceOf().attribEnd(); ++a, ++idx)
{
string attr_name = (*a).getName();
cout << attr_name << ": "
<< book_obj->getValue(attr_name)->asString() << endl;
}
return 0;
} |
e768663468888f4baef84253b6d956b838d0330d | eddc5a0f584fd5abb5b37086ca3c273522629235 | /src/main.cpp | 37c6800dec59c2a5454985e413fd4af3a02c9f6e | [] | no_license | mohamedsayed18/Airhockey2 | 654f9300467c58d356196668cdf7a428cf9e274d | 08925123b50dc0fd9ddb1cbcc5a26bc121824399 | refs/heads/master | 2022-08-03T15:34:15.762348 | 2020-05-25T17:07:02 | 2020-05-25T17:07:02 | 264,381,563 | 0 | 0 | null | 2020-05-20T12:01:06 | 2020-05-16T07:18:02 | C++ | UTF-8 | C++ | false | false | 3,392 | cpp | main.cpp | /*
TODO
simple ball with graphics
* dynamic ball
* grapgic window
walls for the playground: polygonShape.SetAsEdge( b2Vec2(-15,0), b2Vec2(15,0) );
Let's create players
*/
#include "proj.cpp"
int main() {
walls();
players();
//Create dynamic body (ball)
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(3.5f, 2.0f);
b2Body* body = world.CreateBody(&bodyDef); //Create the body
//shape
b2CircleShape player;
player.m_p.Set(0.0f, 0.0f); //Position with respect to centre of shape
player.m_radius = 0.1f; //10 pixel
//fixture
b2FixtureDef fixtureDef;
fixtureDef.shape = &player;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.1f;
fixtureDef.restitution = 0.5;
body->CreateFixture(&fixtureDef);
//b2Vec2 p = body->GetWorldPoint(b2Vec2(0.0f, 0.0f));
//b2Vec2 f (2.1f, 0.3f);
//body->ApplyLinearImpulse( f, p, false);
//simulation
//Let's start simulation
float timeStep = 1.0f / 60.0f;
int32 velocityIterations = 6;
int32 positionIterations = 2;
// The GUI
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!"); //Window
// The ball
sf::CircleShape ball(10.f);
ball.setFillColor(sf::Color::Green);
// players
sf::CircleShape pl1(10.f);
sf::CircleShape pl2(10.f);
sf::CircleShape pl3(10.f);
sf::CircleShape pl4(10.f);
pl1.setFillColor(sf::Color::Blue);
pl2.setFillColor(sf::Color::Blue);
pl3.setFillColor(sf::Color::Blue);
pl4.setFillColor(sf::Color::Blue);
// The walls
sf::RectangleShape rectangle1(sf::Vector2f(700.f, 50.f));
sf::RectangleShape rectangle2(sf::Vector2f(50.f, 300.f));
sf::RectangleShape rectangle3(sf::Vector2f(700.f, 50.f));
sf::RectangleShape rectangle4(sf::Vector2f(50.f, 300.f));
rectangle1.setPosition(0,0);
rectangle2.setPosition(650, 50);
rectangle3.setPosition(0,350);
rectangle4.setPosition(0,50);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
world.Step(timeStep, velocityIterations, positionIterations);
//body->ApplyLinearImpulse( b2Vec2 (0.0f, 0.0f), p, true);
b2Vec2 position = body->GetPosition();
b2Vec2 p1_pos = player1->GetPosition();
b2Vec2 p2_pos = player2->GetPosition();
b2Vec2 p3_pos = player3->GetPosition();
b2Vec2 p4_pos = player4->GetPosition();
float angle = body->GetAngle();
printf("%4.2f %4.2f\n", position.x, position.y);
ball.setPosition(position.x*SCALE, position.y*SCALE);
pl1.setPosition(p1_pos.x*SCALE, p1_pos.y*SCALE);
pl2.setPosition(p2_pos.x*SCALE, p2_pos.y*SCALE);
pl3.setPosition(p3_pos.x*SCALE, p3_pos.y*SCALE);
pl4.setPosition(p4_pos.x*SCALE, p4_pos.y*SCALE);
window.clear();
window.draw(ball);
window.draw(rectangle1);
window.draw(rectangle2);
window.draw(rectangle3);
window.draw(rectangle4);
window.draw(pl1);
window.draw(pl2);
window.draw(pl3);
window.draw(pl4);
window.display();
}
//clean the world
//world->DestroyBody(body);
return 0;
}
|
5e759d4d3a2c5d084891d36787d8d85991dfc78b | 4fc538b794d6ae034e09c5012d02c30eec18c166 | /Collections/SlList.h | 126d52243a148c67d85a7139fcf678b5c303f0c6 | [] | no_license | Vasek-gh/CMakeCrossTest | 91055e517da23c0a6ca01c14b1a1c439e2a35231 | 1c83bd2ac2f42059138b29d5a76c7e7ef7a14370 | refs/heads/master | 2021-01-20T06:19:26.849523 | 2018-02-06T20:42:26 | 2018-02-06T20:42:36 | 89,863,861 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,384 | h | SlList.h | #ifndef GSLBASELIST_H
#define GSLBASELIST_H
#include <stdint.h>
#include "../Debug.h"
#include "../Exception.h"
#include "Consts.h"
#include "Nodes.h"
namespace GreedyContainers {
namespace Internal {
//##############################################################################
//
// BaseQueue
//
//##############################################################################
template<class T, class Allocator>
class BaseSingleLinkedList
{
public:
using NodeType = SlNode<T>;
using NodeAllocatorType = NodePool<NodeType, Allocator>;
using ItemHelperType = ItemHelper<T, NodeType>;
public:
using IterType = SlIter<T>;
using ItemType = Item<T, NodeType>;
~BaseSingleLinkedList()
{
releaseAll();
}
void remove(ItemType& item)
{
removeNode(ItemHelperType::getNode(item));
ItemHelperType::release(item);
}
void clear()
{
releaseAll();
initData();
}
size_t count()
{
return _count;
}
IterType begin()
{
return _head.next;
}
IterType end()
{
return nullptr;
}
protected:
BaseSingleLinkedList(Allocator& allocator, size_t chunkSize, size_t capacity)
: _nodeAllocator(allocator, chunkSize, capacity)
{
initData();
}
BaseSingleLinkedList(BaseSingleLinkedList&& src)
: _nodeAllocator(std::move(src._nodeAllocator))
{
_last = src._last;
_head.next = src._head.next;
_head.value = nullptr;
_count = src._count;
src.initData();
}
template<typename ...Args>
ItemType doAddFirst(Args&&... args)
{
auto node = insertNode(&_head, std::forward<Args>(args)...);
return ItemHelperType::make(node);
}
template<typename ...Args>
ItemType doAddLast(Args&&... args)
{
auto node = insertNode(_last, std::forward<Args>(args)...);
return ItemHelperType::make(node);
}
template<typename ...Args>
ItemType doInsertBefore(ItemType& next, Args&&... args)
{
auto nextNode = ItemHelperType::getNode(next);
auto node = insertNode(getPrev(nextNode), std::forward<Args>(args)...);
return ItemHelperType::make(node);
}
template<typename ...Args>
ItemType doInsertAfter(ItemType& prev, Args&&... args)
{
auto prevNode = ItemHelperType::getNode(prev);
getPrev(prevNode);
auto node = insertNode(prevNode, std::forward<Args>(args)...);
return ItemHelperType::make(node);
}
private:
size_t _count;
NodeType _head;
NodeType* _last;
NodeAllocatorType _nodeAllocator;
void initData()
{
_last = &_head;
_head.next = nullptr;
_head.value = nullptr;
_count = 0;
}
template<typename ...Args>
NodeType* insertNode(NodeType* prev, Args&&... args)
{
auto node = _nodeAllocator.create(std::forward<Args>(args)...);
node->next = prev->next;
prev->next = node;
_count++;
if (node->next == nullptr) {
_last = node;
}
return node;
}
void removeNode(NodeType* node)
{
auto prev = getPrev(node);
auto next = node->next;
_nodeAllocator.release(node);
_count--;
prev->next = next;
if (prev->next == nullptr) {
_last = prev;
}
}
NodeType* getPrev(NodeType* node)
{
ASSERT(node != nullptr);
auto current = &_head;
while (current) {
if (current->next == node) {
return current;
}
current = current->next;
}
RAISE(ArgumentException, Errors::UnknownNode);
}
void releaseAll()
{
auto current = _head.next;
while (current) {
auto next = current->next;
_nodeAllocator.release(current);
current = next;
}
}
};
} // Internal end
//##############################################################################
//
// SlObjList
//
//##############################################################################
template<class T, class Allocator>
class SlObjList : public Internal::BaseSingleLinkedList<T, Allocator>
{
using Parent = Internal::BaseSingleLinkedList<T, Allocator>;
static_assert(
std::is_class<T>::value,
"Type parameter T must be a class type"
);
public:
using Item = typename Parent::ItemType;
using Iter = typename Parent::IterType;
SlObjList(Allocator& allocator, size_t chunkSize, size_t capacity)
: Parent(allocator, chunkSize, capacity)
{}
template<typename ...Args>
Item addFirst(Args&&... args)
{
return this->doAddFirst(std::forward<Args>(args)...);
}
template<typename ...Args>
Item addLast(Args&&... args)
{
return this->doAddLast(std::forward<Args>(args)...);
}
template<typename ...Args>
Item insertBefore(Item& next, Args&&... args)
{
return this->doInsertBefore(next, std::forward<Args>(args)...);
}
template<typename ...Args>
Item insertAfter(Item& prev, Args&&... args)
{
return this->doInsertAfter(prev, std::forward<Args>(args)...);
}
};
//##############################################################################
//
// SlPtrList
//
//##############################################################################
template<class T, class Allocator>
class SlPtrList : public Internal::BaseSingleLinkedList<T*, Allocator>
{
using Parent = Internal::BaseSingleLinkedList<T*, Allocator>;
static_assert(
std::is_class<T>::value,
"Type parameter T must be a class type"
);
public:
using Item = typename Parent::ItemType;
using Iter = typename Parent::IterType;
SlPtrList(Allocator& allocator, size_t chunkSize, size_t capacity)
: Parent(allocator, chunkSize, capacity)
{}
Item addFirst(T* value)
{
return this->doAddFirst(value);
}
Item addLast(T* value)
{
return this->doAddLast(value);
}
Item insertBefore(Item& next, T* value)
{
return this->doInsertBefore(next, value);
}
Item insertAfter(Item& prev, T* value)
{
return this->doInsertAfter(prev, value);
}
};
}
#endif // GSLBASELIST_H
|
236e11340365715727a9c3608bf68d8a0ef53959 | 7e3b297453d4e647c03eca187d8d045e9c74d6be | /src/mapdrawer.cpp | 3a41e1af5372ac41b44748dca55848e657ebb344 | [] | no_license | juyebshin/my_slam | e9507f640428817606ebb395b6b452ed81d28fd4 | 7a4ba813be07e9706142d4cc91b67dc388a14980 | refs/heads/master | 2023-08-31T16:03:28.983812 | 2021-10-06T07:41:49 | 2021-10-06T07:41:49 | 414,081,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,065 | cpp | mapdrawer.cpp | #include "mapdrawer.hpp"
#include "tracking.hpp"
#include "keyframe.hpp"
#include "map.hpp"
#include <iostream>
using namespace std;
namespace MY_SLAM
{
MapDrawer::MapDrawer(Map* pMap) : mpMap(pMap)
{
}
MapDrawer::MapDrawer(Map* pMap, const std::string &strSettingPath) : mpMap(pMap)
{
cv::FileStorage fSettings(strSettingPath, cv::FileStorage::READ);
mKeyFrameSize = fSettings["Viewer.KeyFrameSize"];
mKeyFrameLineWidth = fSettings["Viewer.KeyFrameLineWidth"];
mGraphLineWidth = fSettings["Viewer.GraphLineWidth"];
mPointSize = fSettings["Viewer.PointSize"];
mCameraSize = fSettings["Viewer.CameraSize"];
mCameraLineWidth = fSettings["Viewer.CameraLineWidth"];
}
// this is not used
void MapDrawer::update(Tracking *pTracker)
{
QMutexLocker locker(&mMutexCamera);
mvCameraTraj = pTracker->getTrajectories();
// if(mvCameraTraj.size())
// mCameraPose = cv::Mat(4, 4, CV_32F, mvCameraTraj.back());
mvpKeyFrames = pTracker->getAllKeyFrames();
}
void MapDrawer::getCurrentOpenGLCameraMatrix(float *m)
{
m = new float[16];
if(!mCameraPose.empty())
{
cv::Mat Rwc(3,3,CV_32F);
cv::Mat twc(3,1,CV_32F);
{
QMutexLocker locker(&mMutexCamera);
Rwc = mCameraPose.rowRange(0,3).colRange(0,3).t();
twc = -Rwc*mCameraPose.rowRange(0,3).col(3);
}
m[0] = Rwc.at<float>(0,0);
m[1] = Rwc.at<float>(1,0);
m[2] = Rwc.at<float>(2,0);
m[3] = 0.0;
m[4] = Rwc.at<float>(0,1);
m[5] = Rwc.at<float>(1,1);
m[6] = Rwc.at<float>(2,1);
m[7] = 0.0;
m[8] = Rwc.at<float>(0,2);
m[9] = Rwc.at<float>(1,2);
m[10] = Rwc.at<float>(2,2);
m[11] = 0.0;
m[12] = twc.at<float>(0);
m[13] = twc.at<float>(1);
m[14] = twc.at<float>(2);
m[15] = 1.0;
}
else
{
// Identity matrix
m[0] = 1.0;
m[1] = 0.0;
m[2] = 0.0;
m[3] = 0.0;
m[4] = 0.0;
m[5] = 1.0;
m[6] = 0.0;
m[7] = 0.0;
m[8] = 0.0;
m[9] = 0.0;
m[10] = 1.0;
m[11] = 0.0;
m[12] = 0.0;
m[13] = 0.0;
m[14] = 0.0;
m[15] = 1.0;
}
}
void MapDrawer::getCameraTrajectories(std::vector<cv::Mat> &vTraj)
{
QMutexLocker locker(&mMutexCamera);
// int N = mvpKeyFrames.size();
// sort(mvpKeyFrames.begin(), mvpKeyFrames.end(), KeyFrame::lId);
// vTraj.resize(mvpKeyFrames.size()); // reserve does not work!
// for(int i = 0; i < N; i++)
// {
// KeyFrame* pKF = mvpKeyFrames[i];
// vTraj[i] = pKF->getPose();
// }
std::vector<KeyFrame*> vpKFs = mpMap->getAllKeyFrames();
sort(vpKFs.begin(), vpKFs.end(), KeyFrame::lId);
vTraj.resize(vpKFs.size());
if(vpKFs.size())
cout << "last keyframe id: " << vpKFs.back()->mnId << endl;
for(size_t i = 0; i < vpKFs.size(); i++)
{
KeyFrame* pKF = vpKFs[i];
vTraj[i] = pKF->getPose();
}
}
} // namespace MY_SLAM
|
86c192b98734843303abbde55d581cda98ba5722 | 79fab76db9f2593ecd4b7c90c5b8b25e4d53405e | /src/mew/widgets/ShellFolder.cpp | 4b2214a4d1de520a1c93c0dd0057fd4c4c7c576d | [] | no_license | takechi/Avestan | ecaf544579078e0eba3330b934cbc11844ea38a2 | d17c41eae80956920dfcdc4d49f54f0b34eada1c | refs/heads/master | 2023-07-25T15:45:00.778622 | 2023-07-07T14:35:35 | 2023-07-07T14:35:35 | 54,634,706 | 34 | 6 | null | null | null | null | SHIFT_JIS | C++ | false | false | 48,071 | cpp | ShellFolder.cpp | // ShellFolder.cpp
#pragma once
#include "stdafx.h"
#include "../private.h"
#include "io.hpp"
#include "ShellFolder.h"
#include "../server/main.hpp" // もうぐちゃぐちゃ……
static const UINT MAX_HISTORY = 20;
const DWORD MEW_FWF_ALWAYS = FWF_SHOWSELALWAYS | FWF_NOWEBVIEW;
const DWORD MEW_FWF_ALWAYSNOT = FWF_ABBREVIATEDNAMES | FWF_SNAPTOGRID | FWF_OWNERDATA | FWF_BESTFITWINDOW | FWF_DESKTOP |
FWF_SINGLESEL | FWF_NOSUBFOLDERS | FWF_TRANSPARENT | FWF_NOCLIENTEDGE | FWF_NOSCROLL |
FWF_NOICONS | FWF_SINGLECLICKACTIVATE | FWF_NOWEBVIEW | FWF_HIDEFILENAMES;
// FWF_TRANSPARENT : 効果が無いぽい
// FWF_NOICONS : 何も描画されなくなる
#pragma comment(lib, "imm32.lib")
enum ShellInternalMessage {
// IShellBrowserを実装するウィンドウはこのメッセージを処理しなくてはならないらしいが、
// XPでは呼ばれないような気がする。
WM_GETISHELLBROWSER = WM_USER + 7,
WM_ENABLECHECKBOXCHANGE, // (wParam)bool enabled
};
//==============================================================================
namespace mew {
namespace ui {
#define USE_ADHOC_FIX_FOR_SHELLBROWSER_LISTVIEW_DETAILS
#if defined(USE_ADHOC_FIX_FOR_SHELLBROWSER_LISTVIEW_DETAILS)
constexpr UINT_PTR IDEvent_ListView_Details = 1;
constexpr UINT Elapse_ListView_Details = 50;
VOID CALLBACK setViewModeDetailsTimerProc(HWND hwndList, UINT, UINT_PTR idEvent, DWORD) {
::KillTimer(hwndList, idEvent);
POINT pt;
ListView_GetOrigin(hwndList, &pt);
if (pt.y < 0) {
ListView_SetView(hwndList, LV_VIEW_SMALLICON);
ListView_SetView(hwndList, LV_VIEW_DETAILS);
}
}
#endif
Shell::History::History() { m_cursor = 0; }
bool Shell::History::Add(mew::io::IEntry* entry) {
ASSERT(entry);
if (!m_history.empty()) {
if (entry->Equals(GetRelativeHistory(0))) {
return false;
}
}
m_history.resize(m_cursor);
m_history.push_back(entry);
if (m_cursor > MAX_HISTORY) {
m_history.pop_front();
}
m_cursor = m_history.size();
return true;
}
void Shell::History::Replace(mew::io::IEntry* entry) {
ASSERT(entry);
if (m_cursor == 0) {
return;
}
--m_cursor;
Add(entry);
}
mew::io::IEntry* Shell::History::GetRelativeHistory(int step, size_t* index) {
size_t at = (size_t)math::clamp<int>(m_cursor + step, 1, m_history.size()) - 1;
if (index) {
*index = at;
}
return m_history[at];
}
size_t Shell::History::Back(size_t step) {
if (m_cursor < step) {
size_t c = m_cursor;
m_cursor = 0;
return c;
} else {
m_cursor -= step;
return step;
}
}
size_t Shell::History::BackLength() const { return m_cursor <= 1 ? 0 : m_cursor - 1; }
size_t Shell::History::Forward(size_t step) {
if (m_cursor + step > m_history.size()) {
size_t c = m_cursor;
m_cursor = m_history.size();
return m_history.size() - c;
} else {
m_cursor += step;
return step;
}
}
size_t Shell::History::ForwardLength() const { return m_history.size() - m_cursor; }
//==============================================================================
namespace {
static SHELLFLAGSTATE theShellFlagState;
// メンバには触らないのでスタティックに一つだけ作る
class SHELLDLL_DefView : public CMessageMap {
public:
BOOL ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapId = 0) {
switch (uMsg) {
case WM_CONTEXTMENU: // そのまま親に転送する
lResult = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
return true;
case WM_MOUSEWHEEL:
lResult = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
return true;
case WM_ERASEBKGND:
lResult = 1;
return true;
case WM_NOTIFY:
switch (((NMHDR*)lParam)->code) {
case LVN_BEGINLABELEDIT:
SendMessage(GetParent(hWnd), uMsg, wParam, lParam);
break;
case LVN_ITEMCHANGING:
lResult = SendMessage(GetParent(hWnd), uMsg, wParam, lParam);
if (lResult) return true;
break;
}
break;
}
return false;
}
};
static SHELLDLL_DefView theDefViewMap;
// メンバには触らないのでスタティックに一つだけ作る
class SHELLDLL_ListView : public CMessageMap {
private:
static bool ListView_LoopCursor(HWND hWnd, UINT direction, UINT vkeyReplace) {
if (!theAvesta->LoopCursor) {
return false;
}
int focus = ListView_GetNextItem(hWnd, -1, LVNI_FOCUSED);
if (focus < 0) {
return false;
}
int next = ListView_GetNextItem(hWnd, focus, direction);
if (next >= 0 && next != focus) {
return false;
}
::SendMessage(hWnd, WM_KEYDOWN, vkeyReplace, 0);
return true;
}
public:
BOOL ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapId = 0) {
switch (uMsg) {
case WM_CONTEXTMENU: // そのまま親に転送する
lResult = ::DefWindowProc(hWnd, uMsg, wParam, lParam);
return true;
case WM_LBUTTONDOWN: {
LVHITTESTINFO hit = {GET_XY_LPARAM(lParam), 0, -1, 0};
int index = ListView_HitTest(hWnd, &hit);
if (index >= 0) {
if ((hit.flags & (LVHT_ONITEMICON | LVHT_ONITEMLABEL)) && IsKeyPressed(VK_SHIFT)) {
int selected = ListView_GetNextItem(hWnd, -1, LVNI_ALL | LVNI_SELECTED);
if (selected == -1 || (selected == index && ListView_GetSelectedCount(hWnd) ==
1)) { // 無選択状態での Shift+左クリック の動作が気に入らないため。
ListView_SetItemState(hWnd, index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
::SendMessage(::GetParent(::GetParent(hWnd)), WM_ENABLECHECKBOXCHANGE, (WPARAM) false, lParam);
return TRUE;
}
}
bool onCheckBox = ((hit.flags & LVHT_ONITEMSTATEICON) != 0);
return ::SendMessage(::GetParent(::GetParent(hWnd)), WM_ENABLECHECKBOXCHANGE, (WPARAM)onCheckBox, lParam);
}
break;
}
case WM_MBUTTONDOWN: {
UINT32 m = theAvesta->MiddleClick;
if (m != 0) {
LVHITTESTINFO hit = {GET_XY_LPARAM(lParam), 0, -1, 0};
int index = ListView_HitTest(hWnd, &hit);
if (index >= 0 && (hit.flags & (LVHT_ONITEMICON | LVHT_ONITEMLABEL))) {
if (theAvesta->MiddleSingle) ListView_SetItemState(hWnd, -1, 0, LVIS_SELECTED);
ListView_SetItemState(hWnd, index, LVIS_SELECTED | LVIS_FOCUSED, LVIS_SELECTED | LVIS_FOCUSED);
afx::PumpMessage();
// TODO: ユーザがカスタマイズできるように
UINT32 mods = ui::GetCurrentModifiers();
if (mods == 0) {
mods = m;
}
afx::SetModifierState(VK_RETURN, mods);
::SendMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0);
afx::RestoreModifierState(VK_RETURN);
return true;
}
}
break;
}
case WM_KEYDOWN:
switch (wParam) {
case VK_SPACE:
::SendMessage(::GetParent(::GetParent(hWnd)), WM_ENABLECHECKBOXCHANGE, (WPARAM) true, 0xFFFFFFFF);
break;
case VK_UP:
if (ListView_LoopCursor(hWnd, LVNI_ABOVE, VK_END)) return true;
break;
case VK_DOWN:
if (ListView_LoopCursor(hWnd, LVNI_BELOW, VK_HOME)) return true;
break;
}
break;
case WM_LBUTTONUP:
if (wParam & MK_RBUTTON) {
POINT pt = {GET_XY_LPARAM(lParam)};
::ClientToScreen(hWnd, &pt);
::SendMessage(hWnd, WM_CONTEXTMENU, (WPARAM)hWnd, MAKELPARAM(pt.x, pt.y));
return true;
}
break;
case WM_MOUSEWHEEL:
lResult = ::SendMessage(GetParent(GetParent(hWnd)), uMsg, wParam, lParam);
if (lResult) {
return true;
}
break; // default.
case WM_SYSCHAR:
switch (wParam) {
case 13: // enter : これをつぶしておかないと、ビープが鳴るため。
return true;
}
break;
case LVM_SETVIEW:
::PostMessage(::GetParent(::GetParent(hWnd)), LVM_SETVIEW, wParam, lParam);
break;
}
return false;
}
};
static SHELLDLL_ListView theShellListMap;
// メンバには触らないのでスタティックに一つだけ作る
class SHELLDLL_Header : public CMessageMap {
public:
BOOL ProcessWindowMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult, DWORD dwMsgMapId = 0) {
switch (uMsg) {
case WM_SETFOCUS: {
TRACE(_T("Header WM_SETFOCUS"));
break;
}
case WM_KILLFOCUS: {
TRACE(_T("Header WM_KILLFOCUS"));
break;
}
default:
break;
}
return false;
}
};
static SHELLDLL_Header theShellHeaderMap;
} // namespace
//==============================================================================
class ShellBrowser : public Root<implements<IOleWindow, IShellBrowser, ICommDlgBrowser, ICommDlgBrowser2> > {
private:
Shell& m_Owner;
public:
ShellBrowser(Shell* owner) : m_Owner(*owner) {}
public: // IOleWindow
STDMETHODIMP GetWindow(HWND* lphwnd) {
*lphwnd = m_Owner;
return S_OK;
}
STDMETHODIMP ContextSensitiveHelp(BOOL fEnterMode) { return E_NOTIMPL; }
public: // ICommDlgBrowser
static HRESULT QueryFolderAsDefault(io::IEntry* entry, REFINTF pp) {
string path = entry->Path;
if (!path || afx::PathIsFolder(path.str())) {
return entry->QueryObject(pp);
} else {
return E_FAIL;
}
}
static bool IsVirtualFolder(io::IEntry* folder) {
ASSERT(folder);
if (afx::ILIsRoot(folder->ID)) {
return false; // desktop is not a virtual folder.
}
string path = folder->Path;
return !path;
}
STDMETHODIMP OnDefaultCommand(IShellView* pShellView) { // handle double click and ENTER key if needed
ref<io::IEntryList> selections;
if FAILED (m_Owner.GetContents(&selections, SELECTED)) {
return S_FALSE;
}
ref<IShellFolder> pCurrentFolder = m_Owner.GetCurrentFolder();
const int count = selections->Count;
if (IsVirtualFolder(
m_Owner
.GetCurrentEntry())) { // 仮想フォルダ。この場合は、どうせデフォルト実行以外できないので、OnDefaultExecute()しない。
bool containsFolder = false;
array<io::IEntry> entries;
entries.reserve(count);
// まず、1pass目でフォルダを含んでいるか否かを調べる.
for (int i = 0; i < count; ++i) {
ref<io::IEntry> item;
if FAILED (selections->GetAt(&item, i)) {
continue;
}
ref<io::IEntry> resolved;
item->GetLinked(&resolved);
entries.push_back(resolved);
if (containsFolder) { // すでにフォルダを含むことが分かっている場合は、これ以上のチェックを行う必要は無い
continue;
}
ref<IShellFolder> folder;
containsFolder = SUCCEEDED(QueryFolderAsDefault(resolved, &folder));
}
// 2pass目。フォルダを含まない場合は、デフォルト実行に任せる。
if (!containsFolder) return S_FALSE;
// フォルダを含んでいる場合...
for (size_t i = 0; i < entries.size(); ++i) {
ref<IShellFolder> folder;
if SUCCEEDED (entries[i]->QueryObject(&folder)) {
if (pCurrentFolder != m_Owner.GetCurrentFolder()) {
TRACE(_T("複数のフォルダに対して移動しようとしている"));
continue;
}
m_Owner.OnDefaultDirectoryChange(entries[i], folder);
} else { // zipfldr の場合は、この後で呼ばれるであろう ShellExecuteEx() に失敗するが、まぁ仕方ない……。
m_Owner.OnDefaultExecute(entries[i]);
}
}
} else { // 実フォルダ。
for (int i = 0; i < count; ++i) {
ref<io::IEntry> item;
if FAILED (selections->GetAt(&item, i)) continue;
ref<io::IEntry> resolved;
item->GetLinked(&resolved);
ref<IShellFolder> folder;
if SUCCEEDED (QueryFolderAsDefault(resolved, &folder)) {
if (pCurrentFolder != m_Owner.GetCurrentFolder()) {
TRACE(_T("複数のフォルダに対して移動しようとしている"));
continue;
}
m_Owner.OnDefaultDirectoryChange(resolved, folder);
} else {
m_Owner.OnDefaultExecute(item);
}
}
}
return S_OK;
}
STDMETHODIMP OnStateChange(IShellView* pShellView, ULONG uChange) { // handle selection, rename, focus if needed
// #define caseTrace(what) case what: TRACE(L#what); break;
// switch(uChange) {
// caseTrace(CDBOSC_SETFOCUS )// The focus has been set to the view.
// caseTrace(CDBOSC_KILLFOCUS )// The view has lost the focus.
// caseTrace(CDBOSC_SELCHANGE )// The selected item has changed.
// caseTrace(CDBOSC_RENAME )// An item has been renamed.
// caseTrace(CDBOSC_STATECHANGE )// An item has been checked or unchecked
// }
// #undef caseTrace
return m_Owner.OnStateChange(pShellView, uChange);
}
STDMETHODIMP IncludeObject(IShellView* pShellView, LPCITEMIDLIST pidl) { // 表示ファイルのフィルタリング。
// S_OK: show, S_FALSE: hide
return m_Owner.IncludeObject(pShellView, pidl);
}
public: // ICommDlgBrowser2
STDMETHODIMP GetDefaultMenuText(IShellView* pshv, WCHAR* pszText,
int cchMax) { // デフォルトの選択項目は「選択」なのでほとんど意味がない
return S_FALSE;
}
STDMETHODIMP GetViewFlags(DWORD* pdwFlags) { // すべてのファイルを表示すべきか否かの問い合わせ。
// CDB2GVF_SHOWALLFILES: 隠しファイルを表示する。
// 0: 隠しファイルを表示しない。
return m_Owner.GetViewFlags(pdwFlags);
}
STDMETHODIMP Notify(IShellView* pshv, DWORD dwNotifyType) { // コンテキストメニューが始まったor終わった
return S_OK;
}
public: // IShellBrowser
STDMETHODIMP InsertMenusSB(HMENU hmenuShared, LPOLEMENUGROUPWIDTHS lpMenuWidths) { return E_NOTIMPL; }
STDMETHODIMP SetMenuSB(HMENU hmenuShared, HOLEMENU holemenuReserved, HWND hwndActiveObject) { return E_NOTIMPL; }
STDMETHODIMP RemoveMenusSB(HMENU hmenuShared) { return E_NOTIMPL; }
STDMETHODIMP SetStatusTextSB(LPCOLESTR lpszStatusText) { return E_NOTIMPL; }
STDMETHODIMP EnableModelessSB(BOOL fEnable) { return E_NOTIMPL; }
STDMETHODIMP SetToolbarItems(LPTBBUTTON lpButtons, UINT nButtons, UINT uFlags) { return E_NOTIMPL; }
STDMETHODIMP TranslateAcceleratorSB(LPMSG lpmsg, WORD wID) { return E_NOTIMPL; }
STDMETHODIMP OnViewWindowActive(IShellView* pShellView) { return E_NOTIMPL; }
STDMETHODIMP GetViewStateStream(DWORD grfMode, IStream** ppStream) { return m_Owner.GetViewStateStream(grfMode, ppStream); }
STDMETHODIMP GetControlWindow(UINT id, HWND* lphwnd) {
if (!lphwnd) {
return E_POINTER;
}
switch (id) {
case FCW_STATUS:
*lphwnd = m_Owner;
return S_OK;
}
return E_NOTIMPL;
}
STDMETHODIMP SendControlMsg(UINT id, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT* pret) {
LRESULT lResult;
switch (id) {
case FCW_STATUS:
lResult = m_Owner.SendMessage(uMsg, wParam, lParam);
if (pret) {
*pret = lResult;
}
break;
}
return E_NOTIMPL;
}
STDMETHODIMP QueryActiveShellView(IShellView** ppShellView) { return m_Owner.m_pShellView.copyto(ppShellView); }
STDMETHODIMP BrowseObject(LPCITEMIDLIST pidl, UINT wFlags) { return E_NOTIMPL; }
};
//==============================================================================
Shell::Shell()
: m_WallPaperAlign(DirNone), m_wndShell(&theDefViewMap), m_wndList(&theShellListMap), m_wndHeader(&theShellHeaderMap) {
m_FolderSettings.ViewMode = ListStyleDetails;
m_FolderSettings.fFlags = FWF_AUTOARRANGE | MEW_FWF_ALWAYS;
m_AutoArrange = !!(m_FolderSettings.fFlags & FWF_AUTOARRANGE);
m_CheckBoxChangeEnabled = true;
m_CheckBox = false;
m_FullRowSelect = false;
m_GridLine = false;
m_ShowAllFiles = false;
m_RenameExtension = true;
UpdateShellState();
}
Shell::~Shell() { DisposeShellView(); }
void Shell::DisposeShellView() throw() {
SaveViewState();
if (m_wndHeader) {
m_wndHeader.UnsubclassWindow();
}
if (m_wndList) {
m_wndList.UnsubclassWindow();
}
if (m_wndShell) {
m_wndShell.UnsubclassWindow();
}
if (m_pShellView) {
IShellView* tmp = m_pShellView.detach();
tmp->UIActivate(SVUIA_DEACTIVATE);
tmp->DestroyViewWindow();
tmp->Release();
}
m_pCurrentEntry.clear();
m_pShellBrowser.clear();
}
HRESULT Shell::SaveViewState() {
if (!m_pShellView) {
return E_UNEXPECTED;
}
m_pShellView->GetCurrentInfo(&m_FolderSettings);
m_pViewStateStream.clear();
GetViewStateStream(STGM_WRITE, &m_pViewStateStream);
return m_pShellView->SaveViewState();
}
HRESULT Shell::UpdateShellState() {
SHGetSettings(&theShellFlagState, SSF_SHOWALLOBJECTS);
m_ShowAllFiles = !!theShellFlagState.fShowAllObjects;
return S_OK;
}
inline static MouseAndModifier WM_MOUSE_to_Button(UINT uMsg, WPARAM wParam) {
switch (uMsg) {
case WM_LBUTTONDOWN:
case WM_LBUTTONUP:
case WM_LBUTTONDBLCLK:
return MouseButtonLeft;
case WM_RBUTTONDOWN:
case WM_RBUTTONUP:
case WM_RBUTTONDBLCLK:
return MouseButtonRight;
case WM_MBUTTONDOWN:
case WM_MBUTTONUP:
case WM_MBUTTONDBLCLK:
return MouseButtonMiddle;
case WM_XBUTTONDOWN:
case WM_XBUTTONUP:
case WM_XBUTTONDBLCLK:
switch (GET_XBUTTON_WPARAM(wParam)) {
case XBUTTON1:
return MouseButtonX1;
case XBUTTON2:
return MouseButtonX2;
default:
return ModifierNone;
}
default:
return ModifierNone;
}
}
BOOL Shell::ProcessShellMessage(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& lResult) {
switch (uMsg) {
case WM_NOTIFY:
switch (((NMHDR*)lParam)->code) {
case LVN_BEGINLABELEDIT:
if (NMLVDISPINFO* info = (NMLVDISPINFO*)lParam) {
ref<io::IEntry> entry;
if SUCCEEDED (GetAt(&entry, info->item.iItem)) {
HWND hEdit = m_wndList.GetEditControl();
ASSERT(hEdit);
afx::Edit_SubclassSingleLineTextBox(hEdit, entry->Path.str(), theAvesta->EditOptions | afx::EditTypeFileName);
}
}
return true;
case LVN_ITEMCHANGING:
if (NMLISTVIEW* info = (NMLISTVIEW*)lParam) { // チェック状態の変化
UINT uNewCheck = (info->uNewState & 0x3000);
UINT uOldCheck = (info->uOldState & 0x3000);
lResult = (!m_CheckBoxChangeEnabled && uNewCheck && uOldCheck && uNewCheck != uOldCheck);
}
return true;
default:
break;
}
break; // default.
case WM_CREATE:
m_pShellBrowser.attach(new ShellBrowser(this));
break;
case WM_DESTROY:
DisposeShellView();
break;
case WM_FORWARDMSG:
return lResult = PreTranslateMessage((MSG*)lParam);
case WM_GETISHELLBROWSER:
// AddRef() は必要ない。
// SetWindowLongPtr(DWL_MSGRESULT, (LONG)(IShellBrowser*)this); //use this if dialog
lResult = (LRESULT)(IShellBrowser*)m_pShellBrowser;
return true;
case WM_ENABLECHECKBOXCHANGE:
lResult = false;
if (lParam != 0xFFFFFFFF && m_pShellView && m_CheckBox &&
get_Style() == ListStyleTile) { // TILE モードのときは、チェックボックスが正常に働かない
LVHITTESTINFO hit = {GET_XY_LPARAM(lParam), 0, -1, 0};
m_CheckBoxChangeEnabled = false;
int index = m_wndList.HitTest(&hit);
if (index >= 0) {
if (ref<IFolderView> pFolderView = cast(m_pShellView)) {
LPITEMIDLIST pidl = null;
Point ptItem;
if (SUCCEEDED(pFolderView->Item(index, &pidl)) && SUCCEEDED(pFolderView->GetItemPosition(pidl, &ptItem))) {
Point ptTranslate;
::GetCursorPos(&ptTranslate);
UINT svsi = SVSI_TRANSLATEPT; // これだけだと、TRANSLATEPT のついでに選択状態を変化させてしまうため、
svsi |= (m_wndList.GetItemState(index, LVIS_SELECTED) ? SVSI_SELECT : SVSI_DESELECT); // 選択状態を保存してやる。
if SUCCEEDED (pFolderView->SelectAndPositionItems(1, const_cast<LPCITEMIDLIST*>(&pidl), &ptTranslate, svsi)) {
enum {
XCENTER = 40,
YCENTER = 10,
RADIUS = 8,
};
int dx = math::abs(ptTranslate.x - ptItem.x - XCENTER);
int dy = math::abs(ptTranslate.y - ptItem.y - YCENTER);
if (dx < RADIUS && dy < RADIUS) { // onCheckBox
m_CheckBoxChangeEnabled = true;
m_wndList.SetCheckState(index, !m_wndList.GetCheckState(index));
lResult = true; // cancel default action
}
}
}
ILFree(pidl);
}
}
} else {
m_CheckBoxChangeEnabled = (wParam != 0);
}
return true;
case WM_SETFOCUS:
if (m_wndShell) m_wndShell.SetFocus();
return false;
case WM_SETTINGCHANGE:
UpdateShellState();
break;
case WM_MOUSEWHEEL:
lResult = OnListWheel(wParam, lParam);
return true;
case LVM_SETVIEW:
OnListViewModeChanged();
return true;
}
return false;
}
HRESULT Shell::MimicKeyDown(UINT vkey, UINT mods) {
if (!m_pShellView) {
return E_UNEXPECTED;
}
afx::SetModifierState(vkey, mods);
MSG msg = {m_wndList, WM_KEYDOWN, vkey, static_cast<LPARAM>(MapVirtualKey(vkey, 0) | 1)};
HRESULT hr = m_pShellView->TranslateAccelerator(&msg);
if (hr == S_FALSE) { // 処理されないので、ListViewにKEYDOWNを送ってエミュレート
m_wndList.SendMessage(WM_KEYDOWN, vkey, 0);
}
// ダイアログが表示されるなどし、TranslateAccelerator()が瞬間的に終わらなかった場合に対処する。
afx::RestoreModifierState(vkey);
return hr;
}
HRESULT Shell::ReCreateViewWindow(IShellFolder* pShellFolder, bool reload) {
HRESULT hr;
ASSERT(m_pShellBrowser);
if (!m_pShellBrowser) {
return E_INVALIDARG;
}
RECT rcView = {0, 0, 0, 0};
if (m_wndShell) {
m_wndShell.GetWindowRect(&rcView);
ScreenToClient(&rcView);
}
bool hasFocus = m_wndShell.HasFocus();
ASSERT(pShellFolder);
ref<IShellView> pNewShellView;
hr = pShellFolder->CreateViewObject(m_hWnd, IID_IShellView, (void**)&pNewShellView);
if FAILED (hr) {
TRACE(_T("error: CreateViewObject()"));
return hr;
}
if (m_wndHeader) {
m_wndHeader.UnsubclassWindow();
}
if (m_wndList) {
m_wndList.UnsubclassWindow();
}
if (m_wndShell) {
m_wndShell.UnsubclassWindow();
}
m_pViewStateStream.clear();
if (reload && SUCCEEDED(OnQueryStream(STGM_READ, &m_pViewStateStream))) {
FOLDERSETTINGS settings;
if SUCCEEDED (hr = m_pViewStateStream->Read(&settings, sizeof(FOLDERSETTINGS), NULL)) {
m_FolderSettings = settings;
bitof(m_FolderSettings.fFlags, FWF_CHECKSELECT) = m_CheckBox;
} else {
return hr;
}
}
HWND hwndShell = null;
m_FolderSettings.fFlags |= MEW_FWF_ALWAYS;
m_FolderSettings.fFlags &= ~MEW_FWF_ALWAYSNOT;
if (ref<IShellView2> view2 = cast(pNewShellView)) {
SV2CVW2_PARAMS params = {sizeof(SV2CVW2_PARAMS), m_pShellView, &m_FolderSettings, m_pShellBrowser, &rcView};
if SUCCEEDED (hr = view2->CreateViewWindow2(¶ms)) {
hwndShell = params.hwndView;
}
} else {
hr = pNewShellView->CreateViewWindow(m_pShellView, &m_FolderSettings, m_pShellBrowser, &rcView, &hwndShell);
}
m_pViewStateStream.clear();
if FAILED (hr) {
TRACE(_T("error: ShellListView.ReCreateViewWindow(), CreateViewWindow()"));
return hr;
}
// 作成に成功した。
ASSERT(!m_wndShell);
m_wndShell.SubclassWindow(hwndShell);
if (m_pShellView) {
m_pShellView->UIActivate(SVUIA_DEACTIVATE);
m_pShellView->DestroyViewWindow();
m_pShellView.clear();
}
m_pCurrentFolder = pShellFolder;
m_pShellView = pNewShellView;
m_pShellView->UIActivate(hasFocus ? SVUIA_ACTIVATE_FOCUS : SVUIA_ACTIVATE_NOFOCUS);
// 通常は、一番目の子供がリストビューなのだが、フォントフォルダの表示時は異なる
ASSERT(!m_wndList);
if (HWND hListView = ::FindWindowEx(m_wndShell, NULL, _T("SysListView32"), NULL)) {
m_wndList.SubclassWindow(hListView);
DWORD dwExStyle = 0;
if (m_CheckBox) {
dwExStyle |= LVS_EX_CHECKBOXES;
}
if (m_FullRowSelect) {
dwExStyle |= LVS_EX_FULLROWSELECT;
}
if (m_GridLine) {
dwExStyle |= LVS_EX_GRIDLINES;
}
m_wndList.SetExtendedListViewStyle(dwExStyle, LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES | LVS_EX_CHECKBOXES);
ImmAssociateContext(m_wndList, null);
if (HWND hHeader = m_wndList.GetHeader()) {
m_wndHeader.SubclassWindow(hHeader);
}
if (HFONT hFont = GetFont()) {
m_wndList.SetFont(hFont);
}
}
m_Grouping = (m_wndList ? m_wndList.SendMessage(LVM_ISGROUPVIEWENABLED, 0, 0) != 0 : false);
return S_OK;
}
HRESULT Shell::Refresh() {
if (!m_pShellView) {
return E_UNEXPECTED;
}
int column = 0;
bool ascending = true;
GetSortKey(&column, &ascending);
HRESULT hr = m_pShellView->Refresh();
if FAILED (hr) {
return hr;
}
SetSortKey(column, ascending);
UpdateBackground();
return S_OK;
}
HRESULT Shell::SetStatusByIndex(int index, Status status, bool unique) {
if (ref<IFolderView> folder = cast(m_pShellView)) {
switch (status) {
case FOCUSED:
ASSERT(!unique);
return folder->SelectItem(index, SVSI_FOCUSED | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
case SELECTED:
if (unique)
return folder->SelectItem(index, SVSI_DESELECTOTHERS | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
else
return folder->SelectItem(index, SVSI_SELECT | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
break;
case CHECKED:
ASSERT(!unique);
return folder->SelectItem(index, SVSI_CHECK | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
case UNSELECTED:
ASSERT(!unique);
return folder->SelectItem(index, SVSI_DESELECT | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
default:
return E_NOTIMPL;
}
} else {
ASSERT(0);
return E_NOTIMPL;
}
}
HRESULT Shell::SetStatusByUnknown(IUnknown* unk, Status status, bool unique) {
IShellFolder* folder = GetCurrentFolder();
if (!folder) {
return E_UNEXPECTED;
}
bool newLeaf = false;
LPITEMIDLIST leaf = null;
ref<io::IEntry> entry = cast(unk);
if (entry) {
leaf = ILFindLastID(entry->ID);
} else if (string name = cast(unk)) {
newLeaf = SUCCEEDED(folder->ParseDisplayName(m_hWnd, NULL, const_cast<PWSTR>(name.str()), NULL, &leaf, NULL));
}
if (!leaf) {
try {
ASSERT(!entry);
entry.create(__uuidof(io::Entry), unk);
leaf = ILFindLastID(entry->ID);
} catch (mew::exceptions::Error& e) {
TRACE(e.Message);
return e.Code;
}
}
ASSERT(leaf);
HRESULT hr = SetStatusByIDList(leaf, status, unique);
if (newLeaf) {
ILFree(leaf);
}
return hr;
}
HRESULT Shell::SetStatusByIDList(LPCITEMIDLIST leaf, Status status, bool unique) {
if (!leaf) {
return E_POINTER;
}
switch (status) {
case SELECTED:
if (unique) SelectNone();
return Select(leaf, SVSI_SELECT | SVSI_FOCUSED | SVSI_ENSUREVISIBLE);
default:
return E_INVALIDARG;
}
}
HRESULT Shell::Select(LPCITEMIDLIST leaf, UINT svsi) {
if (!m_pShellView) {
return E_UNEXPECTED;
}
return m_pShellView->SelectItem(leaf, svsi);
}
HRESULT Shell::SelectNone() { return m_pShellView ? m_pShellView->SelectItem(NULL, SVSI_DESELECTOTHERS) : E_FAIL; }
HRESULT Shell::SelectAll() {
if (!m_wndList.IsWindow()) {
return E_UNEXPECTED;
}
m_wndList.SetItemState(-1, LVIS_SELECTED, LVIS_SELECTED); // -1 で全選択
return S_OK;
}
HRESULT Shell::CheckAll(bool check) {
if (!m_CheckBox) {
return S_FALSE;
}
if (!m_wndList.IsWindow()) {
return E_UNEXPECTED;
}
m_CheckBoxChangeEnabled = true;
m_wndList.SetCheckState(-1, check); // -1 で全選択
return S_OK;
}
HRESULT Shell::SelectChecked() {
if (!m_CheckBox) {
return S_FALSE;
}
#if 0 // XP では SVGIO_CHECKED は取得できないっぽい
ref<IEntryList> entries;
HRESULT hr;
if FAILED (hr = GetContents(&entries, CHECKED)) return hr;
int count = entries->Count;
SelectNone();
for (int i = 0; i < count; i++) {
m_pShellView->SelectItem(entries->Leaf[i], SVSI_SELECT | SVSI_CHECK);
}
#else // 仕方ないので、リストビューを参照しながらチェックされたアイテムを選択する
if (!m_wndList.IsWindow()) {
return E_UNEXPECTED;
}
int count = m_wndList.GetItemCount();
int focus = m_wndList.GetNextItem(-1, LVNI_FOCUSED);
int focusNext = INT_MAX;
for (int i = 0; i < count; i++) {
if (m_wndList.GetCheckState(i)) {
m_wndList.SetItemState(i, LVIS_SELECTED, LVIS_SELECTED);
if (math::abs(focusNext - focus) > math::abs(i - focus)) {
focusNext = i;
}
} else {
m_wndList.SetItemState(i, 0, LVIS_SELECTED);
}
}
// 以前のフォーカスに最も近い、選択中の項目をフォーカスする。
if (focusNext < count) {
m_wndList.SetItemState(focusNext, LVIS_FOCUSED, LVIS_FOCUSED);
m_wndList.EnsureVisible(focusNext, false);
}
#endif
return S_OK;
}
HRESULT Shell::GetAt(REFINTF pp, size_t index) {
if (ref<IFolderView> folder = cast(m_pShellView)) {
LPITEMIDLIST pidl;
HRESULT hr = folder->Item(index, &pidl);
if FAILED (hr) return hr;
hr = m_pCurrentEntry->QueryObject(pp, pidl);
ILFree(pidl);
return hr;
}
return E_NOTIMPL;
}
HRESULT Shell::GetContents(REFINTF ppInterface, Status option) {
int svgio = 0;
switch (option) {
case StatusNone:
svgio = SVGIO_ALLVIEW | SVGIO_FLAG_VIEWORDER;
break;
case FOCUSED:
svgio = SVGIO_SELECTION;
break;
case SELECTED:
svgio = SVGIO_SELECTION | SVGIO_FLAG_VIEWORDER;
break;
case CHECKED:
svgio = SVGIO_CHECKED | SVGIO_FLAG_VIEWORDER;
break;
default:
TRESPASS();
}
if SUCCEEDED (GetContents_FolderView(ppInterface, svgio)) {
return S_OK;
} else {
return GetContents_ShellView(ppInterface, svgio);
}
}
HRESULT Shell::GetContents_FolderView(REFINTF ppInterface, int svgio) {
if (ref<IFolderView> folder = cast(m_pShellView)) {
ref<IDataObject> pDataObject;
HRESULT hr = folder->Items(svgio, IID_IDataObject, (void**)&pDataObject);
if FAILED (hr) {
return hr;
}
try {
ref<io::IEntryList> entries(__uuidof(io::EntryList), pDataObject);
return entries->QueryInterface(ppInterface);
} catch (mew::exceptions::Error& e) {
return e.Code;
}
}
return E_FAIL;
}
HRESULT Shell::GetContents_ShellView(REFINTF ppInterface, int svgio) {
HRESULT hr;
if (!m_pShellView) {
return E_UNEXPECTED;
}
// 特別処理
if (svgio == (SVGIO_SELECTION | SVGIO_FLAG_VIEWORDER)) {
return GetContents_Select(ppInterface);
}
if (svgio == (SVGIO_CHECKED | SVGIO_FLAG_VIEWORDER)) {
return GetContents_Checked(ppInterface);
}
ref<IDataObject> pDataObject;
if FAILED (hr = m_pShellView->GetItemObject(svgio, IID_IDataObject, (void**)&pDataObject)) {
return hr;
}
try {
ref<io::IEntryList> entries(__uuidof(io::EntryList), pDataObject);
return entries->QueryInterface(ppInterface);
} catch (mew::exceptions::Error& e) {
return e.Code;
}
}
HRESULT Shell::GetContents_Select(REFINTF ppInterface) {
if (!m_wndList.IsWindow()) {
return E_UNEXPECTED;
}
// IShellView::Item(SVGIO_SELECTION | SVGIO_FLAG_VIEWORDER) は、順番が狂ってしまう。
// 仕方ないので、全部取得し、リストビューを調べて再構築する.
HRESULT hr;
ref<io::IEntryList> entries;
if FAILED (hr = GetContents(&entries, StatusNone)) {
return hr;
}
ASSERT(entries->Count == (size_t)m_wndList.GetItemCount());
int index = -1;
std::vector<size_t> subset;
while (-1 != (index = m_wndList.GetNextItem(index, LVNI_SELECTED))) {
subset.push_back(index);
}
if (subset.empty()) {
return E_FAIL;
}
return entries->CloneSubset(ppInterface, &subset[0], subset.size());
}
HRESULT Shell::GetContents_Checked(REFINTF ppInterface) {
if (!m_wndList.IsWindow()) {
return E_UNEXPECTED;
}
HRESULT hr;
ref<io::IEntryList> entries;
if FAILED (hr = GetContents(&entries, StatusNone)) {
return hr;
}
ASSERT(entries->Count == (size_t)m_wndList.GetItemCount());
std::vector<size_t> subset;
int count = m_wndList.GetItemCount();
for (int i = 0; i < count; i++) {
if (m_wndList.GetCheckState(i)) {
subset.push_back(i);
}
}
if (subset.empty()) {
return E_FAIL;
}
return entries->CloneSubset(ppInterface, &subset[0], subset.size());
}
HRESULT Shell::GoUp(size_t step, bool selectPrev) {
if (!m_pCurrentEntry) {
return E_FAIL;
}
if (step == 0) {
return !afx::ILIsRoot(m_pCurrentEntry->ID);
}
HRESULT hr;
ref<io::IEntry> current = m_pCurrentEntry;
ref<io::IEntry> parent;
if FAILED (hr = m_pCurrentEntry->QueryObject(&parent, step)) {
return hr;
}
if FAILED (hr = GoAbsolute(parent, GoNew)) {
return hr;
}
// 以前いたフォルダにカーソルを合わせる.
if (selectPrev) {
if (LPITEMIDLIST prev = ILCloneFirst((LPITEMIDLIST)(((BYTE*)current->ID) + ILGetSize(parent->ID) - 2))) {
Select(prev, SVSI_FOCUSED | SVSI_SELECT | SVSI_ENSUREVISIBLE);
ILFree(prev);
}
}
return S_OK;
}
// parent 相対の child のIDリストを返す. 親子関係が間違っている場合の動作は未定義.
static LPCITEMIDLIST ILFindRelative(LPCITEMIDLIST parent, LPCITEMIDLIST child) {
size_t size = ILGetSize(parent) - 2; // ターミネータの分だけ-2する
return (LPCITEMIDLIST)(((BYTE*)child) + size);
}
static LPITEMIDLIST ILCreateChild(LPCITEMIDLIST parent, LPCITEMIDLIST child) {
return ILCloneFirst(ILFindRelative(parent, child));
}
HRESULT Shell::GoBack(size_t step, bool selectPrev) {
if (!m_pCurrentEntry) {
return E_FAIL;
}
if (step == 0) {
return m_History.BackLength();
}
HRESULT hr;
ref<io::IEntry> prev = m_pCurrentEntry;
ref<io::IEntry> next = m_History.GetRelativeHistory(-(int)step);
if (!next || next->Equals(prev)) {
return E_FAIL;
}
if FAILED (hr = GoAbsolute(next, GoAgain)) {
return hr;
}
m_History.Back(step);
// 以前いたフォルダにカーソルを合わせる.
if (selectPrev && ILIsParent(next->ID, prev->ID, false)) {
LPITEMIDLIST child = ILCreateChild(next->ID, prev->ID);
Select(child, SVSI_FOCUSED | SVSI_SELECT | SVSI_ENSUREVISIBLE);
ILFree(child);
}
return hr;
}
HRESULT Shell::GoForward(size_t step, bool selectPrev) {
if (!m_pCurrentEntry) {
return E_FAIL;
}
if (step == 0) {
return m_History.ForwardLength();
}
HRESULT hr;
ref<io::IEntry> prev = m_pCurrentEntry;
ref<io::IEntry> next = m_History.GetRelativeHistory(step);
if (!next || next->Equals(prev)) {
return E_FAIL;
}
if FAILED (hr = GoAbsolute(next, GoAgain)) {
return hr;
}
m_History.Forward(step);
// 以前いたフォルダにカーソルを合わせる.
if (selectPrev && ILIsParent(next->ID, prev->ID, false)) {
LPITEMIDLIST child = ILCreateChild(next->ID, prev->ID);
Select(child, SVSI_FOCUSED | SVSI_SELECT | SVSI_ENSUREVISIBLE);
ILFree(child);
}
return hr;
}
HRESULT Shell::GoAbsolute(io::IEntry* path, GoType go) {
HRESULT hr;
if (!path) {
return E_INVALIDARG;
}
// 「フォルダを別ウィンドウで開く」という動作の際に現在の設定が反映されないため、
// OnDirectoryChanging() の前に呼ぶように変更した。
SaveViewState();
if (!OnDirectoryChanging(path, go)) {
return E_ABORT;
}
ref<io::IEntry> resolved;
path->GetLinked(&resolved);
if (!path->Exists()) {
TRACE(_T("error: OpenFolder(not-existing)"));
return STG_E_FILENOTFOUND;
}
if (!resolved->IsFolder()) {
ref<io::IEntry> parentEntry;
if (SUCCEEDED(hr = resolved->GetParent(&parentEntry)) && SUCCEEDED(hr = GoAbsolute(parentEntry, GoNew))) {
SetStatusByIDList(ILFindLastID(resolved->ID), SELECTED);
return S_OK;
} else {
return hr;
}
}
ref<IShellFolder> pShellFolder;
if (FAILED(hr = resolved->QueryObject(&pShellFolder))) {
TRACE(_T("error: ShellListView.GoAbsolute(), GetSelfFolder()"));
// 仕方ないのでデスクトップを。
if FAILED (hr = SHGetDesktopFolder(&pShellFolder)) {
return hr;
}
}
if (m_pCurrentEntry && m_pCurrentEntry->Equals(resolved)) { // 同じフォルダへの移動
return S_OK;
}
ref<io::IEntry> pPrevEntry = m_pCurrentEntry;
m_pCurrentEntry = resolved;
if FAILED (hr = ReCreateViewWindow(pShellFolder, true)) { // 失敗した場合に元に戻す
m_pCurrentEntry = pPrevEntry;
return hr;
}
switch (go) {
case GoNew:
m_History.Add(resolved);
break;
case GoAgain:
break;
case GoReplace:
m_History.Replace(resolved);
break;
default:
TRESPASS();
}
OnDirectoryChanged(resolved, go);
OnListViewModeChanged();
m_wndList.SetFocus();
#if defined(USE_ADHOC_FIX_FOR_SHELLBROWSER_LISTVIEW_DETAILS)
if (get_Style() == ListStyleDetails) {
::SetTimer(m_wndList, IDEvent_ListView_Details, Elapse_ListView_Details, setViewModeDetailsTimerProc);
}
#endif
m_wndList.SetRedraw(true);
return S_OK;
}
HRESULT Shell::EndContextMenu(IContextMenu* pMenu, UINT cmd) {
WCHAR text[MAX_PATH];
HRESULT hr = afx::SHEndContextMenu(pMenu, cmd, m_hWnd, text);
if SUCCEEDED (hr) {
if (str::equals_nocase(text, L"グループで表示(&G)")) {
TRACE(L"INVOKE COMMAND : グループで表示(&G)");
m_Grouping = !m_Grouping;
}
}
return hr;
}
void Shell::OnDefaultDirectoryChange(io::IEntry* folder, IShellFolder* pShellFolder) {
if SUCCEEDED (GoAbsolute(folder)) {
if (IsKeyPressed(VK_RETURN)) {
LVITEM item = {LVIF_STATE, 0};
item.state = item.stateMask = LVIS_FOCUSED | LVIS_SELECTED;
m_wndList.SetItem(&item);
m_wndList.EnsureVisible(0, false);
} else { // ステータスバーに何も表示されなくなるので、ダミーのメッセージを送る
SendMessage(SB_SETTEXT, 0, 0);
}
}
}
HRESULT Shell::GetViewFlags(DWORD* dw) {
if (m_ShowAllFiles) {
*dw = CDB2GVF_SHOWALLFILES;
} else {
*dw = 0;
}
return S_OK;
}
HRESULT Shell::IncludeObject(IShellView* pShellView, LPCITEMIDLIST pidl) {
// 隠しファイルを隠すは、GetViewFlags()だけでは効果が無いため、ここで個別にフィルタリングする
if (!m_pCurrentFolder || !m_pCurrentEntry) {
return S_OK;
}
// フィルタ.
if (m_PatternMask) {
WCHAR name[MAX_PATH];
if SUCCEEDED (afx::ILGetDisplayName(m_pCurrentFolder, pidl, SHGDN_NORMAL | SHGDN_INFOLDER, name, MAX_PATH)) {
if (!afx::PatternEquals(m_PatternMask.str(), name)) {
SFGAOF flags = SFGAO_FOLDER;
if SUCCEEDED (m_pCurrentFolder->GetAttributesOf(1, &pidl,
&flags)) { // パターンがマッチしなかった、非フォルダのみ隠す。
if ((flags & SFGAO_FOLDER) == 0) {
return S_FALSE;
}
}
}
}
}
if (!theShellFlagState.fShowAllObjects) {
return S_OK; // すでにフィルタリング済み
}
if (m_ShowAllFiles) {
return S_OK; // 全部表示するから
}
SFGAOF flags = SFGAO_GHOSTED;
if SUCCEEDED (m_pCurrentFolder->GetAttributesOf(1, &pidl, &flags)) {
return (flags & SFGAO_GHOSTED) ? S_FALSE : S_OK;
} else { // なぜか失敗することがある。仕方ないので、Win32API経由で。
HRESULT result = S_OK;
// SHGetRealIDL(m_pCurrentFolder, pidl, &fullpath) も失敗するので、自前で連結することにする.
LPITEMIDLIST fullpath = ILCombine(m_pCurrentEntry->ID, pidl);
TCHAR path[MAX_PATH];
if SUCCEEDED (afx::ILGetPath(fullpath, path)) {
DWORD dwAttrs = GetFileAttributes(path);
if (dwAttrs != (DWORD)-1 && (dwAttrs & FILE_ATTRIBUTE_HIDDEN)) {
result = S_FALSE;
}
}
ILFree(fullpath);
return result;
}
}
HRESULT Shell::GetViewStateStream(DWORD grfMode, IStream** ppStream) {
if (io::IEntry* folder = GetCurrentEntry()) {
if (grfMode & STGM_WRITE) {
HRESULT hr = OnQueryStream(grfMode, ppStream);
if FAILED (hr) {
return hr;
}
(*ppStream)->Write(&m_FolderSettings, sizeof(FOLDERSETTINGS), NULL);
return S_OK;
} else if (m_pViewStateStream) {
return m_pViewStateStream->QueryInterface(ppStream);
}
}
return E_FAIL;
}
HRESULT Shell::UpdateStyle() {
m_FolderSettings.fFlags = MEW_FWF_ALWAYS;
if (m_AutoArrange) {
m_FolderSettings.fFlags |= FWF_AUTOARRANGE;
}
if (m_CheckBox) {
m_FolderSettings.fFlags |= FWF_CHECKSELECT;
}
if (!m_pCurrentFolder) {
return S_FALSE;
}
int column = 0;
bool ascending = true;
GetSortKey(&column, &ascending);
HRESULT hr = ReCreateViewWindow(m_pCurrentFolder, false);
if FAILED (hr) {
return hr;
}
SetSortKey(column, ascending);
return S_OK;
}
ListStyle Shell::get_Style() const {
if (m_pShellView) {
m_pShellView->GetCurrentInfo(const_cast<FOLDERSETTINGS*>(&m_FolderSettings));
}
return (ListStyle)m_FolderSettings.ViewMode;
}
HRESULT Shell::set_Style(ListStyle style) {
if (style < 1 || 7 < style) {
ASSERT(!"error: Invalid ListStyle");
return E_INVALIDARG;
}
m_FolderSettings.ViewMode = style;
if (ref<IFolderView> folder = cast(m_pShellView)) {
return folder->SetCurrentViewMode(m_FolderSettings.ViewMode);
} else {
return UpdateStyle(); // LVS_* でスタイルを設定すると誤動作する。仕方ないので作り直す。
}
}
bool Shell::get_AutoArrange() const {
Shell* pThis = const_cast<Shell*>(this);
if (m_pShellView) {
m_pShellView->GetCurrentInfo(&pThis->m_FolderSettings);
}
pThis->m_AutoArrange = !!(m_FolderSettings.fFlags & FWF_AUTOARRANGE);
#if defined(USE_ADHOC_FIX_FOR_SHELLBROWSER_LISTVIEW_DETAILS)
if (get_Style() == ListStyleDetails) {
::SetTimer(m_wndList, IDEvent_ListView_Details, Elapse_ListView_Details, setViewModeDetailsTimerProc);
}
#endif
return pThis->m_AutoArrange;
}
HRESULT Shell::set_AutoArrange(bool value) {
if (get_AutoArrange() == value) {
return S_OK;
}
m_AutoArrange = value;
return UpdateStyle();
}
HRESULT Shell::set_CheckBox(bool value) {
if (m_CheckBox == value) {
return S_OK;
}
m_CheckBox = value;
// FOLDERSETTINGS でやらなくても一応大丈夫そう
if (m_wndList) {
m_wndList.SetExtendedListViewStyle(m_CheckBox ? LVS_EX_CHECKBOXES : 0, LVS_EX_CHECKBOXES);
}
return S_OK;
}
HRESULT Shell::set_FullRowSelect(bool value) {
if (m_FullRowSelect == value) {
return S_OK;
}
m_FullRowSelect = value;
if (m_wndList) {
m_wndList.SetExtendedListViewStyle(m_FullRowSelect ? LVS_EX_FULLROWSELECT : 0, LVS_EX_FULLROWSELECT);
}
return S_OK;
}
HRESULT Shell::set_GridLine(bool value) {
if (m_GridLine == value) {
return S_OK;
}
m_GridLine = value;
if (m_wndList) {
m_wndList.SetExtendedListViewStyle(m_GridLine ? LVS_EX_GRIDLINES : 0, LVS_EX_GRIDLINES);
}
return S_OK;
}
HRESULT Shell::set_Grouping(bool value) {
if (!m_pShellView) {
return E_UNEXPECTED;
}
if (m_Grouping == value) {
return S_OK;
}
m_Grouping = afx::ExpEnableGroup(m_pShellView, value);
return S_OK;
}
HRESULT Shell::set_ShowAllFiles(bool value) {
if (m_ShowAllFiles == value) {
return S_OK;
}
m_ShowAllFiles = value;
return UpdateStyle();
}
LRESULT Shell::DefaultContextMenu(WPARAM wParam, LPARAM lParam) {
// 無限ループに陥るの避けるため、サブクラス化されている場合のみ。
if (m_wndShell.m_pfnSuperWindowProc) {
return m_wndShell.DefWindowProc(WM_CONTEXTMENU, wParam, lParam);
}
return 0;
}
bool Shell::PreTranslateMessage(MSG* msg) {
if (!m_wndShell || !m_pShellView) { // 準備が出来ていない
return false;
}
if (m_wndShell != msg->hwnd && !m_wndShell.IsChild(msg->hwnd)) { // シェルビューまたはその子供でなければ処理しない
return false;
} else if (m_wndList.IsChild(msg->hwnd)) { // リストビューの子供=ファイルリネーム中のエディットなので処理を任せる
if (m_pShellView->TranslateAccelerator(msg) == S_OK) {
return true;
} else {
return false;
}
} else { // デフォルトでは、喰ってしまうのに処理しないキーアクセラレータを処理する.
switch (msg->message) {
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
return false;
}
return m_pShellView->TranslateAccelerator(msg) == S_OK;
}
}
void Shell::set_WallPaperFile(string value) {
if (m_WallPaperFile == value) {
return;
}
m_WallPaperFile = value;
UpdateBackground();
}
void Shell::set_WallPaperAlign(UINT32 value) {
if (m_WallPaperAlign == value) {
return;
}
m_WallPaperAlign = value;
UpdateBackground();
}
void Shell::UpdateBackground() {
// どうやら、実質的にタイリングと左上以外は使い物にならないようだ
if (!m_wndList.IsWindow()) {
return;
}
LVBKIMAGE bkgnd = {0};
if (!m_WallPaperFile) {
bkgnd.ulFlags |= LVBKIF_SOURCE_NONE;
} else {
bkgnd.ulFlags |= LVBKIF_SOURCE_URL;
bkgnd.pszImage = const_cast<PTSTR>(m_WallPaperFile.str());
if (m_WallPaperAlign == DirNone) { // タイリング
bkgnd.ulFlags |= LVBKIF_STYLE_TILE;
} else {
bkgnd.ulFlags |= LVBKIF_STYLE_NORMAL;
}
}
m_wndList.SetBkImage(&bkgnd);
}
namespace {
const int MAX_VIEW_MODE = 4;
const int DEFAULT_ICON_SIZE[MAX_VIEW_MODE] = {48, 32, 16, 16};
const PCWSTR PROFILE_ICON_NAME[MAX_VIEW_MODE] = {
L"FolderTile",
L"FolderIcon",
L"FolderList",
L"FolderDetails",
};
static int theIconSize[MAX_VIEW_MODE] = {0};
int GetIconSize(ListStyle style) {
int index;
switch (style) {
case ListStyleIcon:
index = 1;
break;
case ListStyleSmallIcon:
index = 2;
break;
case ListStyleList:
index = 2;
break;
case ListStyleDetails:
index = 3;
break;
// case ListStyleThumnail:
case ListStyleTile:
index = 0;
break;
default:
return 0;
}
if (theIconSize[0] == 0) {
for (int i = 0; i < MAX_VIEW_MODE; ++i) {
theIconSize[i] = theAvesta->GetProfileSint32(L"Style", PROFILE_ICON_NAME[i], DEFAULT_ICON_SIZE[i]);
}
}
if (theIconSize[index] == DEFAULT_ICON_SIZE[index]) {
return 0; // 変更する必要なし。
}
return theIconSize[index];
}
} // namespace
void Shell::OnListViewModeChanged() {
if (!m_wndList.IsWindow()) {
return;
}
m_wndList.SetRedraw(false);
int size = GetIconSize(get_Style());
if (size > 0) {
ref<IImageList> imagelist;
afx::ExpGetImageList(size, &imagelist);
HIMAGELIST hImageList = (HIMAGELIST)imagelist.detach();
m_wndList.SetImageList(hImageList, LVSIL_SMALL);
m_wndList.SetImageList(hImageList, LVSIL_NORMAL);
}
UpdateBackground();
m_wndList.SetRedraw(true);
}
} // namespace ui
} // namespace mew
|
1fdcf81c011ebd5356860aa562e8d26caf359be6 | 408d8348d7698a2d92bef73c68d277b6206e4225 | /src/C4StartupScenSelDlg.cpp | 40669c6479ead345f52a944cdda5125b1b7e1926 | [
"ISC"
] | permissive | legacyclonk/LegacyClonk | b8cad7fa8b3634c79a3c03b3f25e622d74bb2250 | 6281c878e42026b6b10d39819243af8f6673aabd | refs/heads/master | 2023-08-17T03:27:30.561982 | 2023-08-13T16:37:08 | 2023-08-13T16:37:08 | 194,545,617 | 62 | 16 | NOASSERTION | 2022-10-29T15:31:12 | 2019-06-30T17:58:19 | C++ | UTF-8 | C++ | false | false | 67,339 | cpp | C4StartupScenSelDlg.cpp | /*
* LegacyClonk
*
* Copyright (c) RedWolf Design
* Copyright (c) 2005, Sven2
* Copyright (c) 2017-2022, The LegacyClonk Team and contributors
*
* Distributed under the terms of the ISC license; see accompanying file
* "COPYING" for details.
*
* "Clonk" is a registered trademark of Matthes Bender, used with permission.
* See accompanying file "TRADEMARK" for details.
*
* To redistribute this file separately, substitute the full license texts
* for the above references.
*/
// Startup screen for non-parameterized engine start: Scenario selection dialog
#include <C4StartupScenSelDlg.h>
#include <C4Network2Dialogs.h>
#include <C4StartupMainDlg.h>
#include <C4StartupNetDlg.h>
#include "StdMarkup.h"
#include <C4ComponentHost.h>
#include <C4Components.h>
#include <C4RTF.h>
#include <C4Wrappers.h>
#include <C4Log.h>
#include <C4Game.h>
#include <C4GameDialogs.h>
#include <C4Language.h>
#include <C4FileSelDlg.h>
// singleton
C4StartupScenSelDlg *C4StartupScenSelDlg::pInstance = nullptr;
// Map folder data
void C4MapFolderData::Scenario::CompileFunc(StdCompiler *pComp)
{
pComp->Value(mkNamingAdapt(sFilename, "File", StdStrBuf()));
pComp->Value(mkNamingAdapt(sBaseImage, "BaseImage", StdStrBuf()));
pComp->Value(mkNamingAdapt(sOverlayImage, "OverlayImage", StdStrBuf()));
pComp->Value(mkNamingAdapt(singleClick, "SingleClick", false));
pComp->Value(mkNamingAdapt(rcOverlayPos, "Area", C4Rect()));
pComp->Value(mkNamingAdapt(sTitle, "Title", StdStrBuf()));
pComp->Value(mkNamingAdapt(iTitleFontSize, "TitleFontSize", 20));
pComp->Value(mkNamingAdapt(dwTitleInactClr, "TitleColorInactive", 0x7fffffffu));
pComp->Value(mkNamingAdapt(dwTitleActClr, "TitleColorActive", 0x0fffffffu));
pComp->Value(mkNamingAdapt(iTitleOffX, "TitleOffX", 0));
pComp->Value(mkNamingAdapt(iTitleOffY, "TitleOffY", 0));
pComp->Value(mkNamingAdapt(byTitleAlign, "TitleAlign", ACenter));
pComp->Value(mkNamingAdapt(fTitleBookFont, "TitleUseBookFont", true));
pComp->Value(mkNamingAdapt(fImgDump, "ImageDump", false)); // developer help
}
void C4MapFolderData::AccessGfx::CompileFunc(StdCompiler *pComp)
{
pComp->Value(mkNamingAdapt(sPassword, "Access", StdStrBuf()));
pComp->Value(mkNamingAdapt(sOverlayImage, "OverlayImage", StdStrBuf()));
pComp->Value(mkNamingAdapt(rcOverlayPos, "Area", C4Rect()));
}
C4MapFolderData::MapPic::MapPic(const C4GUI::FLOAT_RECT &rcfBounds, const C4Facet &rfct) : C4GUI::Picture(C4Rect(rcfBounds), false), rcfBounds(rcfBounds)
{
SetFacet(rfct);
SetToolTip(LoadResStr("IDS_MSG_MAP_DESC"));
}
void C4MapFolderData::MapPic::MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, uint32_t dwKeyParam)
{
typedef C4GUI::Picture Parent;
Parent::MouseInput(rMouse, iButton, iX, iY, dwKeyParam);
// input: mouse movement or buttons - deselect everything if clicked
if (iButton == C4MC_Button_LeftDown && C4StartupScenSelDlg::pInstance)
{
C4StartupScenSelDlg::pInstance->DeselectAll();
}
}
void C4MapFolderData::MapPic::DrawElement(C4FacetEx &cgo)
{
// get drawing bounds
float x0 = rcfBounds.left + cgo.TargetX, y0 = rcfBounds.top + cgo.TargetY;
// draw the image
GetFacet().DrawXFloat(cgo.Surface, x0, y0, rcfBounds.right - rcfBounds.left, rcfBounds.bottom - rcfBounds.top);
}
void C4MapFolderData::Clear()
{
fCoordinatesAdjusted = false;
fctBackgroundPicture.Clear();
pScenarioFolder = nullptr;
pSelectedEntry = nullptr;
pSelectionInfoBox = nullptr;
rcScenInfoArea.Set(0, 0, 0, 0);
MinResX = MinResY = 0;
fUseFullscreenMap = false;
int i;
for (i = 0; i < iScenCount; ++i) delete ppScenList[i];
iScenCount = 0;
delete[] ppScenList; ppScenList = nullptr;
for (i = 0; i < iAccessGfxCount; ++i) delete ppAccessGfxList[i];
iAccessGfxCount = 0;
delete[] ppAccessGfxList; ppAccessGfxList = nullptr;
pMainDlg = nullptr;
}
bool C4MapFolderData::Load(C4Group &hGroup, C4ScenarioListLoader::Folder *pScenLoaderFolder)
{
// clear previous
Clear();
// load localization info
C4LangStringTable LangTable;
bool fHasLangTable = !!LangTable.LoadEx("StringTbl", hGroup, C4CFN_ScriptStringTbl, Config.General.LanguageEx);
// load core data
StdStrBuf Buf;
if (!hGroup.LoadEntryString(C4CFN_MapFolderData, Buf)) return false;
if (fHasLangTable) LangTable.ReplaceStrings(Buf);
if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(mkNamingAdapt(*this, "FolderMap"), Buf, C4CFN_MapFolderData)) return false;
// check resolution requirement
if (MinResX && MinResX > C4GUI::GetScreenWdt()) return false;
if (MinResY && MinResY > C4GUI::GetScreenHgt()) return false;
// load images
if (!fctBackgroundPicture.Load(hGroup, C4CFN_MapFolderBG))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load background graphic \"%s\"", hGroup.GetName(), C4CFN_MapFolderBG);
return false;
}
int i;
for (i = 0; i < iScenCount; ++i)
{
// init scenario entry stuff
Scenario *pScen = ppScenList[i];
pScen->pScenEntry = pScenLoaderFolder->FindEntryByName(pScen->sFilename.getData());
pScen->pBtn = nullptr;
pScen->sTitle.Replace("TITLE", pScen->pScenEntry ? pScen->pScenEntry->GetName().getData() : "<c ff0000>ERROR</c>" /* scenario not loaded; title cannot be referenced */);
// developer image dump
if (pScen->fImgDump)
{
C4FacetExSurface fctDump; bool fSuccess = false;
if (fctDump.Create(pScen->rcOverlayPos.Wdt, pScen->rcOverlayPos.Hgt, C4FCT_Full, C4FCT_Full))
{
lpDDraw->Blit(fctBackgroundPicture.Surface,
static_cast<float>(pScen->rcOverlayPos.x), static_cast<float>(pScen->rcOverlayPos.y),
static_cast<float>(pScen->rcOverlayPos.Wdt), static_cast<float>(pScen->rcOverlayPos.Hgt),
fctDump.Surface,
0, 0,
fctDump.Wdt, fctDump.Hgt);
fSuccess = fctDump.Surface->SavePNG(pScen->sBaseImage.getData(), true, false, false);
}
if (!fSuccess)
DebugLogF("C4MapFolderData::Load(%s): Could not dump graphic \"%s\"", hGroup.GetName(), pScen->sBaseImage.getData());
continue;
}
// load images
if (pScen->sBaseImage.getLength() > 0) if (!pScen->fctBase.Load(hGroup, pScen->sBaseImage.getData()))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load base graphic \"%s\"", hGroup.GetName(), pScen->sBaseImage.getData());
return false;
}
}
for (i = 0; i < iScenCount; ++i)
{
Scenario *pScen = ppScenList[i];
if (pScen->sOverlayImage.getLength() > 0) if (!pScen->fctOverlay.Load(hGroup, pScen->sOverlayImage.getData()))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load graphic \"%s\"", hGroup.GetName(), pScen->sOverlayImage.getData());
return false;
}
}
for (i = 0; i < iAccessGfxCount; ++i)
{
AccessGfx *pGfx = ppAccessGfxList[i];
if (pGfx->sOverlayImage.getLength() > 0) if (!pGfx->fctOverlay.Load(hGroup, pGfx->sOverlayImage.getData()))
{
DebugLogF("C4MapFolderData::Load(%s): Could not load graphic \"%s\"", hGroup.GetName(), pGfx->sOverlayImage.getData());
return false;
}
}
// all loaded
pScenarioFolder = pScenLoaderFolder;
return true;
}
void C4MapFolderData::CompileFunc(StdCompiler *pComp)
{
// core values
pComp->Value(mkNamingAdapt(rcScenInfoArea, "ScenInfoArea", C4Rect(0, 0, 0, 0)));
pComp->Value(mkNamingAdapt(MinResX, "MinResX", 0));
pComp->Value(mkNamingAdapt(MinResY, "MinResY", 0));
pComp->Value(mkNamingAdapt(fUseFullscreenMap, "FullscreenBG", false));
pComp->Value(mkNamingAdapt(hideTitle, "HideTitle", false));
// compile scenario list
int32_t iOldScenCount = iScenCount;
pComp->Value(mkNamingCountAdapt(iScenCount, "Scenario"));
if (pComp->isCompiler())
{
while (iOldScenCount--) delete ppScenList[iOldScenCount];
delete[] ppScenList;
if (iScenCount)
{
ppScenList = new Scenario *[iScenCount]{};
}
else
ppScenList = nullptr;
}
if (iScenCount)
{
mkPtrAdaptNoNull(*ppScenList);
pComp->Value(mkNamingAdapt(mkArrayAdaptMapS(ppScenList, iScenCount, mkPtrAdaptNoNull<Scenario>), "Scenario"));
}
// compile access gfx list
int32_t iOldAccesGfxCount = iAccessGfxCount;
pComp->Value(mkNamingCountAdapt(iAccessGfxCount, "AccessGfx"));
if (pComp->isCompiler())
{
while (iOldAccesGfxCount--) delete ppAccessGfxList[iOldAccesGfxCount];
delete[] ppAccessGfxList;
if (iAccessGfxCount)
{
ppAccessGfxList = new AccessGfx *[iAccessGfxCount]{};
}
else
ppAccessGfxList = nullptr;
}
if (iAccessGfxCount)
{
mkPtrAdaptNoNull(*ppAccessGfxList);
pComp->Value(mkNamingAdapt(mkArrayAdaptMapS(ppAccessGfxList, iAccessGfxCount, mkPtrAdaptNoNull<AccessGfx>), "AccessGfx"));
}
}
void C4MapFolderData::ConvertFacet2ScreenCoord(const C4Rect &rc, C4GUI::FLOAT_RECT *pfrc, float fBGZoomX, float fBGZoomY, int iOffX, int iOffY)
{
pfrc->left = (fBGZoomX * rc.x) + iOffX;
pfrc->top = (fBGZoomY * rc.y) + iOffY;
pfrc->right = pfrc->left + (fBGZoomX * rc.Wdt);
pfrc->bottom = pfrc->top + (fBGZoomY * rc.Hgt);
}
void C4MapFolderData::ConvertFacet2ScreenCoord(int32_t *piValue, float fBGZoom, int iOff)
{
*piValue = int32_t(floorf(fBGZoom * *piValue + 0.5f)) + iOff;
}
void C4MapFolderData::ConvertFacet2ScreenCoord(C4Rect &rcMapArea, bool fAspect)
{
if (!fctBackgroundPicture.Wdt || !fctBackgroundPicture.Hgt) return; // invalid BG - should not happen
// get zoom of background image
float fBGZoomX = 1.0f, fBGZoomY = 1.0f; int iOffX = 0, iOffY = 0;
if (fAspect)
{
if (fctBackgroundPicture.Wdt * rcMapArea.Hgt > rcMapArea.Wdt * fctBackgroundPicture.Hgt)
{
// background image is limited by width
fBGZoomX = fBGZoomY = static_cast<float>(rcMapArea.Wdt) / fctBackgroundPicture.Wdt;
iOffY = std::max<int>(0, static_cast<int>(rcMapArea.Hgt - (fBGZoomX * fctBackgroundPicture.Hgt))) / 2;
}
else
{
// background image is limited by height
fBGZoomX = fBGZoomY = static_cast<float>(rcMapArea.Hgt) / fctBackgroundPicture.Hgt;
iOffX = std::max<int>(0, static_cast<int>(rcMapArea.Wdt - (fBGZoomY * fctBackgroundPicture.Wdt))) / 2;
}
}
else
{
// do not keep aspect: Independent X and Y zoom
fBGZoomX = static_cast<float>(rcMapArea.Wdt) / fctBackgroundPicture.Wdt;
fBGZoomY = static_cast<float>(rcMapArea.Hgt) / fctBackgroundPicture.Hgt;
}
iOffX -= rcMapArea.x; iOffY -= rcMapArea.y;
C4Rect rcBG; rcBG.Set(0, 0, fctBackgroundPicture.Wdt, fctBackgroundPicture.Hgt);
ConvertFacet2ScreenCoord(rcBG, &rcfBG, fBGZoomX, fBGZoomY, iOffX, iOffY);
// default for scenario info area: 1/3rd of right area
if (!rcScenInfoArea.Wdt)
rcScenInfoArea.Set(static_cast<int32_t>(fctBackgroundPicture.Wdt * 2 / 3), static_cast<int32_t>(fctBackgroundPicture.Hgt / 16), static_cast<int32_t>(fctBackgroundPicture.Wdt / 3), static_cast<int32_t>(fctBackgroundPicture.Hgt * 7 / 8));
// assume all facet coordinates are referring to background image zoom; convert them to screen coordinates by applying zoom and offset
C4GUI::FLOAT_RECT rcfScenInfoArea;
ConvertFacet2ScreenCoord(rcScenInfoArea, &rcfScenInfoArea, fBGZoomX, fBGZoomY, iOffX, iOffY);
rcScenInfoArea.x = static_cast<int32_t>(rcfScenInfoArea.left); rcScenInfoArea.y = static_cast<int32_t>(rcfScenInfoArea.top);
rcScenInfoArea.Wdt = static_cast<int32_t>(rcfScenInfoArea.right - rcfScenInfoArea.left);
rcScenInfoArea.Hgt = static_cast<int32_t>(rcfScenInfoArea.bottom - rcfScenInfoArea.top);
int i;
for (i = 0; i < iScenCount; ++i)
{
Scenario *pScen = ppScenList[i];
ConvertFacet2ScreenCoord(pScen->rcOverlayPos, &(pScen->rcfOverlayPos), fBGZoomX, fBGZoomY, iOffX, iOffY);
// title sizes
ConvertFacet2ScreenCoord(&(pScen->iTitleFontSize), fBGZoomY, 0);
// title position: Relative to title rect; so do not add offset here
ConvertFacet2ScreenCoord(&(pScen->iTitleOffX), fBGZoomX, 0);
ConvertFacet2ScreenCoord(&(pScen->iTitleOffY), fBGZoomY, 0);
}
for (i = 0; i < iAccessGfxCount; ++i) ConvertFacet2ScreenCoord(ppAccessGfxList[i]->rcOverlayPos, &(ppAccessGfxList[i]->rcfOverlayPos), fBGZoomX, fBGZoomY, iOffX, iOffY);
// done
fCoordinatesAdjusted = true;
}
void C4MapFolderData::CreateGUIElements(C4StartupScenSelDlg *pMainDlg, C4GUI::Window &rContainer)
{
this->pMainDlg = pMainDlg;
if (hideTitle)
{
this->pMainDlg->HideTitle(true);
}
// convert all coordinates to match the container sizes
// do this only once; assume container won't change between loads
if (!fCoordinatesAdjusted)
if (!fUseFullscreenMap)
ConvertFacet2ScreenCoord(rContainer.GetClientRect(), true);
else
{
C4Rect rcMapRect = pMainDlg->GetBounds();
rContainer.ClientPos2ScreenPos(rcMapRect.x, rcMapRect.y);
ConvertFacet2ScreenCoord(rcMapRect, false);
}
// empty any previous stuff in container
while (rContainer.GetFirst()) delete rContainer.GetFirst();
// create background image
if (!fUseFullscreenMap)
rContainer.AddElement(new MapPic(rcfBG, fctBackgroundPicture));
else
{
pMainDlg->SetBackground(&fctBackgroundPicture);
}
// create mission access overlays
int i;
for (i = 0; i < iAccessGfxCount; ++i)
{
AccessGfx *pGfx = ppAccessGfxList[i];
const char *szPassword = pGfx->sPassword.getData();
if (!szPassword || !*szPassword || SIsModule(Config.General.MissionAccess, szPassword))
{
// ACCESS TO GFX GRANTED: draw it
rContainer.AddElement(new MapPic(pGfx->rcfOverlayPos, pGfx->fctOverlay));
}
}
// create buttons for scenarios
C4GUI::Button *pBtnFirst = nullptr;
for (i = 0; i < iScenCount; ++i)
{
Scenario *pScen = ppScenList[i];
if (pScen->pScenEntry && !pScen->pScenEntry->HasMissionAccess())
{
// no access to this scenario: Do not create a button at all; not even base image. The scenario is "invisible".
}
else
{
C4GUI::CallbackButtonEx<C4StartupScenSelDlg, C4GUI::FacetButton> *pBtn = new C4GUI::CallbackButtonEx<C4StartupScenSelDlg, C4GUI::FacetButton>
(pScen->fctBase, pScen->fctOverlay, pScen->rcfOverlayPos, 0, pMainDlg, &C4StartupScenSelDlg::OnButtonScenario);
ppScenList[i]->pBtn = pBtn;
if (pScen->pScenEntry)
pBtn->SetToolTip(FormatString(LoadResStr("IDS_MSG_MAP_STARTSCEN"), pScen->pScenEntry->GetName().getData()).getData());
if (pScen->sTitle.getLength() > 0)
{
pBtn->SetText(pScen->sTitle.getData());
pBtn->SetTextColors(InvertRGBAAlpha(pScen->dwTitleInactClr), InvertRGBAAlpha(pScen->dwTitleActClr));
pBtn->SetTextPos(pScen->iTitleOffX, pScen->iTitleOffY, pScen->byTitleAlign);
CStdFont *pUseFont; float fFontZoom = 1.0f;
if (pScen->fTitleBookFont)
pUseFont = &(C4Startup::Get()->Graphics.GetBlackFontByHeight(pScen->iTitleFontSize, &fFontZoom));
else
pUseFont = &(C4GUI::GetRes()->GetFontByHeight(pScen->iTitleFontSize, &fFontZoom));
if (Inside<float>(fFontZoom, 0.8f, 1.25f)) fFontZoom = 1.0f; // some tolerance for font zoom
pBtn->SetTextFont(pUseFont, fFontZoom);
}
rContainer.AddElement(pBtn);
if (!pBtnFirst) pBtnFirst = pBtn;
}
}
// create scenario info listbox
pSelectionInfoBox = new C4GUI::TextWindow(rcScenInfoArea,
C4StartupScenSel_TitlePictureWdt + 2 * C4StartupScenSel_TitleOverlayMargin, C4StartupScenSel_TitlePictureHgt + 2 * C4StartupScenSel_TitleOverlayMargin,
C4StartupScenSel_TitlePicturePadding, 100, 4096, nullptr, true, &C4Startup::Get()->Graphics.fctScenSelTitleOverlay, C4StartupScenSel_TitleOverlayMargin);
pSelectionInfoBox->SetDecoration(false, false, &C4Startup::Get()->Graphics.sfctBookScroll, true);
rContainer.AddElement(pSelectionInfoBox);
}
bool C4MapFolderData::OnButtonScenario(C4GUI::Control *pEl)
{
// get associated scenario entry
int i;
for (i = 0; i < iScenCount; ++i)
if (pEl == ppScenList[i]->pBtn)
break;
if (i == iScenCount) return false;
// select the associated entry
pSelectedEntry = ppScenList[i]->pScenEntry;
return ppScenList[i]->singleClick;
}
void C4MapFolderData::ResetSelection()
{
pSelectedEntry = nullptr;
}
// Scenario list loader
// Entry
C4ScenarioListLoader::Entry::Entry(Folder *pParent) : pNext(nullptr), pParent(pParent), fBaseLoaded(false), fExLoaded(false)
{
// ctor: Put into parent tree node
if (pParent)
{
pNext = pParent->pFirst;
pParent->pFirst = this;
}
iIconIndex = -1;
iDifficulty = 0;
iFolderIndex = 0;
}
C4ScenarioListLoader::Entry::~Entry()
{
// dtor: unlink from parent list (MUST be in there)
if (pParent)
{
Entry **ppCheck = &(pParent->pFirst);
while (*ppCheck != this)
{
ppCheck = &(*ppCheck)->pNext;
}
*ppCheck = pNext;
}
}
bool C4ScenarioListLoader::Entry::Load(C4Group *pFromGrp, const StdStrBuf *psFilename, bool fLoadEx)
{
// nothing to do if already loaded
if (fBaseLoaded && (fExLoaded || !fLoadEx)) return true;
C4Group Group;
// group specified: Load as child
if (pFromGrp)
{
assert(psFilename);
if (!Group.OpenAsChild(pFromGrp, psFilename->getData())) return false;
// set FN by complete entry name
this->sFilename.Take(Group.GetFullName());
}
else
{
// set FN by complete entry name
if (psFilename) this->sFilename.Copy(*psFilename);
// no parent group: Direct load from filename
if (!Group.Open(sFilename.getData())) return false;
}
// okay; load standard stuff from group
bool fNameLoaded = false, fIconLoaded = false;
if (fBaseLoaded)
{
fNameLoaded = fIconLoaded = true;
}
else
{
// Set default name as filename without extension
sName.Copy(GetFilename(sFilename.getData()));
char *szBuf = sName.GrabPointer();
RemoveExtension(szBuf);
sName.Take(szBuf);
sName.Take(C4Language::IconvClonk(sName.getData()));
// load entry specific stuff that's in the front of the group
if (!LoadCustomPre(Group))
return false;
// Load entry name
C4ComponentHost DefNames;
if (DefNames.LoadEx("Title", Group, C4CFN_Title, Config.General.LanguageEx))
if (DefNames.GetLanguageString(Config.General.LanguageEx, sName))
fNameLoaded = true;
DefNames.Close();
// load entry icon
if (Group.FindEntry(C4CFN_IconPNG) && fctIcon.Load(Group, C4CFN_IconPNG))
fIconLoaded = true;
else
{
C4FacetExSurface fctTemp;
if (Group.FindEntry(C4CFN_ScenarioIcon) && fctTemp.Load(Group, C4CFN_ScenarioIcon, C4FCT_Full, C4FCT_Full, true))
{
// old style icon: Blit it on a pieace of paper
fctTemp.Surface->Lock();
for (int y = 0; y < fctTemp.Hgt; ++y)
for (int x = 0; x < fctTemp.Wdt; ++x)
{
uint32_t dwPix = fctTemp.Surface->GetPixDw(x, y, false);
// transparency has some tolerance...
if (Inside<uint8_t>(dwPix & 0xff, 0xb8, 0xff))
if (Inside<uint8_t>((dwPix >> 0x08) & 0xff, 0x00, 0x0f))
if (Inside<uint8_t>((dwPix >> 0x10) & 0xff, 0xb8, 0xff))
fctTemp.Surface->SetPixDw(x, y, 0xffffffff);
}
fctTemp.Surface->Unlock();
int iIconSize = C4Startup::Get()->Graphics.fctScenSelIcons.Hgt;
fctIcon.Create(iIconSize, iIconSize, C4FCT_Full, C4FCT_Full);
C4Startup::Get()->Graphics.fctScenSelIcons.GetPhase(C4StartupScenSel_DefaultIcon_OldIconBG).Draw(fctIcon);
fctTemp.Draw(fctIcon.Surface, (fctIcon.Wdt - fctTemp.Wdt) / 2, (fctIcon.Hgt - fctTemp.Hgt) / 2);
fctTemp.Clear();
fIconLoaded = true;
}
}
// load any entryx-type-specific custom data (e.g. fallbacks for scenario title, and icon)
if (!LoadCustom(Group, fNameLoaded, fIconLoaded)) return false;
// store maker
sMaker.Copy(Group.GetMaker());
fBaseLoaded = true;
}
// load extended stuff: title picture
if (fLoadEx && !fExLoaded)
{
// load desc
C4ComponentHost DefDesc;
if (DefDesc.LoadEx("Desc", Group, C4CFN_ScenarioDesc, Config.General.LanguageEx))
{
C4RTFFile rtf;
rtf.Load(StdBuf::MakeRef(DefDesc.GetData(), SLen(DefDesc.GetData())));
sDesc.Take(rtf.GetPlainText());
}
DefDesc.Close();
// load title
if (!fctTitle.Load(Group, C4CFN_ScenarioTitlePNG, C4FCT_Full, C4FCT_Full, false, true))
fctTitle.Load(Group, C4CFN_ScenarioTitle, C4FCT_Full, C4FCT_Full, true, true);
fExLoaded = true;
// load author
if (Group.IsPacked())
{
const char *strSecAuthors = "RedWolf Design;Clonk History Project;GWE-Team"; // Now hardcoded...
if (SIsModule(strSecAuthors, Group.GetMaker()) && Group.LoadEntryString(C4CFN_Author, sAuthor))
{
// OK; custom author by txt
}
else
// defeault author by group
sAuthor.Copy(Group.GetMaker());
}
else
{
// unpacked groups do not have an author
sAuthor.Clear();
}
// load version
Group.LoadEntryString(C4CFN_Version, sVersion);
}
// done, success
return true;
}
// helper func: Recursive check whether a directory contains a .c4s or .c4f file
bool DirContainsScenarios(const char *szDir)
{
// create iterator on free store to avoid stack overflow with deeply recursed folders
DirectoryIterator *pIter = new DirectoryIterator(szDir);
const char *szChildFilename;
for (; szChildFilename = **pIter; ++*pIter)
{
// Ignore directory navigation entries and CVS folders
if (!*szChildFilename || *GetFilename(szChildFilename) == '.') continue;
if (SEqualNoCase(GetFilename(szChildFilename), "CVS")) continue;
if (WildcardMatch(C4CFN_ScenarioFiles, szChildFilename) || WildcardMatch(C4CFN_FolderFiles, szChildFilename)) break;
if (DirectoryExists(szChildFilename))
if (DirContainsScenarios(szChildFilename))
break;
}
delete pIter;
// return true if loop was broken, in which case a matching entry was found
return !!szChildFilename;
}
C4ScenarioListLoader::Entry *C4ScenarioListLoader::Entry::CreateEntryForFile(const StdStrBuf &sFilename, Folder *pParent)
{
// determine entry type by file type
const char *szFilename = sFilename.getData();
if (!szFilename || !*szFilename) return nullptr;
if (WildcardMatch(C4CFN_ScenarioFiles, sFilename.getData())) return new Scenario(pParent);
if (WildcardMatch(C4CFN_FolderFiles, sFilename.getData())) return new SubFolder(pParent);
// regular, open folder (C4Group-packed folders without extensions are not regarded, because they could contain anything!)
const char *szExt = GetExtension(szFilename);
if ((!szExt || !*szExt) && DirectoryExists(sFilename.getData()))
{
// open folders only if they contain a scenario or folder
if (DirContainsScenarios(szFilename))
return new RegularFolder(pParent);
}
// type not recognized
return nullptr;
}
bool C4ScenarioListLoader::Entry::RenameTo(const char *szNewName)
{
// change name+filename
// some name sanity validation
if (!szNewName || !*szNewName) return false;
if (SEqual(szNewName, sName.getData())) return true;
char fn[_MAX_PATH + 1];
SCopy(szNewName, fn, _MAX_PATH);
// generate new file name
MakeFilenameFromTitle(fn);
if (!*fn) return false;
const char *szExt = GetDefaultExtension();
if (szExt) { SAppend(".", fn, _MAX_PATH); SAppend(szExt, fn, _MAX_PATH); }
char fullfn[_MAX_PATH + 1];
SCopy(sFilename.getData(), fullfn, _MAX_PATH);
char *fullfn_fn = GetFilename(fullfn);
SCopy(fn, fullfn_fn, _MAX_PATH - (fullfn_fn - fullfn));
StdStrBuf strErr(LoadResStr("IDS_FAIL_RENAME"));
// check if a rename is due
if (!ItemIdentical(sFilename.getData(), fullfn))
{
// check for duplicate filename
if (ItemExists(fullfn))
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_FILEEXISTS"), fullfn);
Game.pGUI->ShowMessageModal(sMsg.getData(), strErr.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
// OK; then rename
if (!C4Group_MoveItem(sFilename.getData(), fullfn, true))
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_RENAMEFILE"), sFilename.getData(), fullfn);
Game.pGUI->ShowMessageModal(sMsg.getData(), strErr.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
sFilename.Copy(fullfn);
}
// update real name in group, if this is a group
if (C4Group_IsGroup(fullfn))
{
C4Group Grp;
if (!Grp.Open(fullfn))
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_OPENFILE"), sFilename.getData(), Grp.GetError());
Game.pGUI->ShowMessageModal(sMsg.getData(), strErr.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
if (!Grp.Delete(C4CFN_Title))
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_DELOLDTITLE"), sFilename.getData(), Grp.GetError());
Game.pGUI->ShowMessageModal(sMsg.getData(), strErr.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
if (!SetTitleInGroup(Grp, szNewName)) return false;
if (!Grp.Close())
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_WRITENEWTITLE"), sFilename.getData(), Grp.GetError());
Game.pGUI->ShowMessageModal(sMsg.getData(), strErr.getData(), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
}
// update title
sName.Copy(szNewName);
// done
return true;
}
bool C4ScenarioListLoader::Entry::SetTitleInGroup(C4Group &rGrp, const char *szNewTitle)
{
// default for group files: Create a title text file and set the title in there
// no title needed if filename is sufficient - except for scenarios, where a Scenario.txt could overwrite the title
if (!IsScenario())
{
StdStrBuf sNameByFile; sNameByFile.Copy(GetFilename(sFilename.getData()));
char *szBuf = sNameByFile.GrabPointer();
RemoveExtension(szBuf);
sNameByFile.Take(szBuf);
if (SEqual(szNewTitle, sNameByFile.getData())) return true;
}
// okay, make a title
StdStrBuf sTitle; sTitle.Format("%.2s:%s", Config.General.Language, szNewTitle);
if (!rGrp.Add(C4CFN_WriteTitle, sTitle, false, true))
{
StdStrBuf sMsg; sMsg.Format(LoadResStr("IDS_ERR_ERRORADDINGNEWTITLEFORFIL"), sFilename.getData(), rGrp.GetError());
Game.pGUI->ShowMessageModal(sMsg.getData(), LoadResStr("IDS_FAIL_RENAME"), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return false;
}
return true;
}
// Scenario
bool C4ScenarioListLoader::Scenario::LoadCustomPre(C4Group &rGrp)
{
// load scenario core first
StdStrBuf sFileContents;
if (!rGrp.LoadEntryString(C4CFN_ScenarioCore, sFileContents)) return false;
if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(mkParAdapt(C4S, false), sFileContents, (rGrp.GetFullName() + DirSep C4CFN_ScenarioCore).getData()))
return false;
return true;
}
bool C4ScenarioListLoader::Scenario::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
{
// icon fallback: Standard scenario icon
if (!fIconLoaded)
{
iIconIndex = C4S.Head.Icon;
int32_t iIcon = C4S.Head.Icon;
if (!Inside<int32_t>(iIcon, 0, C4StartupScenSel_IconCount - 1)) iIcon = C4StartupScenSel_DefaultIcon_Scenario;
fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(iIcon));
}
// scenario name fallback to core
if (!fNameLoaded)
sName.Copy(C4S.Head.Title);
// difficulty: Set only for regular rounds (not savegame or record) to avoid bogus sorting
if (!C4S.Head.SaveGame && !C4S.Head.Replay)
iDifficulty = C4S.Head.Difficulty;
else
iDifficulty = 0;
// minimum required player count
iMinPlrCount = C4S.GetMinPlayer();
return true;
}
bool C4ScenarioListLoader::Scenario::Start()
{
// gogo!
if (!(C4StartupScenSelDlg::pInstance)) return false;
return (C4StartupScenSelDlg::pInstance)->StartScenario(this);
}
bool C4ScenarioListLoader::Scenario::CanOpen(StdStrBuf &sErrOut)
{
// safety
C4StartupScenSelDlg *pDlg = C4StartupScenSelDlg::pInstance;
if (!pDlg) return false;
// check mission access
if (C4S.Head.MissionAccess[0] && !SIsModule(Config.General.MissionAccess, C4S.Head.MissionAccess))
{
sErrOut.Copy(LoadResStr("IDS_PRC_NOMISSIONACCESS"));
return false;
}
// replay
if (C4S.Head.Replay)
{
// replays can currently not be launched in network mode
if (pDlg->IsNetworkStart())
{
sErrOut.Copy(LoadResStr("IDS_PRC_NONETREPLAY"));
return false;
}
}
// regular game
else
{
// check player count
int32_t iPlrCount = SModuleCount(Config.General.Participants);
int32_t iMaxPlrCount = C4S.Head.MaxPlayer;
if (C4S.Head.SaveGame)
{
// Some scenarios have adjusted MaxPlayerCount to 0 after starting to prevent future joins
// make sure it's possible to start the savegame anyway
iMaxPlrCount = std::max<int32_t>(iMinPlrCount, iMaxPlrCount);
}
// normal scenarios: At least one player except in network mode, where it is possible to wait for the additional players
// Melees need at least two
if ((iPlrCount < iMinPlrCount))
{
if (pDlg->IsNetworkStart())
{
// network game: Players may yet join in lobby
// only issue a warning for too few players (by setting the error but not returning false here)
sErrOut.Format(LoadResStr("IDS_MSG_TOOFEWPLAYERSNET"), static_cast<int>(iMinPlrCount));
}
else
{
// for regular games, this is a fatal no-start-cause
sErrOut.Format(LoadResStr("IDS_MSG_TOOFEWPLAYERS"), static_cast<int>(iMinPlrCount));
return false;
}
}
// scenarios (both normal and savegame) may also impose a maximum player restriction
if (iPlrCount > iMaxPlrCount)
{
sErrOut.Format(LoadResStr("IDS_MSG_TOOMANYPLAYERS"), static_cast<int>(C4S.Head.MaxPlayer));
return false;
}
}
// Okay, start!
return true;
}
StdStrBuf C4ScenarioListLoader::Scenario::GetOpenText()
{
return StdStrBuf(LoadResStr("IDS_BTN_STARTGAME"));
}
StdStrBuf C4ScenarioListLoader::Scenario::GetOpenTooltip()
{
return StdStrBuf(LoadResStr("IDS_DLGTIP_SCENSELNEXT"));
}
// Folder
C4ScenarioListLoader::Folder::~Folder()
{
delete pMapData;
ClearChildren();
}
bool C4ScenarioListLoader::Folder::Start()
{
// open as subfolder
if (!C4StartupScenSelDlg::pInstance) return false;
return C4StartupScenSelDlg::pInstance->OpenFolder(this);
}
int
#ifdef _MSC_VER
__cdecl
#endif
EntrySortFunc(const void *pEl1, const void *pEl2)
{
C4ScenarioListLoader::Entry *pEntry1 = *static_cast<C4ScenarioListLoader::Entry * const *>(pEl1), *pEntry2 = *static_cast<C4ScenarioListLoader::Entry * const *>(pEl2);
// sort folders before scenarios
bool fS1, fS2;
if (!(fS1 = !pEntry1->GetIsFolder()) != !true != !(fS2 = !pEntry2->GetIsFolder())) return fS1 - fS2;
// sort by folder index (undefined index 0 goes to the end)
if (!Config.Startup.AlphabeticalSorting) if (pEntry1->GetFolderIndex() || pEntry2->GetFolderIndex())
{
if (!pEntry1->GetFolderIndex()) return +1;
if (!pEntry2->GetFolderIndex()) return -1;
int32_t iDiff = pEntry1->GetFolderIndex() - pEntry2->GetFolderIndex();
if (iDiff) return iDiff;
}
// sort by numbered standard scenario icons
if (Inside(pEntry1->GetIconIndex(), 2, 11))
{
int32_t iDiff = pEntry1->GetIconIndex() - pEntry2->GetIconIndex();
if (iDiff) return iDiff;
}
// sort by difficulty (undefined difficulty goes to the end)
if (!Config.Startup.AlphabeticalSorting) if (pEntry1->GetDifficulty() || pEntry2->GetDifficulty())
{
if (!pEntry1->GetDifficulty()) return +1;
if (!pEntry2->GetDifficulty()) return -1;
int32_t iDiff = pEntry1->GetDifficulty() - pEntry2->GetDifficulty();
if (iDiff) return iDiff;
}
// otherwise, sort by name
return stricmp(pEntry1->GetName().getData(), pEntry2->GetName().getData());
}
uint32_t C4ScenarioListLoader::Folder::GetEntryCount() const
{
uint32_t iCount = 0;
for (Entry *i = pFirst; i; i = i->pNext) ++iCount;
return iCount;
}
void C4ScenarioListLoader::Folder::Sort()
{
// use C-Library-QSort on a buffer of entry pointers; then re-link list
if (!pFirst) return;
uint32_t iCount, i;
Entry **ppEntries = new Entry *[i = iCount = GetEntryCount()], **ppI, *pI = pFirst, **ppIThis;
for (ppI = ppEntries; i--; pI = pI->pNext) * ppI++ = pI;
qsort(ppEntries, iCount, sizeof(Entry *), &EntrySortFunc);
ppIThis = &pFirst;
for (ppI = ppEntries; iCount--; ppIThis = &((*ppIThis)->pNext)) * ppIThis = *ppI++;
*ppIThis = nullptr;
delete[] ppEntries;
}
void C4ScenarioListLoader::Folder::ClearChildren()
{
// folder deletion: del all the tree non-recursively
Folder *pDelFolder = this, *pCheckFolder;
for (;;)
{
// delete all children as long as they are not folders
Entry *pChild;
while (pChild = pDelFolder->pFirst)
if (pCheckFolder = pChild->GetIsFolder())
// child entry if folder: Continue delete in there
pDelFolder = pCheckFolder;
else
// regular child entry: del it
// destructor of child will remove it from list
delete pChild;
// this emptied: Done!
if (pDelFolder == this) break;
// deepest child recursion reached: Travel up folders
pDelFolder = (pCheckFolder = pDelFolder)->pParent;
assert(pDelFolder);
delete pCheckFolder;
}
}
bool C4ScenarioListLoader::Folder::LoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf *psFilename, bool fLoadEx, bool fReload)
{
// contents already loaded?
if (fContentsLoaded && !fReload) return true;
// clear previous
delete pMapData; pMapData = nullptr;
// if filename is not given, assume it's been loaded in this entry
if (!psFilename) psFilename = &this->sFilename; else this->sFilename.Ref(*psFilename);
// nothing loaded: Load now
if (!DoLoadContents(pLoader, pFromGrp, *psFilename, fLoadEx)) return false;
// sort loaded stuff by name
Sort();
return true;
}
C4ScenarioListLoader::Entry *C4ScenarioListLoader::Folder::FindEntryByName(const char *szFilename) const
{
// do a case-insensitive filename comparison
for (Entry *pEntry = pFirst; pEntry; pEntry = pEntry->GetNext())
if (SEqualNoCase(szFilename, GetFilename(pEntry->GetEntryFilename().getData())))
return pEntry;
// nothing found
return nullptr;
}
StdStrBuf C4ScenarioListLoader::Folder::GetOpenText()
{
return StdStrBuf(LoadResStr("IDS_BTN_OPEN"));
}
StdStrBuf C4ScenarioListLoader::Folder::GetOpenTooltip()
{
return StdStrBuf(LoadResStr("IDS_DLGTIP_SCENSELNEXT"));
}
bool C4ScenarioListLoader::Folder::LoadCustomPre(C4Group &rGrp)
{
// load folder core if available
StdStrBuf sFileContents;
if (rGrp.LoadEntryString(C4CFN_FolderCore, sFileContents))
if (!CompileFromBuf_LogWarn<StdCompilerINIRead>(C4F, sFileContents, (rGrp.GetFullName() + DirSep C4CFN_FolderCore).getData()))
return false;
return true;
}
// SubFolder
bool C4ScenarioListLoader::SubFolder::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
{
// default icon fallback
if (!fIconLoaded)
fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(C4StartupScenSel_DefaultIcon_Folder));
// folder index
iFolderIndex = C4F.Head.Index;
return true;
}
bool C4ScenarioListLoader::SubFolder::DoLoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf &sFilename, bool fLoadEx)
{
assert(pLoader);
// clear any previous
ClearChildren();
// group specified: Load as child
C4Group Group;
if (pFromGrp)
{
if (!Group.OpenAsChild(pFromGrp, sFilename.getData())) return false;
}
else
// no parent group: Direct load from filename
if (!Group.Open(sFilename.getData())) return false;
// get number of entries, to estimate progress
const char *szC4CFN_ScenarioFiles = C4CFN_ScenarioFiles; // assign values for constant comparison
const char *szSearchMask; int32_t iEntryCount = 0;
for (szSearchMask = szC4CFN_ScenarioFiles; szSearchMask;)
{
Group.ResetSearch();
while (Group.FindNextEntry(szSearchMask)) ++iEntryCount;
// next search mask
if (szSearchMask == szC4CFN_ScenarioFiles)
szSearchMask = C4CFN_FolderFiles;
else
szSearchMask = nullptr;
}
// initial progress estimate
if (!pLoader->DoProcessCallback(0, iEntryCount)) return false;
// iterate through group contents
char ChildFilename[_MAX_FNAME + 1]; StdStrBuf sChildFilename; int32_t iLoadCount = 0;
for (szSearchMask = szC4CFN_ScenarioFiles; szSearchMask;)
{
Group.ResetSearch();
while (Group.FindNextEntry(szSearchMask, ChildFilename))
{
sChildFilename.Ref(ChildFilename);
// okay; create this item
Entry *pNewEntry = Entry::CreateEntryForFile(sChildFilename, this);
if (pNewEntry)
{
// ...and load it
if (!pNewEntry->Load(&Group, &sChildFilename, fLoadEx))
{
DebugLogF("Error loading entry \"%s\" in SubFolder \"%s\"!", sChildFilename.getData(), Group.GetFullName().getData());
delete pNewEntry;
}
}
// mark progress
if (!pLoader->DoProcessCallback(++iLoadCount, iEntryCount)) return false;
}
// next search mask
if (szSearchMask == szC4CFN_ScenarioFiles)
szSearchMask = C4CFN_FolderFiles;
else
szSearchMask = nullptr;
}
// load map folder data
if (Config.Graphics.ShowFolderMaps && Group.FindEntry(C4CFN_MapFolderData))
{
pMapData = new C4MapFolderData();
if (!pMapData->Load(Group, this))
{
// load error :(
delete pMapData;
pMapData = nullptr;
}
}
// done, success
fContentsLoaded = true;
return true;
}
// RegularFolder
bool C4ScenarioListLoader::RegularFolder::LoadCustom(C4Group &rGrp, bool fNameLoaded, bool fIconLoaded)
{
// default icon fallback
if (!fIconLoaded)
fctIcon.Set(C4Startup::Get()->Graphics.fctScenSelIcons.GetSection(C4StartupScenSel_DefaultIcon_WinFolder));
// folder index
iFolderIndex = C4F.Head.Index;
return true;
}
bool C4ScenarioListLoader::RegularFolder::DoLoadContents(C4ScenarioListLoader *pLoader, C4Group *pFromGrp, const StdStrBuf &sFilename, bool fLoadEx)
{
// clear any previous
ClearChildren();
// regular folders must exist and not be within group!
assert(!pFromGrp);
if (!DirectoryExists(sFilename.getData())) return false;
DirectoryIterator DirIter(sFilename.getData());
const char *szChildFilename; StdStrBuf sChildFilename;
// get number of entries, to estimate progress
int32_t iCountLoaded = 0, iCountTotal = 0;
for (; szChildFilename = *DirIter; ++DirIter)
{
if (!*szChildFilename || *GetFilename(szChildFilename) == '.') continue;
++iCountTotal;
}
// initial progress estimate
if (!pLoader->DoProcessCallback(iCountLoaded, iCountTotal)) return false;
// do actual loading of files
for (DirIter.Reset(sFilename.getData()); szChildFilename = *DirIter; ++DirIter)
{
// Ignore directory navigation entries and CVS folders
if (!*szChildFilename || *GetFilename(szChildFilename) == '.') continue;
if (SEqualNoCase(GetFilename(szChildFilename), "CVS")) continue;
sChildFilename.Ref(szChildFilename);
// filename okay; create this item
Entry *pNewEntry = Entry::CreateEntryForFile(sChildFilename, this);
if (pNewEntry)
{
// ...and load it
if (!pNewEntry->Load(nullptr, &sChildFilename, fLoadEx))
{
DebugLogF("Error loading entry \"%s\" in Folder \"%s\"!", sChildFilename.getData(), sFilename.getData());
delete pNewEntry;
}
}
// progress callback
if (!pLoader->DoProcessCallback(++iCountLoaded, iCountTotal)) return false;
}
// done, success
fContentsLoaded = true;
return true;
}
// C4ScenarioListLoader
C4ScenarioListLoader::C4ScenarioListLoader() : pRootFolder(nullptr), pCurrFolder(nullptr),
iLoading(0), iProgress(0), iMaxProgress(0), fAbortThis(false), fAbortPrevious(false) {}
C4ScenarioListLoader::~C4ScenarioListLoader()
{
delete pRootFolder;
}
bool C4ScenarioListLoader::BeginActivity(bool fAbortPrevious)
{
// if previous activities were running, stop them first if desired
if (iLoading && fAbortPrevious)
this->fAbortPrevious = true;
// mark this activity
++iLoading;
// progress of activity not yet decided
iProgress = iMaxProgress = 0;
// okay; start activity
return true;
}
void C4ScenarioListLoader::EndActivity()
{
assert(iLoading);
if (!--iLoading)
{
// last activity done: Reset any flags
fAbortThis = false;
fAbortPrevious = false;
iProgress = iMaxProgress = 0;
}
else
{
// child activity done: Transfer abort flag for next activity
fAbortThis = fAbortPrevious;
}
}
bool C4ScenarioListLoader::DoProcessCallback(int32_t iProgress, int32_t iMaxProgress)
{
this->iProgress = iProgress;
this->iMaxProgress = iMaxProgress;
// callback to dialog
if (C4StartupScenSelDlg::pInstance) C4StartupScenSelDlg::pInstance->ProcessCallback();
auto checkTimer = false;
const auto now = timeGetTime();
// limit to real 10 FPS, as it may unnecessarily slow down loading a lot otherwise
if (lastCheckTimer == 0 || now - lastCheckTimer > 100)
{
checkTimer = true;
lastCheckTimer = now;
}
// process callback - abort at a few ugly circumstances...
if (Application.HandleMessage(0, checkTimer) == HR_Failure // WM_QUIT message?
|| !C4StartupScenSelDlg::pInstance // host dialog removed?
|| !C4StartupScenSelDlg::pInstance->IsShown() // host dialog closed?
) return false;
// and also abort if flagged
return !fAbortThis;
}
bool C4ScenarioListLoader::Load(const StdStrBuf &sRootFolder)
{
// (unthreaded) loading of all entries in root folder
if (!BeginActivity(true)) return false;
delete pRootFolder; pRootFolder = nullptr;
pCurrFolder = pRootFolder = new RegularFolder(nullptr);
bool fSuccess = pRootFolder->LoadContents(this, nullptr, &sRootFolder, false, false);
EndActivity();
return fSuccess;
}
bool C4ScenarioListLoader::Load(Folder *pSpecifiedFolder, bool fReload)
{
// call safety
if (!pRootFolder || !pSpecifiedFolder) return false;
// set new current and load it
if (!BeginActivity(true)) return false;
pCurrFolder = pSpecifiedFolder;
bool fSuccess = pCurrFolder->LoadContents(this, nullptr, nullptr, false, fReload);
EndActivity();
return fSuccess;
}
bool C4ScenarioListLoader::LoadExtended(Entry *pEntry)
{
// call safety
if (!pRootFolder || !pEntry) return false;
// load info of selection
if (!BeginActivity(false)) return false;
bool fSuccess = pEntry->Load(nullptr, nullptr, true);
EndActivity();
return fSuccess;
}
bool C4ScenarioListLoader::FolderBack()
{
// call safety
if (!pRootFolder || !pCurrFolder) return false;
// already in root: Can't go up
if (pCurrFolder == pRootFolder) return false;
// otherwise, up one level
return Load(pCurrFolder->GetParent(), false);
}
bool C4ScenarioListLoader::ReloadCurrent()
{
// call safety
if (!pRootFolder || !pCurrFolder) return false;
// reload current
return Load(pCurrFolder, true);
}
// Scenario selection GUI
// font clrs
const uint32_t ClrScenarioItem = 0xff000000,
ClrScenarioItemXtra = 0x7f000000,
ClrScenarioItemDisabled = 0x7f000000;
// C4StartupScenSelDlg::ScenListItem
C4StartupScenSelDlg::ScenListItem::ScenListItem(C4GUI::ListBox *pForListBox, C4ScenarioListLoader::Entry *pForEntry, C4GUI::Element *pInsertBeforeElement)
: pIcon(nullptr), pNameLabel(nullptr), pScenListEntry(pForEntry)
{
assert(pScenListEntry);
CStdFont &rUseFont = C4Startup::Get()->Graphics.BookFont;
StdStrBuf sIgnore;
bool fEnabled = pScenListEntry->CanOpen(sIgnore);
// calc height
int32_t iHeight = rUseFont.GetLineHeight() + 2 * IconLabelSpacing;
// create subcomponents
pIcon = new C4GUI::Picture(C4Rect(0, 0, iHeight, iHeight), true);
pIcon->SetFacet(pScenListEntry->GetIconFacet());
StdStrBuf name = pScenListEntry->GetName();
CMarkup::StripMarkup(&name);
pNameLabel = new C4GUI::Label(name.getData(), iHeight + IconLabelSpacing, IconLabelSpacing, ALeft, fEnabled ? ClrScenarioItem : ClrScenarioItemDisabled, &rUseFont, false, false);
// calc own bounds - use icon bounds only, because only the height is used when the item is added
SetBounds(pIcon->GetBounds());
// add components
AddElement(pIcon); AddElement(pNameLabel);
// tooltip by name, so long names can be read via tooltip
SetToolTip(pScenListEntry->GetName().getData());
// add to listbox (will get resized horizontally and moved) - zero indent; no tree structure in this dialog
pForListBox->InsertElement(this, pInsertBeforeElement, 0);
// update name label width to reflect new horizontal size
// name label width must be set so rename edit will take its size
pNameLabel->SetAutosize(false);
C4Rect rcNLB = pNameLabel->GetBounds(); rcNLB.Wdt = GetClientRect().Wdt - rcNLB.x - IconLabelSpacing;
pNameLabel->SetBounds(rcNLB);
}
void C4StartupScenSelDlg::ScenListItem::UpdateOwnPos()
{
// parent for client rect
typedef C4GUI::Window ParentClass;
ParentClass::UpdateOwnPos();
// reposition items
C4GUI::ComponentAligner caBounds(GetContainedClientRect(), IconLabelSpacing, IconLabelSpacing);
// nothing to reposition for now...
}
void C4StartupScenSelDlg::ScenListItem::MouseInput(C4GUI::CMouse &rMouse, int32_t iButton, int32_t iX, int32_t iY, uint32_t dwKeyParam)
{
// inherited processing
typedef C4GUI::Window BaseClass;
BaseClass::MouseInput(rMouse, iButton, iX, iY, dwKeyParam);
}
bool C4StartupScenSelDlg::ScenListItem::CheckNameHotkey(const char *c)
{
// return whether this item can be selected by entering given char:
// first char of name must match
// FIXME: make unicode-ready
if (!pScenListEntry) return false;
const char *szName = pScenListEntry->GetName().getData();
return szName && (toupper(*szName) == toupper(c[0]));
}
bool C4StartupScenSelDlg::ScenListItem::KeyRename()
{
// rename this entry
C4StartupScenSelDlg::pInstance->StartRenaming(new C4GUI::CallbackRenameEdit<C4StartupScenSelDlg::ScenListItem, RenameParams>(pNameLabel, this, RenameParams(), &C4StartupScenSelDlg::ScenListItem::DoRenaming, &C4StartupScenSelDlg::ScenListItem::AbortRenaming));
return true;
}
void C4StartupScenSelDlg::ScenListItem::AbortRenaming(RenameParams par)
{
// no renaming
C4StartupScenSelDlg::pInstance->SetRenamingDone();
}
C4GUI::RenameEdit::RenameResult C4StartupScenSelDlg::ScenListItem::DoRenaming(RenameParams par, const char *szNewName)
{
// check validity for new name
if (!GetEntry()->RenameTo(szNewName)) return C4GUI::RenameEdit::RR_Invalid;
// rename label
pNameLabel->SetText(GetEntry()->GetName().getData());
// main dlg update
C4StartupScenSelDlg::pInstance->SetRenamingDone();
C4StartupScenSelDlg::pInstance->ResortFolder();
C4StartupScenSelDlg::pInstance->UpdateSelection();
C4StartupScenSelDlg::pInstance->FocusScenList();
// done; rename accepted and control deleted by ResortFolder
return C4GUI::RenameEdit::RR_Deleted;
}
// C4StartupScenSelDlg
C4StartupScenSelDlg::C4StartupScenSelDlg(bool fNetwork) : C4StartupDlg(LoadResStrNoAmp(fNetwork ? "IDS_DLG_NETSTART" : "IDS_DLG_STARTGAME")), pScenLoader(nullptr), fIsInitialLoading(false), fStartNetworkGame(fNetwork), pMapData(nullptr), pRenameEdit(nullptr), pfctBackground(nullptr), btnAllowUserChange{nullptr}
{
// assign singleton
pInstance = this;
// screen calculations
UpdateSize();
int32_t iButtonWidth, iCaptionFontHgt;
int iButtonHeight = C4GUI_ButtonHgt;
int iBookPageWidth;
int iExtraHPadding = rcBounds.Wdt >= 700 ? rcBounds.Wdt / 50 : 0;
int iExtraVPadding = rcBounds.Hgt >= 540 ? rcBounds.Hgt / 20 : 0;
C4GUI::GetRes()->CaptionFont.GetTextExtent("<< BACK", iButtonWidth, iCaptionFontHgt, true);
iButtonWidth *= 3;
C4GUI::ComponentAligner caMain(GetClientRect(), 0, 0, true);
C4GUI::ComponentAligner caButtonArea(caMain.GetFromBottom(caMain.GetHeight() / 8), rcBounds.Wdt / (rcBounds.Wdt >= 700 ? 128 : 256), 0);
C4Rect rcMap = caMain.GetCentered(caMain.GetWidth(), caMain.GetHeight());
int iYOversize = caMain.GetHeight() / 10; // overlap of map to top
rcMap.y -= iYOversize; rcMap.Hgt += iYOversize;
C4GUI::ComponentAligner caMap(rcMap, 0, 0, true);
caMap.ExpandTop(-iYOversize);
C4GUI::ComponentAligner caBook(caMap.GetCentered(caMap.GetWidth() * 11 / 12 - 4 * iExtraHPadding, caMap.GetHeight()), rcBounds.Wdt / 30, iExtraVPadding, false);
C4GUI::ComponentAligner caBookLeft(caBook.GetFromLeft(iBookPageWidth = caBook.GetWidth() * 4 / 9 + 4 - iExtraHPadding * 2), 0, 5);
// tabular for different scenario selection designs
pScenSelStyleTabular = new C4GUI::Tabular(rcMap, C4GUI::Tabular::tbNone);
pScenSelStyleTabular->SetSheetMargin(0);
pScenSelStyleTabular->SetDrawDecoration(false);
AddElement(pScenSelStyleTabular);
C4GUI::Tabular::Sheet *pSheetBook = pScenSelStyleTabular->AddSheet(nullptr);
// map sheet; later queried via GetSheet(ShowStyle_Map)
pScenSelStyleTabular->AddSheet(nullptr);
// scenario selection list
CStdFont &rScenSelCaptionFont = C4Startup::Get()->Graphics.BookFontTitle;
pScenSelCaption = new C4GUI::Label("", caBookLeft.GetFromTop(rScenSelCaptionFont.GetLineHeight()), ACenter, ClrScenarioItem, &rScenSelCaptionFont, false);
pSheetBook->AddElement(pScenSelCaption);
pScenSelCaption->SetToolTip(LoadResStr("IDS_DLGTIP_SELECTSCENARIO"));
// search bar
const char *labelText = LoadResStr("IDS_DLG_SEARCH");
int32_t width = 100, height;
C4GUI::GetRes()->TextFont.GetTextExtent(labelText, width, height, true);
C4GUI::ComponentAligner caSearchBar(caBookLeft.GetFromBottom(height), 0, 0);
auto *searchLabel = new C4GUI::WoodenLabel(labelText, caSearchBar.GetFromLeft(width + 10), C4GUI_Caption2FontClr, &C4GUI::GetRes()->TextFont);
searchLabel->SetToolTip(LoadResStr("IDS_DLGTIP_SEARCHLIST"));
pSheetBook->AddElement(searchLabel);
searchBar = new C4GUI::CallbackEdit<C4StartupScenSelDlg>(caSearchBar.GetAll(), this, &C4StartupScenSelDlg::OnSearchBarEnter);
searchBar->SetToolTip(LoadResStr("IDS_DLGTIP_SEARCHLIST"));
pSheetBook->AddElement(searchBar);
// scenario selection list box
pScenSelList = new C4GUI::ListBox(caBookLeft.GetAll());
pScenSelList->SetToolTip(LoadResStr("IDS_DLGTIP_SELECTSCENARIO"));
pScenSelList->SetDecoration(false, &C4Startup::Get()->Graphics.sfctBookScroll, true);
pSheetBook->AddElement(pScenSelList);
pScenSelList->SetSelectionChangeCallbackFn(new C4GUI::CallbackHandler<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::OnSelChange));
pScenSelList->SetSelectionDblClickFn(new C4GUI::CallbackHandler<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::OnSelDblClick));
// scenario selection list progress label
pScenSelProgressLabel = new C4GUI::Label("", pScenSelList->GetBounds().GetMiddleX(), pScenSelList->GetBounds().GetMiddleX() - iCaptionFontHgt / 2, ACenter, ClrScenarioItem, &(C4Startup::Get()->Graphics.BookFontCapt), false);
pSheetBook->AddElement(pScenSelProgressLabel);
// right side of book: Displaying current selection
pSelectionInfo = new C4GUI::TextWindow(caBook.GetFromRight(iBookPageWidth), C4StartupScenSel_TitlePictureWdt + 2 * C4StartupScenSel_TitleOverlayMargin, C4StartupScenSel_TitlePictureHgt + 2 * C4StartupScenSel_TitleOverlayMargin,
C4StartupScenSel_TitlePicturePadding, 100, 4096, nullptr, true, &C4Startup::Get()->Graphics.fctScenSelTitleOverlay, C4StartupScenSel_TitleOverlayMargin);
pSelectionInfo->SetDecoration(false, false, &C4Startup::Get()->Graphics.sfctBookScroll, true);
pSheetBook->AddElement(pSelectionInfo);
// back button
C4GUI::CallbackButton<C4StartupScenSelDlg> *btn;
AddElement(btn = new C4GUI::CallbackButton<C4StartupScenSelDlg>(LoadResStr("IDS_BTN_BACK"), caButtonArea.GetFromLeft(iButtonWidth, iButtonHeight), &C4StartupScenSelDlg::OnBackBtn));
btn->SetToolTip(LoadResStr("IDS_DLGTIP_BACKMAIN"));
AddElement(btn);
// next button
pOpenBtn = new C4GUI::CallbackButton<C4StartupScenSelDlg>(LoadResStr("IDS_BTN_OPEN"), caButtonArea.GetFromRight(iButtonWidth, iButtonHeight), &C4StartupScenSelDlg::OnNextBtn);
pOpenBtn->SetToolTip(LoadResStr("IDS_DLGTIP_SCENSELNEXT"));
// allow user change button
AddElement(btnAllowUserChange = new C4GUI::CheckBox(caButtonArea.GetFromRight(iButtonWidth, iButtonHeight), LoadResStr("IDS_DLG_ALLOWUSERCHANGE"), false));
// game options boxes
pGameOptionButtons = new C4GameOptionButtons(caButtonArea.GetAll(), fNetwork, true, false);
AddElement(pGameOptionButtons);
// next button adding
AddElement(pOpenBtn);
// dlg starts with focus on listbox
SetFocus(pScenSelList, false);
// key bindings
keyBack.reset(new C4KeyBinding(C4KeyCodeEx(K_LEFT), "StartupScenSelFolderUp", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyBack), C4CustomKey::PRIO_CtrlOverride));
keyRefresh.reset(new C4KeyBinding(C4KeyCodeEx(K_F5), "StartupScenSelReload", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyRefresh), C4CustomKey::PRIO_CtrlOverride));
keyForward.reset(new C4KeyBinding(C4KeyCodeEx(K_RIGHT), "StartupScenSelNext", KEYSCOPE_Gui,
new C4GUI::DlgKeyCB<C4StartupScenSelDlg>(*this, &C4StartupScenSelDlg::KeyForward), C4CustomKey::PRIO_CtrlOverride));
keyRename.reset(new C4KeyBinding(C4KeyCodeEx(K_F2), "StartupScenSelRename", KEYSCOPE_Gui,
new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyRename), C4CustomKey::PRIO_CtrlOverride));
keyDelete.reset(new C4KeyBinding(C4KeyCodeEx(K_DELETE), "StartupScenSelDelete", KEYSCOPE_Gui,
new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyDelete), C4CustomKey::PRIO_CtrlOverride));
keyCheat.reset(new C4KeyBinding(C4KeyCodeEx(KEY_M, KEYS_Alt), "StartupScenSelCheat", KEYSCOPE_Gui,
new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyCheat), C4CustomKey::PRIO_CtrlOverride));
keySearch.reset(new C4KeyBinding(C4KeyCodeEx(KEY_F, KEYS_Control), "StartupScenSelSearch", KEYSCOPE_Gui,
new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeySearch), C4CustomKey::PRIO_CtrlOverride));
keyEscape.reset(new C4KeyBinding(C4KeyCodeEx(K_ESCAPE), "StartupScenSelEscape", KEYSCOPE_Gui,
new C4GUI::ControlKeyDlgCB<C4StartupScenSelDlg>(pScenSelList, *this, &C4StartupScenSelDlg::KeyEscape), C4CustomKey::PRIO_CtrlOverride));
}
C4StartupScenSelDlg::~C4StartupScenSelDlg()
{
delete pScenLoader;
if (this == pInstance) pInstance = nullptr;
}
void C4StartupScenSelDlg::DrawElement(C4FacetEx &cgo)
{
// draw background
if (pfctBackground)
DrawBackground(cgo, *pfctBackground);
else
DrawBackground(cgo, C4Startup::Get()->Graphics.fctScenSelBG);
}
void C4StartupScenSelDlg::HideTitle(bool hide)
{
if (hide == !pFullscreenTitle)
{
return;
}
FullscreenDialog::SetTitle(hide ? "" : LoadResStrNoAmp(fStartNetworkGame ? "IDS_DLG_NETSTART" : "IDS_DLG_STARTGAME"));
}
void C4StartupScenSelDlg::OnShown()
{
C4StartupDlg::OnShown();
// init file list
fIsInitialLoading = true;
if (!pScenLoader) pScenLoader = new C4ScenarioListLoader();
pScenLoader->Load(StdStrBuf(Config.General.ExePath));
UpdateList();
UpdateSelection();
fIsInitialLoading = false;
// network activation by dialog type
Game.NetworkActive = fStartNetworkGame;
}
void C4StartupScenSelDlg::OnClosed(bool fOK)
{
AbortRenaming();
// clear laoded scenarios
if (pScenLoader)
{
delete pScenLoader;
pScenLoader = nullptr;
UpdateList(); // must clear scenario list, because it points to deleted stuff
UpdateSelection(); // must clear picture facet of selection!
}
// dlg abort: return to main screen
if (!fOK)
{
// clear settings: Password
Game.Network.SetPassword(nullptr);
C4Startup::Get()->SwitchDialog(C4Startup::SDID_Back);
}
}
void C4StartupScenSelDlg::UpdateUseCrewBtn()
{
C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
C4SForceFairCrew eOpt = pSel ? pSel->GetFairCrewAllowed() : C4SFairCrew_Free;
pGameOptionButtons->SetForceFairCrewState(eOpt);
}
void C4StartupScenSelDlg::UpdateList()
{
AbortRenaming();
// default: Show book (also for loading screen)
pMapData = nullptr;
pScenSelStyleTabular->SelectSheet(ShowStyle_Book, false);
// and delete any stuff from map selection
C4GUI::Tabular::Sheet *pMapSheet = pScenSelStyleTabular->GetSheet(ShowStyle_Map);
while (pMapSheet->GetFirst()) delete pMapSheet->GetFirst();
pfctBackground = nullptr;
// for now, all the list is loaded at once anyway
// so just clear and add all loaded items
// remember old selection
C4ScenarioListLoader::Entry *pOldSelection = GetSelectedEntry();
C4GUI::Element *pEl;
while (pEl = pScenSelList->GetFirst()) delete pEl;
pScenSelCaption->SetText("");
// scen loader still busy: Nothing to add
if (!pScenLoader) return;
if (pScenLoader->IsLoading())
{
StdStrBuf sProgressText;
sProgressText.Format(LoadResStr("IDS_MSG_SCENARIODESC_LOADING"), static_cast<int32_t>(pScenLoader->GetProgressPercent()));
pScenSelProgressLabel->SetText(sProgressText.getData());
pScenSelProgressLabel->SetVisibility(true);
return;
}
pScenSelProgressLabel->SetVisibility(false);
// is this a map folder? Then show the map instead
C4ScenarioListLoader::Folder *pFolder = pScenLoader->GetCurrFolder();
if (pMapData = pFolder->GetMapData())
{
pMapData->ResetSelection();
pMapData->CreateGUIElements(this, *pScenSelStyleTabular->GetSheet(ShowStyle_Map));
pScenSelStyleTabular->SelectSheet(ShowStyle_Map, false);
}
else
{
// book style selection
HideTitle(false);
// add what has been loaded
for (C4ScenarioListLoader::Entry *pEnt = pScenLoader->GetFirstEntry(); pEnt; pEnt = pEnt->GetNext())
{
StdStrBuf name = pEnt->GetName();
CMarkup::StripMarkup(&name);
if (!SLen(searchBar->GetText()) || SSearchNoCase(name.getData(), searchBar->GetText()))
{
ScenListItem *pEntItem = new ScenListItem(pScenSelList, pEnt);
if (pEnt == pOldSelection) pScenSelList->SelectEntry(pEntItem, false);
}
else if (pEnt == pOldSelection)
{
pOldSelection = nullptr;
}
}
// set title of current folder
// but not root
if (pFolder && pFolder != pScenLoader->GetRootFolder())
pScenSelCaption->SetText(pFolder->GetName().getData());
else
{
// special root title
pScenSelCaption->SetText(LoadResStr("IDS_DLG_SCENARIOS"));
}
// new list has been loaded: Select first entry if nothing else had been selected
if (!pOldSelection) pScenSelList->SelectFirstEntry(false);
}
}
void C4StartupScenSelDlg::ResortFolder()
{
// if it's still loading, sorting will be done in the end anyway
if (!pScenLoader || pScenLoader->IsLoading()) return;
C4ScenarioListLoader::Folder *pFolder = pScenLoader->GetCurrFolder();
if (!pFolder) return;
pFolder->Resort();
UpdateList();
}
void C4StartupScenSelDlg::UpdateSelection()
{
AbortRenaming();
if (!pScenLoader)
{
C4Facet fctNoPic;
pSelectionInfo->SetPicture(fctNoPic);
pSelectionInfo->ClearText(false);
SetOpenButtonDefaultText();
return;
}
// determine target text box
C4GUI::TextWindow *pSelectionInfo = pMapData ? pMapData->GetSelectionInfoBox() : this->pSelectionInfo;
// get selected entry
C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
if (!pSel)
{
// no selection: Display data of current parent folder
pSel = pScenLoader->GetCurrFolder();
// but not root
if (pSel == pScenLoader->GetRootFolder()) pSel = nullptr;
}
// get title image and desc of selected entry
C4Facet fctTitle; StdStrBuf sTitle, sDesc, sVersion, sAuthor;
if (pSel)
{
pScenLoader->LoadExtended(pSel); // 2do: Multithreaded
fctTitle = pSel->GetTitlePicture();
sTitle.Ref(pSel->GetName());
sDesc.Ref(pSel->GetDesc());
sVersion.Ref(pSel->GetVersion());
sAuthor.Ref(pSel->GetAuthor());
// never show a pure title string: There must always be some text or an image
if (!fctTitle.Surface && (!sDesc || !*sDesc.getData()))
sTitle.Clear();
// selection specific open/start button
pOpenBtn->SetText(pSel->GetOpenText().getData());
pOpenBtn->SetToolTip(pSel->GetOpenTooltip().getData());
if (auto *scenario = dynamic_cast<C4ScenarioListLoader::Scenario *>(pSel); scenario)
{
btnAllowUserChange->SetEnabled(!scenario->GetC4S().Definitions.LocalOnly);
btnAllowUserChange->SetChecked(scenario->GetC4S().Definitions.AllowUserChange);
}
else
{
btnAllowUserChange->SetChecked(false);
btnAllowUserChange->SetEnabled(false);
}
}
else
{
btnAllowUserChange->SetChecked(false);
btnAllowUserChange->SetEnabled(false);
SetOpenButtonDefaultText();
}
// set data in selection component
pSelectionInfo->ClearText(false);
pSelectionInfo->SetPicture(fctTitle);
if (!!sTitle && (!sDesc || !*sDesc.getData())) pSelectionInfo->AddTextLine(sTitle.getData(), &C4Startup::Get()->Graphics.BookFontCapt, ClrScenarioItem, false, false);
if (!!sDesc) pSelectionInfo->AddTextLine(sDesc.getData(), &C4Startup::Get()->Graphics.BookFont, ClrScenarioItem, false, false, &C4Startup::Get()->Graphics.BookFontCapt);
if (!!sAuthor) pSelectionInfo->AddTextLine(FormatString(LoadResStr("IDS_CTL_AUTHOR"), sAuthor.getData()).getData(),
&C4Startup::Get()->Graphics.BookFont, ClrScenarioItemXtra, false, false);
if (!!sVersion) pSelectionInfo->AddTextLine(FormatString(LoadResStr("IDS_DLG_VERSION"), sVersion.getData()).getData(),
&C4Startup::Get()->Graphics.BookFont, ClrScenarioItemXtra, false, false);
pSelectionInfo->UpdateHeight();
// usecrew-button
UpdateUseCrewBtn();
}
C4StartupScenSelDlg::ScenListItem *C4StartupScenSelDlg::GetSelectedItem()
{
return static_cast<ScenListItem *>(pScenSelList->GetSelectedItem());
}
C4ScenarioListLoader::Entry *C4StartupScenSelDlg::GetSelectedEntry()
{
// map layout: Get selection from map
if (pMapData) return pMapData->GetSelectedEntry();
// get selection in listbox
ScenListItem *pSel = static_cast<ScenListItem *>(pScenSelList->GetSelectedItem());
return pSel ? pSel->GetEntry() : nullptr;
}
bool C4StartupScenSelDlg::StartScenario(C4ScenarioListLoader::Scenario *pStartScen)
{
assert(pStartScen);
if (!pStartScen) return false;
// get required object definitions
if (btnAllowUserChange->GetChecked())
{
// get definitions as user selects them
std::vector<std::string> defs = pStartScen->GetC4S().Definitions.GetModules();
if (defs.empty())
{
defs.push_back("Objects.c4d");
}
if (!C4DefinitionSelDlg::SelectDefinitions(GetScreen(), defs))
// user aborted during definition selection
return false;
Game.DefinitionFilenames = defs;
Game.FixedDefinitions = true;
}
else
{
// for no user change, just set default objects. Custom settings will override later anyway
Game.DefinitionFilenames.push_back("Objects.c4d");
}
// set other default startup parameters
SCopy(pStartScen->GetEntryFilename().getData(), Game.ScenarioFilename);
Game.fLobby = !!Game.NetworkActive; // always lobby in network
Game.fObserve = false;
// start with this set!
C4Startup::Get()->Start();
return true;
}
bool C4StartupScenSelDlg::OpenFolder(C4ScenarioListLoader::Folder *pNewFolder)
{
// open it through loader
if (!pScenLoader) return false;
searchBar->ClearText();
bool fSuccess = pScenLoader->Load(pNewFolder, false);
UpdateList();
UpdateSelection();
if (!pMapData) SetFocus(pScenSelList, false);
return fSuccess;
}
bool C4StartupScenSelDlg::DoOK()
{
AbortRenaming();
// get selected entry
C4ScenarioListLoader::Entry *pSel = GetSelectedEntry();
if (!pSel) return false;
// check if open is possible
StdStrBuf sError;
if (!pSel->CanOpen(sError))
{
GetScreen()->ShowMessage(sError.getData(), LoadResStr("IDS_MSG_CANNOTSTARTSCENARIO"), C4GUI::Ico_Error);
return false;
}
// if CanOpen returned true but set an error message, that means it's a warning. Display it!
if (sError.getLength())
{
if (!GetScreen()->ShowMessageModal(sError.getData(), LoadResStrNoAmp("IDS_DLG_STARTGAME"), C4GUI::MessageDialog::btnOKAbort, C4GUI::Ico_Notify, &Config.Startup.HideMsgStartDedicated))
// user chose to not start it
return false;
}
// start it!
return pSel->Start();
}
bool C4StartupScenSelDlg::DoBack(bool fAllowClose)
{
AbortRenaming();
// if in a subfolder, try backtrace folders first
if (pScenLoader && pScenLoader->FolderBack())
{
searchBar->ClearText();
UpdateList();
UpdateSelection();
return true;
}
// while this isn't multithreaded, the dialog must not be aborted while initial load...
if (pScenLoader && pScenLoader->IsLoading()) return false;
// return to main screen
if (fAllowClose)
{
Close(false);
return true;
}
return false;
}
void C4StartupScenSelDlg::DoRefresh()
{
if (pScenLoader && !pScenLoader->IsLoading())
{
pScenSelList->SelectNone(false);
pScenLoader->ReloadCurrent();
UpdateList();
UpdateSelection();
}
}
void C4StartupScenSelDlg::SetOpenButtonDefaultText()
{
pOpenBtn->SetText(LoadResStr("IDS_BTN_OPEN"));
pOpenBtn->SetToolTip(LoadResStr("IDS_DLGTIP_SCENSELNEXT"));
}
bool C4StartupScenSelDlg::KeyRename()
{
// no rename in map mode
if (pMapData) return false;
// not if renaming already
if (IsRenaming()) return false;
// forward to selected scenario list item
ScenListItem *pSel = GetSelectedItem();
if (!pSel) return false;
return pSel->KeyRename();
}
bool C4StartupScenSelDlg::KeyDelete()
{
// do not delete from map folder
if (pMapData) return false;
// cancel renaming
AbortRenaming();
// delete selected item: Confirmation first
ScenListItem *pSel = GetSelectedItem();
if (!pSel) return false;
C4ScenarioListLoader::Entry *pEnt = pSel->GetEntry();
StdStrBuf sWarning;
bool fOriginal = false;
if (C4Group_IsGroup(pEnt->GetEntryFilename().getData()))
{
C4Group Grp;
if (Grp.Open(pEnt->GetEntryFilename().getData()))
{
fOriginal = !!Grp.GetOriginal();
}
Grp.Close();
}
sWarning.Format(LoadResStr(fOriginal ? "IDS_MSG_DELETEORIGINAL" : "IDS_MSG_PROMPTDELETE"), FormatString("%s %s", pEnt->GetTypeName().getData(), pEnt->GetName().getData()).getData());
GetScreen()->ShowRemoveDlg(new C4GUI::ConfirmationDialog(sWarning.getData(), LoadResStr("IDS_MNU_DELETE"),
new C4GUI::CallbackHandlerExPar<C4StartupScenSelDlg, ScenListItem *>(this, &C4StartupScenSelDlg::DeleteConfirm, pSel), C4GUI::MessageDialog::btnYesNo));
return true;
}
void C4StartupScenSelDlg::DeleteConfirm(ScenListItem *pSel)
{
// deletion confirmed. Do it.
C4ScenarioListLoader::Entry *pEnt = pSel->GetEntry();
if (!C4Group_DeleteItem(pEnt->GetEntryFilename().getData(), true))
{
StdStrBuf sMsg; sMsg.Format("%s", LoadResStr("IDS_FAIL_DELETE"));
Game.pGUI->ShowMessageModal(sMsg.getData(), LoadResStr("IDS_MNU_DELETE"), C4GUI::MessageDialog::btnOK, C4GUI::Ico_Error);
return;
}
// remove from scenario list
pScenSelList->SelectEntry(pSel->GetNext(), false);
delete pEnt;
delete pSel;
}
bool C4StartupScenSelDlg::KeyCheat()
{
return Game.pGUI->ShowRemoveDlg(new C4GUI::InputDialog(LoadResStr("IDS_TEXT_ENTERMISSIONPASSWORD"), LoadResStr("IDS_DLG_MISSIONACCESS"), C4GUI::Ico_Options,
new C4GUI::InputCallback<C4StartupScenSelDlg>(this, &C4StartupScenSelDlg::KeyCheat2),
false));
}
bool C4StartupScenSelDlg::KeySearch()
{
SetFocus(searchBar, false);
return true;
}
bool C4StartupScenSelDlg::KeyEscape()
{
if (GetFocus() == searchBar)
{
SetFocus(pScenSelList, false);
return true;
}
return false;
}
void C4StartupScenSelDlg::KeyCheat2(const StdStrBuf &rsCheatCode)
{
// Special character "-": remove mission password(s)
if (SEqual2(rsCheatCode.getData(), "-"))
{
const char *szPass = rsCheatCode.getPtr(1);
if (szPass && *szPass)
{
SRemoveModules(Config.General.MissionAccess, szPass, false);
UpdateList();
UpdateSelection();
return;
}
}
// No special character: add mission password(s)
const char *szPass = rsCheatCode.getPtr(0);
if (szPass && *szPass)
{
SAddModules(Config.General.MissionAccess, szPass, false);
UpdateList();
UpdateSelection();
return;
}
}
void C4StartupScenSelDlg::FocusScenList()
{
SetFocus(pScenSelList, false);
}
void C4StartupScenSelDlg::OnButtonScenario(C4GUI::Control *pEl)
{
// map button was clicked: Update selected scenario
if (!pMapData || !pEl) return;
// OnButtonScenario may change the current selection
if (C4ScenarioListLoader::Entry *pSel{GetSelectedEntry()}; pMapData->OnButtonScenario(pEl) || (pSel && pSel == GetSelectedEntry()))
{
DoOK();
return;
}
// the first click selects it
SetFocus(pEl, false);
UpdateSelection();
}
void C4StartupScenSelDlg::DeselectAll()
{
// Deselect all so current folder info is displayed
if (GetFocus()) C4GUI::GUISound("ArrowHit");
SetFocus(nullptr, true);
if (pMapData) pMapData->ResetSelection();
UpdateSelection();
}
void C4StartupScenSelDlg::StartRenaming(C4GUI::RenameEdit *pNewRenameEdit)
{
pRenameEdit = pNewRenameEdit;
}
void C4StartupScenSelDlg::AbortRenaming()
{
if (pRenameEdit) pRenameEdit->Abort();
}
// NICHT: 9, 7.2.2, 113-114
|
b14ce85622c10884a48c052c5f67801fbb69ce62 | b9b3e707b93adce9a7e81aeb6787d10a7e85145b | /src/lib/xml_compiler/src/xml_compiler+filter_vector.cpp | 9e626c06386429292fa2ab1d9d92f1d0cd2eb25b | [] | no_license | smontsaroff/KeyRemap4MacBook | 886a9f88dd1770dd786c57903340b4ad9f468cf7 | ba1d9270f40a37991ca55a988a3c0d8825a594bb | refs/heads/master | 2020-11-30T13:37:02.488355 | 2012-04-10T04:47:04 | 2012-04-10T04:47:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,278 | cpp | xml_compiler+filter_vector.cpp | #include <boost/algorithm/string.hpp>
#include "bridge.h"
#include "pqrs/vector.hpp"
#include "pqrs/xml_compiler.hpp"
namespace pqrs {
xml_compiler::filter_vector::filter_vector(void)
{}
xml_compiler::filter_vector::filter_vector(const symbol_map& symbol_map, const boost::property_tree::ptree& pt)
{
for (auto& it : pt) {
/* */ if (it.first == "not") {
add(symbol_map, BRIDGE_FILTERTYPE_APPLICATION_NOT, "ApplicationType::", it.second.data());
} else if (it.first == "only") {
add(symbol_map, BRIDGE_FILTERTYPE_APPLICATION_ONLY, "ApplicationType::", it.second.data());
} else if (it.first == "device_not") {
add(symbol_map, BRIDGE_FILTERTYPE_DEVICE_NOT, "", it.second.data());
} else if (it.first == "device_only") {
add(symbol_map, BRIDGE_FILTERTYPE_DEVICE_ONLY, "", it.second.data());
} else if (it.first == "config_not") {
add(symbol_map, BRIDGE_FILTERTYPE_CONFIG_NOT, "ConfigIndex::", it.second.data());
} else if (it.first == "config_only") {
add(symbol_map, BRIDGE_FILTERTYPE_CONFIG_ONLY, "ConfigIndex::", it.second.data());
} else if (it.first == "modifier_not") {
add(symbol_map, BRIDGE_FILTERTYPE_MODIFIER_NOT, "", it.second.data());
} else if (it.first == "modifier_only") {
add(symbol_map, BRIDGE_FILTERTYPE_MODIFIER_ONLY, "", it.second.data());
} else if (it.first == "inputmode_not") {
add(symbol_map, BRIDGE_FILTERTYPE_INPUTMODE_NOT, "InputMode::", it.second.data());
} else if (it.first == "inputmode_only") {
add(symbol_map, BRIDGE_FILTERTYPE_INPUTMODE_ONLY, "InputMode::", it.second.data());
} else if (it.first == "inputmodedetail_not") {
add(symbol_map, BRIDGE_FILTERTYPE_INPUTMODEDETAIL_NOT, "InputModeDetail::", it.second.data());
} else if (it.first == "inputmodedetail_only") {
add(symbol_map, BRIDGE_FILTERTYPE_INPUTMODEDETAIL_ONLY, "InputModeDetail::", it.second.data());
}
}
}
std::vector<uint32_t>&
xml_compiler::filter_vector::get(void)
{
return data_;
}
const std::vector<uint32_t>&
xml_compiler::filter_vector::get(void) const
{
return data_;
}
bool
xml_compiler::filter_vector::empty(void) const
{
return data_.empty();
}
void
xml_compiler::filter_vector::add(const symbol_map& symbol_map,
uint32_t filter_type,
const std::string& prefix,
const std::string& string)
{
std::vector<std::string> values;
pqrs::string::split_by_comma(values, string);
data_.push_back(values.size() + 1); // +1 == filter_type
data_.push_back(filter_type);
for (auto& v : values) {
// support '|' for <modifier_only>.
// For example: <modifier_only>ModifierFlag::COMMAND_L|ModifierFlag::CONTROL_L, ModifierFlag::COMMAND_L|ModifierFlag::OPTION_L</modifier_only>
std::vector<std::string> items;
pqrs::string::split_by_pipe(items, v);
uint32_t filter_value = 0;
for (auto& i : items) {
std::string key = prefix + i;
normalize_identifier(key);
filter_value |= symbol_map.get(key);
}
data_.push_back(filter_value);
}
}
}
|
e625114cff274edc2268329824c040c7bfd8fae1 | 602fbf9679ac93a1d3c1fe46c122a7f23fa63291 | /codingninjas/format.cpp | db2aab18ab53e726aedf270e86a3c254473d7b9e | [] | no_license | shivansh2598/cp | 47e3446e4587f7ee82866516a2a7e47818abf2fb | 579caa111d1210296aa064eea49a35e088e5f60b | refs/heads/master | 2020-09-11T06:31:07.633835 | 2020-05-05T01:12:55 | 2020-05-05T01:12:55 | 221,972,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,093 | cpp | format.cpp | #include <bits/stdc++.h>
typedef long long int lli;
typedef unsigned long long int ulli;
typedef long double ld;
#define forn(i, n) for (lli i = 0; i < lli(n); ++i)
#define for1(i, n) for (lli i = 1; i <= lli(n); ++i)
#define fore(i, l, r) for (lli i = lli(l); i <= lli(r); ++i)
#define ford(i, n) for (lli i = lli(n) - 1; i >= 0; --i)
#define pb push_back
#define vectvalue lli x;cin >> x;vect.pb(x)
using namespace std;
void vprint(vector<int>&v)
{ for(int i=0;i<v.size();i++)cout<<v[i]<<' ';cout<<endl;}
void aprint(int *arr,int n)
{ for(int i=0;i<n;i++)cout<<arr[i]<<' ';cout<<endl;}
bool comp(pair<int,int>a,pair<int,int>b){
if(b.second==a.second)
return a.first<b.first;
return a.second<b.second;
}
int main(){
lli n;
cin>>n;
vector<pair<int,int>>vect;
forn(i,n){
pair<int,int>p;
cin>>p.first>>p.second;
vect.pb(p);
}
sort(vect.begin(),vect.end(),comp);
int count=0;
int end=-1;
forn(i,n){
if(vect[i].first>end)
{
count++;
end=vect[i].second;
}
}
cout<<count<<endl;
} |
50fe8506a28d0a54c08229bc8557d694d9b9bf25 | 7ccccd69629354409566ba01d93572a4da0ba364 | /Desarrollo/BulletTest/BulletTest/Animation/Salto.cpp | 2c5b45d1544a69afade7da855becb995068d21bd | [] | no_license | Juliyo/LastBullet | eac779d78f0e8d62eb71ac4ecaa838e828825736 | 4f93b5260eaba275aa47c3ed13a93e7d7e60c0e9 | refs/heads/master | 2021-09-11T12:27:29.583652 | 2018-01-18T14:14:52 | 2018-01-18T14:14:52 | 104,806,970 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,780 | cpp | Salto.cpp | #include "Salto.h"
#include <Death.h>
#include <Run.h>
#include <Character.h>
#include <Idle.h>
#include <Weapons/Weapon.h>
#include <AnimationMachine.h>
void Salto::Enter(Character * pEnemy)
{
//Seteamos la animacion segun el arma actual
setCurrentAnimationByWeapon(pEnemy);
pEnemy->getAnimationMachine()->currWeapon = (Type::eWeapon)pEnemy->getCurrentWeaponType();
pEnemy->getNode()->setFrameTime(milliseconds(27));
}
void Salto::Exit(Character * pEnemy)
{
}
void Salto::Execute(Character * pCharacter)
{
//Muero y pongo animacion de muerte
if (pCharacter->getLifeComponent()->isDying()) {
pCharacter->getAnimationMachine()->ChangeState(&Death::i());
return;
}
//Compruebo si salto
if (pCharacter->isOnGround()) {
pCharacter->getAnimationMachine()->ChangeState(&Run::i());
return;
}
//Si por alguna razon cambio de arma cambiamos de animacion al vuelo
if (pCharacter->getCurrentWeaponType() != pCharacter->getAnimationMachine()->currWeapon) {
//Continuamos la animacion por donde iba
int currentFrame = pCharacter->getNode()->getCurrentFrame();
setCurrentAnimationByWeapon(pCharacter);
pCharacter->getNode()->setCurrentFrame(currentFrame);
}
}
void Salto::setCurrentAnimationByWeapon(Character * pEnemy)
{
if (pEnemy->getCurrentWeaponType() == Type::eWeapon::Asalto) {
pEnemy->getNode()->setCurrentAnimation("saltoAsalto");
}
else if (pEnemy->getCurrentWeaponType() == Type::eWeapon::Rocket) {
pEnemy->getNode()->setCurrentAnimation("saltoRocket");
}
else if (pEnemy->getCurrentWeaponType() == Type::eWeapon::Pistola) {
pEnemy->getNode()->setCurrentAnimation("saltoAsalto");
}
else if (pEnemy->getCurrentWeaponType() == Type::eWeapon::Sniper) {
pEnemy->getNode()->setCurrentAnimation("saltoAsalto");
}
}
Salto::~Salto()
{
}
|
9c8b494569f4d888ebcc7fefeced4fe0eba85655 | 4acd8607d2a9761ec8895a4e59f1bccc77ae9ccd | /shark/example/env/cpp/2048.h | 87a8c1d6c4549c7ae3120a520717b1bbfe08c147 | [
"MIT"
] | permissive | 7starsea/shark | 64859267a777565eff7677f3a4467cf14c945b3a | 5030f576da6f5998728d80170480e68a3debfe79 | refs/heads/master | 2022-04-21T00:32:46.869884 | 2020-04-17T02:53:03 | 2020-04-17T02:53:03 | 254,661,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,122 | h | 2048.h | #ifndef SHARE_EXAMPLE_ENV_2048_H
#define SHARE_EXAMPLE_ENV_2048_H
#include <vector>
#include "inc/cnarray.hpp"
#include "crandom.h"
typedef cndarray<int, 2> int_2darray;
typedef cndarray<uint8_t, 2> uint8_2darray;
typedef cndarray<uint8_t, 3> uint8_3darray;
/// the game 2048 implementation algorithm is copied from https://github.com/nneonneo/2048-ai
namespace Game2048N{
typedef uint64_t board_t;
typedef uint16_t row_t;
static const board_t ROW_MASK = 0xFFFFULL;
static const board_t COL_MASK = 0x000F000F000F000FULL;
void to_m_board(board_t board, uint8_2darray & arr);
void to_m_board(board_t board, uint8_3darray & arr);
board_t to_c_board(const uint8_2darray & arr);
// Transpose rows/columns in a board:
// 0123 048c
// 4567 --> 159d
// 89ab 26ae
// cdef 37bf
board_t transpose(board_t x);
static inline board_t unpack_col(row_t row) {
board_t tmp = row;
return (tmp | (tmp << 12ULL) | (tmp << 24ULL) | (tmp << 36ULL)) & COL_MASK;
}
static inline row_t reverse_row(row_t row) {
return (row >> 12) | ((row >> 4) & 0x00F0) | ((row << 4) & 0x0F00) | (row << 12);
}
class Game2048{
public:
Game2048();
void seed(int seed_id){ rand_.seed(seed_id); rand24_.seed(seed_id + 1000);}
void reset();
float step(int action);
std::vector<int> legal_actions()const;
float score()const{return score_; }
int max_value()const{ return 1 << get_max_rank(board_); }
static int get_max_rank(board_t board);
static int count_distinct_tiles(board_t board);
// Count the number of empty positions (= zero nibbles) in a board.
// Precondition: the board cannot be fully empty.
static int count_empty(board_t x);
board_t insert_tile_rand(board_t board, board_t tile);
protected:
board_t board_;
float score_;
CRandom rand_;
CRandom rand24_;
protected:
board_t draw_tile(){return rand24_.sample() < 90 ? 1 : 2; }
protected:
static board_t execute_move(int move, board_t board);
static board_t execute_move_0(board_t);
static board_t execute_move_1(board_t);
static board_t execute_move_2(board_t);
static board_t execute_move_3(board_t);
};
}
#endif
|
1e705fcc5e138d86425b16f247a18630678ac3b3 | d6b4bdf418ae6ab89b721a79f198de812311c783 | /mariadb/include/tencentcloud/mariadb/v20170312/model/CreateHourDBInstanceRequest.h | 41d8bbb5adfdd0a795fd89f6c5b90d612563ed59 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp-intl-en | d0781d461e84eb81775c2145bacae13084561c15 | d403a6b1cf3456322bbdfb462b63e77b1e71f3dc | refs/heads/master | 2023-08-21T12:29:54.125071 | 2023-08-21T01:12:39 | 2023-08-21T01:12:39 | 277,769,407 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,091 | h | CreateHourDBInstanceRequest.h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_MARIADB_V20170312_MODEL_CREATEHOURDBINSTANCEREQUEST_H_
#define TENCENTCLOUD_MARIADB_V20170312_MODEL_CREATEHOURDBINSTANCEREQUEST_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/mariadb/v20170312/model/ResourceTag.h>
#include <tencentcloud/mariadb/v20170312/model/DBParamValue.h>
namespace TencentCloud
{
namespace Mariadb
{
namespace V20170312
{
namespace Model
{
/**
* CreateHourDBInstance request structure.
*/
class CreateHourDBInstanceRequest : public AbstractModel
{
public:
CreateHourDBInstanceRequest();
~CreateHourDBInstanceRequest() = default;
std::string ToJsonString() const;
/**
* 获取AZs to deploy instance nodes. You can specify up to two AZs.
* @return Zones AZs to deploy instance nodes. You can specify up to two AZs.
*
*/
std::vector<std::string> GetZones() const;
/**
* 设置AZs to deploy instance nodes. You can specify up to two AZs.
* @param _zones AZs to deploy instance nodes. You can specify up to two AZs.
*
*/
void SetZones(const std::vector<std::string>& _zones);
/**
* 判断参数 Zones 是否已赋值
* @return Zones 是否已赋值
*
*/
bool ZonesHasBeenSet() const;
/**
* 获取Number of nodes.
* @return NodeCount Number of nodes.
*
*/
int64_t GetNodeCount() const;
/**
* 设置Number of nodes.
* @param _nodeCount Number of nodes.
*
*/
void SetNodeCount(const int64_t& _nodeCount);
/**
* 判断参数 NodeCount 是否已赋值
* @return NodeCount 是否已赋值
*
*/
bool NodeCountHasBeenSet() const;
/**
* 获取Memory size in GB.
* @return Memory Memory size in GB.
*
*/
int64_t GetMemory() const;
/**
* 设置Memory size in GB.
* @param _memory Memory size in GB.
*
*/
void SetMemory(const int64_t& _memory);
/**
* 判断参数 Memory 是否已赋值
* @return Memory 是否已赋值
*
*/
bool MemoryHasBeenSet() const;
/**
* 获取Storage size in GB.
* @return Storage Storage size in GB.
*
*/
int64_t GetStorage() const;
/**
* 设置Storage size in GB.
* @param _storage Storage size in GB.
*
*/
void SetStorage(const int64_t& _storage);
/**
* 判断参数 Storage 是否已赋值
* @return Storage 是否已赋值
*
*/
bool StorageHasBeenSet() const;
/**
* 获取Number of instances to purchase.
* @return Count Number of instances to purchase.
*
*/
int64_t GetCount() const;
/**
* 设置Number of instances to purchase.
* @param _count Number of instances to purchase.
*
*/
void SetCount(const int64_t& _count);
/**
* 判断参数 Count 是否已赋值
* @return Count 是否已赋值
*
*/
bool CountHasBeenSet() const;
/**
* 获取Project ID. If this parameter is not passed in, the default project will be used.
* @return ProjectId Project ID. If this parameter is not passed in, the default project will be used.
*
*/
int64_t GetProjectId() const;
/**
* 设置Project ID. If this parameter is not passed in, the default project will be used.
* @param _projectId Project ID. If this parameter is not passed in, the default project will be used.
*
*/
void SetProjectId(const int64_t& _projectId);
/**
* 判断参数 ProjectId 是否已赋值
* @return ProjectId 是否已赋值
*
*/
bool ProjectIdHasBeenSet() const;
/**
* 获取Unique ID of the network. If this parameter is not passed in, the classic network will be used.
* @return VpcId Unique ID of the network. If this parameter is not passed in, the classic network will be used.
*
*/
std::string GetVpcId() const;
/**
* 设置Unique ID of the network. If this parameter is not passed in, the classic network will be used.
* @param _vpcId Unique ID of the network. If this parameter is not passed in, the classic network will be used.
*
*/
void SetVpcId(const std::string& _vpcId);
/**
* 判断参数 VpcId 是否已赋值
* @return VpcId 是否已赋值
*
*/
bool VpcIdHasBeenSet() const;
/**
* 获取Unique ID of the subnet. If `VpcId` is specified, this parameter is required.
* @return SubnetId Unique ID of the subnet. If `VpcId` is specified, this parameter is required.
*
*/
std::string GetSubnetId() const;
/**
* 设置Unique ID of the subnet. If `VpcId` is specified, this parameter is required.
* @param _subnetId Unique ID of the subnet. If `VpcId` is specified, this parameter is required.
*
*/
void SetSubnetId(const std::string& _subnetId);
/**
* 判断参数 SubnetId 是否已赋值
* @return SubnetId 是否已赋值
*
*/
bool SubnetIdHasBeenSet() const;
/**
* 获取Database engine version. Valid values: `5.7`, `8.0`, `10.0`, `10.1`.
* @return DbVersionId Database engine version. Valid values: `5.7`, `8.0`, `10.0`, `10.1`.
*
*/
std::string GetDbVersionId() const;
/**
* 设置Database engine version. Valid values: `5.7`, `8.0`, `10.0`, `10.1`.
* @param _dbVersionId Database engine version. Valid values: `5.7`, `8.0`, `10.0`, `10.1`.
*
*/
void SetDbVersionId(const std::string& _dbVersionId);
/**
* 判断参数 DbVersionId 是否已赋值
* @return DbVersionId 是否已赋值
*
*/
bool DbVersionIdHasBeenSet() const;
/**
* 获取Custom name of the instance.
* @return InstanceName Custom name of the instance.
*
*/
std::string GetInstanceName() const;
/**
* 设置Custom name of the instance.
* @param _instanceName Custom name of the instance.
*
*/
void SetInstanceName(const std::string& _instanceName);
/**
* 判断参数 InstanceName 是否已赋值
* @return InstanceName 是否已赋值
*
*/
bool InstanceNameHasBeenSet() const;
/**
* 获取Security group ID. If this parameter is not passed in, no security groups will be associated when the instance is created.
* @return SecurityGroupIds Security group ID. If this parameter is not passed in, no security groups will be associated when the instance is created.
*
*/
std::vector<std::string> GetSecurityGroupIds() const;
/**
* 设置Security group ID. If this parameter is not passed in, no security groups will be associated when the instance is created.
* @param _securityGroupIds Security group ID. If this parameter is not passed in, no security groups will be associated when the instance is created.
*
*/
void SetSecurityGroupIds(const std::vector<std::string>& _securityGroupIds);
/**
* 判断参数 SecurityGroupIds 是否已赋值
* @return SecurityGroupIds 是否已赋值
*
*/
bool SecurityGroupIdsHasBeenSet() const;
/**
* 获取Whether IPv6 is supported. Valid values: `0` (unsupported), `1` (supported).
* @return Ipv6Flag Whether IPv6 is supported. Valid values: `0` (unsupported), `1` (supported).
*
*/
int64_t GetIpv6Flag() const;
/**
* 设置Whether IPv6 is supported. Valid values: `0` (unsupported), `1` (supported).
* @param _ipv6Flag Whether IPv6 is supported. Valid values: `0` (unsupported), `1` (supported).
*
*/
void SetIpv6Flag(const int64_t& _ipv6Flag);
/**
* 判断参数 Ipv6Flag 是否已赋值
* @return Ipv6Flag 是否已赋值
*
*/
bool Ipv6FlagHasBeenSet() const;
/**
* 获取Array of tag key-value pairs.
* @return ResourceTags Array of tag key-value pairs.
*
*/
std::vector<ResourceTag> GetResourceTags() const;
/**
* 设置Array of tag key-value pairs.
* @param _resourceTags Array of tag key-value pairs.
*
*/
void SetResourceTags(const std::vector<ResourceTag>& _resourceTags);
/**
* 判断参数 ResourceTags 是否已赋值
* @return ResourceTags 是否已赋值
*
*/
bool ResourceTagsHasBeenSet() const;
/**
* 获取If you create a disaster recovery instance, you need to use this parameter to specify the region of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
* @return DcnRegion If you create a disaster recovery instance, you need to use this parameter to specify the region of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*
*/
std::string GetDcnRegion() const;
/**
* 设置If you create a disaster recovery instance, you need to use this parameter to specify the region of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
* @param _dcnRegion If you create a disaster recovery instance, you need to use this parameter to specify the region of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*
*/
void SetDcnRegion(const std::string& _dcnRegion);
/**
* 判断参数 DcnRegion 是否已赋值
* @return DcnRegion 是否已赋值
*
*/
bool DcnRegionHasBeenSet() const;
/**
* 获取If you create a disaster recovery instance, you need to use this parameter to specify the ID of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
* @return DcnInstanceId If you create a disaster recovery instance, you need to use this parameter to specify the ID of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*
*/
std::string GetDcnInstanceId() const;
/**
* 设置If you create a disaster recovery instance, you need to use this parameter to specify the ID of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
* @param _dcnInstanceId If you create a disaster recovery instance, you need to use this parameter to specify the ID of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*
*/
void SetDcnInstanceId(const std::string& _dcnInstanceId);
/**
* 判断参数 DcnInstanceId 是否已赋值
* @return DcnInstanceId 是否已赋值
*
*/
bool DcnInstanceIdHasBeenSet() const;
/**
* 获取List of parameters. Valid values:
`character_set_server` (character set; required); `lower_case_table_names` (table name case sensitivity; required; 0: case-sensitive; 1: case-insensitive);
`innodb_page_size` (innoDB data page size; default size: 16 KB); `sync_mode` (sync mode; 0: async; 1: strong sync; 2: downgradable strong sync; default value: 2).
* @return InitParams List of parameters. Valid values:
`character_set_server` (character set; required); `lower_case_table_names` (table name case sensitivity; required; 0: case-sensitive; 1: case-insensitive);
`innodb_page_size` (innoDB data page size; default size: 16 KB); `sync_mode` (sync mode; 0: async; 1: strong sync; 2: downgradable strong sync; default value: 2).
*
*/
std::vector<DBParamValue> GetInitParams() const;
/**
* 设置List of parameters. Valid values:
`character_set_server` (character set; required); `lower_case_table_names` (table name case sensitivity; required; 0: case-sensitive; 1: case-insensitive);
`innodb_page_size` (innoDB data page size; default size: 16 KB); `sync_mode` (sync mode; 0: async; 1: strong sync; 2: downgradable strong sync; default value: 2).
* @param _initParams List of parameters. Valid values:
`character_set_server` (character set; required); `lower_case_table_names` (table name case sensitivity; required; 0: case-sensitive; 1: case-insensitive);
`innodb_page_size` (innoDB data page size; default size: 16 KB); `sync_mode` (sync mode; 0: async; 1: strong sync; 2: downgradable strong sync; default value: 2).
*
*/
void SetInitParams(const std::vector<DBParamValue>& _initParams);
/**
* 判断参数 InitParams 是否已赋值
* @return InitParams 是否已赋值
*
*/
bool InitParamsHasBeenSet() const;
/**
* 获取ID of the instance to be rolled back, such as “2021-11-22 00:00:00”.
* @return RollbackInstanceId ID of the instance to be rolled back, such as “2021-11-22 00:00:00”.
*
*/
std::string GetRollbackInstanceId() const;
/**
* 设置ID of the instance to be rolled back, such as “2021-11-22 00:00:00”.
* @param _rollbackInstanceId ID of the instance to be rolled back, such as “2021-11-22 00:00:00”.
*
*/
void SetRollbackInstanceId(const std::string& _rollbackInstanceId);
/**
* 判断参数 RollbackInstanceId 是否已赋值
* @return RollbackInstanceId 是否已赋值
*
*/
bool RollbackInstanceIdHasBeenSet() const;
/**
* 获取Rollback time.
* @return RollbackTime Rollback time.
*
*/
std::string GetRollbackTime() const;
/**
* 设置Rollback time.
* @param _rollbackTime Rollback time.
*
*/
void SetRollbackTime(const std::string& _rollbackTime);
/**
* 判断参数 RollbackTime 是否已赋值
* @return RollbackTime 是否已赋值
*
*/
bool RollbackTimeHasBeenSet() const;
private:
/**
* AZs to deploy instance nodes. You can specify up to two AZs.
*/
std::vector<std::string> m_zones;
bool m_zonesHasBeenSet;
/**
* Number of nodes.
*/
int64_t m_nodeCount;
bool m_nodeCountHasBeenSet;
/**
* Memory size in GB.
*/
int64_t m_memory;
bool m_memoryHasBeenSet;
/**
* Storage size in GB.
*/
int64_t m_storage;
bool m_storageHasBeenSet;
/**
* Number of instances to purchase.
*/
int64_t m_count;
bool m_countHasBeenSet;
/**
* Project ID. If this parameter is not passed in, the default project will be used.
*/
int64_t m_projectId;
bool m_projectIdHasBeenSet;
/**
* Unique ID of the network. If this parameter is not passed in, the classic network will be used.
*/
std::string m_vpcId;
bool m_vpcIdHasBeenSet;
/**
* Unique ID of the subnet. If `VpcId` is specified, this parameter is required.
*/
std::string m_subnetId;
bool m_subnetIdHasBeenSet;
/**
* Database engine version. Valid values: `5.7`, `8.0`, `10.0`, `10.1`.
*/
std::string m_dbVersionId;
bool m_dbVersionIdHasBeenSet;
/**
* Custom name of the instance.
*/
std::string m_instanceName;
bool m_instanceNameHasBeenSet;
/**
* Security group ID. If this parameter is not passed in, no security groups will be associated when the instance is created.
*/
std::vector<std::string> m_securityGroupIds;
bool m_securityGroupIdsHasBeenSet;
/**
* Whether IPv6 is supported. Valid values: `0` (unsupported), `1` (supported).
*/
int64_t m_ipv6Flag;
bool m_ipv6FlagHasBeenSet;
/**
* Array of tag key-value pairs.
*/
std::vector<ResourceTag> m_resourceTags;
bool m_resourceTagsHasBeenSet;
/**
* If you create a disaster recovery instance, you need to use this parameter to specify the region of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*/
std::string m_dcnRegion;
bool m_dcnRegionHasBeenSet;
/**
* If you create a disaster recovery instance, you need to use this parameter to specify the ID of the associated primary instance so that the disaster recovery instance can sync data with the primary instance over the Data Communication Network (DCN).
*/
std::string m_dcnInstanceId;
bool m_dcnInstanceIdHasBeenSet;
/**
* List of parameters. Valid values:
`character_set_server` (character set; required); `lower_case_table_names` (table name case sensitivity; required; 0: case-sensitive; 1: case-insensitive);
`innodb_page_size` (innoDB data page size; default size: 16 KB); `sync_mode` (sync mode; 0: async; 1: strong sync; 2: downgradable strong sync; default value: 2).
*/
std::vector<DBParamValue> m_initParams;
bool m_initParamsHasBeenSet;
/**
* ID of the instance to be rolled back, such as “2021-11-22 00:00:00”.
*/
std::string m_rollbackInstanceId;
bool m_rollbackInstanceIdHasBeenSet;
/**
* Rollback time.
*/
std::string m_rollbackTime;
bool m_rollbackTimeHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_MARIADB_V20170312_MODEL_CREATEHOURDBINSTANCEREQUEST_H_
|
07f5a65309e41499197f897ebdf0a60e2f68d52a | 09a74d737490b78f51533e51e370a55e38692cbd | /Examples/Ubuntu/NewBlashPlayer/XGUI/Window.cpp | ff6ab4a7ae769eec65650cdb8b02c6ba4d1f8592 | [
"MIT"
] | permissive | zuohouwei/NewBlashPlayer | 90b57076c9c0b142e338910a6b8d69e376ecf4c8 | af2104ff143ea885ff7a6808aa12b65c12203c1f | refs/heads/master | 2020-04-07T02:01:16.622611 | 2018-11-05T14:59:49 | 2018-11-05T14:59:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,681 | cpp | Window.cpp | #include "Widget.hpp"
#include "Window.hpp"
#include "XApp.hpp"
namespace Xgui
{
Window::Window(Widget *parent, const String &title, int x, int y, size_t w, size_t h, Flags flags)
: Widget(parent, x, y, w, h, flags)
{
_init(title);
}
Window::Window(Widget *parent, const String &title, const Point &pos, const Size &size, Flags flags)
: Widget(parent, pos, size)
{
_init(title);
}
Window::Window(Widget *parent, const String &title, const Rect &rect, Flags flags)
: Widget(parent, rect)
{
_init(title);
}
void Window::_init(const String &title)
{
mTitle = title;
//create the video
create();
char green[] ="#FF00FF";
XColor color;
Colormap colormap = DefaultColormap(xUIGetApp()->getDisplay(), 0);
XParseColor(xUIGetApp()->getDisplay(), colormap, green, &color);
XAllocColor(xUIGetApp()->getDisplay(), colormap, &color);
XSetWindowBackground(xUIGetApp()->getDisplay(), _X11Window, color.pixel);
// XSetForeground(Xgui::display, _X11GC, color.pixel);
// XSetBackground(Xgui::display, _X11GC, color.pixel);
}
bool Window::create() {
Widget::create();
if (!xUIGetApp()->getTopLevelWindow()) {
xUIGetApp()->setTopLevelWindow(this);
}
XSelectInput(xUIGetApp()->getDisplay(), _X11Window, ExposureMask|ButtonPressMask|ButtonReleaseMask|
StructureNotifyMask|KeyPressMask|KeyReleaseMask|KeymapStateMask);
XStoreName(xUIGetApp()->getDisplay(), _X11Window, mTitle.c_str());
}
} |
58ccbffb9f5d21a2a4cc097a1810ca627b5705c0 | 1d1f7340cbe8266f7426ca600381a6c759ec9c6e | /arduino/hardware/arduino/bootloaders/diskloader/src/USBDesc.cpp | ade072a522e3dfc5e9ebe389aded77c6b962d3d1 | [] | no_license | Android410/my-codeblock-arduino-addons | f951cce5e167a5c0f7076697366deca5c00005e0 | 661f9fcab82c7c22f918963c12ef5defe6999abd | refs/heads/master | 2021-01-22T06:44:17.249431 | 2013-02-17T13:19:41 | 2013-02-17T13:19:41 | 7,993,054 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,140 | cpp | USBDesc.cpp |
/* Copyright (c) 2011, Peter Barrett
**
** Permission to use, copy, modify, and/or distribute this software for
** any purpose with or without fee is hereby granted, provided that the
** above copyright notice and this permission notice appear in all copies.
**
** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
** SOFTWARE.
*/
#include "Platform.h"
//====================================================================================================
//====================================================================================================
// Actual device descriptors
const u16 STRING_LANGUAGE[2] = {
(3<<8) | (2+2),
0x0409 // English
};
const u16 STRING_SERIAL[13] = {
(3<<8) | (2+2*12),
USB_SERIAL_STRING
};
const u16 STRING_IPRODUCT[28] = {
(3<<8) | (2+2*27),
#if USB_PID == USB_PID_LEONARDO
'A','r','d','u','i','n','o',' ','L','e','o','n','a','r','d','o',' ','b','o','o','t','l','o','a','d','e','r'
#elif USB_PID == USB_PID_MICRO
'A','r','d','u','i','n','o',' ','M','i','c','r','o',' ','b','o','o','t','l','o','a','d','e','r',' ',' ',' '
#endif
};
const u16 STRING_IMANUFACTURER[12] = {
(3<<8) | (2+2*11),
'A','r','d','u','i','n','o',' ','L','L','C'
};
//#ifdef CDC_ENABLED
DeviceDescriptor USB_DeviceDescriptorA = D_DEVICE(0X02,0X00,0X00,64,USB_VID,USB_PID,0x100,0,IPRODUCT,ISERIAL,1);
//#else
DeviceDescriptor USB_DeviceDescriptor = D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,0,IPRODUCT,ISERIAL,1);
//#endif
Config USB_ConfigDescriptor =
{
D_CONFIG(sizeof(Config),INTERFACE_COUNT),
#ifdef CDC_ENABLED
// CDC
{
D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1),
// CDC communication interface
D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd)
D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management
D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,2), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0
D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40),
// CDC data interface
D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0),
D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0)
},
#endif
// HID
{
D_INTERFACE(HID_INTERFACE,1,3,0,0),
D_HIDREPORT(30),
D_ENDPOINT(USB_ENDPOINT_IN (HID_ENDPOINT_INT),USB_ENDPOINT_TYPE_INTERRUPT,0x40,0x40)
}
};
|
4b1bea20507069ec06fe2e29036a43e933361b04 | 061ba3bcef6ea114720b62ca521239dc25534212 | /Game/Widget.h | 8557f190b1a59dbc229c409a22e6402c778bf3d5 | [] | no_license | TobyTicehurst/SFML-Game | a4998ed8733ffcf311c88b13362110578eafcab8 | 3970e091311d5c3eb1c33142b77371651dfb8c8f | refs/heads/master | 2020-03-23T20:42:56.465215 | 2018-07-23T20:47:49 | 2018-07-23T20:47:49 | 142,057,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 703 | h | Widget.h | #pragma once
#include "SFML\Graphics.hpp"
#include "GUIEntity.h"
#include "Renderer.h"
namespace GUI {
// Base class for GUI elements
class Widget {
public:
// constructor
Widget(sf::Vector2f& pos, Renderable& renderable);
virtual void input(const sf::Event& e, const sf::Vector2f mouseWorldPosition) = 0;
virtual void draw(Renderer& renderer) const = 0;
// true if cursor is inside the widget
bool mouseOver(const sf::Vector2f& mousePosition) const;
// true if mouseOver is true and left mouse button was pressed
bool clicked(const sf::Vector2f& mousePosition, const sf::Event& e) const;
protected:
// entity contains position and texture via a renderable
GUIEntity m_entity;
};
} |
c81702ae2fa2a7d6c96437d53b67877673d155f1 | 8f10297e94acd909df00d7a972d7ad22da3ddf4d | /SPACESKATE/src/h/number.h | 4ac3572808eaed7a55f0ee7cc239f975258c7a99 | [] | no_license | KanYuhei/SPACESKATE | d37bc6869353c9b6dc2e93d608314e094401b246 | eba05bb8a8256a23a99c888d9886900e2416147b | refs/heads/master | 2021-05-11T11:23:34.346436 | 2018-02-19T07:25:07 | 2018-02-19T07:25:07 | 117,636,922 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,727 | h | number.h | //*************************************************************************************************
// 数値処理 (number.h)
// Author : YUHEI KAN
//*************************************************************************************************
#ifndef _NUMBER_H_
#define _NUMBER_H_
//*************************************************************************************************
// インクルードファイル
//*************************************************************************************************
#include "main.h"
//*************************************************************************************************
// マクロ定義
//*************************************************************************************************
//*************************************************************************************************
// 構造体
//*************************************************************************************************
//*************************************************************************************************
// クラス
//*************************************************************************************************
//数値クラス
class CNumber
{
public:
CNumber(); //コンストラクタ
~CNumber(); //デコンストラクタ
HRESULT Init(void); //初期化処理
void Uninit(void); //終了処理
void Update(void); //更新処理
void Draw(void); //描画処理
static CNumber *Create( D3DXVECTOR3 Pos,
D3DXVECTOR3 Size); //自身を生成
static HRESULT Load(void); //テクスチャのロード
static void Unload(void); //テクスチャのアンロード
void SetNumber(int nNumber); //数値の設定
private:
static LPDIRECT3DTEXTURE9 m_pTexture; //テクスチャへのポインタ
LPDIRECT3DVERTEXBUFFER9 m_pVtxBuff; //頂点バッファへのポインタ
D3DXVECTOR3 m_pos; //座標
D3DXVECTOR3 m_size; //サイズ
D3DXVECTOR2 m_Tex; //テクスチャ座標
D3DXVECTOR2 m_TexSize; //テクスチャサイズ
};
//*************************************************************************************************
// プロトタイプ宣言
//*************************************************************************************************
#endif //_NUMBER_H_ |
b32fe8c50af17467bf94ced9a0aeffca60467ca2 | 820e2bcb91474d6d679f37ac4a1894fb7bc389ec | /tests/unit_tests/components/bar.cpp | f00a3d50cd355f05969fe90ce420679f712c64e1 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | aokellermann/polybar | 7835c81363372f303b12c9cb5cd01f392741e491 | e205f05c3750777fecc406d2d4931c507e25ac5f | refs/heads/master | 2022-06-06T18:37:19.870798 | 2020-05-06T23:40:15 | 2020-05-06T23:40:15 | 260,815,155 | 1 | 0 | MIT | 2020-05-03T02:38:28 | 2020-05-03T02:38:28 | null | UTF-8 | C++ | false | false | 1,210 | cpp | bar.cpp | #include "common/test.hpp"
#include "components/bar.hpp"
using namespace polybar;
/**
* \brief Class for parameterized tests on geom_format_to_pixels
*
* The first element in the tuple is the expected return value, the second
* value is the format string. The max value is always 1000
*/
class GeomFormatToPixelsTest :
public ::testing::Test,
public ::testing::WithParamInterface<pair<double, string>> {};
vector<pair<double, string>> to_pixels_no_offset_list = {
{1000, "100%"},
{0, "0%"},
{1000, "150%"},
{100, "10%"},
{0, "0"},
{1234, "1234"},
{1.234, "1.234"},
};
vector<pair<double, string>> to_pixels_with_offset_list = {
{1000, "100%:-0"},
{1000, "100%:+0"},
{1010, "100%:+10"},
{990, "100%:-10"},
{10, "0%:+10"},
{1000, "99%:+10"},
{0, "1%:-100"},
};
INSTANTIATE_TEST_SUITE_P(NoOffset, GeomFormatToPixelsTest,
::testing::ValuesIn(to_pixels_no_offset_list));
INSTANTIATE_TEST_SUITE_P(WithOffset, GeomFormatToPixelsTest,
::testing::ValuesIn(to_pixels_with_offset_list));
TEST_P(GeomFormatToPixelsTest, correctness) {
double exp = GetParam().first;
std::string str = GetParam().second;
EXPECT_DOUBLE_EQ(exp, geom_format_to_pixels(str, 1000));
}
|
043cf92b578c701000011d9776b83ce2222e4f59 | 8bd29781d66e4d5f47fb68696aa0d7f0d17dff2f | /ps/ps.cpp | da781895912e4560f4f11963e43ced6a09182b37 | [] | no_license | pawanaichra/Basic-image-processing-using-opencv | 342ae50942385fe2902144d20b15f6df0805168d | 12dab4f61e4e644fe54d1b2d20816874f0f6038f | refs/heads/master | 2020-06-14T03:34:08.205614 | 2016-12-08T06:29:29 | 2016-12-08T06:29:29 | 75,521,783 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,033 | cpp | ps.cpp | #include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
#include<stdio.h>
int i, j;
using namespace cv;
using namespace std;
bool R1(int R, int G, int B ){
bool e1 = (R>95) && (G>40) && (B>20) && ((max(R, max(G, B)) - min(R, min(G, B)))>15) && (abs(R - G)>15) && (R>G) && (R>B);
bool e2 = (R>220) && (G>210) && (B>170) && (abs(R - G) <= 15) && (R>B) && (G>B);
return (e1 || e2);
}
bool R2(float Y, float Cr, float Cb) {
bool e3 = Cr <= 1.5862*Cb + 20;
bool e4 = Cr >= 0.3448*Cb + 76.2069;
bool e5 = Cr >= -4.5652*Cb + 234.5652;
bool e6 = Cr <= -1.15*Cb + 301.75;
bool e7 = Cr <= -2.2857*Cb + 432.85;
return e3 && e4 && e5 && e6 && e7;
}
bool R3(float H, float S, float V) {
return (H<25) || (H > 230);
}
Mat GetSkin(Mat const &src) {
// allocate the result matrix
Mat dst = src.clone();
Vec3b cwhite = Vec3b::all(255);
Vec3b cblack = Vec3b::all(0);
Mat src_ycrcb, src_hsv;
cvtColor(src, src_ycrcb, CV_BGR2YCrCb);
src.convertTo(src_hsv, CV_32FC3);
cvtColor(src_hsv, src_hsv, CV_BGR2HSV);
normalize(src_hsv, src_hsv, 0.0, 255.0, NORM_MINMAX, CV_32FC3);
for (int i = 0; i < src.rows; i++) {
for (int j = 0; j < src.cols; j++) {
Vec3b pix_bgr = src.ptr<Vec3b>(i)[j];
int B = pix_bgr.val[0];
int G = pix_bgr.val[1];
int R = pix_bgr.val[2];
// apply rgb rule
bool a = R1(R, G, B);
Vec3b pix_ycrcb = src_ycrcb.ptr<Vec3b>(i)[j];
int Y = pix_ycrcb.val[0];
int Cr = pix_ycrcb.val[1];
int Cb = pix_ycrcb.val[2];
// apply ycrcb rule
bool b = R2(Y, Cr, Cb);
Vec3f pix_hsv = src_hsv.ptr<Vec3f>(i)[j];
float H = pix_hsv.val[0];
float S = pix_hsv.val[1];
float V = pix_hsv.val[2];
// apply hsv rule
bool c = R3(H, S, V);
if (!(a&&b&&c))
dst.ptr<Vec3b>(i)[j] = cblack;
}
}
return dst;
}
int main(int argc, const char *argv[]) {
Mat image;
VideoCapture cap("ps.mp4");
int a = 0, b = 0, c = 1, d = 0, e = 0, f = 0, g = 0, h = 0, counter = 0, kp = 0, z = 0;
while (1)
{
z++;
if (z % 10 != 0)
continue;
cap >> image;
Mat skin = GetSkin(image);
GaussianBlur(skin, skin, Size(7, 7), 1.5, 1.5);
Mat Gray;
cvtColor(skin, Gray, CV_BGR2GRAY);
for (i = 0; i<Gray.rows; i++)
{
for (j = 0; j<Gray.cols; j++)
{
if (Gray.at<uchar>(i, j)>80)
Gray.at<uchar>(i, j) = 255;
else
Gray.at<uchar>(i, j) = 0;
}
}
// Show the results:
namedWindow("original", WINDOW_AUTOSIZE);
//namedWindow("skin", 1);
namedWindow("Gray", WINDOW_AUTOSIZE);
imshow("original", image);
//imshow("skin", skin);
imshow("Gray", Gray);
c = 1;
a = 0;
b = 0;
for (i = 200; i < Gray.rows - 200; i++)
{
for (j = 200; j < Gray.cols - 200; j++)
{
if (Gray.at<uchar>(i, j) == 255)
{
a += i;
b += j;
c++;//kp++;
//counter=1;
}
}
}
a = a / c;
b = b / c;
if (b == 0 && g>0 && h>0 && a == 0)
{
f++;
}
h = a; g = b;
cout << "Count = " << f << "\n ";
if (waitKey(20) >= 0)
break;
}
}
|
201d47883adb7925767934a03c3b76deaa20fd15 | 7461bdef94212ae9326bc4ab923d59950ac93f89 | /disp_tut/drawdisparea.h | 9abec6c236e409c99021fdc16c32886d89a85bbd | [] | no_license | zOrg1331/qzdisp | 9ddc7bee7116fbc25dabb34f45274bc30bbdad82 | f15afba02e4c86002b1a90c9901bbe4767e5300f | refs/heads/master | 2016-08-04T17:43:07.193313 | 2008-03-22T14:23:44 | 2008-03-22T14:23:44 | 32,092,059 | 0 | 0 | null | null | null | null | KOI8-R | C++ | false | false | 1,173 | h | drawdisparea.h | // Time-stamp: <drawdisparea.h - 23:09:20 14.12.2005>
/*****************************************************************
*** Заголовочный файл виджета, позволяющего мышкой нарисовать ***
*** функциональную зависимость ***
*****************************************************************/
/* code: Наконечный Павел <zorg1331@gmail.com> */
#ifndef DRAWDISPAREA_H
#define DRAWDISPAREA_H
#include <QColor>
#include <QImage>
#include <QPoint>
#include <QWidget>
class DrawDispArea : public QWidget
{
Q_OBJECT
public:
DrawDispArea(QWidget *parent = 0);
int getYValue(int);
public slots:
void clearImage();
protected:
void mousePressEvent(QMouseEvent *event);
void mouseMoveEvent(QMouseEvent *event);
void mouseReleaseEvent(QMouseEvent *event);
void paintEvent(QPaintEvent *event);
void resizeEvent(QResizeEvent *event);
private:
void drawLineTo(const QPoint &endPoint);
void clearColumn(int point);
void resizeImage(QImage *image, const QSize &newSize);
bool scribbling;
QImage image;
QPoint lastPoint;
};
#endif
|
ec4926289fe9fe2b10ac6dfcdca529a2ed5c6a7a | bed3ac926beac0f4e0293303d7b2a6031ee476c9 | /Modules/Registration/Common/include/itkImageToSpatialObjectRegistrationMethod.h | f902afb43bf1a0a5f8bd515e44dfa43c888c9af1 | [
"IJG",
"Zlib",
"LicenseRef-scancode-proprietary-license",
"SMLNJ",
"BSD-3-Clause",
"BSD-4.3TAHOE",
"LicenseRef-scancode-free-unknown",
"Spencer-86",
"LicenseRef-scancode-llnl",
"FSFUL",
"Libpng",
"libtiff",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive",
... | permissive | InsightSoftwareConsortium/ITK | ed9dbbc5b8b3f7511f007c0fc0eebb3ad37b88eb | 3eb8fd7cdfbc5ac2d0c2e5e776848a4cbab3d7e1 | refs/heads/master | 2023-08-31T17:21:47.754304 | 2023-08-31T00:58:51 | 2023-08-31T14:12:21 | 800,928 | 1,229 | 656 | Apache-2.0 | 2023-09-14T17:54:00 | 2010-07-27T15:48:04 | C++ | UTF-8 | C++ | false | false | 8,878 | h | itkImageToSpatialObjectRegistrationMethod.h | /*=========================================================================
*
* Copyright NumFOCUS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#ifndef itkImageToSpatialObjectRegistrationMethod_h
#define itkImageToSpatialObjectRegistrationMethod_h
#include "itkProcessObject.h"
#include "itkImage.h"
#include "itkImageToSpatialObjectMetric.h"
#include "itkSingleValuedNonLinearOptimizer.h"
#include "itkDataObjectDecorator.h"
namespace itk
{
/** \class ImageToSpatialObjectRegistrationMethod
* \brief Base class for Image Registration Methods
*
*
* This class is templated over the type of the image and the type
* of the SpatialObject to be registered.
* A generic Transform is used by this class. That allows
* to select at run time the particular type of transformation that
* is to be applied for registering the images.
*
* This method use a generic Metric in order to compare the two images.
* the final goal of the registration method is to find the set of
* parameters of the Transformation that optimizes the metric.
*
* The registration method also support a generic optimizer that can
* be selected at run-time. The only restriction for the optimizer is
* that it should be able to operate in single-valued cost functions
* given that the metrics used to compare images provide a single
* value as output.
*
* The terms : Fixed image and Moving SpatialObject are used in this class
* to indicate that the SpatialObject is being mapped by the transform.
*
* This class uses the coordinate system of the Fixed image and searches
* for a transform that will map the Moving SpatialObject on top of
* the Fixed image. For doing so, a Metric will be continuously applied to
* compare the Fixed image with the Transformed Moving SpatialObject.
*
* The ImageToSpatialObjectRegistrationMethod is different from the rest of the
* registration framework in ITK regarding the interpretation of the Transform
* with respect to the Fixed and Moving objects. In most of the ITK
* registration framework, the Transform computed by the optimizer is the one
* that maps points from the space of the Fixed object into the space of the
* Moving object. This direction of the transform is the one that makes easier
* to resample the Moving object into the space of the Fixed object.
*
* In the particular case of ImageToSpatialObject registration, the
* Transform to be computed is the one mapping points from the SpatialObject
* into the Image. This allows the SpatialObject to drive the location and
* geometry of the measurements made in the image - thereby if the spatial
* object is sparse and/or contains varying geometric features, the metric
* applied to measure how well that object matches with the image can be
* rapidly computed only at the sparse locations and using measures that
* match the local geometry that should be at those locations in the image.
* This is particularly useful for fast intra-operative registration when the
* pre-operative data is used to define a SpatialObject and can anticipate
* how that object will appear in the intra-operative images.
*
* A full discussion of the Transform directions in the ITK registration
* framework can be found in the ITK Software Guide.
*
* \ingroup RegistrationFilters
* \ingroup ITKRegistrationCommon
*/
template <typename TFixedImage, typename TMovingSpatialObject>
class ITK_TEMPLATE_EXPORT ImageToSpatialObjectRegistrationMethod : public ProcessObject
{
public:
ITK_DISALLOW_COPY_AND_MOVE(ImageToSpatialObjectRegistrationMethod);
/** Standard class type aliases. */
using Self = ImageToSpatialObjectRegistrationMethod;
using Superclass = ProcessObject;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(ImageToSpatialObjectRegistrationMethod, ProcessObject);
/** Type of the Fixed image. */
using FixedImageType = TFixedImage;
using FixedImageConstPointer = typename FixedImageType::ConstPointer;
/** Type of the Moving image. */
using MovingSpatialObjectType = TMovingSpatialObject;
using MovingSpatialObjectConstPointer = typename MovingSpatialObjectType::ConstPointer;
/** Type of the metric. */
using MetricType = ImageToSpatialObjectMetric<FixedImageType, MovingSpatialObjectType>;
using MetricPointer = typename MetricType::Pointer;
/** Type of the Transform . */
using TransformType = typename MetricType::TransformType;
using TransformPointer = typename TransformType::Pointer;
/** Type for the output: Using Decorator pattern for enabling
* the Transform to be passed in the data pipeline */
using TransformOutputType = DataObjectDecorator<TransformType>;
using TransformOutputPointer = typename TransformOutputType::Pointer;
using TransformOutputConstPointer = typename TransformOutputType::ConstPointer;
/** Type of the Interpolator. */
using InterpolatorType = typename MetricType::InterpolatorType;
using InterpolatorPointer = typename InterpolatorType::Pointer;
/** Type of the optimizer. */
using OptimizerType = SingleValuedNonLinearOptimizer;
/** Type of the Transformation parameters This is the same type used to
* represent the search space of the optimization algorithm */
using ParametersType = typename MetricType::TransformParametersType;
/** Smart Pointer type to a DataObject. */
using DataObjectPointer = typename DataObject::Pointer;
/** Set/Get the Fixed image. */
itkSetConstObjectMacro(FixedImage, FixedImageType);
itkGetConstObjectMacro(FixedImage, FixedImageType);
/** Set/Get the Moving Spatial Object. */
itkSetConstObjectMacro(MovingSpatialObject, MovingSpatialObjectType);
itkGetConstObjectMacro(MovingSpatialObject, MovingSpatialObjectType);
/** Set/Get the Optimizer. */
itkSetObjectMacro(Optimizer, OptimizerType);
itkGetModifiableObjectMacro(Optimizer, OptimizerType);
/** Set/Get the Metric. */
itkSetObjectMacro(Metric, MetricType);
itkGetModifiableObjectMacro(Metric, MetricType);
/** Set/Get the Transform. */
itkSetObjectMacro(Transform, TransformType);
itkGetModifiableObjectMacro(Transform, TransformType);
/** Set/Get the Interpolator. */
itkSetObjectMacro(Interpolator, InterpolatorType);
itkGetModifiableObjectMacro(Interpolator, InterpolatorType);
/** Set/Get the initial transformation parameters. */
itkSetMacro(InitialTransformParameters, ParametersType);
itkGetConstReferenceMacro(InitialTransformParameters, ParametersType);
/** Get the last transformation parameters visited by
* the optimizer. */
itkGetConstReferenceMacro(LastTransformParameters, ParametersType);
/** Returns the transform resulting from the registration process */
const TransformOutputType *
GetOutput() const;
/** Make a DataObject of the correct type to be used as the specified
* output. */
using DataObjectPointerArraySizeType = ProcessObject::DataObjectPointerArraySizeType;
using Superclass::MakeOutput;
DataObjectPointer
MakeOutput(DataObjectPointerArraySizeType output) override;
/** Method to return the latest modified time of this object or
* any of its cached ivars */
ModifiedTimeType
GetMTime() const override;
protected:
ImageToSpatialObjectRegistrationMethod();
~ImageToSpatialObjectRegistrationMethod() override = default;
void
PrintSelf(std::ostream & os, Indent indent) const override;
/** Method invoked by the pipeline in order to trigger the computation of
* the registration. */
void
GenerateData() override;
/** Initialize by setting the interconnects between the components. */
void
Initialize();
ParametersType m_InitialTransformParameters{};
ParametersType m_LastTransformParameters{};
private:
MetricPointer m_Metric{};
OptimizerType::Pointer m_Optimizer{};
MovingSpatialObjectConstPointer m_MovingSpatialObject{};
FixedImageConstPointer m_FixedImage{};
TransformPointer m_Transform{};
InterpolatorPointer m_Interpolator{};
};
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
# include "itkImageToSpatialObjectRegistrationMethod.hxx"
#endif
#endif
|
a74c0a2a271a5b127514be66b801b259c68d181b | b877e5288d286b36ac987f23b4d85589b6f53e8f | /Google/3/3.cpp | 7292f9c37af21ea424e17f008658484691a05fad | [] | no_license | bitsimplify-com/coding-interview | 8635cc406518351579807173d561946482744fdb | 743605ab1630cb19ff6f0fe479a7e8df61215d91 | refs/heads/master | 2022-12-05T17:41:47.180917 | 2020-09-03T04:04:18 | 2020-09-03T04:04:18 | 229,760,805 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 986 | cpp | 3.cpp | #include <iostream>
#include <map>
#include <string>
std::pair<std::string, int> longest_k_substring(std::string s, int k) {
int result = 0;
std::string result_str;
int i = 0;
std::map<char, int> map;
for (int j = 0; j < s.length(); j++) {
char c = s[j];
map[c] += 1;
if (map.size() <= k) {
if (result < j - i + 1) {
result = j - i + 1;
result_str = std::string(s.begin() + i, s.begin() + j + 1);
}
} else {
while (map.size() > k) {
// Prune from the left
char l = s[i];
int count = map[l];
if (count == 1) {
map.erase(l);
} else {
map[l] -= 1;
}
i++;
}
}
}
return {result_str, result};
}
int main() {
std::string s;
int p;
int num_iter;
std::cin >> num_iter;
while (num_iter--) {
std::cin >> s >> p;
auto res = longest_k_substring(s, p);
std::cout << res.first << ' ' << res.second << '\n';
}
return 0;
}
|
0bdb3d732734ef049993cf774c386b9b69986511 | 08e6050aa7d453a89614b9c25bf79500cfb3e99b | /src/cells/cell.hpp | dd328d7aac9be826805b06f84c060211286e69ba | [] | no_license | Damtev/nokia-test-task | 3f5cde11d3b15b42a3f92612ee4c590c9c1a64a5 | 934130c539ba5e56e34ce3af6096e04f8033f082 | refs/heads/master | 2022-11-25T08:42:54.527134 | 2020-07-30T15:49:40 | 2020-07-30T15:49:40 | 283,233,223 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | hpp | cell.hpp | //
// Created by damtev on 28.07.2020.
//
#pragma once
#include <string>
#include <optional>
#include "evaluation_state.hpp"
namespace cell {
using namespace cell;
class Cell {
public:
Cell(std::string_view column_id, size_t row_id);
virtual ~Cell() = default;
[[nodiscard]] EvaluationState GetState() const;
void SetState(EvaluationState state);
virtual long long Evaluate() = 0;
[[nodiscard]] const std::string &GetColumnId() const;
void SetColumnId(const std::string &column_id);
[[nodiscard]] size_t GetRowId() const;
void SetRowId(size_t row_id);
[[nodiscard]] std::string GetPosition() const;
protected:
EvaluationState state_;
std::string column_id_;
size_t row_id_;
std::optional<long long> evaluated_value = {};
};
} |
16eb741dec275932b3a8f53c470ce851790f29f0 | 1c44d2f2d034f8a0c41f5fbeaf93cd5b10eeaab8 | /proj.win32/propertyManager.h | ffc376aa1750fb8ebc2e03bf2d38140600bd383a | [] | no_license | HowarXie1995/Cocos-Graduation | 48392ce46b1a33bb98699894fc38a8d1ef94d950 | 8844348f0661ddb958eb06432d90f2a69021779b | refs/heads/master | 2020-05-01T04:19:40.668593 | 2019-05-06T06:19:35 | 2019-05-06T06:19:35 | 177,271,108 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,154 | h | propertyManager.h | #ifndef __propertyManager_h__
#define __propertyManager_h__
#include <iostream>
#include "cocos2d.h"
USING_NS_CC;
class propertyManager:public Ref
{
public:
CREATE_FUNC(propertyManager);
virtual bool init();
public:
//快速创建一个成员变量,并生成一个set方法和get方法
CC_SYNTHESIZE(int, ID, ID); //角色ID
CC_SYNTHESIZE(int, HP, HP); //角色血量
CC_SYNTHESIZE(int, ATK, ATK); //角色攻击力
CC_SYNTHESIZE(int, Sped, Sped); //保存角色速度
CC_SYNTHESIZE(unsigned int, LockLimit, LockLimit); //索地区
CC_SYNTHESIZE(unsigned int, ATKLimit, ATKLimit); //攻击区
CC_SYNTHESIZE(std::string, ArmatureName, ArmatureName); //动画资源路径的保存
CC_SYNTHESIZE(std::string, DataName, DataName); //动画名字的保存
CC_SYNTHESIZE(std::string, PlayerName, PlayerName); //角色名字的保存
CC_SYNTHESIZE(Rect, HitRect, HitRect); //攻击框
CC_SYNTHESIZE(Point, HitPoint, HitPoint); //攻击框起始点坐标
CC_SYNTHESIZE(Rect, GetHitRect, GetHitRect); //攻击框
CC_SYNTHESIZE(Point, GetHitPoint, GetHitPoint); //攻击框起始点坐标
};
#endif // !__propertyManager_h__
|
92cdc67ebefe947cf3de251efe7c5ee5195464f4 | 5f10d4a8a77f6373ece172ed6159ce6c6fe59fd8 | /plotter/src/SerialLog.cpp | 95968c413b77b7006cade12e06b620f1699a3b21 | [] | no_license | tuangu/XY-plotter | a8d84895ef650eed919c3fda7ca15c6fa2273267 | 2815bd8bc62b4f865e3cf2f8487df1afca8b2dd1 | refs/heads/master | 2022-03-06T01:40:38.613978 | 2019-10-13T14:44:29 | 2019-10-13T14:44:29 | 103,531,626 | 4 | 3 | null | 2017-10-16T09:38:56 | 2017-09-14T12:50:33 | C | UTF-8 | C++ | false | false | 754 | cpp | SerialLog.cpp | #include "board.h"
#include "SerialLog.h"
#include "semphr.h"
#include "portmacro.h"
SerialLog::SerialLog() {
serialMutex = xSemaphoreCreateMutex();
}
SerialLog::~SerialLog() {
if (serialMutex != NULL) {
vSemaphoreDelete(serialMutex);
}
}
void SerialLog::write(char *description) {
if (serialMutex != NULL) {
if (xSemaphoreTake(serialMutex, portMAX_DELAY) == pdPASS) {
Board_UARTPutSTR(description);
xSemaphoreGive(serialMutex);
}
}
}
int SerialLog::read() {
if (serialMutex != NULL) {
if (xSemaphoreTake(serialMutex, portMAX_DELAY) == pdPASS) {
int c = Board_UARTGetChar();
xSemaphoreGive(serialMutex);
return c;
}
}
}
|
345533ef0c043dfa973fb2c68ddc326a4a0a04ea | 2ec6b9887226a7f038a1947d1dd423f633f1ce8a | /Labs/Prelab03/src/Hupp_Prelab03_Source.cpp | 547d293827f59c1fa54cf0e207dc23d654699dd7 | [] | no_license | Huppdo/ECCS1611 | d7845f6b82339635d42beeb62ffd4a037a2ec0ee | 06d6448a33a57bc54d3f130b3d2deadce2a2659e | refs/heads/master | 2023-01-03T23:01:48.646355 | 2020-10-25T23:02:29 | 2020-10-25T23:02:29 | 287,006,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,577 | cpp | Hupp_Prelab03_Source.cpp | //Dominic Hupp - ECCS1611 - Prelab 3
/*
Compute tax rate and total cost
*/
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
//Initialize user input variables
double taxRate = 0, totalCost = 0;
//Initialize hidden variables
double taxOnPurchase = 0;
int roundingPlace = -1;
//Get user input
cout << "Please enter the tax rate without the percentage sign (ex. 6.5) -- ";
cin >> taxRate;
cout << endl << "Please enter the total cost of your purchase (ex. 15.01) -- ";
cin >> totalCost;
//Change tax rate to decimal from percent
taxRate /= 100;
//Compute tax on purchase
taxOnPurchase = taxRate * totalCost;
//Compute third decimal place
roundingPlace = (int)(taxOnPurchase * 1000) % 10;
//Decide if to round or not
if (roundingPlace < 0) {
cout << "Error in code; aborting" << endl << endl;
return 1;
}
else if (roundingPlace <= 4) {
cout << "3rd Decimal smaller than 4, rounding down" << endl << endl;
taxOnPurchase += 0.00; //Does nothing
}
else {
cout << "3rd Decimal larger than 4, rounding up" << endl << endl;
taxOnPurchase += 0.01;
}
//Ensure rounded value only has two decimal places
taxOnPurchase = (double)((int)(taxOnPurchase * 100))/100;
//Add tax to total cost
totalCost = totalCost + taxOnPurchase;
//Display total cost
cout << "The total is $" << fixed << setprecision(2) << taxOnPurchase << endl << endl;
cout << "The total cost with tax is $" << fixed << setprecision(2) << totalCost;
cout << endl << endl;
} |
e1b1b24022d3c1b83a1f738c0dd77b2349073440 | f7dc806f341ef5dbb0e11252a4693003a66853d5 | /thirdparty/icu4c/common/ustrenum.cpp | a60b2208f683ed042e4b93bc4aae5731453d4f7b | [
"MIT",
"OFL-1.1",
"JSON",
"LicenseRef-scancode-nvidia-2002",
"BSD-3-Clause",
"Zlib",
"MPL-2.0",
"CC0-1.0",
"BSL-1.0",
"Libpng",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"Unlicense",
"ICU",
"NTP",
"NAIST-2003",
"LicenseRef-scancode-unicode",
"GPL-2.0-or-later",
"LicenseR... | permissive | godotengine/godot | 8a2419750f4851d1426a8f3bcb52cac5c86f23c2 | 970be7afdc111ccc7459d7ef3560de70e6d08c80 | refs/heads/master | 2023-08-21T14:37:00.262883 | 2023-08-21T06:26:15 | 2023-08-21T06:26:15 | 15,634,981 | 68,852 | 18,388 | MIT | 2023-09-14T21:42:16 | 2014-01-04T16:05:36 | C++ | UTF-8 | C++ | false | false | 10,978 | cpp | ustrenum.cpp | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
**********************************************************************
* Copyright (c) 2002-2014, International Business Machines
* Corporation and others. All Rights Reserved.
**********************************************************************
* Author: Alan Liu
* Created: November 11 2002
* Since: ICU 2.4
**********************************************************************
*/
#include "utypeinfo.h" // for 'typeid' to work
#include "unicode/ustring.h"
#include "unicode/strenum.h"
#include "unicode/putil.h"
#include "uenumimp.h"
#include "ustrenum.h"
#include "cstring.h"
#include "cmemory.h"
#include "uassert.h"
U_NAMESPACE_BEGIN
// StringEnumeration implementation ---------------------------------------- ***
StringEnumeration::StringEnumeration()
: chars(charsBuffer), charsCapacity(sizeof(charsBuffer)) {
}
StringEnumeration::~StringEnumeration() {
if (chars != nullptr && chars != charsBuffer) {
uprv_free(chars);
}
}
// StringEnumeration base class clone() default implementation, does not clone
StringEnumeration *
StringEnumeration::clone() const {
return nullptr;
}
const char *
StringEnumeration::next(int32_t *resultLength, UErrorCode &status) {
const UnicodeString *s=snext(status);
if(U_SUCCESS(status) && s!=nullptr) {
unistr=*s;
ensureCharsCapacity(unistr.length()+1, status);
if(U_SUCCESS(status)) {
if(resultLength!=nullptr) {
*resultLength=unistr.length();
}
unistr.extract(0, INT32_MAX, chars, charsCapacity, US_INV);
return chars;
}
}
return nullptr;
}
const char16_t *
StringEnumeration::unext(int32_t *resultLength, UErrorCode &status) {
const UnicodeString *s=snext(status);
if(U_SUCCESS(status) && s!=nullptr) {
unistr=*s;
if(resultLength!=nullptr) {
*resultLength=unistr.length();
}
return unistr.getTerminatedBuffer();
}
return nullptr;
}
const UnicodeString *
StringEnumeration::snext(UErrorCode &status) {
int32_t length;
const char *s=next(&length, status);
return setChars(s, length, status);
}
void
StringEnumeration::ensureCharsCapacity(int32_t capacity, UErrorCode &status) {
if(U_SUCCESS(status) && capacity>charsCapacity) {
if(capacity<(charsCapacity+charsCapacity/2)) {
// avoid allocation thrashing
capacity=charsCapacity+charsCapacity/2;
}
if(chars!=charsBuffer) {
uprv_free(chars);
}
chars=(char *)uprv_malloc(capacity);
if(chars==nullptr) {
chars=charsBuffer;
charsCapacity=sizeof(charsBuffer);
status=U_MEMORY_ALLOCATION_ERROR;
} else {
charsCapacity=capacity;
}
}
}
UnicodeString *
StringEnumeration::setChars(const char *s, int32_t length, UErrorCode &status) {
if(U_SUCCESS(status) && s!=nullptr) {
if(length<0) {
length=(int32_t)uprv_strlen(s);
}
char16_t *buffer=unistr.getBuffer(length+1);
if(buffer!=nullptr) {
u_charsToUChars(s, buffer, length);
buffer[length]=0;
unistr.releaseBuffer(length);
return &unistr;
} else {
status=U_MEMORY_ALLOCATION_ERROR;
}
}
return nullptr;
}
bool
StringEnumeration::operator==(const StringEnumeration& that)const {
return typeid(*this) == typeid(that);
}
bool
StringEnumeration::operator!=(const StringEnumeration& that)const {
return !operator==(that);
}
// UStringEnumeration implementation --------------------------------------- ***
UStringEnumeration * U_EXPORT2
UStringEnumeration::fromUEnumeration(
UEnumeration *uenumToAdopt, UErrorCode &status) {
if (U_FAILURE(status)) {
uenum_close(uenumToAdopt);
return nullptr;
}
UStringEnumeration *result = new UStringEnumeration(uenumToAdopt);
if (result == nullptr) {
status = U_MEMORY_ALLOCATION_ERROR;
uenum_close(uenumToAdopt);
return nullptr;
}
return result;
}
UStringEnumeration::UStringEnumeration(UEnumeration* _uenum) :
uenum(_uenum) {
U_ASSERT(_uenum != 0);
}
UStringEnumeration::~UStringEnumeration() {
uenum_close(uenum);
}
int32_t UStringEnumeration::count(UErrorCode& status) const {
return uenum_count(uenum, &status);
}
const char *UStringEnumeration::next(int32_t *resultLength, UErrorCode &status) {
return uenum_next(uenum, resultLength, &status);
}
const UnicodeString* UStringEnumeration::snext(UErrorCode& status) {
int32_t length;
const char16_t* str = uenum_unext(uenum, &length, &status);
if (str == 0 || U_FAILURE(status)) {
return 0;
}
return &unistr.setTo(str, length);
}
void UStringEnumeration::reset(UErrorCode& status) {
uenum_reset(uenum, &status);
}
UOBJECT_DEFINE_RTTI_IMPLEMENTATION(UStringEnumeration)
U_NAMESPACE_END
// C wrapper --------------------------------------------------------------- ***
#define THIS(en) ((icu::StringEnumeration*)(en->context))
U_CDECL_BEGIN
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static void U_CALLCONV
ustrenum_close(UEnumeration* en) {
delete THIS(en);
uprv_free(en);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static int32_t U_CALLCONV
ustrenum_count(UEnumeration* en,
UErrorCode* ec)
{
return THIS(en)->count(*ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static const char16_t* U_CALLCONV
ustrenum_unext(UEnumeration* en,
int32_t* resultLength,
UErrorCode* ec)
{
return THIS(en)->unext(resultLength, *ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static const char* U_CALLCONV
ustrenum_next(UEnumeration* en,
int32_t* resultLength,
UErrorCode* ec)
{
return THIS(en)->next(resultLength, *ec);
}
/**
* Wrapper API to make StringEnumeration look like UEnumeration.
*/
static void U_CALLCONV
ustrenum_reset(UEnumeration* en,
UErrorCode* ec)
{
THIS(en)->reset(*ec);
}
/**
* Pseudo-vtable for UEnumeration wrapper around StringEnumeration.
* The StringEnumeration pointer will be stored in 'context'.
*/
static const UEnumeration USTRENUM_VT = {
nullptr,
nullptr, // store StringEnumeration pointer here
ustrenum_close,
ustrenum_count,
ustrenum_unext,
ustrenum_next,
ustrenum_reset
};
U_CDECL_END
/**
* Given a StringEnumeration, wrap it in a UEnumeration. The
* StringEnumeration is adopted; after this call, the caller must not
* delete it (regardless of error status).
*/
U_CAPI UEnumeration* U_EXPORT2
uenum_openFromStringEnumeration(icu::StringEnumeration* adopted, UErrorCode* ec) {
UEnumeration* result = nullptr;
if (U_SUCCESS(*ec) && adopted != nullptr) {
result = (UEnumeration*) uprv_malloc(sizeof(UEnumeration));
if (result == nullptr) {
*ec = U_MEMORY_ALLOCATION_ERROR;
} else {
uprv_memcpy(result, &USTRENUM_VT, sizeof(USTRENUM_VT));
result->context = adopted;
}
}
if (result == nullptr) {
delete adopted;
}
return result;
}
// C wrapper --------------------------------------------------------------- ***
U_CDECL_BEGIN
typedef struct UCharStringEnumeration {
UEnumeration uenum;
int32_t index, count;
} UCharStringEnumeration;
static void U_CALLCONV
ucharstrenum_close(UEnumeration* en) {
uprv_free(en);
}
static int32_t U_CALLCONV
ucharstrenum_count(UEnumeration* en,
UErrorCode* /*ec*/) {
return ((UCharStringEnumeration*)en)->count;
}
static const char16_t* U_CALLCONV
ucharstrenum_unext(UEnumeration* en,
int32_t* resultLength,
UErrorCode* /*ec*/) {
UCharStringEnumeration *e = (UCharStringEnumeration*) en;
if (e->index >= e->count) {
return nullptr;
}
const char16_t* result = ((const char16_t**)e->uenum.context)[e->index++];
if (resultLength) {
*resultLength = (int32_t)u_strlen(result);
}
return result;
}
static const char* U_CALLCONV
ucharstrenum_next(UEnumeration* en,
int32_t* resultLength,
UErrorCode* /*ec*/) {
UCharStringEnumeration *e = (UCharStringEnumeration*) en;
if (e->index >= e->count) {
return nullptr;
}
const char* result = ((const char**)e->uenum.context)[e->index++];
if (resultLength) {
*resultLength = (int32_t)uprv_strlen(result);
}
return result;
}
static void U_CALLCONV
ucharstrenum_reset(UEnumeration* en,
UErrorCode* /*ec*/) {
((UCharStringEnumeration*)en)->index = 0;
}
static const UEnumeration UCHARSTRENUM_VT = {
nullptr,
nullptr, // store StringEnumeration pointer here
ucharstrenum_close,
ucharstrenum_count,
uenum_unextDefault,
ucharstrenum_next,
ucharstrenum_reset
};
static const UEnumeration UCHARSTRENUM_U_VT = {
nullptr,
nullptr, // store StringEnumeration pointer here
ucharstrenum_close,
ucharstrenum_count,
ucharstrenum_unext,
uenum_nextDefault,
ucharstrenum_reset
};
U_CDECL_END
U_CAPI UEnumeration* U_EXPORT2
uenum_openCharStringsEnumeration(const char* const strings[], int32_t count,
UErrorCode* ec) {
UCharStringEnumeration* result = nullptr;
if (U_SUCCESS(*ec) && count >= 0 && (count == 0 || strings != 0)) {
result = (UCharStringEnumeration*) uprv_malloc(sizeof(UCharStringEnumeration));
if (result == nullptr) {
*ec = U_MEMORY_ALLOCATION_ERROR;
} else {
U_ASSERT((char*)result==(char*)(&result->uenum));
uprv_memcpy(result, &UCHARSTRENUM_VT, sizeof(UCHARSTRENUM_VT));
result->uenum.context = (void*)strings;
result->index = 0;
result->count = count;
}
}
return (UEnumeration*) result;
}
U_CAPI UEnumeration* U_EXPORT2
uenum_openUCharStringsEnumeration(const char16_t* const strings[], int32_t count,
UErrorCode* ec) {
UCharStringEnumeration* result = nullptr;
if (U_SUCCESS(*ec) && count >= 0 && (count == 0 || strings != 0)) {
result = (UCharStringEnumeration*) uprv_malloc(sizeof(UCharStringEnumeration));
if (result == nullptr) {
*ec = U_MEMORY_ALLOCATION_ERROR;
} else {
U_ASSERT((char*)result==(char*)(&result->uenum));
uprv_memcpy(result, &UCHARSTRENUM_U_VT, sizeof(UCHARSTRENUM_U_VT));
result->uenum.context = (void*)strings;
result->index = 0;
result->count = count;
}
}
return (UEnumeration*) result;
}
// end C Wrapper
|
0a40b57a63fcc2dc048d8b5aece34f5d41cd5948 | 93d4a019012e135427e5c14f98fddefb9979e906 | /qtquick2-integration/ex_basic_integration/window.cpp | 377f7aee0991ee3a79e4be545b93795d463d7472 | [] | no_license | kaabimg/opengl-demos | ebd2e5770e2be564a1ff68ad226641bd1afdb954 | 86581600e6256aa12d0e2afbb16b06b0bd78e8fc | refs/heads/master | 2021-01-01T06:41:03.755143 | 2013-07-04T19:55:57 | 2013-07-04T19:55:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | window.cpp | #include "window.h"
#include "basicusagescene.h"
#include <QDebug>
#include <QGuiApplication>
#include <QOpenGLContext>
#include <QSurfaceFormat>
#include <QTimer>
Window::Window( QWindow* parent )
: QQuickView( parent ),
m_scene( new BasicUsageScene )
{
setClearBeforeRendering( false );
QObject::connect( this, &Window::sceneGraphInitialized,
this, &Window::initialiseOpenGLScene, Qt::DirectConnection);
QObject::connect( this, &Window::beforeRendering,
this, &Window::renderOpenGLScene, Qt::DirectConnection);
QObject::connect( this, &Window::sceneGraphInvalidated,
this, &Window::cleanupOpenGLScene, Qt::DirectConnection);
}
void Window::initialiseOpenGLScene()
{
m_scene->initialise();
m_scene->resize( width(), height() );
}
void Window::renderOpenGLScene()
{
m_scene->render();
}
void Window::cleanupOpenGLScene()
{
m_scene->cleanup();
}
|
ce5a497e34f485393516b6912ed36b71c0591f83 | 09c9637a1e7d939672900490f502bbc6c28e0e82 | /Software3DRenderer/SWR/Display.h | 328ffb35f6e57b550dfe83017a293f39446c2123 | [] | no_license | idenys1024/Software3DRender | 8755e3d50c85f96964c44852966f0fa20e5b0088 | b5bc8dc48145f192bddca5aaf144d1112eaf0090 | refs/heads/master | 2020-05-18T20:11:42.171206 | 2017-11-08T04:07:08 | 2017-11-08T04:07:08 | 41,029,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | h | Display.h | //
// SWRDisplay.h
// Software3DRenderer
//
// Created by Denys Kunytskyi on 8/20/15.
// Copyright (c) 2015 Denys Kunytskyi. All rights reserved.
//
#ifndef __Software3DRenderer__SWRDisplay__
#define __Software3DRenderer__SWRDisplay__
#include <stdio.h>
#include <memory>
namespace SWR {
class RenderContext;
class Scene;
class Display
{
public:
static std::shared_ptr<Display> GetConfiguredDisplay(int w,int h);
Display(int w,int h);
virtual ~Display();
void Resize(int newW, int newH);
void DoDrawFrame(float deltaTime);
void SwapBuffers();
const unsigned char* const GetDisplayRGBAData() const;
int GetWidth() const;
int GetHeight() const;
void SetScene(std::shared_ptr<Scene> newScene);
protected:
std::shared_ptr<RenderContext> _frameBuffer;
std::shared_ptr<Scene> _currentScene;
};
}
#endif /* defined(__Software3DRenderer__SWRDisplay__) */
|
080f7fefae8f17408e8eef4d81de4e4b52edfc23 | 9f556fbe5092b1b4d235a6736d147ce173f802cc | /TestClass.cpp | 47c70ceb21cd15096136d8f7da68bc38bf3f4fe5 | [] | no_license | Lonefish/Graham | 35681c625a1a913bc6669ac601b92a916711b8db | 85bc2cf065d5e56a46f70c04200f03370c67a0b4 | refs/heads/master | 2016-09-05T10:22:38.878538 | 2015-09-08T18:54:42 | 2015-09-08T18:54:42 | 40,053,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | cpp | TestClass.cpp | /*
* TestClass.cpp
*
* Created on: Aug 1, 2015
* Author: lonefish
*/
#include "TestClass.h"
//Include Graham header
#include "Graham.h"
#include <iostream>
/*
* TODO
* Check input for numbers only
* Fix constructor/init method
* Convert input to base 32
* Try vector maybe?
* malloc to make a dynamic array
* bigint in different bases, standard 32
*/
int main() {
Stopwatch s;
s.startClock();
Graham::BigInt z;
z.init("3");
Graham::BigInt y;
y.init("3");
z.print("z");
y.print("y");
y.powerMod(195387, 7);
z.print("z");
y.print("y");
s.stopClock();
std::cout << "Time taken in ms :" << s.difference();
return 0;
}
TestClass::TestClass() {
// TODO Auto-generated constructor stub
}
TestClass::~TestClass() {
// TODO Auto-generated destructor stub
}
|
ff8080be005b2ca70e639c032576fabe97259f8d | 386a7666e7b5418bf9c7fe2626bea45a67fcaa19 | /Graphs/topological_sort/P16249.cc | fb6168f6fff5541f8819571cd5e0b98f76286c02 | [] | no_license | sanchyy/Jutge-EDA | d6392b6f05407273561df0595b33645ea70b4b02 | 4d88e0a42236a05716467e49a0d89bc6f823d2fd | refs/heads/master | 2021-04-28T07:05:32.074448 | 2018-05-28T09:54:33 | 2018-05-28T09:54:33 | 122,217,246 | 0 | 1 | null | 2018-05-28T06:58:50 | 2018-02-20T15:34:01 | C++ | UTF-8 | C++ | false | false | 423 | cc | P16249.cc | #include <iostream>
#include <vector>
#include <utility>
#include <stack>
using namespace std;
using VS = vector <string>;
using VE = vector <int>;
using VVE = vector <VE>;
int n,m;
list <int> topological_sort() {
}
int main() {
while (cin >> n) {
for (int i = 0; i < n; ++i) {
}
cin >> m;
for (int i = 0; i < n; ++i) {
}
topological_sort();
}
}
|
36cd8c2031311d39588cf8f85cb20ba41270cb84 | 181e5901afb7079762cae1b0a491c8a390ae6870 | /src/http/parser.h | a5a26dffefb5ebe7ac14bdd4e8d14acaa23fdb13 | [
"MIT"
] | permissive | hrxcodes/cbftp | baf3cc2da40d0edc04731cc1948122c4bd1eba48 | bf2784007dcc4cc42775a2d40157c51b80383f81 | refs/heads/master | 2022-04-21T04:11:30.532918 | 2020-04-01T06:05:07 | 2020-04-01T06:05:07 | 258,615,100 | 0 | 0 | MIT | 2020-04-24T20:17:59 | 2020-04-24T20:17:58 | null | UTF-8 | C++ | false | false | 1,211 | h | parser.h | #pragma once
#include <string>
#include <vector>
#include "../ext/picohttpparser.h"
namespace http {
class Message;
enum class State {
BODY = 0,
HEADERS = 1,
PARSING_FAILED = -1,
PARTIAL = -2,
BODY_TOO_LONG = -3,
URI_TOO_LONG = -4,
UNKNOWN = -5
};
struct Result {
Result();
Result(State state, const char* data = nullptr, size_t datalen = 0, bool complete = false);
State state;
const char* data;
size_t datalen;
bool complete;
};
#define MAX_HEADERS 100
/* Base class for the common parts of HTTP request and response parsing. */
class Parser {
public:
explicit Parser();
virtual ~Parser();
/* Feed incoming data from a socket into the parser. Returns false if a parsing
* error occurred.
*/
Result feed(const char* data, size_t datalen);
/* Clear the parsing buffer. */
void clear();
protected:
/* Called by parse() in subclasses. */
void parseHeaders(Message& msg, struct phr_header* headers, size_t numheaders);
private:
virtual int parse(const char* data, size_t datalen, size_t prevdatalen = 0) = 0;
std::vector<char> headers;
size_t headerslen;
size_t bodylen;
size_t contentlen;
bool inbody;
};
} // namespace http
|
40f9e15b1e528cac18a5a651a55081f2234681ef | cdb2160523b3742ea058ab5c22ebf6e44cb7f87d | /C++/boj/boj9020.cpp | 5337d7a7fa123097ef294f3265193dde1fa8e4ca | [] | no_license | ryul99/algorithm-study | 68193471264a8bb249e047c922c2f66144eed6a7 | d64c388ca7d0c3b01e8e8a480f5fc435772f154b | refs/heads/master | 2023-03-06T14:44:24.498487 | 2023-02-23T21:16:35 | 2023-02-23T21:16:35 | 149,987,036 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | cpp | boj9020.cpp | #include <cstring>
#include <string>
#include <cstdio>
#include <iostream>
#include <vector>
#include <map>
#include <utility>
#include <algorithm>
#include <set>
#include <unordered_set>
#include <stack>
#include <queue>
#include <cmath>
using namespace std;
//https://www.acmicpc.net/problem/9020
int main(int argc, char const *argv[]) {
//ios_base::sync_with_stdio(false)
set<int> prime = {2};
for (int i = 3; i < 10000; ++i) {
bool is_prime = true;
for (int j : prime) {
if (i % j == 0) {
is_prime = false;
break;
}
}
if (is_prime)
prime.insert(i);
}
int T;
scanf("%d", &T);
for (int i = 0; i < T; ++i) {
int N, a = -1, b = -1;
scanf("%d", &N);
for (int p : prime) {
if (p > N / 2)
break;
if (prime.find(N - p) != prime.end()) {
a = p;
b = N - p;
}
}
printf("%d %d\n", a, b);
}
return 0;
}
|
557f8688d0411ab945e2ce623d02b7972b2c90f1 | de0bf8338ab09bfcae20d0d4383edcc46c8ab6c2 | /32K_bwt_mtf_rle_bin/sav/arithmetic_encode.cpp | 63cae38de4224fa99c8de172e8a8442c4a54a593 | [] | no_license | already5chosen/arith_coding | 384f6633af45a0acdf2cf26abd3df871b55ecfe6 | 67666c909a2f43d5ae01ed0873224f0b20d52739 | refs/heads/master | 2021-05-07T08:17:10.940940 | 2018-11-29T23:45:44 | 2018-11-29T23:45:44 | 109,333,044 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,204 | cpp | arithmetic_encode.cpp | #include <cstdio>
#include <cmath>
#include <cfloat>
#include <cstring>
#include <algorithm>
#include "arithmetic_encode.h"
#include "arithmetic_coder_cfg.h"
static const unsigned VAL_RANGE = 1u << RANGE_BITS;
// return quantized code of h0/(h0+h1) in range [0..scale]
static unsigned quantize_histogram_pair(unsigned h0, unsigned h1, unsigned scale)
{
if (h0 == 0)
return 0;
if (h1 == 0)
return scale;
unsigned hTot = h0 + h1;
// printf("%u+%u => %.2f\n", h0, h1, (log2(hTot)*hTot-log2(h0)*h0-log2(h1)*h1)/8);
double M_PI = 3.1415926535897932384626433832795;
unsigned val = round((asin(h0*2.0/hTot - 1.0)/M_PI + 0.5)*scale);
if (val < 1)
val = 1;
else if (val >= scale)
val = scale-1;
return val;
}
static uint8_t h2qh_tab[ARITH_CODER_CNT_MAX+1];
static uint16_t qh2h_tab[ARITH_CODER_QH_SCALE+1];
static double log2_tab[ARITH_CODER_CNT_MAX+1];
static double entropy_tab[ARITH_CODER_CNT_MAX+1];
static double quantized_entropy_tab[ARITH_CODER_CNT_MAX+1];
void arithmetic_encode_init_tables()
{
for (int i = 1; i <= ARITH_CODER_CNT_MAX; ++i)
log2_tab[i] = log2(i);
for (int i = 1; i < ARITH_CODER_CNT_MAX; ++i)
entropy_tab[i] =
log2_tab[ARITH_CODER_CNT_MAX]*ARITH_CODER_CNT_MAX
- log2_tab[i]*i
- log2_tab[ARITH_CODER_CNT_MAX-i]*(ARITH_CODER_CNT_MAX-i);
h2qh_tab[ARITH_CODER_CNT_MAX] = ARITH_CODER_QH_SCALE;
for (int i = 1; i < ARITH_CODER_CNT_MAX; ++i)
h2qh_tab[i] = quantize_histogram_pair(i, ARITH_CODER_CNT_MAX-i, ARITH_CODER_QH_SCALE);
qh2h_tab[ARITH_CODER_QH_SCALE] = VAL_RANGE;
double M_PI = 3.1415926535897932384626433832795;
for (int i = 1; i < ARITH_CODER_QH_SCALE; ++i)
qh2h_tab[i] = int(round((sin((i*2-ARITH_CODER_QH_SCALE)*(M_PI/2/ARITH_CODER_QH_SCALE))+1.0)*(VAL_RANGE/2)));
for (int i = 1; i < ARITH_CODER_CNT_MAX; ++i) {
int32_t ra = qh2h_tab[h2qh_tab[i]];
quantized_entropy_tab[i] =
RANGE_BITS*ARITH_CODER_CNT_MAX
- log2(ra)*i
- log2(VAL_RANGE-ra)*(ARITH_CODER_CNT_MAX-i);
// printf("%3d %2d %5d %.3f\n", i, h2qh_tab[i], ra, quantized_entropy_tab[i]);
}
}
enum {
// context header
CONTEXT_HDR_SRC_OFFSET_I=0,
CONTEXT_HDR_SRC_LEN_I,
CONTEXT_HDR_QH_OFFSET_I,
CONTEXT_HDR_QH_LEN_I,
CONTEXT_HDR_PREV_C0_I,
CONTEXT_HDR_MODEL_LEN_I,
CONTEXT_HDR_S_ENTROPY_I,
CONTEXT_HDR_Q_ENTROPY_I = CONTEXT_HDR_S_ENTROPY_I + sizeof(double)/sizeof(uint32_t),
CONTEXT_HDR_Q1_ENTROPY_I = CONTEXT_HDR_Q_ENTROPY_I + sizeof(double)/sizeof(uint32_t),
CONTEXT_HDR_QH_OFFSETS_I = CONTEXT_HDR_Q1_ENTROPY_I + sizeof(double)/sizeof(uint32_t),
CONTEXT_HDR_CNTRS_I = CONTEXT_HDR_QH_OFFSETS_I + 258,
CONTEXT_CNTRS_SZ = (258*2*sizeof(uint8_t)-1)/sizeof(uint32_t) + 1,
CONTEXT_HDR_PREV_QH_I = CONTEXT_HDR_CNTRS_I + CONTEXT_CNTRS_SZ,
CONTEXT_PREV_QH_SZ = (258*sizeof(uint8_t)-1)/sizeof(uint32_t) + 1,
CONTEXT_HDR_PREV_H_I = CONTEXT_HDR_PREV_QH_I + CONTEXT_PREV_QH_SZ,
CONTEXT_PREV_H_SZ = (258*sizeof(uint8_t)-1)/sizeof(uint32_t) + 1,
CONTEXT_HDR_LEN = CONTEXT_HDR_PREV_H_I + CONTEXT_PREV_H_SZ,
};
void arithmetic_encode_init_context(uint32_t* context, int tilelen)
{
uint32_t srcOffset = CONTEXT_HDR_LEN;
context[CONTEXT_HDR_SRC_OFFSET_I] = srcOffset;
context[CONTEXT_HDR_SRC_LEN_I] = 0;
context[CONTEXT_HDR_QH_OFFSET_I] = srcOffset + (tilelen*2-1)/sizeof(uint32_t) + 1;
context[CONTEXT_HDR_QH_LEN_I] = 0;
context[CONTEXT_HDR_PREV_C0_I] = 0;
context[CONTEXT_HDR_MODEL_LEN_I] = 0;
memset(&context[CONTEXT_HDR_S_ENTROPY_I], 0, sizeof(double));
memset(&context[CONTEXT_HDR_Q_ENTROPY_I], 0, sizeof(double));
memset(&context[CONTEXT_HDR_Q1_ENTROPY_I], 0, sizeof(double));
memset(&context[CONTEXT_HDR_QH_OFFSETS_I], 0, sizeof(uint32_t)*258);
memset(&context[CONTEXT_HDR_CNTRS_I], 0, sizeof(uint32_t)*CONTEXT_CNTRS_SZ);
memset(&context[CONTEXT_HDR_PREV_QH_I], ARITH_CODER_QH_SCALE/2, sizeof(uint32_t)*CONTEXT_PREV_QH_SZ);
memset(&context[CONTEXT_HDR_PREV_H_I], ARITH_CODER_CNT_MAX/2, sizeof(uint32_t)*CONTEXT_PREV_H_SZ);
}
static int calculate_model_length(unsigned prev, unsigned val)
{
int modelLen = 1; // isEqual ?
if (prev != val) {
unsigned ra = prev, diff = val - prev;
if (val > prev) {
modelLen += (prev != 0); // sign
ra = ARITH_CODER_QH_SCALE - prev;
} else {
modelLen += (prev != ARITH_CODER_QH_SCALE); // sign
diff = prev - val;
}
prev = val;
if (ra > 1) {
modelLen += 1; // is +/-1
if (diff > 1) {
ra -= 1;
diff -= 2;
while (ra > 1) {
modelLen += 1;
unsigned mid = ra / 2;
if (diff < mid) {
ra = mid;
} else {
ra -= mid;
diff -= mid;
}
}
}
}
}
return modelLen;
}
static void add_double(uint32_t* dst, double val) {
double x;
memcpy(&x, dst, sizeof(double));
x += val;
memcpy(dst, &x, sizeof(double));
}
void arithmetic_encode_chunk_callback(void* context_ptr, const uint8_t* src, int srclen)
{
uint32_t* context = static_cast<uint32_t*>(context_ptr);
uint8_t* cntrs = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_CNTRS_I]);
uint8_t* prevQh = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_PREV_QH_I]);
uint8_t* prevH = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_PREV_H_I]);
uint8_t* qh = reinterpret_cast<uint8_t*>(&context[context[CONTEXT_HDR_QH_OFFSET_I]]);
uint32_t qhlen = context[CONTEXT_HDR_QH_LEN_I];
int prevC0 = context[CONTEXT_HDR_PREV_C0_I];
// update histograms
double entropy = 0;
double quantizedEntropy = 0;
double quantizedEntropy1 = 0;
for (int i = 0; i < srclen; ++i) {
unsigned c = src[i];
if (c == 255) {
// escape sequence for symbols 255 and 256
c = unsigned(src[i+1]) + 1;
++i;
}
unsigned tLo = 0, tHi = 256;
do {
unsigned tMid = (tLo*3 + tHi)/4;
unsigned b = c > tMid;
tLo = (b == 0) ? tLo : tMid + 1;
tHi = (b == 0) ? tMid : tHi;
unsigned idx = (tMid < 2) & prevC0 ? tMid : tMid + 2; // separate statistics for non-MS characters of zero run
unsigned cntr0 = cntrs[idx*2+0];
if (cntr0 == 0) {
context[CONTEXT_HDR_QH_OFFSETS_I+idx] = qhlen;
++qhlen;
}
cntr0 += 1;
cntrs[idx*2+0] = cntr0;
cntrs[idx*2+1] += b;
if (cntr0 == ARITH_CODER_CNT_MAX) {
int hVal = cntrs[idx*2+1];
cntrs[idx*2+0] = cntrs[idx*2+1] = 0;
entropy += entropy_tab[hVal];
{
quantizedEntropy += quantized_entropy_tab[hVal];
unsigned qhVal = h2qh_tab[hVal]; // quantized '1'-to-total ratio
qh[context[CONTEXT_HDR_QH_OFFSETS_I+idx]] = qhVal;
// estimate model length
context[CONTEXT_HDR_MODEL_LEN_I] += calculate_model_length(prevQh[idx], qhVal);
prevQh[idx] = qhVal;
}
{
int prevHVal = prevH[idx];
prevH[idx] = hVal;
int newQhVal = h2qh_tab[hVal];
int oldQhVal = h2qh_tab[prevHVal];
double oldQhEntropy = 0;
if (hVal != 0 && hVal != ARITH_CODER_CNT_MAX) {
unsigned ra = (uint32_t(prevHVal)*VAL_RANGE*2 + ARITH_CODER_CNT_MAX)/(ARITH_CODER_CNT_MAX*2);
oldQhEntropy =
RANGE_BITS*ARITH_CODER_CNT_MAX
- log2(ra)*hVal
- log2(VAL_RANGE-ra)*(ARITH_CODER_CNT_MAX-hVal);
}
int nxtQhVal = oldQhVal;
if (newQhVal != oldQhVal) {
double newQhEntropy = quantized_entropy_tab[hVal]; // case of change of qh
if (newQhEntropy+1 < oldQhEntropy) {
oldQhEntropy = newQhEntropy;
nxtQhVal = newQhVal;
}
}
quantizedEntropy1 += oldQhEntropy;
quantizedEntropy1 += calculate_model_length(oldQhVal, nxtQhVal);
}
}
} while (tLo != tHi);
prevC0 = (c < 2);
}
context[CONTEXT_HDR_PREV_C0_I] = prevC0;
context[CONTEXT_HDR_QH_LEN_I] = qhlen;
add_double(&context[CONTEXT_HDR_S_ENTROPY_I], entropy);
add_double(&context[CONTEXT_HDR_Q_ENTROPY_I], quantizedEntropy);
add_double(&context[CONTEXT_HDR_Q1_ENTROPY_I], quantizedEntropy1);
uint8_t* dst = reinterpret_cast<uint8_t*>(&context[context[CONTEXT_HDR_SRC_OFFSET_I]]);
uint32_t dstlen = context[CONTEXT_HDR_SRC_LEN_I];
context[CONTEXT_HDR_SRC_LEN_I] = dstlen + srclen;
memcpy(&dst[dstlen], src, srclen);
}
// return estimate of result length
static int prepare(uint32_t* context, double* pInfo)
{
uint8_t* cntrs = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_CNTRS_I]);
uint8_t* prevQh = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_PREV_QH_I]);
uint8_t* prevH = reinterpret_cast<uint8_t*>(&context[CONTEXT_HDR_PREV_H_I]);
uint8_t* qh = reinterpret_cast<uint8_t*>(&context[context[CONTEXT_HDR_QH_OFFSET_I]]);
double entropy, quantizedEntropy, quantizedEntropy1;
memcpy(&entropy, &context[CONTEXT_HDR_S_ENTROPY_I], sizeof(double));
memcpy(&quantizedEntropy, &context[CONTEXT_HDR_Q_ENTROPY_I], sizeof(double));
memcpy(&quantizedEntropy1, &context[CONTEXT_HDR_Q1_ENTROPY_I], sizeof(double));
int32_t modelLen = context[CONTEXT_HDR_MODEL_LEN_I];
// process partial sections
for (int idx = 0; idx < 258; ++idx) {
unsigned tot = cntrs[idx*2+0];
if (tot != 0) {
unsigned h0 = cntrs[idx*2+1];
unsigned qhVal = quantize_histogram_pair(h0, tot-h0, ARITH_CODER_QH_SCALE);
qh[context[CONTEXT_HDR_QH_OFFSETS_I+idx]] = qhVal;
entropy +=
log2_tab[tot]*tot
- log2_tab[h0]*h0
- log2_tab[tot-h0]*(tot-h0);
if (h0 != 0 && h0 != tot) {
int32_t ra0 = qh2h_tab[qhVal];
quantizedEntropy +=
RANGE_BITS*tot
- log2(ra0)*h0
- log2(VAL_RANGE-ra0)*(tot-h0);
{
int prevHVal = prevH[idx];
int newQhVal = qhVal;
int oldQhVal = h2qh_tab[prevHVal];
double oldQhEntropy = 0;
int ra = (uint32_t(prevHVal)*VAL_RANGE*2 + ARITH_CODER_CNT_MAX)/(ARITH_CODER_CNT_MAX*2);
oldQhEntropy =
RANGE_BITS*tot
- log2(ra)*h0
- log2(VAL_RANGE-ra)*(tot-h0);
int nxtQhVal = oldQhVal;
if (newQhVal != oldQhVal) {
int32_t ra0 = qh2h_tab[qhVal];
double newQhEntropy =
RANGE_BITS*tot
- log2(ra0)*h0
- log2(VAL_RANGE-ra0)*(tot-h0);
if (newQhEntropy < oldQhEntropy) {
oldQhEntropy = newQhEntropy;
nxtQhVal = newQhVal;
}
}
quantizedEntropy1 += oldQhEntropy;
quantizedEntropy1 += calculate_model_length(oldQhVal, nxtQhVal);
}
}
// estimate model length
modelLen += calculate_model_length(prevQh[idx], qhVal);
}
}
if (pInfo) {
pInfo[0] = entropy;
pInfo[1] = modelLen;
pInfo[3] = quantizedEntropy;
pInfo[4] = quantizedEntropy1/8;
}
return ceil((quantizedEntropy+modelLen)/8);
}
static void inc_dst(uint8_t* dst) {
uint8_t val;
do {
--dst;
*dst = (val = *dst + 1);
} while (val==0);
}
static uint16_t* encodeQh(uint16_t* wrBits, unsigned val, unsigned prev)
{
int isNotEqual = (val != prev);
wrBits[0] = isNotEqual;
wrBits[1] = VAL_RANGE/2;
wrBits += 2;
if (isNotEqual) {
int up = val > prev;
wrBits[0] = up;
wrBits[1] = VAL_RANGE/2;
unsigned ra = prev, diff = val - prev;
if (up) {
if (prev != 0)
wrBits += 2;
ra = ARITH_CODER_QH_SCALE - prev;
} else {
if (prev != ARITH_CODER_QH_SCALE)
wrBits += 2;
diff = prev - val;
}
prev = val;
if (ra > 1) {
int gtThanOne = diff > 1;
wrBits[0] = gtThanOne;
wrBits[1] = VAL_RANGE/2;
wrBits += 2;
if (gtThanOne) {
ra -= 1;
diff -= 2;
while (ra > 1) {
unsigned mid = ra / 2;
int ge = diff >= mid;
wrBits[0] = ge;
wrBits[1] = VAL_RANGE/2;
wrBits += 2;
if (ge) {
ra -= mid;
diff -= mid;
} else {
ra = mid;
}
}
}
}
}
return wrBits;
}
static int encode(uint8_t* dst, const uint32_t* context)
{
uint8_t cntrs[258] = {0};
uint8_t prevQh[258];
uint16_t currH[258];
memset(prevQh, ARITH_CODER_QH_SCALE/2, sizeof(prevQh));
const uint64_t MSB_MSK = uint64_t(255) << 56;
const uint64_t MIN_RANGE = uint64_t(1) << (33-RANGE_BITS);
uint64_t lo = 0; // scaled by 2**64
uint64_t range = uint64_t(1) << (64-RANGE_BITS); // scaled by 2**(64-RANGE_BITS)
uint8_t* dst0 = dst;
uint64_t prevLo = lo;
const uint8_t* qh = reinterpret_cast<const uint8_t*>(&context[context[CONTEXT_HDR_QH_OFFSET_I]]);
const uint8_t* src = reinterpret_cast<const uint8_t*>(&context[context[CONTEXT_HDR_SRC_OFFSET_I]]);
const int srclen = context[CONTEXT_HDR_SRC_LEN_I];
unsigned prevC0 = 0;
for (int src_i = 0; src_i < srclen; ++src_i) {
uint16_t bitsBuf[9*9*2];
uint16_t* wrBits = bitsBuf;
unsigned c = src[src_i];
if (c == 255) {
// escape sequence for symbols 255 and 256
c = unsigned(src[src_i+1]) + 1;
++src_i;
}
unsigned tLo = 0, tHi = 256;
do {
unsigned tMid = (tLo*3 + tHi)/4;
unsigned idx = (tMid < 2) & prevC0 ? tMid : tMid + 2; // separate statistics for non-MS characters of zero run
int hVal = VAL_RANGE/2;
int cntr = cntrs[idx];
if (cntr == 0) {
unsigned qhVal = *qh++;
unsigned prevQhVal = prevQh[idx];
prevQh[idx] = qhVal;
wrBits = encodeQh(wrBits, qhVal, prevQhVal);
currH[idx] = qhVal != ARITH_CODER_QH_SCALE ? qh2h_tab[qhVal] : 0;
}
++cntr;
if (cntr == ARITH_CODER_CNT_MAX)
cntr = 0;
cntrs[idx] = cntr;
hVal = currH[idx];
unsigned b = c > tMid;
wrBits[0] = b;
wrBits[1] = hVal;
if (hVal != 0)
wrBits += 2;
tLo = (b == 0) ? tLo : tMid + 1;
tHi = (b == 0) ? tMid : tHi;
} while (tLo != tHi);
prevC0 = (c < 2);
for (uint16_t* rdBits = bitsBuf; rdBits != wrBits; rdBits += 2) {
unsigned b = rdBits[0];
unsigned hVal = rdBits[1];
uint64_t cLo = b == 0 ? 0 : VAL_RANGE - hVal;
uint64_t cRa = b == 0 ? VAL_RANGE - hVal : hVal;
lo += range * cLo;
range = range * cRa;
// at this point range is scaled by 2**64 - the same scale as lo
uint64_t nxtRange = range >> RANGE_BITS;
if (nxtRange <= MIN_RANGE) {
// re-normalize
if (lo < prevLo) // lo overflow
inc_dst(dst); //dst = inc_dst(dst0, dst);
dst[0] = lo >> (64-8*1);
dst[1] = lo >> (64-8*2);
dst[2] = lo >> (64-8*3);
dst += 3;
lo <<= 24;
nxtRange = range << (24-RANGE_BITS);
prevLo = lo;
}
range = nxtRange;
}
}
// output last bits
if (lo < prevLo) // lo overflow
inc_dst(dst); //dst = inc_dst(dst0, dst);
uint64_t hi = lo + ((range<<RANGE_BITS)-1);
if (hi > lo) {
uint64_t dbits = lo ^ hi;
while ((dbits & MSB_MSK)==0) {
// lo and hi have the same upper octet
*dst++ = uint8_t(hi>>56);
hi <<= 8;
dbits <<= 8;
}
// put out last octet
*dst++ = uint8_t(hi>>56);
} else {
inc_dst(dst); //dst = inc_dst(dst0, dst);
}
return dst - dst0;
}
// return value:
// 0 - not compressible, because all input characters have approximately equal probability or because input is too short
// >0 - the length of compressed buffer
int arithmetic_encode(uint32_t* context, uint8_t* dst, int origlen, double* pInfo)
{
int estlen = prepare(context, pInfo);
if (estlen >= origlen)
return 0; // not compressible
int reslen = encode(dst, context);
if (pInfo) {
double modelLenBits = pInfo[1];
pInfo[2] = reslen*8.0 - modelLenBits;
// pInfo[4] = 0;
pInfo[5] = 0;
}
if (reslen >= origlen)
return 0; // not compressible
return reslen;
}
/*
pInfo[0] = entropy;
pInfo[1] = modelLenBits;
pInfo[2] = reslen*8.0 - modelLenBits;;
pInfo[3] = quantizedEntropy;
pInfo[4] = hdrs->a[0].nChunks;
pInfo[5] = hdrs->a[1].nChunks;
*/
|
0fcd1e63fd8b6817c498b2014c16678b074009f1 | 8da9d3c3e769ead17f5ad4a4cba6fb3e84a9e340 | /src/chila/connectionTools/lib/hana/other/CompletionScanner.cpp | 180e527779bfb21b6151a5d993e0a886a60ae091 | [] | no_license | blockspacer/chila | 6884a540fafa73db37f2bf0117410c33044adbcf | b95290725b54696f7cefc1c430582f90542b1dec | refs/heads/master | 2021-06-05T10:22:53.536352 | 2016-08-24T15:07:49 | 2016-08-24T15:07:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,671 | cpp | CompletionScanner.cpp | /* Copyright 2011-2015 Roberto Daniel Gimenez Gamarra (chilabot@gmail.com)
* (C.I.: 1.439.390 - Paraguay)
*/
//#include "CompletionScanner.hpp"
//#include "CScannerGrammar.hpp"
//#include <boost/filesystem.hpp>
//#include <boost/range.hpp>
//
//CHILA_LIB_MISC__DEF_NAMESPACE(4, (chila,connectionTools,lib,other))
//{
// namespace cfLib = chila::flow::lib;
//
// void parseFile(const boost::filesystem::path &file, chila::flow::lib::CompletionList &cList);
//
// chila::flow::lib::CompletionsSPtr CompletionScanner::generate()
// {
// chila::flow::lib::CompletionsSPtr completions = cfLib::Completions::create();
//
// for (const auto &implPath : nspAssoc)
// {
// typedef std::map<std::string, cfLib::CompletionConnectorSPtr> CConnMap;
// CConnMap cConnectors;
//
// boost::filesystem::directory_iterator dirIt(basePath / implPath), dirEnd;
//
// for (const auto &path : boost::make_iterator_range(dirIt, dirEnd))
// if (boost::filesystem::is_regular(path) && (path.extension() == ".hpp" || path.extension() == ".cpp"))
// {
// cfLib::CompletionConnectorSPtr &cConnector = cConnectors[path.stem().string()];
// if (!cConnector) cConnector = cfLib::CompletionConnector::create();
//
// parseFile(path, cConnector->completions());
// }
//
// for (const auto &vt : cConnectors)
// {
// completions->compConnections().add(implPath.name() + "." + vt.first, vt.second);
// }
// }
//
// return completions;
// }
//
//
//
//}}}}
//
|
a9ebeb78123e53a4958e07e6755a7cb5e9227aa3 | 3e57edd4844ce4fd9dff3017aa02cfe50fe238c1 | /practice26.cpp | d8a8bd1e5972630122075ebc9abc0899d584a909 | [] | no_license | cristianoro7/ArithmeticPractice | 5f315604bfb2c72dd459ffaf34a04319b9576a29 | 1e5eae44ac68d8347644274f18200dfa23a73aac | refs/heads/master | 2021-05-10T19:00:39.435390 | 2018-03-07T02:46:31 | 2018-03-07T02:46:31 | 118,140,395 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | practice26.cpp | #include <cstddef>
/**
* 题目: 给定一棵二叉搜索树,在二叉搜索树的基础上,将之转换成有序的双向链表。即,不需要额外的辅助空间。
*/
typedef struct binary_tree_node {
int v;
binary_tree_node *left;
binary_tree_node *right;
} binary_tree_node;
void convert_node(binary_tree_node *root, binary_tree_node **last_node) {
if (root == NULL) {
return;
}
binary_tree_node *current = root;
if (root->left != NULL) {
convert_node(root->left, last_node);
}
current->left = *last_node;
if (*last_node != NULL) {
(*last_node)->right = current;
}
*last_node = current;
if (current->right != NULL) {
convert_node(root->right, last_node);
}
}
binary_tree_node *convert(binary_tree_node *root) {
if (root == NULL) {
return root;
}
binary_tree_node *last_node = NULL;
convert_node(root, &last_node);
binary_tree_node *head = last_node;
while (head != NULL && head->left != NULL) {
head = head->left;
}
return head;
} |
1f496255f00bed60d6febd11f82a68a0ab14b24e | cce447eed4ac66d76e77816296ca2724b88fbe09 | /tutorial2.cc | e7b5c387127f6bb1992a69b65add1f08b70a4917 | [] | no_license | haadimn/pythia-tutorial | 8671b1882ccf08783a5390958ff936e0a78ae240 | 2c9e9e0f08a2a09f22cd20f727675a641c2b578d | refs/heads/master | 2023-07-06T18:21:39.144225 | 2021-08-03T07:38:35 | 2021-08-03T07:38:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cc | tutorial2.cc | #include <iostream>
#include "Pythia8/Pythia.h"
int main()
{
int nevents = 10;
Pythia8::Pythia pythia;
pythia.readString("Beams:idA = 2212");
pythia.readString("Beams:idB = 2212");
pythia.readString("Beams:eCM = 14.e3");
pythia.readString("SoftQCD:all = on");
pythia.readString("HardQCD:all = on");
Pythia8::Hist hpz("Momentum Distribution", 100, -10, 10);
pythia.init();
for(int i = 0; i < nevents; i++)
{
if(!pythia.next()) continue;
int entries = pythia.event.size();
std::cout << "Event: " << i << std::endl;
std::cout << "Event size: " << entries << std::endl;
for(int j = 0; j < entries; j++)
{
int id = pythia.event[j].id();
double m = pythia.event[j].m();
double px = pythia.event[j].px();
double py = pythia.event[j].py();
double pz = pythia.event[j].pz();
double pabs = sqrt(pow(px,2) + pow(py,2) + pow(pz,2));
hpz.fill(pz);
std::cout << id << " " << m << " " << pabs << std::endl;
}
}
std::cout << hpz << std::endl;
Pythia8::HistPlot hpl("tutorial2");
hpl.frame("output", "Momentum Distribution", "Momentum", "Entries");
hpl.add(hpz);
hpl.plot();
return 0;
}
|
5b72c5a19a46d0aae5603fa0f3761a1b390d9441 | 224802d12bf3a2c8426572a4e2fe3f5a09eaa576 | /ROBOT/ROBOT.cpp | d5901edca669b4c4c48e2d061e10fceb097add68 | [] | no_license | docphil209/Robot-Kinematics | 75310b11fda28e65d942a23ae32b32beed376c43 | d7d922febf71a7916d3f4ee306d54e625f493b4e | refs/heads/master | 2020-03-22T04:15:03.759737 | 2018-07-02T19:25:38 | 2018-07-02T19:25:38 | 139,484,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,665 | cpp | ROBOT.cpp | #include "Arduino.h"
#include "ROBOT.h"
#include "encoder.h"
#include <BasicLinearAlgebra.h>
#include <Geometry.h>
#include "SPI.h"
ROBOT::ROBOT(int encPin8, int encPin9, int encPin10)
{
encoder enc8(encPin8),enc9(encPin9),enc10(encPin10); // Instance of the encoder class
// Initialize encoders and zero them
enc8.init();enc9.init(); enc10.init();
enc8.clearCount(); enc9.clearCount(); enc10.clearCount();
}
Rotation ROBOT::ROTATION_MATRIX(float ROT_X,float ROT_Y,float ROT_Z)
{
//Computes the rotation matrix for each of the joints based on the endocder measurements. Referenced page 132 of notebook.
Transformation ROT;
//Compute the matrix
ROT.R.FromEulerAngles(ROT_X,ROT_Y,ROT_Z);
return ROT.R;
}
Point ROBOT::FORWARD_KINEMATICS(Transformation H01,Transformation H12, Transformation H23, Point P3)
{
//Computes the forward kinematics to find the POI with respect to the base coordinate system
Point result;
result=(H01.p+H01.R*(H12.p+H12.R*(H23.p+H23.R*P3)));
return result;
}
Point ROBOT::CS_ORIGINS(float x, float y, float z)
{
// Builds the "point" object from coordinates
Point result;
// Coordinates of point
result.X()=x;
result.Y()=y;
result.Z()=z;
// Define transformation matricees
return result;
}
void ROBOT::PRINT_ANGLE(float THETA_1,float THETA_2,float THETA_3){
//Prints the angle of each of the encoders in radians
Serial.print("Encoder 8, 9, and 10 angles (Rad) = ");
Serial.print(THETA_1); Serial.print(", ");
Serial.print(THETA_2); Serial.print(", ");
Serial.print(THETA_3); Serial.print(' ');
} |
7c48245db23fcbebd0093e770279498cf0c8e616 | 91e4ac1da8f8258f7c5629a69a7887102d4e3c62 | /src/BQos/ascii_defs.hpp | ea94f7b9a7de6cabf1748c6f6b77b9c3599e9388 | [] | no_license | mapengfei53/BQos | 0eecf52f5d5636de0f27b71d0af219a657b60ff0 | a07ff5b86efd5511504b997577e9c4e2ab7ec255 | refs/heads/master | 2022-03-31T10:49:09.424944 | 2020-01-01T03:01:26 | 2020-01-01T03:01:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | hpp | ascii_defs.hpp | /*
* ascii_defs.hpp
*
* Created on: Dec 27, 2019
* Author: badquanta
*/
#ifndef SRC_BQOS_ASCII_DEFS_HPP_
#define SRC_BQOS_ASCII_DEFS_HPP_
/**
* @brief These defines simply name various ASCII control character values.
*/
#define ASCII_NUL 0x00
#define ASCII_StartOfHeading 0x01
#define ASCII_StartOfText 0x02
#define ASCII_EndOfText 0x03
#define ASCII_EndOfTransmission 0x04
#define ASCII_Enquiry 0x05
#define ASCII_Acknowledge 0x06
#define ASCII_Bell 0x07
#define ASCII_Backspace 0x08
#define ASCII_H_Tabulation 0x09
#define ASCII_LineFeed 0x0A
#define ASCII_V_Tabulation 0x0B
#define ASCII_FormFeed 0x0C
#define ASCII_CarriageReturn 0x0D
#define ASCII_ShiftOut 0x0E
#define ASCII_ShiftIn 0x0F
#define ASCII_DataLinkEscape 0x10
#define ASCII_DeviceControl1 0x11
#define ASCII_DeviceControl2 0x12
#define ASCII_DeviceControl3 0x13
#define ASCII_DeviceControl4 0x14
#define ASCII_NegativeAcknowledge 0x15
#define ASCII_SynchronousIdle 0x16
#define ASCII_EndOfTransmissionBlock 0x17
#define ASCII_Cancel 0x18
#define ASCII_EndOfMedium 0x19
#define ASCII_Substitute 0x1A
#define ASCII_Escape 0x1B
#define ASCII_FileSeparator 0x1C
#define ASCII_GroupSeparator 0x1D
#define ASCII_RecordSeparator 0x1E
#define ASCII_UnitSeparator 0x1F
#define ASCII_Delete 0x7F
#endif /* SRC_BQOS_ASCII_DEFS_HPP_ */
|
0aa80f9adbc886aa32cca8b68ae43134f1f9b99a | 81495b25f46059b55f2576a5bdcf51bbfe57f859 | /result/ListServicesResult.cpp | 650de6f0938cd825a670b637769e10c1bf47392b | [
"CC-BY-4.0"
] | permissive | chaytanyasinha/gwadoc | fae2699271497383f318da34684e91d159432fc9 | 403a226aa7e8dc32fa2d00a016c679f9bdddb990 | refs/heads/master | 2022-12-02T11:37:29.569481 | 2020-07-31T12:11:00 | 2020-07-31T12:11:00 | 270,653,667 | 0 | 0 | CC-BY-4.0 | 2020-06-08T12:07:10 | 2020-06-08T12:07:10 | null | UTF-8 | C++ | false | false | 373 | cpp | ListServicesResult.cpp | #include <ListServicesResult.h>
namespace Nacos
{
int ListServicesResult::getCount() const
{
return Count;
}
void ListServicesResult::setCount(int value)
{
Count = value;
}
std::vector<std::wstring> ListServicesResult::getDoms() const
{
return Doms;
}
void ListServicesResult::setDoms(const std::vector<std::wstring> &value)
{
Doms = value;
}
}
|
1b5a2f4c5f0ff4c2dbca65fd63b386ea87607c6d | 2328a8996bcf01625789d4ab277fa4e68573254d | /config.h | cefe61d2d620fbc731c87b465bb0e12f8eb8a865 | [
"MIT"
] | permissive | caseif/dbo-get | 7d1caf988c3a677ab05ad3d74fbc15375e788444 | d82072d34c113ed1e112261a374d156fd840803a | refs/heads/master | 2020-07-10T21:03:34.216573 | 2017-02-15T04:26:03 | 2017-02-15T04:26:03 | 67,659,744 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | h | config.h | #pragma once
#include <map>
#include <string>
class Config {
private:
std::map<std::string, std::string> configMap;
void load();
void save();
public:
Config();
Config(Config const&) = delete;
void operator = (Config const&) = delete;
static Config& getInstance();
const static std::string KEY_STORE;
std::string* get(std::string key);
void set(std::string key, std::string value);
};
|
28ece80351975037b9666be46d8afa2c3227f585 | b5ee7131ce7fc906accf761fbded47737e51b274 | /BetterMUD/BetterMUD/entities/Action.cpp | 98466e24034cd579a3ad9994ef657d2d868495a6 | [] | no_license | JeffM2501/bettermud | 1116072276ba029e1d5cd17c6b760e6da4e0c9b6 | 3d8ac9f22c8c7b7f383bf0399828f46602dfe519 | refs/heads/master | 2021-07-16T09:14:30.507875 | 2021-03-28T20:52:08 | 2021-03-28T20:52:08 | 90,657,600 | 0 | 0 | null | 2017-05-08T18:01:51 | 2017-05-08T18:01:51 | null | UTF-8 | C++ | false | false | 5,694 | cpp | Action.cpp | // MUD Programming
// Ron Penton
// (C)2003
// Action.cpp - This file contains the Action type for BetterMUD.
//
//
#include "Action.h"
#include "../accessors/Accessors.h"
namespace BetterMUD
{
void TimedAction::Hook()
{
if( actionevent.actiontype == "attemptsay" ||
actionevent.actiontype == "command" ||
actionevent.actiontype == "attemptenterportal" ||
actionevent.actiontype == "attempttransport" ||
actionevent.actiontype == "transport" ||
actionevent.actiontype == "destroycharacter" )
{
character( actionevent.data1 ).AddHook( this );
}
else if( actionevent.actiontype == "attemptgetitem" ||
actionevent.actiontype == "attemptdropitem" )
{
character( actionevent.data1 ).AddHook( this );
item( actionevent.data2 ).AddHook( this );
}
else if( actionevent.actiontype == "attemptgiveitem" )
{
character( actionevent.data1 ).AddHook( this );
character( actionevent.data2 ).AddHook( this );
item( actionevent.data3 ).AddHook( this );
}
else if( actionevent.actiontype == "destroyitem" )
{
item( actionevent.data1 ).AddHook( this );
}
else if( actionevent.actiontype == "messagelogic" ||
actionevent.actiontype == "dellogic" ||
actionevent.actiontype == "do" ||
actionevent.actiontype == "modifyattribute" )
{
switch( actionevent.data1 )
{
case CHARACTER:
character( actionevent.data2 ).AddHook( this );
break;
case ITEM:
item( actionevent.data2 ).AddHook( this );
break;
case ROOM:
room( actionevent.data2 ).AddHook( this );
break;
case PORTAL:
portal( actionevent.data2 ).AddHook( this );
break;
case REGION:
region( actionevent.data2 ).AddHook( this );
break;
}
}
}
void TimedAction::Unhook()
{
valid = false;
if( actionevent.actiontype == "attemptsay" ||
actionevent.actiontype == "command" ||
actionevent.actiontype == "attemptenterportal" ||
actionevent.actiontype == "attempttransport" ||
actionevent.actiontype == "transport" ||
actionevent.actiontype == "destroycharacter" )
{
character( actionevent.data1 ).DelHook( this );
}
else if( actionevent.actiontype == "attemptgetitem" ||
actionevent.actiontype == "attemptdropitem" )
{
character( actionevent.data1 ).DelHook( this );
item( actionevent.data2 ).DelHook( this );
}
else if( actionevent.actiontype == "attemptgiveitem" )
{
character( actionevent.data1 ).DelHook( this );
character( actionevent.data2 ).DelHook( this );
item( actionevent.data3 ).DelHook( this );
}
else if( actionevent.actiontype == "destroyitem" )
{
item( actionevent.data1 ).DelHook( this );
}
else if( actionevent.actiontype == "messagelogic" ||
actionevent.actiontype == "dellogic" ||
actionevent.actiontype == "do" ||
actionevent.actiontype == "modifyattribute" )
{
switch( actionevent.data1 )
{
case CHARACTER:
character( actionevent.data2 ).DelHook( this );
break;
case ITEM:
item( actionevent.data2 ).DelHook( this );
break;
case ROOM:
room( actionevent.data2 ).DelHook( this );
break;
case PORTAL:
portal( actionevent.data2 ).DelHook( this );
break;
case REGION:
region( actionevent.data2 ).DelHook( this );
break;
}
}
}
void TimedAction::Save( std::ofstream& p_stream )
{
if( !valid )
return;
p_stream << "[TIMER]\n";
p_stream << " [TIME] ";
BasicLib::insert( p_stream, executiontime );
p_stream << "\n [NAME] " << actionevent.actiontype << "\n";
p_stream << " [DATA1] " << actionevent.data1 << "\n";
p_stream << " [DATA2] " << actionevent.data2 << "\n";
p_stream << " [DATA3] " << actionevent.data3 << "\n";
p_stream << " [DATA4] " << actionevent.data4 << "\n";
// set the string data to "0", so that SOMETHING is written out to disk.
// writing nothing would be a disaster, because the load function assumes
// that something is there (whitespace... blah!).
// note that this is acceptible because if the parameter is "", then
// it is assumed to be unused anyway, so saving and loading a "0" will
// make it ignored
if( actionevent.stringdata == "" )
actionevent.stringdata = "0";
p_stream << " [STRING] " << actionevent.stringdata << "\n";
p_stream << "[/TIMER]\n";
}
void TimedAction::Load( std::ifstream& p_stream )
{
std::string temp;
p_stream >> temp >> temp; // "[TIMER]" and "[TIME]"
BasicLib::extract( p_stream, executiontime );
p_stream >> temp >> std::ws;
std::getline( p_stream, actionevent.actiontype );
p_stream >> temp >> actionevent.data1;
p_stream >> temp >> actionevent.data2;
p_stream >> temp >> actionevent.data3;
p_stream >> temp >> actionevent.data4;
p_stream >> temp >> std::ws;
std::getline( p_stream, actionevent.stringdata );
p_stream >> temp;
}
} // end namespace BetterMUD
|
066792c6ac088161a17021c27aae888fa663ed0e | 4460a247e28bbf46ad73b0a12c03c56a9f517871 | /partc3/Part 3/Chapter 2/part3_ch2_prob6.cpp | fba69733c1c60d8ee372e74e87ea1947da388632 | [] | no_license | kimyir111/kimyir | 484139b89fd5827c22299cac31e3c0ba86881576 | 842eb6215449d9ce88355adbf4b94947f460ffb8 | refs/heads/master | 2023-03-12T20:45:48.496439 | 2021-02-27T06:07:45 | 2021-02-27T06:07:45 | 260,115,349 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 449 | cpp | part3_ch2_prob6.cpp | #include <stdio.h>
#include <string.h>
int main () {
char str[32] = "";
int i = 0;
int transGap = 'a' - 'A';
printf("Enter string: ");
scanf("%s", str);
printf("Length of string : %d\n", strlen(str));
for (i = 0; i < strlen(str); i++) {
if (str[i] >= 'a' && str[i] <= 'z') str[i] -= transGap;
else if (str[i] >= 'A' && str[i] <= 'Z') str[i] += transGap;
}
printf("Result string : %s\n", str);
return 0;
}
|
fa7932969c30824a50efd4c6db8ba94570dd54c4 | 2891cee60e3ad5d74824791642edeecebdc6ef2a | /client/main.cpp | e96d022580c4648fb2a96457fdf610dcbd51476b | [] | no_license | garretraziel/icp | 647d63e58b3501b787d07541710fb46ecae2f8dc | d834eabc7ca6643b1820877863b432d7fc18a021 | refs/heads/master | 2016-09-06T17:07:06.397805 | 2012-05-07T16:46:46 | 2012-05-07T16:46:46 | 3,975,350 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 555 | cpp | main.cpp | /**
* @file main.cpp
* @author Lukas Brabec <xbrabe09@stud.fit.vutbr.cz>
* @author Jan Sedlak <xsedla85@stud.fit.vutbr.cz>
* @version 1.0
*
* @section DESCRIPTION
*
* Hlavni funkce programu, a event handling na strane klienta
*
*/
#include <QtGui/QApplication>
#include "mainwindow.h"
/**
* Main funkce programu
* @param argc pocet argumentu
* @param vektor argumentu
* @return return code progamu
*/
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
|
8141c9106f76c95069b4baefd756e4cf8a440be8 | bd4e9485575db9b7ee883680f88ff42c6c0d5cc6 | /PluginTileoverlay/qgeotiledmap_test.cpp | 7f8a7852dd0489c8f99071aa5162aa054fb63af8 | [] | no_license | paoletto/LocationXamples | dee979d6315d6ec13c04c257850b2301b447dc0d | b490805941d15cfa54fb987ebb71605a7f76fa69 | refs/heads/master | 2021-01-18T13:07:53.132138 | 2018-08-20T16:53:42 | 2018-08-20T16:53:42 | 80,720,891 | 5 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,306 | cpp | qgeotiledmap_test.cpp | /****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qgeotiledmap_test.h"
#include <QtLocation/private/qgeotiledmap_p_p.h>
#include <QtLocation/private/qgeomapparameter_p.h>
QT_BEGIN_NAMESPACE
class QGeoTiledMapTestPrivate: public QGeoTiledMapPrivate
{
Q_DECLARE_PUBLIC(QGeoTiledMapTest)
public:
QGeoTiledMapTestPrivate(QGeoTiledMappingManagerEngine *engine)
: QGeoTiledMapPrivate(engine)
{
}
~QGeoTiledMapTestPrivate()
{
}
void addParameter(QGeoMapParameter *param) override
{
Q_Q(QGeoTiledMapTest);
if (param->type() == QStringLiteral("cameraCenter_test")) {
// We assume that cameraCenter_test parameters have a QGeoCoordinate property named "center"
// Handle the parameter
QGeoCameraData cameraData = m_cameraData;
QGeoCoordinate newCenter = param->property("center").value<QGeoCoordinate>();
cameraData.setCenter(newCenter);
q->setCameraData(cameraData);
// Connect for further changes handling
q->connect(param, SIGNAL(propertyUpdated(QGeoMapParameter *, const char *)),
q, SLOT(onCameraCenter_testChanged(QGeoMapParameter*, const char*)));
}
}
void removeParameter(QGeoMapParameter *param) override
{
Q_Q(QGeoTiledMapTest);
param->disconnect(q);
}
};
QGeoTiledMapTest::QGeoTiledMapTest(QGeoTiledMappingManagerEngine *engine, QObject *parent)
: QGeoTiledMap(*new QGeoTiledMapTestPrivate(engine), engine, parent), m_engine(engine)
{
}
void QGeoTiledMapTest::onCameraCenter_testChanged(QGeoMapParameter *param, const char *propertyName)
{
Q_D(QGeoTiledMapTest);
if (strcmp(propertyName, "center") == 0) {
QGeoCameraData cameraData = d->m_cameraData;
// Not testing for propertyName as this param has only one allowed property
QGeoCoordinate newCenter = param->property(propertyName).value<QGeoCoordinate>();
cameraData.setCenter(newCenter);
setCameraData(cameraData);
}
}
QT_END_NAMESPACE
|
f632e2eaf7a2fd9c8302c2a609d5c99255bf3b89 | 61d3d7864aadf9686bf8b67a6a52c6ce6218a32e | /A. Helpful Maths.cpp | 8dc342a8158a680cfdaeefa3d3408947b89dcc48 | [] | no_license | jonckjunior/Codeforce | c47dc45f0cfa7217d7ab713a39a6be107b7bc3ec | b49a6914fc57bbdd947f15906926d501672cd93e | refs/heads/master | 2021-09-11T23:31:58.115876 | 2018-04-13T01:23:08 | 2018-04-13T01:23:08 | 114,308,537 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | cpp | A. Helpful Maths.cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
string s; cin >> s;
for(int i = 0; i < s.size(); i++)
s[i] = (s[i] == '+' ? ' ' : s[i]);
istringstream iss(s);
vector<int> v;
while(iss >> s){
v.push_back(stoi(s));
}
sort(v.begin(), v.end());
for(int i = 0; i < v.size(); i++){
if(i+1 == v.size())
printf("%d\n", v[i]);
else
printf("%d+", v[i]);
}
return 0;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.