blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1004b63ada7fa3a1789bd709b3ef9eee444c007f | 6ad4557321bf8e3fddb06501382b8af02b92e7e4 | /ARA/reconstruction3.cpp | aa7de6d17dfbed9d83de5651849eebd88e8a1388 | [] | no_license | RomLei/EC-RSF | e21ba198774f4c518f579b5313c40adb45c091a3 | aca0e5dc4818c23a93ab1d81bef293b0a5d45c7d | refs/heads/master | 2020-07-11T08:24:36.489384 | 2019-08-26T14:09:08 | 2019-08-26T14:14:34 | 204,488,970 | 1 | 1 | null | null | null | null | GB18030 | C++ | false | false | 296 | cpp | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<iostream>
#include<iomanip>
#include<vector>
#include"ARA.h"
using namespace std;
bool reconstruction3(vector<node> &rnode, vector<vector<int>> &G, vector<vector<int>> &Gbackup)//对剩余的节点进行完全重建
{
return true;
} | [
"ronglei1994@126.com"
] | ronglei1994@126.com |
d5dbbde70832c05ac77cb0ad6df6708744168394 | 8e8f31a13efeb173bea12c3a4e674cc80a92f20b | /victor/catkin_ws/src/camera/src/listener3.cpp | 9445a580d9529b8093324d198d652c19c1b38aa4 | [] | no_license | emotionrobots/students | a2a7e31cb082de04be4d94c0cc1f852bf7409583 | f4e70117236bccb8b13091c8395348b575cb36e6 | refs/heads/master | 2021-09-27T08:16:13.793474 | 2018-08-05T20:29:10 | 2018-08-05T20:29:10 | 67,504,742 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,231 | cpp | #include <iostream>
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <pcl_conversions/pcl_conversions.h>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <fstream>
#define mp make_pair
#define pb push_back
using namespace std;
using namespace pcl;
using namespace sensor_msgs;
using namespace cv;
const int HEIGHT = 480, WIDTH = 640;
Point3d xyz[480][640];
Mat src(HEIGHT, WIDTH, CV_8UC3);
bool hasRead = false;
vector<Point> corners;
bool cmp(const Point& p1, const Point& p2) {
return p1.x == p2.x ? p1.y < p2.y : p1.x < p2.x;
}
void call_back(const sensor_msgs::PointCloud2ConstPtr& cloud) {
pcl::PointCloud<pcl::PointXYZRGB> PointCloudXYZRGB;
pcl::fromROSMsg(*cloud, PointCloudXYZRGB);
int max_i = cloud->height * cloud->width;
for (int i = 0; i < max_i; i++) {
int r = i / cloud->width, c = i % cloud->width;
PointXYZRGB p = PointCloudXYZRGB.points[i];
float z = p.z;
xyz[r][c] = Point3d(p.x, -p.y, p.z);
src.at<Vec3b>(Point(c, r)) = Vec3b(p.b, p.g, p.r);
}
hasRead = true;
}
void read() {
hasRead = false;
while (!hasRead) {
ros::spinOnce();
}
}
void show() {
for (int i = 0; i < corners.size(); i++) {
// cout << '(' << corners[i].first << ", " << corners[i].second << ')' << endl;
circle(src, Point(corners[i].x, corners[i].y), 5, Scalar(0, 0, 255), -1);
}
imshow("show1", src);
}
void compress_lines(vector<Vec2f>& lines) {
vector<double> weights(lines.size(), 1);
for (int i = 0; i < lines.size(); i++) {
double total_r = lines[i][0], total_a = lines[i][1];
for (int j = lines.size() - 1; j > i; j--) {
double diff_a = abs(lines[i][1] - lines[j][1]);
if (abs(lines[i][0] - lines[j][0]) < 50) {
if (diff_a < .2) {
total_r += lines[j][0];
total_a += lines[j][1];
weights[i] += weights[j];
lines.erase(lines.begin() + j);
} else if (diff_a > CV_PI - .2) {
total_r += lines[j][0];
total_a += lines[j][1] > CV_PI / 2 ? lines[j][1] - CV_PI : lines[j][1];
weights[i] += weights[j];
lines.erase(lines.begin() + j);
}
}
}
lines[i][0] = total_r / weights[i];
lines[i][1] = total_a / weights[i];
if (lines[i][1] < 0) lines[i][1] += CV_PI;
}
}
vector<Point> inter(const vector<Vec2f>& lines) {
vector<Point> points;
for (int i = 0; i < lines.size(); i++) {
double r1 = lines[i][0], a1 = lines[i][1];
// cout << r1 << ' ' << a1 << endl;
for (int j = i + 1; j < lines.size(); j++) {
double r2 = lines[j][0], a2 = lines[j][1];
double x = (r1 / sin(a1) - r2 / sin(a2)) / (cos(a1) / sin(a1) - cos(a2) / sin(a2));
double y = (-cos(a1) / sin(a1)) * x + r1 / sin(a1);
if (-1 < x && x < 640 && -1 < y && y < 480 && abs(a1 - a2) > .2 && abs(a1 - a2) < CV_PI - .2) {
points.pb(Point(x, y));
}
}
}
return points;
}
Point3d trans(const Point3d& p, double h, double a, double d) {
double x1 = p.x, y1 = p.y, z1 = p.z;
double x2 = x1, y2 = y1*sin(a) - z1*cos(a) + h, z2 = y1*cos(a) + z1*sin(a);
double x3 = d - z2, y3 = x2, z3 = y2;
return Point3d(x3, y3, z3);
}
vector<Point> compress_points(const vector<Point>& points) {
vector<pair<pair<double, double>, int>> cluster;
for (int i = 0; i < points.size(); i++) {
cluster.pb(mp(mp(points[i].x, points[i].y), 1));
}
while (cluster.size() > 4) {
int i1 = 0, i2 = 1;
pair<double, double> c1 = cluster[0].first, c2 = cluster[1].first;
double dist = hypot(c1.first - c2.first, c1.second - c2.second);
for (int i = 0; i < cluster.size(); i++) {
pair<double, double> c3 = cluster[i].first;
for (int j = i + 1; j < cluster.size(); j++) {
pair<double, double> c4 = cluster[j].first;
double dist2 = hypot(c3.first - c4.first, c3.second - c4.second);
if (dist2 < dist) {
c1 = c3;
c2 = c4;
dist = dist2;
i1 = i;
i2 = j;
}
}
}
double xsum1 = cluster[i1].first.first * cluster[i1].second;
double ysum1 = cluster[i1].first.second * cluster[i1].second;
double xsum2 = cluster[i2].first.first * cluster[i2].second;
double ysum2 = cluster[i2].first.second * cluster[i2].second;
int total = cluster[i1].second + cluster[i2].second;
cluster.erase(cluster.begin() + i2);
cluster.erase(cluster.begin() + i1);
cluster.pb(mp(mp((xsum1 + xsum2) / total, (ysum1 + ysum2) / total), total));
}
vector<Point> points2;
for (int i = 0; i < cluster.size(); i++) {
points2.pb(Point(cvRound(cluster[i].first.first), cluster[i].first.second));
}
return points2;
}
bool get_corners() {
Mat dst, cdst;
Canny(src, dst, 150, 450, 3);
cvtColor(dst, cdst, CV_GRAY2BGR);
// cout << "d1" << endl;
vector<Vec2f> lines;
HoughLines(dst, lines, 1, CV_PI/180, 65, 0, 0 );
// cout << "lines " << lines.size() << endl;
compress_lines(lines);
cout << "lines " << lines.size() << endl;
for (int i = 0; i < lines.size(); i++) {
float rho = lines[i][0], theta = lines[i][1];
Point pt1, pt2;
double a = cos(theta), b = sin(theta);
double x0 = a*rho, y0 = b*rho;
pt1.x = cvRound(x0 + 1000*(-b));
pt1.y = cvRound(y0 + 1000*(a));
pt2.x = cvRound(x0 - 1000*(-b));
pt2.y = cvRound(y0 - 1000*(a));
line(cdst, pt1, pt2, Scalar(0,0,255), 3, CV_AA);
}
if (lines.size() > 100) return false;
/*
23
14
*/
vector<Point> points = inter(lines);
corners = compress_points(points);
sort(corners.begin(), corners.end(), cmp);
for (int i = 0; i < corners.size(); i++) {
Point p = corners[i];
cout << p.x << ' ' << p.y << endl;
cout << xyz[p.y][p.x].x << ' ' << xyz[p.y][p.x].y << ' ' << xyz[p.y][p.x].z << endl;
}
cout << "----------------------------" << endl;
imshow("show1", dst);
if (waitKey(700) != -1) exit(0);
imshow("show1", cdst);
if (waitKey(700) != -1) exit(0);
return true;
}
int main(int argc, char** argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Rate loop_rate(30);
ros::Subscriber sub;
sub = n.subscribe("/camera/depth_registered/points", 1, call_back);
namedWindow("show1", CV_WINDOW_AUTOSIZE);
//
while (true) {
// cout << 'a' << endl;
// src = imread(argv[1], 0);
// cout << 'b' << endl;
do {
read();
} while (!get_corners());
// cout << 'c' << endl;
show();
// cout << 'd' << endl;
if (waitKey(700) != -1) break;
}
return 0;
}m | [
"larrylisky@gmail.com"
] | larrylisky@gmail.com |
91f68a3b383a6f6f28dd62bf0a07442cf062890e | 0fc70d8a4494e8e3ac7e41874119a79c5e99e255 | /pthread_handle.h | a68ca938ecefa23e1509b9df50225100e426e2fe | [] | no_license | zrj12345/jpush_server | 420f6b1e6fa4a077e9ae04547ed5954fa7ed32df | 5706fdcbdf8c1ad96dcd36f27cc17f1d50cb2bd7 | refs/heads/master | 2021-01-18T15:08:25.305221 | 2015-12-23T22:51:05 | 2015-12-23T22:51:05 | 48,404,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 808 | h | #ifndef _PTHREAD_HANDLE_H_
#define _PTHREAD_HANDLE_H_
#include "files.h"
#include "DbPool.h"
#include "redisclient.h"
#include <pthread.h>
#include <list>
typedef void *(*event_deal)(void *arg);
class pthread_handle{
public:
struct func_arg{
event_deal func_pointer;
void* arg;
};
~pthread_handle();
pthread_handle(int thread_num = 4):max_thread_num(thread_num){};
void pool_event_init(int thread_num);
int thread_run();
int pool_destroy();
int pool_event_add(event_deal func,void *arg);
static void* thread_event(void *arg);
private:
pthread_cond_t queue_ready;
pthread_mutex_t queue_lock;
list<func_arg> event_list;
void *event_arg;
pthread_t *threadid;
int max_thread_num;
bool shutdown;
};
#endif | [
"qzhangrongjie@163.com"
] | qzhangrongjie@163.com |
de2128505fdf7482d22b08480974dfaa79438a1c | fdc302e4f54a71616d29636abb6957a1ae4e1e5a | /lab3/dog.cpp | fc91912d8388a5a0818f71e20ef0a85f41aa7300 | [] | no_license | SVerma19/Cplusplus | c45268f55d4f6a2a05a9163c5bc1dfe430258dbc | 2f3eaa378a9bc008164c62e7df3b16490297d0ae | refs/heads/master | 2022-06-26T14:42:30.868639 | 2020-05-11T18:42:09 | 2020-05-11T18:42:09 | 263,125,455 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 234 | cpp | #include "dog.h"
Dog::Dog(string name_) : Animal(name_) {}
void Dog::makesSound() {
cout << "BARK!" << endl;
}
string Dog::getName() {
return name;
}
Dog::~Dog() {
cout << "freeing (the memory space for) a Dog. " << endl;
}
| [
"noreply@github.com"
] | SVerma19.noreply@github.com |
1c95ced8c73a9e5ce36ad751756740a5b4182775 | 213e10692025d34aad0b16aea2a52ee58f378b7d | /Atcoder/BC188/A.cpp | 1dcc201f08db5c580043bd86b6b91a97417d1724 | [] | no_license | arealdeadone/contests | 348de137916b56abcd3c0a4eb79f7ea838ac74f3 | fb78c0cf97a78f8a651fd66749ba0847a988df98 | refs/heads/master | 2023-03-08T07:36:56.415616 | 2021-02-20T02:50:58 | 2021-02-20T02:50:58 | 340,546,203 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,000 | cpp | #include <bits/stdc++.h>
using namespace std;
// template {{{
#define pb push_back
#define eb emplace_back
#define mp make_pair
#define mt make_tuple
#define lb lower_bound
#define ub upper_bound
#define f first
#define s second
#define resz resize
#define sz(x) int((x).size())
#define all(x) (x).begin(), (x).end()
#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) for (int i = 0; i < (a); i++)
#define FORd(i, a, b) for (int i = (b)-1; i >= (a); i--)
#define F0Rd(i, a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)
#define sort_by(x, y) sort(all(x), [&](const auto& a, const auto& b) { return y; })
using ll = long long;
using llu = unsigned long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using vb = vector<bool>;
using vd = vector<double>;
using vs = vector<string>;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using pdd = pair<double, double>;
using vpii = vector<pii>;
using vpll = vector<pll>;
using vpdd = vector<pdd>;
template<typename T> void ckmin(T& a, const T& b) { a = min(a, b); }
template<typename T> void ckmax(T& a, const T& b) { a = max(a, b); }
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count());
namespace __input {
template<class T1, class T2> void re(pair<T1,T2>& p);
template<class T> void re(vector<T>& a);
template<class T, size_t SZ> void re(array<T,SZ>& a);
template<class T> void re(T& x) { cin >> x; }
void re(double& x) { string t; re(t); x = stod(t); }
template<class Arg, class... Args> void re(Arg& first, Args&... rest) {
re(first); re(rest...);
}
template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}
using namespace __input;
namespace __output {
template<class T1, class T2> void pr(const pair<T1,T2>& x);
template<class T, size_t SZ> void pr(const array<T,SZ>& x);
template<class T> void pr(const vector<T>& x);
template<class T> void pr(const set<T>& x);
template<class T1, class T2> void pr(const map<T1,T2>& x);
template<class T> void pr(const T& x) { cout << x; }
template<class Arg, class... Args> void pr(const Arg& first, const Args&... rest) {
pr(first); pr(rest...);
}
template<class T1, class T2> void pr(const pair<T1,T2>& x) {
pr("{",x.f,", ",x.s,"}");
}
#ifdef RACHURI_LOCAL
template<class T, bool pretty = true> void prContain(const T& x) {
if (pretty) pr("{");
bool fst = 1; for (const auto& a: x) pr(!fst?pretty?", ":" ":"",a), fst = 0;
if (pretty) pr("}");
}
#else
template<class T, bool pretty = false> void prContain(const T& x) {
if (pretty) pr("{");
bool fst = 1; for (const auto& a: x) pr(!fst?pretty?", ":" ":"",a), fst = 0;
if (pretty) pr("}");
}
#endif
template<class T> void pc(const T& x) { prContain<T, false>(x); pr("\n"); }
template<class T, size_t SZ> void pr(const array<T,SZ>& x) { prContain(x); }
template<class T> void pr(const vector<T>& x) { prContain(x); }
template<class T> void pr(const set<T>& x) { prContain(x); }
template<class T1, class T2> void pr(const map<T1,T2>& x) { prContain(x); }
void ps() { pr("\n"); }
template<class Arg> void ps(const Arg& first) {
pr(first); ps();
}
template<class Arg, class... Args> void ps(const Arg& first, const Args&... rest) {
pr(first," "); ps(rest...);
}
}
using namespace __output;
#define TRACE(x) x
#define __pn(x) pr(#x, " = ")
#ifdef RACHURI_LOCAL
#define pd(...) __pn((__VA_ARGS__)), ps(__VA_ARGS__), cout << flush
#else
#define pd(...)
#endif
namespace __algorithm {
template<typename T> void dedup(vector<T>& v) {
sort(all(v)); v.erase(unique(all(v)), v.end());
}
template<typename T> typename vector<T>::const_iterator find(const vector<T>& v, const T& x) {
auto it = lower_bound(all(v), x); return it != v.end() && *it == x ? it : v.end();
}
template<typename T> size_t index(const vector<T>& v, const T& x) {
auto it = find(v, x); assert(it != v.end()); return it - v.begin();
}
}
using namespace __algorithm;
namespace __io {
FILE* setIn(string s) { return freopen(s.c_str(),"r",stdin); }
FILE* setOut(string s) { return freopen(s.c_str(),"w",stdout); }
void setIO(string s = "") {
ios_base::sync_with_stdio(0); cin.tie(0);
cout << setprecision(15);
if (sz(s)) { setIn(s+".in"), setOut(s+".out"); }
}
}
using namespace __io;
// }}}
int main() {
setIO();
int x,y;
re(x); re(y);
int ms = min(x,y);
int ma = int x,y;
re(x); re(y);
int ms = min(x,y);
int ma = max(x,y);
if(ms+3 > ma) ps("Yes");
else ps("No");max(x,y);
if(ms+3 > ma) ps("Yes");
else ps("No");
return 0;
}
| [
"Arvind_Rachuri@Dell.com"
] | Arvind_Rachuri@Dell.com |
a2a39e41c3b13e548d5919b5d01430c4002017d9 | 3b74df8a933fbcb3ee3f7a2202aacdc240b939b7 | /libraries/fc/vendor/websocketpp/websocketpp/transport/asio/security/none.hpp | 2dde03a59962371243c8f73377fd98f299e0f967 | [
"Zlib",
"BSD-3-Clause",
"MIT"
] | permissive | techsharesteam/techshares | 746111254c29d18376ddaddedcb6b3b66aa085ec | 47c58630a578204147057b7504e571e19546444f | refs/heads/master | 2021-01-21T14:43:23.261812 | 2017-04-23T13:03:31 | 2017-04-23T13:03:31 | 58,311,014 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,688 | hpp | /*
* Copyright (c) 2015, Peter Thorson. 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.
* * Neither the name of the WebSocket++ Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL PETER THORSON 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 WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#define WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
#include <websocketpp/uri.hpp>
#include <websocketpp/transport/asio/security/base.hpp>
#include <websocketpp/common/asio.hpp>
#include <websocketpp/common/memory.hpp>
#include <sstream>
#include <string>
namespace websocketpp {
namespace transport {
namespace asio {
/// A socket policy for the asio transport that implements a plain, unencrypted
/// socket
namespace basic_socket {
/// The signature of the socket init handler for this socket policy
typedef lib::function<void(connection_hdl,lib::asio::ip::tcp::socket&)>
socket_init_handler;
/// Basic Asio connection socket component
/**
* transport::asio::basic_socket::connection implements a connection socket
* component using Asio ip::tcp::socket.
*/
class connection : public lib::enable_shared_from_this<connection> {
public:
/// Type of this connection socket component
typedef connection type;
/// Type of a shared pointer to this connection socket component
typedef lib::shared_ptr<type> ptr;
/// Type of a pointer to the Asio io_service being used
typedef lib::asio::io_service* io_service_ptr;
/// Type of a pointer to the Asio io_service strand being used
typedef lib::shared_ptr<lib::asio::io_service::strand> strand_ptr;
/// Type of the ASIO socket being used
typedef lib::asio::ip::tcp::socket socket_type;
/// Type of a shared pointer to the socket being used.
typedef lib::shared_ptr<socket_type> socket_ptr;
explicit connection() : m_state(UNINITIALIZED) {
//std::cout << "transport::asio::basic_socket::connection constructor"
// << std::endl;
}
/// Get a shared pointer to this component
ptr get_shared() {
return shared_from_this();
}
/// Check whether or not this connection is secure
/**
* @return Whether or not this connection is secure
*/
bool is_secure() const {
return false;
}
/// Set the socket initialization handler
/**
* The socket initialization handler is called after the socket object is
* created but before it is used. This gives the application a chance to
* set any Asio socket options it needs.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_socket() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally.
*/
lib::asio::ip::tcp::socket & get_next_layer() {
return *m_socket;
}
/// Retrieve a pointer to the underlying socket
/**
* This is used internally. It can also be used to set socket options, etc
*/
lib::asio::ip::tcp::socket & get_raw_socket() {
return *m_socket;
}
/// Get the remote endpoint address
/**
* The iostream transport has no information about the ultimate remote
* endpoint. It will return the string "iostream transport". To indicate
* this.
*
* TODO: allow user settable remote endpoint addresses if this seems useful
*
* @return A string identifying the address of the remote endpoint
*/
std::string get_remote_endpoint(lib::error_code & ec) const {
std::stringstream s;
lib::asio::error_code aec;
lib::asio::ip::tcp::endpoint ep = m_socket->remote_endpoint(aec);
if (aec) {
ec = error::make_error_code(error::pass_through);
s << "Error getting remote endpoint: " << aec
<< " (" << aec.message() << ")";
return s.str();
} else {
ec = lib::error_code();
s << ep;
return s.str();
}
}
protected:
/// Perform one time initializations
/**
* init_asio is called once immediately after construction to initialize
* Asio components to the io_service
*
* @param service A pointer to the endpoint's io_service
* @param strand A shared pointer to the connection's asio strand
* @param is_server Whether or not the endpoint is a server or not.
*/
lib::error_code init_asio (io_service_ptr service, strand_ptr, bool)
{
if (m_state != UNINITIALIZED) {
return socket::make_error_code(socket::error::invalid_state);
}
m_socket = lib::make_shared<lib::asio::ip::tcp::socket>(
lib::ref(*service));
m_state = READY;
return lib::error_code();
}
/// Set uri hook
/**
* Called by the transport as a connection is being established to provide
* the uri being connected to to the security/socket layer.
*
* This socket policy doesn't use the uri so it is ignored.
*
* @since 0.6.0
*
* @param u The uri to set
*/
void set_uri(uri_ptr) {}
/// Pre-initialize security policy
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection. This method is not allowed to
* write any bytes to the wire. This initialization happens before any
* proxies or other intermediate wrappers are negotiated.
*
* @param callback Handler to call back with completion information
*/
void pre_init(init_handler callback) {
if (m_state != READY) {
callback(socket::make_error_code(socket::error::invalid_state));
return;
}
if (m_socket_init_handler) {
m_socket_init_handler(m_hdl,*m_socket);
}
m_state = READING;
callback(lib::error_code());
}
/// Post-initialize security policy
/**
* Called by the transport after all intermediate proxies have been
* negotiated. This gives the security policy the chance to talk with the
* real remote endpoint for a bit before the websocket handshake.
*
* @param callback Handler to call back with completion information
*/
void post_init(init_handler callback) {
callback(lib::error_code());
}
/// Sets the connection handle
/**
* The connection handle is passed to any handlers to identify the
* connection
*
* @param hdl The new handle
*/
void set_handle(connection_hdl hdl) {
m_hdl = hdl;
}
/// Cancel all async operations on this socket
void cancel_socket() {
m_socket->cancel();
}
void async_shutdown(socket_shutdown_handler h) {
lib::asio::error_code ec;
m_socket->shutdown(lib::asio::ip::tcp::socket::shutdown_both, ec);
h(ec);
}
lib::error_code get_ec() const {
return lib::error_code();
}
/// Translate any security policy specific information about an error code
/**
* Translate_ec takes a boost error code and attempts to convert its value
* to an appropriate websocketpp error code. The plain socket policy does
* not presently provide any additional information so all errors will be
* reported as the generic transport pass_through error.
*
* @since 0.3.0
*
* @param ec The error code to translate_ec
* @return The translated error code
*/
lib::error_code translate_ec(lib::asio::error_code) {
// We don't know any more information about this error so pass through
return make_error_code(transport::error::pass_through);
}
private:
enum state {
UNINITIALIZED = 0,
READY = 1,
READING = 2
};
socket_ptr m_socket;
state m_state;
connection_hdl m_hdl;
socket_init_handler m_socket_init_handler;
};
/// Basic ASIO endpoint socket component
/**
* transport::asio::basic_socket::endpoint implements an endpoint socket
* component that uses Boost ASIO's ip::tcp::socket.
*/
class endpoint {
public:
/// The type of this endpoint socket component
typedef endpoint type;
/// The type of the corresponding connection socket component
typedef connection socket_con_type;
/// The type of a shared pointer to the corresponding connection socket
/// component.
typedef socket_con_type::ptr socket_con_ptr;
explicit endpoint() {}
/// Checks whether the endpoint creates secure connections
/**
* @return Whether or not the endpoint creates secure connections
*/
bool is_secure() const {
return false;
}
/// Set socket init handler
/**
* The socket init handler is called after a connection's socket is created
* but before it is used. This gives the end application an opportunity to
* set asio socket specific parameters.
*
* @param h The new socket_init_handler
*/
void set_socket_init_handler(socket_init_handler h) {
m_socket_init_handler = h;
}
protected:
/// Initialize a connection
/**
* Called by the transport after a new connection is created to initialize
* the socket component of the connection.
*
* @param scon Pointer to the socket component of the connection
*
* @return Error code (empty on success)
*/
lib::error_code init(socket_con_ptr scon) {
scon->set_socket_init_handler(m_socket_init_handler);
return lib::error_code();
}
private:
socket_init_handler m_socket_init_handler;
};
} // namespace basic_socket
} // namespace asio
} // namespace transport
} // namespace websocketpp
#endif // WEBSOCKETPP_TRANSPORT_SECURITY_NONE_HPP
| [
"thsgroupteamcontact@gmail.com"
] | thsgroupteamcontact@gmail.com |
aa3fb525029e7bbb3544bec767d27e3b686b8e28 | 89330e5b2100a37000782ef0d21209a825ffe13f | /mini/utils.cpp | 0b69f4cc76a34213ad3d13c809aad35f7a3b344a | [] | no_license | vladsol/gs-manager | c5f36b9821518e5d5ad5f0e74ea23550ac4118fc | f98795d98ebd98fafc1a81c3f257c09f968aae82 | refs/heads/master | 2021-01-20T01:56:25.405292 | 2017-04-25T09:59:40 | 2017-04-25T09:59:40 | 89,345,213 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | cpp | #include "utils.h"
void SimpleConfigBase::SetParams(StringMap & params)
{
ForEachI(params, i) {
string param = i->first;
string val = i->second;
if (m_params.find(param) != m_params.end()) {
if (val == "on") val = "true";
if (val == "off") val ="false";
m_params[param]=val;
}
}
}
void SimpleConfigBase::SetParansFormSes(isp_api::Session & ses)
{
StringVector params;
ses.GetParams(params);
ForEachI(params, i) {
string param = *i;
string val = ses.Param(*i);
if (m_params.find(param) != m_params.end()) {
if (val == "on") val = "true";
if (val == "off") val ="false";
m_params[param] = val;
}
}
}
void SimpleConfigBase::ConfToSes(isp_api::Session & ses) {
ForEachI(m_params, param) {
string val = param->second;
if (val == "true") val = "on";
if (val == "false") val ="off";
ses.NewNode(param->first.c_str(),val);
}
}
void SimpleConfigBase::SetParam(const string & param, const string & value)
{
if (m_params.find(param) != m_params.end())
m_params[param]=value;
} | [
"vladsol@ukr.net"
] | vladsol@ukr.net |
feb17bb2612e827945662ce7d9cb1223a9968c48 | b66715c97e48731ebba2afb8d81d02beb695c691 | /UVa/11262 - Weird Fence.cpp | caccad7908dbec39dc9b365a8e7c8d5ac7e797b1 | [] | no_license | justHusam/Competitive-Programming | c105b982108db914d80c759741302a9828b123b4 | 4c86037370774dc18beb1f2b302a59f2e84979d4 | refs/heads/master | 2020-03-19T10:26:12.874772 | 2018-09-14T12:24:41 | 2018-09-14T12:24:41 | 136,369,844 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 100;
int n, k, x[N], y[N], vis[N], vs, match[N];
vector<int> L, R, g[N];
char s[6];
inline int dist(int i, int j) {
return (x[i] - x[j]) * (x[i] - x[j]) + (y[i] - y[j]) * (y[i] - y[j]);
}
bool DFS(int v) {
vis[v] = vs;
for (int i = 0; i < g[v].size(); ++i) {
int u = match[g[v][i]];
if (u == -1 || (vis[u] != vs && DFS(u))) {
match[g[v][i]] = v;
return true;
}
}
return false;
}
bool check(int mid) {
for (int i = 0; i < n; ++i) {
g[i].clear();
match[i] = -1;
}
for (int i = 0; i < L.size(); ++i)
for (int j = 0; j < R.size(); ++j)
if (dist(L[i], R[j]) <= 1LL * mid * mid)
g[L[i]].push_back(R[j]);
int res = 0;
for (int i = 0; i < n; ++i) {
++vs;
if (DFS(i))
++res;
}
return res >= k;
}
int main(int argc, char **argv) {
int t;
scanf("%d", &t);
while (t-- != 0) {
scanf("%d%d", &n, &k);
L.clear();
R.clear();
for (int i = 0; i < n; ++i) {
scanf("%d%d%s", &x[i], &y[i], s);
if (s[0] == 'r')
L.push_back(i);
else
R.push_back(i);
}
int l = 1, r = 1e4, res = -1;
while (l <= r) {
int mid = (l + r) >> 1;
if (check(mid)) {
res = mid;
r = mid - 1;
} else
l = mid + 1;
}
if (res == -1)
puts("Impossible");
else
printf("%d\n", res);
}
return 0;
}
| [
"husam.sa3@gmail.com"
] | husam.sa3@gmail.com |
6c8d3087d1a312486fcabbe7599ee87060ca0bfd | 1ed1ed934e4175bb20024311a007d60ae784b046 | /TWOSQ.Sub3/TWOSQ.Sub3.cpp | 1de17d37c169d190d564c29f71a9610d35112cbf | [] | no_license | kkkcoder/Code_in_thptchuyen.ntucoder.net | f568cddc01b641c9a6a3c033a4b48ca59bb6435e | c4c0e19ea56a6560014cbb6e4d7489fb16e8aad7 | refs/heads/master | 2023-07-16T16:15:39.421817 | 2021-08-29T15:56:35 | 2021-08-29T15:56:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,103 | cpp | // Tiếp tục với series chuyện có thật ... do ARSENAL1886 bịa ra!!!
// ARSENAL1886 vừa chiến thắng cuộc thi “Tìm hiểu kiến thức vũ trụ” và nhận được phần thưởng
// do ban tổ chức tài trợ. Phần thưởng được bố trí trên một bảng kích thước m × n (tượng trưng cho
// vũ trụ), các dòng của bảng được đánh số từ 1 đến m từ trên xuống dưới, các cột của bảng được
// đánh số từ 1 đến n từ trái qua phải. Ô nằm trên giao của dòng i và cột j được gọi là ô (i,j) và trên
// ô đó chứa một món quà có giá trị là aij (1 ≤ i ≤ m, 1 ≤ j ≤ n)
// Để nhận phần thưởng, ARSENAL1886 sẽ chọn 2 hình vuông kích thước k × k không giao nhau.
// Nhân ngày 20/10, anh ấy muốn tìm hai hình vuông sao cho tổng giá trị của các món quà trong hai
// hình vuông đó là lớn nhất (để có một món quà thật ý nghĩa tặng bạn gái, mà bạn đó là ai thì ... đến
// cả ARSENAL1886 còn không biết nữa :D)
// Yêu cầu: Cho m, n, k và giá trị các phần quà trên bảng. Hãy đưa ra tổng giá trị lớn nhất có thể được
// khi chọn hai hình vuông k × k
// Input:
// • Dòng thứ nhất chứa ba số nguyên dương m, n, k
// • Dòng thứ i trong số m dòng tiếp theo chứa n số nguyên dương, số thứ j là
// aij (1 ≤ aij ≤ 106
// )
// • k luôn thoả mãn có cách chọn 2 hình vuông
// Output:
// • Một số nguyên duy nhất là kết quả bài toán
#include <bits/stdc++.h>
using namespace std;
const int nmax = 100005;
vector<long long> h[nmax], h2[nmax], a[nmax];
long long ans = 0;
vector<long long> L[nmax], maxL[nmax];
vector<long long> R[nmax], maxR[nmax];
int m, n, k, x;
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
//freopen("KC2DIV1B.inp","r",stdin);
//freopen("KC2DIV1B.out","w",stdout);
cin >> m >> n >> k;
for (int i = 0; i <= m + 1; i++)
{
a[i].resize(n + 2);
h[i].resize(n + 2);
h2[i].resize(n + 2);
L[i].resize(n + 2);
maxL[i].resize(n + 2);
R[i].resize(n + 2);
maxR[i].resize(n + 2);
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
{
cin >> x;
a[i][j] = x;
if (i > k)
h[i][j] = h[i - 1][j] + a[i][j] - a[i - k][j];
else
h[i][j] = h[i - 1][j] + a[i][j];
}
for (int i = m; i >= 1; i--)
for (int j = n; j >= 1; j--)
{
if (i + k <= m)
h2[i][j] = h2[i + 1][j] + a[i][j] - a[i + k][j];
else
h2[i][j] = h2[i + 1][j] + a[i][j];
}
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
{
if (j > k)
L[i][j] = L[i][j - 1] + h[i][j] - h[i][j - k];
else
L[i][j] = L[i][j - 1] + h[i][j];
}
maxL[k][k] = L[k][k];
for (int i = k + 1; i <= n; i++)
maxL[k][i] = max(maxL[k][i - 1], L[k][i]);
for (int i = k + 1; i <= m; i++)
for (int j = k; j <= n; j++)
maxL[i][j] = max(maxL[i - 1][j], max(maxL[i][j - 1], L[i][j]));
for (int i = m; i >= 1; i--)
for (int j = n; j >= 1; j--)
{
if (j + k <= n)
R[i][j] = R[i][j + 1] + h2[i][j] - h2[i][j + k];
else
R[i][j] = R[i][j + 1] + h2[i][j];
}
maxR[m - k + 1][n - k + 1] = R[m - k + 1][n - k + 1];
for (int i = n - k + 1; i >= 1; i--)
maxR[m - k + 1][i] = max(maxR[m - k + 1][i + 1], R[m - k + 1][i]);
for (int i = m - k; i >= 1; i--)
for (int j = n - k + 1; j >= 1; j--)
maxR[i][j] = max(maxR[i + 1][j], max(maxR[i][j + 1], R[i][j]));
for (int i = k; i <= m; i++)
for (int j = k; j <= n; j++)
ans = max(ans, maxL[i][j] + max(maxR[1][j + 1], maxR[i + 1][1]));
cout << ans << endl;
}
| [
"lam3082004@gmail.com"
] | lam3082004@gmail.com |
9fb563fcf2fda13df50c8e1323e94eeed89e1b6c | d49f9912788a9e3bba936731955e53b69596a3fd | /custom_widgets/material_widgets/components/scrollwidget.h | 8d1da729fac5cea3f2e04ffcec86625ff891059f | [] | no_license | ChechenItza/Daily-Planner | 9f6af0dcb3512a059c9783b36f0cd12b69a7f532 | 61b2978bc2057f1010a60a6ca391aebaf84f8daf | refs/heads/master | 2022-11-09T16:27:47.272176 | 2020-06-28T13:30:59 | 2020-06-28T13:30:59 | 99,214,353 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,070 | h | #ifndef SCROLLWIDGET_H
#define SCROLLWIDGET_H
#include <QScrollBar>
class ScrollBarPrivate;
class ScrollBar : public QScrollBar
{
Q_OBJECT
public:
explicit ScrollBar(QWidget *parent = 0);
~ScrollBar();
void setUseThemeColors(bool value);
bool useThemeColors() const;
void setCanvasColor(const QColor &color);
QColor canvasColor() const;
void setBackgroundColor(const QColor &color);
QColor backgroundColor() const;
void setSliderColor(const QColor &color);
QColor sliderColor() const;
void setHideOnMouseOut(bool state);
bool hideOnMouseOut() const;
QSize sizeHint() const Q_DECL_OVERRIDE;
protected:
//void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
//void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE;
void paintEvent(QPaintEvent *event) Q_DECL_OVERRIDE;
const QScopedPointer<ScrollBarPrivate> d_ptr;
//private:
// QMouseEvent translateEventGeometry(QMouseEvent *event);
Q_DISABLE_COPY(ScrollBar)
Q_DECLARE_PRIVATE(ScrollBar)
};
#endif // SCROLLWIDGET_H
| [
"artka.kazaktar@gmail.com"
] | artka.kazaktar@gmail.com |
7f11aeb453ed821e7b1c28e13dfc670137a7aa18 | 39c96d2f9714272eba18f2877ca81e93fc3c8706 | /UCL_Interface/UCL.cpp | 06a3ce3dd1647a14933b9315c3e388c0a8eb9ad0 | [] | no_license | ZJQxxn/UCL_Interface | 04c6d4d26bb51c40d3171d3fb93383b10ce73e9c | e37f5c528525a4d9c736eaf5d970a06c4ba9a4ca | refs/heads/master | 2020-12-02T23:53:32.426844 | 2017-07-27T15:28:51 | 2017-07-27T15:28:51 | 95,956,304 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,160 | cpp | //UCL类函数的定义
//声明在UCL.h中
#include "stdafx.h"
#include "UCL.h"
#include <fstream>
#include <string>
#include <vector>
using namespace std;
UCL::UCL(const string& filename)
{
readFromFile(filename);
}
void UCL::readFromFile(const string& filename)
{
vector <string> UCL;
ifstream file;
file.open(filename);
if (!file)
{
exit(1);
}
string str;
file >> str;
file.close();
convert(str, UCL);
vector <string>::iterator it = UCL.begin();
for (size_t count = 0; count < 32; count++)
{
UCL_Code.push_back(*it);
it++;
}
for (; it != UCL.end(); ++it)
{
UCL_Properties.push_back(*it);
}
}
vector<string>& UCL::getCode()
{
return UCL_Code;
}
vector<string>& UCL::getProperties()
{
return UCL_Properties;
}
string UCL::hexToBin(char *str)
{
string result;
if (strlen(str) == 1) //不足八位的,补零构成八位
{
result += "0000";
}
for (size_t i = 0; i < strlen(str); ++i)
{
switch (str[i])
{
case '0':
result += "0000";
break;
case '1':
result += "0001";
break;
case '2':
result += "0010";
break;
case '3':
result += "0011";
break;
case '4':
result += "0100";
break;
case '5':
result += "0101";
break;
case '6':
result += "0110";
break;
case '7':
result += "0111";
break;
case '8':
result += "1000";
break;
case '9':
result += "1001";
break;
case 'a':
result += "1010";
break;
case 'b':
result += "1011";
break;
case 'c':
result += "1100";
break;
case 'd':
result += "1101";
break;
case 'e':
result += "1110";
break;
case 'f':
result += "1111";
break;
}
}
return result;
}
void UCL::convert(string &original, vector <string>&UCL) //convert original(hex) to result(binary)
{
char *sentence = new char[original.length()];
char *tokenPtr;
char *save;
strcpy_s(sentence, original.length() + 1, original.c_str()); /*c_str() returns a char* with '\0' (char* is temporary and can't be used for assignment)*/
tokenPtr = strtok_s(sentence, "-", &save);
while (tokenPtr != nullptr)
{
UCL.push_back(hexToBin(tokenPtr));
tokenPtr = strtok_s(NULL, "-", &save);
}
} | [
"zhangjiaqi_seu@outlook.com"
] | zhangjiaqi_seu@outlook.com |
a58d6220cde3d01acd4892b9496c7dc6ecc174f5 | 58db9457d804e4340b006cd2cdaa1e90cd998fd0 | /PlainParameter.h | d46505a6e280ebb611acf2f37602e05a8f7c3590 | [] | no_license | robmister2/LAB1_NEW | 1ccd854e6c83d0be73c2ebba956ac0c315d90993 | 994fa970a71a15646b7a16c954c19bfd04f642c4 | refs/heads/master | 2023-03-31T21:00:41.294840 | 2021-04-02T15:21:58 | 2021-04-02T15:21:58 | 334,052,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h |
#ifndef LAB1_NEW_PLAINPARAMETER_H
#define LAB1_NEW_PLAINPARAMETER_H
#include "Parameter.h"
#include <vector>
using namespace std;
class PlainParameter:
public Parameter{
private:
string name;
public:
PlainParameter(string name1, bool isConstant1);
string getName();
string toString();
};
#endif //LAB1_NEW_PLAINPARAMETER_H
| [
"robofcoin@gmail.com"
] | robofcoin@gmail.com |
fcdd02c442150e5458daec83766b360b5d077ea4 | 7b85e4966ea025893569d50b07127a45ea263c7f | /atcoder/ARC 114/C.cpp | 26a0c827fc6a636152921c4d9573cc16e2710cae | [
"MIT"
] | permissive | ApocalypseMac/CP | 22e437b2d844ad0a2d4fe50590276ac4b8461dc4 | b2db9aa5392a362dc0d979411788267ed9a5ff1d | refs/heads/master | 2023-04-25T14:49:28.510588 | 2021-05-08T15:11:02 | 2021-05-08T15:11:02 | 308,243,143 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,001 | cpp | #include <bits/stdc++.h>
#include <ext/pb_ds/tree_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds; //required
using namespace std;
template<typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
#define debug(x) cout << #x << " is " << x << "\n"
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define flush cout.flush()
typedef long long ll;
const int MOD = 998244353;
ll dp[5005][5005]; // i ** j % MOD 0 ** 0 == 1
ll p[5005]; // \sumi_1^m-1 i ** j % MOD
int pow(int a, int b, int p){
int ans = 1 % p;
for (; b; b >>= 1){
if (b & 1) ans = (ll)ans * a % p;
a = (ll) a * a % p;
}
return ans;
}
void init(int m, int n){
for (int i = 0; i <= m; ++i){
dp[i][0] = 1;
}
for (int i = 1; i <= m; ++i){
for(int j = 1; j <= n; ++j){
dp[i][j] = dp[i][j-1] * i % MOD;
}
}
for(int j = 0; j <= n; ++j){
// p[j] = 1;
for (int i = 0; i < m; ++i){
p[j] += dp[i][j];
p[j] %= MOD;
}
}
// for (int i = 0; i <= m; ++i){
// for(int j = 0; j <= n; ++j){
// cout << i << ' ' << j << ' ' << dp[i][j] << '\n';
// }
// }
// for (int j = 0; j <= n; ++j){
// cout << j << ' ' << p[j] << '\n';
// }
}
int main(){
fast;
int n, m;
cin >> n >> m;
memset(dp, 0, sizeof(dp));
memset(p, 0, sizeof(p));
init(m, n);
ll res = n * dp[m][n];
res %= MOD;
// debug(res);
for (int i = 0; i < n; ++i){
for (int j = 0; j < i; ++j){
res -= dp[m][n-(i-j)-1] * p[i-j-1];
res %= MOD;
if (res < 0){
res += MOD;
}
// cout << i << ' ' << j << ' ' << dp[m][n-(i-j)-1] << ' ' << p[i-j-1] << ' ' << res << '\n';
}
}
cout << res << '\n';
return 0;
} | [
"ApocalypseMac@users.noreply.github.com"
] | ApocalypseMac@users.noreply.github.com |
3b84ab6f75124b90ad0d02d7685aa8245600c6c2 | 6faba6af82f9646b22da924cc87174578488b2b8 | /MiClase.h.cpp | f4ddf8aedf78f3eb2727fd41aa76ae3845d0465b | [] | no_license | IvethS/JuegoDeHerencia | a21a6980f6b98de643c86f6c43582dbb3043f366 | 22bc70bddf18e95115f5fa4335596040d391a7ea | refs/heads/master | 2020-12-30T09:51:40.596702 | 2014-11-03T14:16:32 | 2014-11-03T14:16:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp | #include "MiClase.h.h"
MiClase::MiClase()
{
//ctor
}
MiClase::~MiClase()
{
//dtor
}
| [
"alumno@localhost.localdomain"
] | alumno@localhost.localdomain |
541faf90e1589d0cf8b615ec98a1286e098dbd05 | c5bf80e5868dd000c82c981434413d6ed9d3e0be | /src/core/transformations/blur_gaussian.cpp | c41fc6cb03eeb09207fc2e61cea6601669e52a37 | [] | no_license | pto2013ErasmusStudents/Image-Processing | 9fc3a680fa6914d71849ad9487a4d23afe6b6f05 | bb100fca47bf775a36e1e1f687ad2dbf036f4494 | refs/heads/master | 2021-01-23T02:59:00.271508 | 2014-02-20T12:55:18 | 2014-02-20T12:55:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 871 | cpp | #include "blur_gaussian.h"
BlurGaussian::BlurGaussian(PNM* img) :
Convolution(img)
{
}
BlurGaussian::BlurGaussian(PNM* img, ImageViewer* iv) :
Convolution(img, iv)
{
}
PNM* BlurGaussian::transform()
{
emit message("Blurring...");
int size = getParameter("size").toInt();
radius = (size/2)+1;
sigma = getParameter("sigma").toDouble();
return convolute(getMask(size, Normalize), RepeatEdge);
}
math::matrix<double> BlurGaussian::getMask(int size, Mode)
{
math::matrix<double> mask(size, size);
for (int i=0;i<size;i++){
for (int j=0;j<size;j++){
mask(i,j)=getGauss(i,j,sigma);
}
}
return mask;
}
double BlurGaussian::getGauss(int x, int y, double sigma)
{
double pi=3.14159;
double value = (1/(2*pi*sigma*sigma))*exp(-(x^2+y^2)/(2*sigma*sigma));
return value;
}
| [
"marta.hidalgo@udc.es"
] | marta.hidalgo@udc.es |
e9144536aa0262736eb26ca959a124f5162e554b | 4a954052c8578fc786be249ee1eaacc576a454ef | /working_version/srcs/Portal.hpp | c7a5d1b4c7eafb1d590aa6729c817de7981a609c | [] | no_license | ldehaudt/BasicalyBomberman | bb47c32b320bdf09ed8dc597506882651c4b8fab | 9a6919507a24ae363021bfd15d15a827c69f747c | refs/heads/master | 2020-04-11T05:34:56.129784 | 2018-12-12T22:49:20 | 2018-12-12T22:49:20 | 161,553,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | hpp | #ifndef PORTAL_HPP
#define PORTAL_HPP
#include "Position.hpp"
#include "Object.hpp"
#include "Player.hpp"
class Portal : public Object{
public:
Portal(Pos2D pos, Board& b, int);
void onPlayer(Player& player);
void deadEnemy();
private:
int numEnemy;
};
#endif | [
"ldehaudt@e1r6p11.42.fr"
] | ldehaudt@e1r6p11.42.fr |
7a4f0d329c51bf36217cbfd1c9566bfe669ceca3 | be5ca13f5d582e172883b01ef4b89f2527fcec1f | /02_arc/079d.cpp | c806dd8c8ab9159cbb11ae96307700fa6fe694af | [] | no_license | sinhrks/CompetitiveProgramming | 8569bb001411b58b50aa1f5e2f187c17fe5fb2f1 | 7e310bd0e8b64a888289eebe8b37ed0554cced6f | refs/heads/master | 2021-09-01T09:35:50.406900 | 2017-12-26T08:13:34 | 2017-12-26T08:13:34 | 103,657,034 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | #include <assert.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <numeric>
#include <functional>
#include <iostream>
#include <string>
#include <array>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <complex>
#include <bitset>
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
ll K;
cin >> K;
int N = 50;
vector<ll> ans(N, 0);
for (int j = 0; j < N; j++) {
ans[j] = j + K / N;
}
ll remain = K % N;
for (int j = 0; j < remain; j++) {
ans[j] += N;
for (int k = 0; k < N; k++) {
if (k != j) {
ans[k] -= 1;
}
}
}
cout << N << endl;
for (int i = 0; i < N; i++) {
cout << ans[i];
if (i < N - 1) {
cout << " ";
}
}
cout << endl;
return 0;
}
| [
"sinhrks@gmail.com"
] | sinhrks@gmail.com |
259f38cd68aa4b56692148e8bc5928041047388f | 8c5eda3178f44a7e41fda784aa1cd4dd083426a6 | /src/numbernames.cpp | 74b09e704530a71848596db324bc847047a8e95e | [] | no_license | littlewhywhat/playing-with-shifts | f7b5015c573f865ade1ca66268281caef0c0cd80 | ad3633005f6c9a51aef0b090cf5729a5fdacb73f | refs/heads/master | 2020-12-02T06:16:08.130060 | 2017-07-17T18:13:05 | 2017-07-17T18:13:05 | 96,802,944 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 193 | cpp | #include "numbernames.h"
std::string NumberNames::get_name(const std::string & prefix, int number) {
std::string name = prefix;
name.append(std::to_string(number));
return name;
}
| [
"vaivorom@fit.cvut.cz"
] | vaivorom@fit.cvut.cz |
0e480a98abb130347ad3265f770a87a846f611c2 | f785f72ca62115be56830c32cf3cb61d62cea7af | /shpreader2.5/CshpxAndDbfFile.h | eb9049dd801ab509a6428049d4db2cc4c78e7be8 | [] | no_license | CHCDST-SY/shp | bb94963934e018ad63052795379752d2d8fdcf22 | f19611284d107960e0a5f01a082891fe582055ce | refs/heads/main | 2023-06-18T11:57:31.938020 | 2021-07-20T08:56:24 | 2021-07-20T08:56:24 | 387,636,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h | #ifndef CSHPXANDDBFFILE_H
#define CSHPXANDDBFFILE_H
#include "CFileReader.h"
#include "CFileWriter.h"
#include "CdbfFile.h"
#include "CDataManager.h"
class CshpxAndDbfFile
{
public:
CshpxAndDbfFile();
virtual ~CshpxAndDbfFile();
virtual void readShpxAndDbf(string sFilePath);
virtual void writeShpxAndDbf(string sFilePath);
protected:
CDataManager m_CdataSaver;
CdbfFile m_Cdbf;
CFileReader m_Creader;
CFileWriter m_Cwriter;
};
#endif // CSHPXANDDBFFILE_H
| [
"noreply@github.com"
] | CHCDST-SY.noreply@github.com |
71338de0071378b88d056ac018184555c28044a8 | 7166e08738c1151a5e3d1242e19d655aaccc9ec5 | /LeetCode/Perfect_Squares/Main.cpp | 4466c3aaeab49bf8c13be8c6efb400132bd1de1e | [] | no_license | CaseyYang/LeetCode | 4602e3a5612c43e37f936e7a35abead6ebbf2cbc | ea3b3ea70a8012c5f5d82108642b88816a2788b2 | refs/heads/master | 2021-01-25T05:22:56.600363 | 2015-10-25T07:33:53 | 2015-10-25T07:33:53 | 26,250,162 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
using namespace std;
class Solution {
public:
int numSquares(int n) {
if (n == 0) return 0;
vector<int> result = vector<int>();
result.push_back(0);
for (int i = 1; i <= n; ++i){
result.push_back(i);
for (int j = 1; j <= sqrt(i); ++j){
result[i] = min(result[i], 1 + result[i - j*j]);
}
}
return result[n];
}
}; | [
"knightykc@gmail.com"
] | knightykc@gmail.com |
4d9626d5218bb70024ea3e39eafdcdb5f9b59d80 | 6def4a70e1435633fc2c48a4abbd4e70bae7e8fe | /TypeConversions/typeConversions.cpp | cd5e39e91bb26efa23267d06c7202ef21938b518 | [] | no_license | kjhe11e/NodeJsAddons | 55e02d5c9ef83039a2424a824f31f3ced7e72c0e | e17e4527595ce9c2f9db29825335fcbde9ad605a | refs/heads/master | 2021-01-22T20:45:12.827807 | 2019-10-03T03:40:12 | 2019-10-03T03:40:12 | 85,355,443 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,679 | cpp | #include <node.h>
#include <string>
#include <algorithm>
#include <iostream>
using namespace v8;
void PassNumber(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
/*Local<Number> target = args[0]->ToNumber();
double value = target->NumberValue();*/
double value = args[0]->NumberValue();
value += 10;
Local<Number> returnVal = Number::New(isolate, value);
args.GetReturnValue().Set(returnVal);
}
void ReverseStr(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if(!args[0]->IsString()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Input must be a string")
));
} else {
v8::String::Utf8Value s(args[0]);
std::string str(*s); //wrap in c++
std::reverse(str.begin(), str.end());
Local<String> reversedString = String::NewFromUtf8(isolate, str.c_str());
args.GetReturnValue().Set(reversedString);
}
}
void IncrementArray(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Array> arr = Local<Array>::Cast(args[0]);
for(unsigned int i = 0; i < arr->Length(); i++) {
double value = arr->Get(i)->NumberValue();
arr->Set(i, Number::New(isolate, value + 1));
}
// Since objects (and arrays) are mutable, these changes will be reflected
// even if we don't explicitly return
}
// Called when addon is require'd from JS
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "passNumber", PassNumber);
NODE_SET_METHOD(exports, "reverseStr", ReverseStr);
NODE_SET_METHOD(exports, "incrementArray", IncrementArray);
}
NODE_MODULE(typeConversions, Init) // macros
| [
"kjhelle4@gmail.com"
] | kjhelle4@gmail.com |
af4c2476549ecc51d0aa5f6a5ce60e50ac7f7f3d | 036cc01b29b56149326548cc5ca2617814f934cb | /example-klanglichtstrom/src/ofApp.h | 0550da1eced036d3137dcc57ae9ab42120f3b2f7 | [
"MIT"
] | permissive | colaplate/ofxLiveSet | 310869be1563d5abce7cec5c10ff5cb34a00fb1b | c6b95d9e4e15e8373b5912aa836366fb614f4b9f | refs/heads/master | 2021-01-03T00:00:50.966548 | 2019-12-15T18:56:53 | 2019-12-15T18:56:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 907 | h | #pragma once
#include "ofMain.h"
#include "ofxApp.h"
#include "ofxDmx.h"
#include "ofxLiveSet.h"
#include "./visualisation.h"
// out comment if you dont have an enttec usb interface connected
#define SENDDMX
class ofApp : public ofxApp
{
public:
ofApp();
void setup();
void update();
void draw();
void exit();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y);
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
ofxLiveSet::project::pointer _project;
ofxLiveSet::session::pointer _session;
ofxDmx _dmx;
visualisation _visualisation;
}; | [
"thomas.geissl@gmail.com"
] | thomas.geissl@gmail.com |
598c018547b9101c37c66a6121b664c4e6095b63 | e7af073f0013c1b63219cff9579e0f1029396e78 | /src/client/DocParser.cpp | 5b203f23087514e02d4fd6fa1f0df1e4c5d777cb | [
"BSD-2-Clause"
] | permissive | ms-building-blocks/credb | 703941337f86d6b212ed7d6fd9027c7ce599fa85 | 0956ee0b8d246d00a375fd978cbd2ea787688d98 | refs/heads/master | 2021-05-09T19:00:41.879431 | 2018-01-26T20:49:08 | 2018-01-26T20:49:08 | 119,178,204 | 1 | 0 | null | 2018-01-27T15:54:23 | 2018-01-27T15:54:22 | null | UTF-8 | C++ | false | false | 3,778 | cpp | #include "DocParser.h"
#define BOOST_RESULT_OF_USE_DECLTYPE
#define BOOST_SPIRIT_USE_PHOENIX_V3
#include <boost/phoenix/bind/bind_function.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <cowlang/cow.h>
#include <fstream>
#include <glog/logging.h>
namespace credb
{
using namespace boost::spirit;
void print(const std::string &str) { std::cout << str << std::endl; }
template <typename Iterator>
struct obj_grammar : qi::grammar<Iterator, qi::unused_type(), qi::space_type>
{
obj_grammar() : obj_grammar::base_type(start)
{
using ascii::char_;
using boost::phoenix::bind;
using qi::_1;
using qi::eps;
using qi::int_;
using qi::lexeme;
using qi::lit;
using qi::no_skip;
using qi::string;
array = char_('[') >> *(char_(' ')) >> char_(']') >> *(char_('\n'));
dictentry = key >> ':' >> string("dict") >> string(":=") >>
char_('{')[bind([&]() { writer.start_map(current_key); })] >> *(char_(' ')) >>
char_('}')[bind([&]() { writer.end_map(); })];
code = +~char_(";");
key = (+char_("a-zA-Z_"))[bind(
[&](const std::vector<char> &v) { current_key = std::string(v.begin(), v.end()); }, _1)];
intentry = key >> ':' >> string("int") >> string(":=") >>
int_[bind([&](int val) { writer.write_integer(current_key, val); }, _1)];
funcentry = key >> ':' >> string("func") >> string(":=") >>
no_skip[code[bind(
[&](const std::string &c) {
try
{
auto bin = cow::compile_code(c);
writer.write_binary(current_key, bin);
}
catch(std::runtime_error &e)
{
LOG(ERROR) << "failed to compile code: \n" << c;
}
},
_1)]] >>
char_(";");
start = eps > char_('{')[bind([&]() { writer.start_map(""); })] >>
*(intentry | funcentry | dictentry) >>
lit('}')[bind([&]() { writer.end_map(); })] >> *(char_('\n'));
key.name("key");
dictentry.name("dict entry");
intentry.name("int entry");
funcentry.name("func entry");
start.name("root");
qi::on_error<qi::fail>(start, boost::phoenix::ref(std::cout)
<< "Error! Expected " << qi::_4 << " but got: '"
<< boost::phoenix::construct<std::string>(qi::_3, qi::_2) << "'\n");
}
qi::rule<Iterator, qi::unused_type(), qi::space_type> dictentry, array, intentry, funcentry, key, start;
qi::rule<Iterator, std::string()> code;
json::Writer writer;
std::string current_key;
std::string current_code;
};
json::Document parse_document_file(const std::string &filename)
{
using qi::char_;
using qi::phrase_parse;
using qi::space;
std::ifstream file(filename);
file.unsetf(std::ios::skipws);
if(!file)
{
throw std::runtime_error("cannot open object file");
}
auto fstart = istream_iterator(file);
auto fend = istream_iterator();
obj_grammar<istream_iterator> parser;
auto res = phrase_parse(fstart, fend, parser, space);
if(!res)
{
throw std::runtime_error("Failed to parse object file");
}
if(fstart != fend)
{
throw std::runtime_error("Couldn't read until the end");
}
return parser.writer.make_document();
}
} // namespace credb
| [
"kaimast@cs.cornell.edu"
] | kaimast@cs.cornell.edu |
83814323e45b31ec5705aeaccaa5fb843755ccdf | 5b952b10a4cf77745ecafee2174cd0e5bed13113 | /fft.cpp | 8bacd8314b8fec31dd72ead1392d9ec2e2582751 | [
"MIT"
] | permissive | cuklev/frequency-analyzer | 723ba9543bcd4f1092256c84b42dfe72f0e9b2da | 5069afa1b2c642b0532c58f955ca6767883294e7 | refs/heads/master | 2021-01-12T06:17:52.552148 | 2017-12-06T20:46:26 | 2017-12-06T20:46:26 | 77,337,150 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,477 | cpp | #include "fft.hpp"
#include <vector>
#include <complex>
namespace {
using ComplexNumber = std::complex<double>;
const uint32_t Mask0 = 0x55555555;
const uint32_t Mask1 = 0x33333333;
const uint32_t Mask2 = 0x0F0F0F0F;
const uint32_t Mask3 = 0x00FF00FF;
const uint32_t Mask4 = 0x0000FFFF;
inline void swap_mask(uint32_t& n, uint32_t mask, int bit_count) {
n = ((n & mask) << bit_count) | ((n >> bit_count) & mask);
}
inline uint32_t reverse_bits(uint32_t n, int bit_count) {
swap_mask(n, Mask0, 1);
swap_mask(n, Mask1, 2);
swap_mask(n, Mask2, 4);
swap_mask(n, Mask3, 8);
swap_mask(n, Mask4, 16);
return n >> (32 - bit_count);
}
}
void fft_get_amplitudes(short* buffer, size_t sample_count, double* amplitudes) {
int bit_count = __builtin_ctz(sample_count);
auto data = std::vector<ComplexNumber>(sample_count);
for(size_t i = 0; i < sample_count; ++i) {
auto j = reverse_bits(i, bit_count);
data[j] = {(double) buffer[i], 0};
}
for(int k = 0; k < bit_count; ++k) {
double angle = M_PI / (1 << k);
ComplexNumber primitive_root = {cos(angle), sin(angle)};
for(unsigned i = 0; i < data.size(); i += (2u << k)) {
ComplexNumber w = {1, 0};
for(unsigned j = i; j < i + (1u << k); ++j) {
data[j + (1u << k)] *= w;
auto diff = data[j] - data[j + (1u << k)];
data[j] += data[j + (1u << k)];
data[j + (1u << k)] = diff;
w *= primitive_root;
}
}
}
for(size_t i = 0; i < sample_count; ++i)
amplitudes[i] = abs(data[i]);
}
| [
"cuki@cukii.tk"
] | cuki@cukii.tk |
a6146e70c98fe0c6f16ccf726e22feb92cff360f | 1302a788aa73d8da772c6431b083ddd76eef937f | /WORKING_DIRECTORY/bionic/libc/bionic/ifaddrs.cpp | 408949c131f9d57f39efb431a35570621aa4131e | [
"Martin-Birgmeier",
"MIT",
"SunPro",
"ISC",
"BSD-4-Clause",
"BSD-4.3TAHOE",
"Apache-2.0",
"BSD-2-Clause",
"HPND",
"LicenseRef-scancode-ibm-dhcp",
"SMLNJ",
"BSD-3-Clause",
"BSD-4-Clause-UC",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | rockduan/androidN-android-7.1.1_r28 | b3c1bcb734225aa7813ab70639af60c06d658bf6 | 10bab435cd61ffa2e93a20c082624954c757999d | refs/heads/master | 2021-01-23T03:54:32.510867 | 2017-03-30T07:17:08 | 2017-03-30T07:17:08 | 86,135,431 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,724 | cpp | /*
* Copyright (C) 2015 The Android Open Source Project
* 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 OWNER 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.
*/
#include <ifaddrs.h>
#include <errno.h>
#include <linux/if_packet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "private/ErrnoRestorer.h"
#include "bionic_netlink.h"
// The public ifaddrs struct is full of pointers. Rather than track several
// different allocations, we use a maximally-sized structure with the public
// part at offset 0, and pointers into its hidden tail.
struct ifaddrs_storage {
// Must come first, so that `ifaddrs_storage` is-a `ifaddrs`.
ifaddrs ifa;
// The interface index, so we can match RTM_NEWADDR messages with
// earlier RTM_NEWLINK messages (to copy the interface flags).
int interface_index;
// Storage for the pointers in `ifa`.
sockaddr_storage addr;
sockaddr_storage netmask;
sockaddr_storage ifa_ifu;
char name[IFNAMSIZ + 1];
ifaddrs_storage(ifaddrs** list) {
memset(this, 0, sizeof(*this));
// push_front onto `list`.
ifa.ifa_next = *list;
*list = reinterpret_cast<ifaddrs*>(this);
}
void SetAddress(int family, const void* data, size_t byteCount) {
// The kernel currently uses the order IFA_ADDRESS, IFA_LOCAL, IFA_BROADCAST
// in inet_fill_ifaddr, but let's not assume that will always be true...
if (ifa.ifa_addr == nullptr) {
// This is an IFA_ADDRESS and haven't seen an IFA_LOCAL yet, so assume this is the
// local address. SetLocalAddress will fix things if we later see an IFA_LOCAL.
ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
} else {
// We already saw an IFA_LOCAL, which implies this is a destination address.
ifa.ifa_dstaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
}
}
void SetBroadcastAddress(int family, const void* data, size_t byteCount) {
// ifa_broadaddr and ifa_dstaddr overlap in a union. Unfortunately, it's possible
// to have an interface with both. Keeping the last thing the kernel gives us seems
// to be glibc 2.19's behavior too, so our choice is being source compatible with
// badly-written code that assumes ifa_broadaddr and ifa_dstaddr are interchangeable
// or supporting interfaces with both addresses configured. My assumption is that
// bad code is more common than weird network interfaces...
ifa.ifa_broadaddr = CopyAddress(family, data, byteCount, &ifa_ifu);
}
void SetLocalAddress(int family, const void* data, size_t byteCount) {
// The kernel source says "for point-to-point IFA_ADDRESS is DESTINATION address,
// local address is supplied in IFA_LOCAL attribute".
// -- http://lxr.free-electrons.com/source/include/uapi/linux/if_addr.h#L17
// So copy any existing IFA_ADDRESS into ifa_dstaddr...
if (ifa.ifa_addr != nullptr) {
ifa.ifa_dstaddr = reinterpret_cast<sockaddr*>(memcpy(&ifa_ifu, &addr, sizeof(addr)));
}
// ...and then put this IFA_LOCAL into ifa_addr.
ifa.ifa_addr = CopyAddress(family, data, byteCount, &addr);
}
// Netlink gives us the prefix length as a bit count. We need to turn
// that into a BSD-compatible netmask represented by a sockaddr*.
void SetNetmask(int family, size_t prefix_length) {
// ...and work out the netmask from the prefix length.
netmask.ss_family = family;
uint8_t* dst = SockaddrBytes(family, &netmask);
memset(dst, 0xff, prefix_length / 8);
if ((prefix_length % 8) != 0) {
dst[prefix_length/8] = (0xff << (8 - (prefix_length % 8)));
}
ifa.ifa_netmask = reinterpret_cast<sockaddr*>(&netmask);
}
void SetPacketAttributes(int ifindex, unsigned short hatype, unsigned char halen) {
sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(&addr);
sll->sll_ifindex = ifindex;
sll->sll_hatype = hatype;
sll->sll_halen = halen;
}
private:
sockaddr* CopyAddress(int family, const void* data, size_t byteCount, sockaddr_storage* ss) {
// Netlink gives us the address family in the header, and the
// sockaddr_in or sockaddr_in6 bytes as the payload. We need to
// stitch the two bits together into the sockaddr that's part of
// our portable interface.
ss->ss_family = family;
memcpy(SockaddrBytes(family, ss), data, byteCount);
// For IPv6 we might also have to set the scope id.
if (family == AF_INET6 && (IN6_IS_ADDR_LINKLOCAL(data) || IN6_IS_ADDR_MC_LINKLOCAL(data))) {
reinterpret_cast<sockaddr_in6*>(ss)->sin6_scope_id = interface_index;
}
return reinterpret_cast<sockaddr*>(ss);
}
// Returns a pointer to the first byte in the address data (which is
// stored in network byte order).
uint8_t* SockaddrBytes(int family, sockaddr_storage* ss) {
if (family == AF_INET) {
sockaddr_in* ss4 = reinterpret_cast<sockaddr_in*>(ss);
return reinterpret_cast<uint8_t*>(&ss4->sin_addr);
} else if (family == AF_INET6) {
sockaddr_in6* ss6 = reinterpret_cast<sockaddr_in6*>(ss);
return reinterpret_cast<uint8_t*>(&ss6->sin6_addr);
} else if (family == AF_PACKET) {
sockaddr_ll* sll = reinterpret_cast<sockaddr_ll*>(ss);
return reinterpret_cast<uint8_t*>(&sll->sll_addr);
}
return nullptr;
}
};
static void __getifaddrs_callback(void* context, nlmsghdr* hdr) {
ifaddrs** out = reinterpret_cast<ifaddrs**>(context);
if (hdr->nlmsg_type == RTM_NEWLINK) {
ifinfomsg* ifi = reinterpret_cast<ifinfomsg*>(NLMSG_DATA(hdr));
// Create a new ifaddr entry, and set the interface index and flags.
ifaddrs_storage* new_addr = new ifaddrs_storage(out);
new_addr->interface_index = ifi->ifi_index;
new_addr->ifa.ifa_flags = ifi->ifi_flags;
// Go through the various bits of information and find the name.
rtattr* rta = IFLA_RTA(ifi);
size_t rta_len = IFLA_PAYLOAD(hdr);
while (RTA_OK(rta, rta_len)) {
if (rta->rta_type == IFLA_ADDRESS) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->addr)) {
new_addr->SetAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFLA_BROADCAST) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->ifa_ifu)) {
new_addr->SetBroadcastAddress(AF_PACKET, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetPacketAttributes(ifi->ifi_index, ifi->ifi_type, RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFLA_IFNAME) {
if (RTA_PAYLOAD(rta) < sizeof(new_addr->name)) {
memcpy(new_addr->name, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->ifa.ifa_name = new_addr->name;
}
}
rta = RTA_NEXT(rta, rta_len);
}
} else if (hdr->nlmsg_type == RTM_NEWADDR) {
ifaddrmsg* msg = reinterpret_cast<ifaddrmsg*>(NLMSG_DATA(hdr));
// We should already know about this from an RTM_NEWLINK message.
const ifaddrs_storage* addr = reinterpret_cast<const ifaddrs_storage*>(*out);
while (addr != nullptr && addr->interface_index != static_cast<int>(msg->ifa_index)) {
addr = reinterpret_cast<const ifaddrs_storage*>(addr->ifa.ifa_next);
}
// If this is an unknown interface, ignore whatever we're being told about it.
if (addr == nullptr) return;
// Create a new ifaddr entry and copy what we already know.
ifaddrs_storage* new_addr = new ifaddrs_storage(out);
// We can just copy the name rather than look for IFA_LABEL.
strcpy(new_addr->name, addr->name);
new_addr->ifa.ifa_name = new_addr->name;
new_addr->ifa.ifa_flags = addr->ifa.ifa_flags;
new_addr->interface_index = addr->interface_index;
// Go through the various bits of information and find the address
// and any broadcast/destination address.
rtattr* rta = IFA_RTA(msg);
size_t rta_len = IFA_PAYLOAD(hdr);
while (RTA_OK(rta, rta_len)) {
if (rta->rta_type == IFA_ADDRESS) {
if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
new_addr->SetAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
new_addr->SetNetmask(msg->ifa_family, msg->ifa_prefixlen);
}
} else if (rta->rta_type == IFA_BROADCAST) {
if (msg->ifa_family == AF_INET) {
new_addr->SetBroadcastAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
}
} else if (rta->rta_type == IFA_LOCAL) {
if (msg->ifa_family == AF_INET || msg->ifa_family == AF_INET6) {
new_addr->SetLocalAddress(msg->ifa_family, RTA_DATA(rta), RTA_PAYLOAD(rta));
}
}
rta = RTA_NEXT(rta, rta_len);
}
}
}
int getifaddrs(ifaddrs** out) {
// We construct the result directly into `out`, so terminate the list.
*out = nullptr;
// Open the netlink socket and ask for all the links and addresses.
NetlinkConnection nc;
bool okay = nc.SendRequest(RTM_GETLINK) && nc.ReadResponses(__getifaddrs_callback, out) &&
nc.SendRequest(RTM_GETADDR) && nc.ReadResponses(__getifaddrs_callback, out);
if (!okay) {
freeifaddrs(*out);
// Ensure that callers crash if they forget to check for success.
*out = nullptr;
return -1;
}
return 0;
}
void freeifaddrs(ifaddrs* list) {
while (list != nullptr) {
ifaddrs* current = list;
list = list->ifa_next;
free(current);
}
}
| [
"duanliangsilence@gmail.com"
] | duanliangsilence@gmail.com |
5c9f9feafc4f9acbfa3f7b55fbfbf5cab553a398 | 5bc04daeef5284871264a7446aadf7552ec0d195 | /lib/percy/cryptominisat/src/searchstats.cpp | adde61afacd9b0fbee60784d40bc11d2be1f7803 | [
"MIT",
"GPL-1.0-or-later",
"GPL-2.0-only"
] | permissive | Ace-Ma/LSOracle | a8fd7efe8927f8154ea37407bac727e409098ed5 | 6e940906303ef6c2c6b96352f44206567fdd50d3 | refs/heads/master | 2020-07-23T15:36:18.224385 | 2019-08-16T15:58:33 | 2019-08-16T15:58:33 | 207,612,130 | 0 | 0 | MIT | 2019-09-10T16:42:43 | 2019-09-10T16:42:43 | null | UTF-8 | C++ | false | false | 12,107 | cpp | /******************************************
Copyright (c) 2016, Mate Soos
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
***********************************************/
#include "searchstats.h"
using namespace CMSat;
SearchStats& SearchStats::operator+=(const SearchStats& other)
{
numRestarts += other.numRestarts;
blocked_restart += other.blocked_restart;
blocked_restart_same += other.blocked_restart_same;
//Decisions
decisions += other.decisions;
decisionsAssump += other.decisionsAssump;
decisionsRand += other.decisionsRand;
decisionFlippedPolar += other.decisionFlippedPolar;
//Conflict minimisation stats
litsRedNonMin += other.litsRedNonMin;
litsRedFinal += other.litsRedFinal;
recMinCl += other.recMinCl;
recMinLitRem += other.recMinLitRem;
permDiff_attempt += other.permDiff_attempt;
permDiff_rem_lits += other.permDiff_rem_lits;
permDiff_success += other.permDiff_success;
furtherShrinkAttempt += other.furtherShrinkAttempt;
binTriShrinkedClause += other.binTriShrinkedClause;
cacheShrinkedClause += other.cacheShrinkedClause;
furtherShrinkedSuccess += other.furtherShrinkedSuccess;
stampShrinkAttempt += other.stampShrinkAttempt;
stampShrinkCl += other.stampShrinkCl;
stampShrinkLit += other.stampShrinkLit;
moreMinimLitsStart += other.moreMinimLitsStart;
moreMinimLitsEnd += other.moreMinimLitsEnd;
recMinimCost += other.recMinimCost;
//Red stats
learntUnits += other.learntUnits;
learntBins += other.learntBins;
learntLongs += other.learntLongs;
otfSubsumed += other.otfSubsumed;
otfSubsumedImplicit += other.otfSubsumedImplicit;
otfSubsumedLong += other.otfSubsumedLong;
otfSubsumedRed += other.otfSubsumedRed;
otfSubsumedLitsGained += other.otfSubsumedLitsGained;
guess_different += other.guess_different;
cache_hit += other.cache_hit;
red_cl_in_which0 += other.red_cl_in_which0;
//Hyper-bin & transitive reduction
advancedPropCalled += other.advancedPropCalled;
hyperBinAdded += other.hyperBinAdded;
transReduRemIrred += other.transReduRemIrred;
transReduRemRed += other.transReduRemRed;
//Stat structs
resolvs += other.resolvs;
conflStats += other.conflStats;
//Time
cpu_time += other.cpu_time;
return *this;
}
SearchStats& SearchStats::operator-=(const SearchStats& other)
{
numRestarts -= other.numRestarts;
blocked_restart -= other.blocked_restart;
blocked_restart_same -= other.blocked_restart_same;
//Decisions
decisions -= other.decisions;
decisionsAssump -= other.decisionsAssump;
decisionsRand -= other.decisionsRand;
decisionFlippedPolar -= other.decisionFlippedPolar;
//Conflict minimisation stats
litsRedNonMin -= other.litsRedNonMin;
litsRedFinal -= other.litsRedFinal;
recMinCl -= other.recMinCl;
recMinLitRem -= other.recMinLitRem;
permDiff_attempt -= other.permDiff_attempt;
permDiff_rem_lits -= other.permDiff_rem_lits;
permDiff_success -= other.permDiff_success;
furtherShrinkAttempt -= other.furtherShrinkAttempt;
binTriShrinkedClause -= other.binTriShrinkedClause;
cacheShrinkedClause -= other.cacheShrinkedClause;
furtherShrinkedSuccess -= other.furtherShrinkedSuccess;
stampShrinkAttempt -= other.stampShrinkAttempt;
stampShrinkCl -= other.stampShrinkCl;
stampShrinkLit -= other.stampShrinkLit;
moreMinimLitsStart -= other.moreMinimLitsStart;
moreMinimLitsEnd -= other.moreMinimLitsEnd;
recMinimCost -= other.recMinimCost;
//Red stats
learntUnits -= other.learntUnits;
learntBins -= other.learntBins;
learntLongs -= other.learntLongs;
otfSubsumed -= other.otfSubsumed;
otfSubsumedImplicit -= other.otfSubsumedImplicit;
otfSubsumedLong -= other.otfSubsumedLong;
otfSubsumedRed -= other.otfSubsumedRed;
otfSubsumedLitsGained -= other.otfSubsumedLitsGained;
guess_different -= other.guess_different;
cache_hit -= other.cache_hit;
red_cl_in_which0 -= other.red_cl_in_which0;
//Hyper-bin & transitive reduction
advancedPropCalled -= other.advancedPropCalled;
hyperBinAdded -= other.hyperBinAdded;
transReduRemIrred -= other.transReduRemIrred;
transReduRemRed -= other.transReduRemRed;
//Stat structs
resolvs -= other.resolvs;
conflStats -= other.conflStats;
//Time
cpu_time -= other.cpu_time;
return *this;
}
SearchStats SearchStats::operator-(const SearchStats& other) const
{
SearchStats result = *this;
result -= other;
return result;
}
void SearchStats::printCommon(uint64_t props) const
{
print_stats_line("c restarts"
, numRestarts
, float_div(conflStats.numConflicts, numRestarts)
, "confls per restart"
);
print_stats_line("c blocked restarts"
, blocked_restart
, float_div(blocked_restart, numRestarts)
, "per normal restart"
);
print_stats_line("c time", cpu_time);
print_stats_line("c decisions", decisions
, stats_line_percent(decisionsRand, decisions)
, "% random"
);
print_stats_line("c propagations", props);
print_stats_line("c decisions/conflicts"
, float_div(decisions, conflStats.numConflicts)
);
}
void SearchStats::print_short(uint64_t props) const
{
//Restarts stats
printCommon(props);
conflStats.print_short(cpu_time);
print_stats_line("c conf lits non-minim"
, litsRedNonMin
, float_div(litsRedNonMin, conflStats.numConflicts)
, "lit/confl"
);
print_stats_line("c conf lits final"
, float_div(litsRedFinal, conflStats.numConflicts)
);
print_stats_line("c guess different"
, guess_different
, stats_line_percent(guess_different, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c cache hit re-learnt cl"
, cache_hit
, stats_line_percent(cache_hit, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c red which0"
, red_cl_in_which0
, stats_line_percent(red_cl_in_which0, conflStats.numConflicts)
, "% of confl"
);
}
void SearchStats::print(uint64_t props) const
{
printCommon(props);
conflStats.print(cpu_time);
/*assert(numConflicts
== conflsBin + conflsTri + conflsLongIrred + conflsLongRed);*/
cout << "c LEARNT stats" << endl;
print_stats_line("c units learnt"
, learntUnits
, stats_line_percent(learntUnits, conflStats.numConflicts)
, "% of conflicts");
print_stats_line("c bins learnt"
, learntBins
, stats_line_percent(learntBins, conflStats.numConflicts)
, "% of conflicts");
print_stats_line("c long learnt"
, learntLongs
, stats_line_percent(learntLongs, conflStats.numConflicts)
, "% of conflicts"
);
print_stats_line("c otf-subs"
, otfSubsumed
, ratio_for_stat(otfSubsumed, conflStats.numConflicts)
, "/conflict"
);
print_stats_line("c otf-subs implicit"
, otfSubsumedImplicit
, stats_line_percent(otfSubsumedImplicit, otfSubsumed)
, "%"
);
print_stats_line("c otf-subs long"
, otfSubsumedLong
, stats_line_percent(otfSubsumedLong, otfSubsumed)
, "%"
);
print_stats_line("c otf-subs learnt"
, otfSubsumedRed
, stats_line_percent(otfSubsumedRed, otfSubsumed)
, "% otf subsumptions"
);
print_stats_line("c otf-subs lits gained"
, otfSubsumedLitsGained
, ratio_for_stat(otfSubsumedLitsGained, otfSubsumed)
, "lits/otf subsume"
);
print_stats_line("c guess different"
, guess_different
, stats_line_percent(guess_different, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c cache hit re-learnt cl"
, cache_hit
, stats_line_percent(cache_hit, conflStats.numConflicts)
, "% of confl"
);
print_stats_line("c red which0"
, red_cl_in_which0
, stats_line_percent(red_cl_in_which0, conflStats.numConflicts)
, "% of confl"
);
cout << "c SEAMLESS HYPERBIN&TRANS-RED stats" << endl;
print_stats_line("c advProp called"
, advancedPropCalled
);
print_stats_line("c hyper-bin add bin"
, hyperBinAdded
, ratio_for_stat(hyperBinAdded, advancedPropCalled)
, "bin/call"
);
print_stats_line("c trans-red rem irred bin"
, transReduRemIrred
, ratio_for_stat(transReduRemIrred, advancedPropCalled)
, "bin/call"
);
print_stats_line("c trans-red rem red bin"
, transReduRemRed
, ratio_for_stat(transReduRemRed, advancedPropCalled)
, "bin/call"
);
cout << "c CONFL LITS stats" << endl;
print_stats_line("c orig "
, litsRedNonMin
, ratio_for_stat(litsRedNonMin, conflStats.numConflicts)
, "lit/confl"
);
print_stats_line("c recurs-min effective"
, recMinCl
, stats_line_percent(recMinCl, conflStats.numConflicts)
, "% attempt successful"
);
print_stats_line("c recurs-min lits"
, recMinLitRem
, stats_line_percent(recMinLitRem, litsRedNonMin)
, "% less overall"
);
print_stats_line("c permDiff call%"
, stats_line_percent(permDiff_attempt, conflStats.numConflicts)
, stats_line_percent(permDiff_success, permDiff_attempt)
, "% attempt successful"
);
print_stats_line("c permDiff lits-rem"
, permDiff_rem_lits
, ratio_for_stat(permDiff_rem_lits, permDiff_attempt)
, "less lits/cl on attempts"
);
print_stats_line("c further-min call%"
, stats_line_percent(furtherShrinkAttempt, conflStats.numConflicts)
, stats_line_percent(furtherShrinkedSuccess, furtherShrinkAttempt)
, "% attempt successful"
);
print_stats_line("c bintri-min lits"
, binTriShrinkedClause
, stats_line_percent(binTriShrinkedClause, litsRedNonMin)
, "% less overall"
);
print_stats_line("c cache-min lits"
, cacheShrinkedClause
, stats_line_percent(cacheShrinkedClause, litsRedNonMin)
, "% less overall"
);
print_stats_line("c stamp-min call%"
, stats_line_percent(stampShrinkAttempt, conflStats.numConflicts)
, stats_line_percent(stampShrinkCl, stampShrinkAttempt)
, "% attempt successful"
);
print_stats_line("c stamp-min lits"
, stampShrinkLit
, stats_line_percent(stampShrinkLit, litsRedNonMin)
, "% less overall"
);
print_stats_line("c final avg"
, ratio_for_stat(litsRedFinal, conflStats.numConflicts)
);
//General stats
//print_stats_line("c Memory used", (double)mem_used / 1048576.0, " MB");
#if !defined(_MSC_VER) && defined(RUSAGE_THREAD)
print_stats_line("c single-thread CPU time", cpu_time, " s");
#else
print_stats_line("c all-threads sum CPU time", cpu_time, " s");
#endif
}
| [
"u1219556@lnissrv4.eng.utah.edu"
] | u1219556@lnissrv4.eng.utah.edu |
0565e34f5037257917532642ca570db09b5ec01e | e755f58efd833ee1133b427ea21cbd052e9907ed | /src/include/migraphx/op/elu.hpp | bbf73d8a70a1500a595ff2aa5589e7f6a82fbeff | [
"MIT"
] | permissive | f0rmiga/AMDMIGraphX | 87d33acbd77341098f0040039c342129d829e3ce | e66968a25f9342a28af1157b06cbdbf8579c5519 | refs/heads/master | 2022-12-16T18:55:26.749316 | 2020-07-10T22:16:55 | 2020-07-10T22:16:55 | 290,550,990 | 0 | 0 | NOASSERTION | 2020-08-26T16:39:36 | 2020-08-26T16:39:35 | null | UTF-8 | C++ | false | false | 900 | hpp | #ifndef MIGRAPHX_GUARD_OPERATORS_ELU_HPP
#define MIGRAPHX_GUARD_OPERATORS_ELU_HPP
#include <array>
#include <migraphx/operation.hpp>
#include <migraphx/check_shapes.hpp>
#include <migraphx/stringutils.hpp>
#include <migraphx/streamutils.hpp>
#include <migraphx/literal.hpp>
#include <migraphx/shape_for_each.hpp>
#include <migraphx/config.hpp>
#include <cmath>
#include <utility>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace op {
struct elu
{
std::string name() const { return "elu"; }
float alpha;
shape compute_shape(std::vector<shape> inputs) const
{
check_shapes{inputs, *this}.has(1);
return inputs.front();
}
template <class Self, class F>
static auto reflect(Self& self, F f)
{
return pack(f(self.alpha, "alpha"));
}
};
} // namespace op
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
#endif
| [
"Shucai.Xiao@amd.com"
] | Shucai.Xiao@amd.com |
0a03d7e69838ee7c96d55abc0e12532684402e61 | f0dbabac157fc79094062513cfcc28be253d9b70 | /modules/types/include/Tanker/Types/TankerSecretProvisionalIdentity.hpp | c7d90eecaa9198e1ba6c7b7d067eb4b8d3a6ced6 | [
"Apache-2.0"
] | permissive | TankerHQ/sdk-native | 4c3a81d83a9e144c432ca74c3e327225e6814e91 | c062edc4b6ad26ce90e0aebcc2359adde4ca65db | refs/heads/master | 2023-08-19T02:59:40.445973 | 2023-08-09T12:04:46 | 2023-08-09T12:04:46 | 160,206,027 | 20 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 265 | hpp | #pragma once
#include <Tanker/Crypto/EncryptionKeyPair.hpp>
#include <Tanker/Crypto/SignatureKeyPair.hpp>
namespace Tanker
{
struct TankerSecretProvisionalIdentity
{
Crypto::EncryptionKeyPair encryptionKeyPair;
Crypto::SignatureKeyPair signatureKeyPair;
};
}
| [
"alexandre.bossard@tanker.io"
] | alexandre.bossard@tanker.io |
e556587cbec6791a4dc8e5c1f0549d5b4fea1742 | bc2e7366c81ed4b996d3571c90d9470af47e4dc8 | /Problems/Problem4/src/main/Book.cpp | 6e798bfb3889b10ac125fe793661fb4a749ff00b | [] | no_license | arprabhu/CPP_Exercises | 046577ea73be9abfa17f66d5dd72800e5a5ab95b | 496541c3d0da7cc5294ad72cd29be339c1f69c05 | refs/heads/master | 2020-03-08T16:11:05.657844 | 2018-04-05T16:19:30 | 2018-04-05T16:19:30 | 128,232,901 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 145 | cpp | #include <Book.h>
Book::Book(const std::string& title ):title(title){
}
std::string Book::read(){
return std::string("Read book: " + title);
} | [
"38109924+arprabhu@users.noreply.github.com"
] | 38109924+arprabhu@users.noreply.github.com |
b47ad9dfb349186a3395a0890dcce4732c6dbac6 | 4b2aa0114449523ca9d98e9e25005c130d64547b | /ICPC/Challenge2013/GA/current_snapshot/classes.h | e24a13e06e9bdb586d901a0b7ebb28f7505a048f | [] | no_license | HowardChengUleth/codelibrary | 7793d86df4f82994770e8f1c19c7d240cadac9cd | d93fa3fc94792276c6f2cf2b480a445ec0bb8c32 | refs/heads/master | 2023-03-06T00:45:23.522994 | 2023-03-02T01:45:22 | 2023-03-02T01:45:22 | 136,532,622 | 10 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 12,798 | h | #ifndef __UOFL_ICPC_CHALLENGE_CLASSES__
#define __UOFL_ICPC_CHALLENGE_CLASSES__
#include <iostream>
#include <vector>
#include <tr1/tuple>
#include <cassert>
#include <queue>
#include "globals.h"
using namespace std;
using namespace std::tr1;
////////////////////////////////////////////////////////////////////////////
// Union Find
////////////////////////////////////////////////////////////////////////////
struct UnionFind
{
vector<int> uf;
UnionFind(int n) : uf(n) {
for (int i = 0; i < n; i++) uf[i] = i;
}
int find(int x) {
return (uf[x] == x) ? x : (uf[x] = find(uf[x]));
}
bool merge(int x, int y) {
int res1 = find(x), res2 = find(y);
if (res1 == res2) return false;
uf[res2] = res1;
return true;
}
};
extern UnionFind uf;
////////////////////////////////////////////////////////////////////////////
// Gold
////////////////////////////////////////////////////////////////////////////
struct Gold{
int row,col,id;
};
extern vector<Gold> golds; //, golds2;
////////////////////////////////////////////////////////////////////////////
// Position
////////////////////////////////////////////////////////////////////////////
class Position {
public:
Position(uchar r=0, uchar c=0): row(r), col(c) {}
bool operator==(const Position &p) const { return (row == p.row) && (col == p.col); }
public:
char row;
char col;
};
ostream& operator<<(ostream &os, const Position &p);
istream& operator>>(istream &is, Position &p);
const Position NO_POS = Position(-1, -1);
extern vector<Position> nuggets;
////////////////////////////////////////////////////////////////////////////
// Move
////////////////////////////////////////////////////////////////////////////
class Move {
private:
Move(char dr, char dc, char l) : dRow(dr), dCol(dc), label(l) {}
public:
Position apply(const Position &p) const {
return Position(p.row + dRow, p.col + dCol);
}
bool operator==(const Move &m) const {
if (this == &m) return true;
if (this->dRow != m.dRow)
return false;
if (this->dCol != m.dCol)
return false;
return true;
}
public:
char dRow;
char dCol;
char label;
static const Move UP;
static const Move DOWN;
static const Move LEFT;
static const Move RIGHT;
static const Move NONE;
};
const Move& reverse(const Move &m);
const Move& getMove(cmd c);
////////////////////////////////////////////////////////////////////////////
// Board
////////////////////////////////////////////////////////////////////////////
typedef tuple<int,int,int,int,cmd> tiiiic; // Like the typedef name?
typedef priority_queue<tiiiic,vector<tiiiic>,greater<tiiiic> > PQ;
class Board {
private:
int uf_index(int r, int c) const
{
return r * WIDTH + c;
}
/*
void BFS_no_fall();
void SS_BFS_no_fall(int r,int c,int dist[HEIGHT][WIDTH]);
void SS_BFS_with_fall(int r,int c,int delay);
void update_and_add(PQ& pq,vector<cmd> moves[HEIGHT][WIDTH],
int dist2[HEIGHT][WIDTH][11],
int nDist,int nI,int nJ,int nD,cmd nC);
*/
public:
/* ============================================
Storage
The board will be stored as a 2D array of unsigned chars. However, I've used a bit of a different mapping
than what the game does:
1 : empty
2 : ladder
3 : gold cell
4-153: removed gold cell, will resurface in val-3 turns
154: brick
155-179 : removed brick by our player, will resurface in val-154 turns
180-204 : removed brick by our opponent, will resurface in val-179 turns
205-229 : removed brick by both opponents, will resurface in val-204 turns
Using this approach, we can store complete information regarding cells using single chars for each cell.
============================================= */
Board() {}
vector<cmd> valid_moves(int row,int col,bool canDig) const;
vector<Move> valid_movesM(int row,int col,bool canDig) const;
uchar operator[](const Position &p) const {
return cells[(uchar)p.row][(uchar)p.col];
}
uchar& operator[](const Position &p) {
return cells[(uchar)p.row][(uchar)p.col];
}
bool removedGold(const Position &p) const {
return ((*this)[p] > 3) && ( (*this)[p] < 154 );
}
void removeBrick(const Position &p, bool isMe) {
if (isMe) {
if ((*this)[p] == 204)
(*this)[p] = 229;
else
(*this)[p] = 179;
} else {
if ((*this)[p] == 179)
(*this)[p] = 229;
else
(*this)[p] = 204;
}
}
int brick_respawns_in(int r, int c) const
{
Position p(r,c);
if (visible(p) != REMOVED_BRICK) return -1;
if (cells[r][c] > 204) return cells[r][c] - 204;
if (cells[r][c] > 179) return cells[r][c] - 179;
if (cells[r][c] > 154) return cells[r][c] - 154;
#ifndef FINAL_VERSION
assert(false);
#endif
return -1;
}
int gold_respawns_in(int r, int c) const
{
if (cells[r][c] == 3) return -1;
if (4 <= cells[r][c] && cells[r][c] <= 153) return cells[r][c]-3;
return -1;
}
bool opp_dug_me(int r, int c) const
{
return cells[r][c] >= 180;
}
// returns what is visible. Gold cells that have removed gold will return as empty. Removed bricks will always
// return as removed brick, regardless of who removed it.
uchar visible(const Position &p) const {
uchar c = (*this)[p];
if (c == 1)
return EMPTY;
if (c == 2)
return LADDER;
if (c == 3)
return GOLD;
if (c < 154)
return EMPTY;
if (c == 154)
return BRICK;
return REMOVED_BRICK;
}
uchar visible(int r, int c) const;
Board visibleBoard() const {
Board b(*this);
for (int row = 0; row < HEIGHT; row++) {
for (int col = 0; col < WIDTH; col++) {
Position p(row, col);
b[p] = visible(p);
}
}
return b;
}
// Initializes the board before anyone is on it
//void init(int r,int c,int delay);
/*
// initializes the SCCs
void initSCC();
int scc_index(int r, int c)
{
return uf.find(uf_index(r, c));
}
bool is_SCC_leaf(int r, int c)
{
return SCC_leaf[scc_index(r, c)];
}
*/
// Determines if you can stand on a location.
// -- Only considers the map layout, not Enemies.
bool canStand(int r, int c) const;
public: // not necessary, but I'm used to having my member variables in the bottom of my declaration beneath a modifier.
uchar cells[HEIGHT][WIDTH];
};
ostream& operator<<(ostream &os, const Board &p);
istream& operator>>(istream &is, Board &p);
/////////////////////////////////////////////////////////////////////////
// Dude
/////////////////////////////////////////////////////////////////////////
class Dude {
public:
Dude(const Position &p=Position(0,0)) : pos(p), death_count(0) {}
bool isDead() const { return pos == Position(-1,-1); }
public:
Position pos;
int death_count; // death count is the number of remaining turns until alive again.
};
/////////////////////////////////////////////////////////////////////////
// Player
/////////////////////////////////////////////////////////////////////////
class Player : public Dude {
public:
Player(const Position &p=Position(0,0)) : Dude(p), score(0), mason_count(0) {}
public:
int score;
uchar mason_count;
};
istream& operator>>(istream &is, Player &p);
ostream& operator<<(ostream &os, const Player &p);
/////////////////////////////////////////////////////////////////////////
// Enemy
/////////////////////////////////////////////////////////////////////////
class Enemy : public Dude {
public:
Enemy(const Position &p=Position(0,0)) : Dude(p), ip(0), master(-1), lastMove(0) { }
public:
uchar ip; // instruction pointer
string stack; // stack of moves
char master; // 0 - me, 1 - me, -1 - you
int lastMove;
char respawn_row, respawn_col;
};
istream& operator>>(istream &is, Enemy &p);
ostream& operator<<(ostream &os, const Enemy &p);
extern vector<Enemy> enemies,enemies2;
/////////////////////////////////////////////////////////////////////////
// Game
/////////////////////////////////////////////////////////////////////////
class Game {
public:
Game() : turns(0) { }
public:
int turns;
Board board;
Position me, you;
vector<Position> enemyPos;
vector<string> enemyProgram;
};
istream& operator>>(istream &is, Game &g);
ostream& operator<<(ostream &os, const Game &g);
extern Game g;
/////////////////////////////////////////////////////////////////////////
// State
/////////////////////////////////////////////////////////////////////////
class State {
public:
State() : turn(0) {}
State(const Game &g);
bool fallingDude(const Dude &p) const;
bool fallingEnemy(const Enemy &p) const;
bool legal(const Position &p) const;
bool canNonFall(const Dude &p, const Move &move) const;
void applyNonFall(const Dude &p, Dude &newp, const Move &move) const;
void applyMoveDude(const Dude &p, Dude &newp, const cmd &command) const;
void update(const Move *prevMove[HEIGHT][WIDTH],
Position prevPosition[HEIGHT][WIDTH],
queue< pair<Position, int> > &myqueue, const Position &position,
int step, const Position &prev, const Move &move) const;
bool fallingPursuit(const Position &pos) const;
pair<const Move *, int> getPursuitMove(const Enemy &enemy,
const Player &player,
const Move **moves, int limit) const;
void applyMoveEnemy(const Enemy &enemy, Enemy &newEnemy,
string program, bool left, int turn) const;
void killDude(Dude &d, uchar turns) const {
d.pos = Position(-1, -1);
d.death_count = turns;
}
void restoreDude(Dude &d, const Position &start) {
d.pos = start;
}
bool canDestroyBrick(const Player &p, const Position &sideCell,
const Position &targetCell) const;
void respawn(Dude &d, const Position &start) const {
if (d.death_count > 0) {
d.death_count--;
if (d.death_count == 0) {
d.pos = start;
}
}
}
void checkForCollision(Player &p) {
if (p.isDead())
return;
for (unsigned int i = 0; i < enemies.size(); i++) {
if (p.pos == enemies[i].pos) {
killDude(p, 50);
return;
}
}
}
State getNewState(const Game &g, cmd myCommand, cmd yourCommand) const {
State newState(*this);
return getNewState(g, myCommand, yourCommand, newState);
}
State& getNewState(const Game &g, cmd myCommand, cmd yourCommand,
State &newState) const;
public:
int turn;
Board board;
bool visited[HEIGHT][WIDTH];
Player me, you;
vector<Enemy> enemies;
};
istream& readInState(istream &is, State &g, int enemyCount);
ostream& operator<<(ostream &os, const State &s);
/////////////////////////////////////////////////////////////////////////
// StateEngine
/////////////////////////////////////////////////////////////////////////
class StateEngine {
public:
StateEngine(const Game &pg, bool kgoe=true)
: g(pg), gameStatus(new State(g)), ourStatus(0), killGameOnError(kgoe) {}
void next(istream &is, const string &myMove);
public:
const Game g;
State *gameStatus;
State *ourStatus;
bool killGameOnError;
};
extern StateEngine *se;
/////////////////////////////////////////////////////////////////////////
// Lookahead
/////////////////////////////////////////////////////////////////////////
class Lookahead {
public:
static void getViableCommands( const State &status, const Player &p,
vector<cmd> &commands );
private:
static double boundedLookaheadScore( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, State *stack );
public:
static int boundedLookahead( const Game &g, const State &status,
int maxDepth, int turns_remaining,
vector<cmd> &potentials );
static double boundedLookaheadScoreABD( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, State *stack );
static int boundedLookaheadABD( const Game &g, const State &status,
int maxDepth, int turns_remaining,
int threshold, vector<cmd> &potentials );
static double boundedLookaheadScoreNewDecay( const Game &g, const State &status,
int depth, int max_depth,
int turns_remaining, int oldScore, double currScore, double decay, State *stack );
};
/////////////////////////////////////////////////////////////////////////
// Utilities
/////////////////////////////////////////////////////////////////////////
// this is a sanity check. It is a superficial check that compares to what
// we are receiving from the game engine.
bool equivalent(const Player &e1, const Player &e2);
bool equivalent(const Enemy &e1, const Enemy &e2);
bool equivalent(const State &s1, const State &s2, bool verbose=false);
#endif
| [
"howard.cheng@uleth.ca"
] | howard.cheng@uleth.ca |
3635711d76d04483288c9b589d062ebd7caa8344 | ae4d038d994359a59d0681d4d63fac5236e03ca0 | /src/qiskit-simulator/src/simulator.hpp | 21a9af4efa7faf03134964dc726349a645c2f71d | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | akarazeev/qiskit-sdk-py | df51f1ff4b142355f60a4e237d1e5613b1ff5914 | d54d2bab8ba3ea76946ec11e7fbdf67f5d5c49b1 | refs/heads/master | 2021-04-15T18:57:02.080231 | 2018-03-25T08:48:09 | 2018-03-25T08:48:09 | 126,679,293 | 0 | 0 | Apache-2.0 | 2018-03-25T08:45:42 | 2018-03-25T08:45:42 | null | UTF-8 | C++ | false | false | 10,333 | hpp | /*
Copyright (c) 2017 IBM Corporation. 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.
*/
/**
* @file simulator.hpp
* @brief Simulator class
* @author Christopher J. Wood <cjwood@us.ibm.com>
*/
#ifndef _Simulator_hpp_
#define _Simulator_hpp_
#include <chrono>
#include <iostream>
#include <random>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
// Parallelization
#ifdef _OPENMP
#include <omp.h> // OpenMP
#else
#include <future> // C++11
#endif
#include "circuit.hpp"
#include "misc.hpp"
#include "noise_models.hpp"
#include "types.hpp"
// Engines
#include "base_engine.hpp"
#include "sampleshots_engine.hpp"
#include "vector_engine.hpp"
// Backends
#include "clifford_backend.hpp"
#include "ideal_backend.hpp"
#include "qubit_backend.hpp"
namespace QISKIT {
/***************************************************************************/ /**
*
* Simulator class
*
******************************************************************************/
class Simulator {
public:
std::string id = ""; // simulation id
std::string simulator = "qubit"; // simulator backend label
std::vector<Circuit> circuits; // QISKIT program
// Multithreading Params
uint_t max_memory_gb = 16; // max memory to use
uint_t max_threads_shot = 0; // 0 for automatic
uint_t max_threads_gate = 0; // 0 for automatic
// Constructor
inline Simulator(){};
// Execute all quantum circuits
json_t execute();
// Execute a single circuit
template <class Engine, class Backend>
json_t run_circuit(Circuit &circ) const;
};
/*******************************************************************************
*
* Simulator Methods
*
******************************************************************************/
json_t Simulator::execute() {
// Initialize ouput JSON
std::chrono::time_point<myclock_t> start = myclock_t::now(); // start timer
json_t ret;
ret["id"] = id;
if (simulator == "clifford")
ret["backend"] = std::string("local_clifford_simulator");
else
ret["backend"] = std::string("local_qiskit_simulator");
ret["simulator"] = simulator;
// Choose simulator and execute circuits
try {
bool qobj_success = true;
for (auto &circ : circuits) {
json_t circ_res;
// Choose Simulator Backend
if (simulator == "clifford")
circ_res = run_circuit<BaseEngine<Clifford>, CliffordBackend>(circ);
else if (simulator == "ideal")
circ_res = run_circuit<SampleShotsEngine, IdealBackend>(circ);
else
circ_res = run_circuit<VectorEngine, QubitBackend>(circ);
// Check results
qobj_success &= circ_res["success"].get<bool>();
ret["result"].push_back(circ_res);
}
ret["time_taken"] =
std::chrono::duration<double>(myclock_t::now() - start).count();
ret["status"] = std::string("COMPLETED");
ret["success"] = qobj_success;
} catch (std::exception &e) {
ret["success"] = false;
ret["status"] = std::string("ERROR: ") + e.what();
}
return ret;
}
//------------------------------------------------------------------------------
template <class Engine, class Backend>
json_t Simulator::run_circuit(Circuit &circ) const {
std::chrono::time_point<myclock_t> start = myclock_t::now(); // start timer
json_t ret; // results JSON
// Check max qubits
uint_t max_qubits =
static_cast<uint_t>(floor(log2(max_memory_gb * 1e9 / 16.)));
if ((simulator == "qubit" || simulator == "ideal") &&
circ.nqubits > max_qubits) {
ret["success"] = false;
std::stringstream msg;
msg << "ERROR: Number of qubits (" << circ.nqubits
<< ") exceeds maximum memory (" << max_memory_gb << " GB).";
ret["status"] = msg.str();
return ret;
}
// Try to execute circuit
try {
// Initialize reference engine and backend from JSON config
Engine engine = circ.config;
Backend backend = circ.config;
// Set RNG Seed
uint_t rng_seed = (circ.rng_seed < 0) ? std::random_device()()
: static_cast<uint_t>(circ.rng_seed);
// Thread number
#ifdef _OPENMP
uint_t ncpus = omp_get_num_procs(); // OMP method
omp_set_nested(1); // allow nested parallel threads
#else
uint_t ncpus = std::thread::hardware_concurrency(); // C++11 method
#endif
ncpus = std::max(1ULL, ncpus); // check 0 edge case
int_t dq = (max_qubits > circ.nqubits) ? max_qubits - circ.nqubits : 0;
uint_t threads = std::max<uint_t>(1UL, 2 * dq);
if (simulator == "ideal" && circ.opt_meas)
threads = 1; // single shot thread
else {
threads = std::min<uint_t>(threads, ncpus);
threads = std::min<uint_t>(threads, circ.shots);
if (max_threads_shot > 0)
threads = std::min<uint_t>(max_threads_shot, threads);
}
uint_t gate_threads = std::max<uint_t>(1UL, ncpus / threads);
if (max_threads_gate > 0)
gate_threads = std::min<uint_t>(max_threads_gate, gate_threads);
// Single-threaded shots loop
if (threads < 2) {
// Run shots on single-thread
backend.set_rng_seed(rng_seed);
engine.run_program(circ, &backend, circ.shots, gate_threads);
}
// Parallelized shots loop
else {
// Set rng seed for each thread
std::vector<std::pair<uint_t, uint_t>> shotseed;
for (uint_t j = 0; j < threads; ++j)
shotseed.push_back(std::make_pair(circ.shots / threads, rng_seed + j));
shotseed[0].first += (circ.shots % threads);
// OMP Execution
#ifdef _OPENMP
std::vector<Engine> futures(threads);
#pragma omp parallel for if (threads > 1) num_threads(threads)
for (uint_t j = 0; j < threads; j++) {
const auto &ss = shotseed[j];
Backend be(backend);
be.set_rng_seed(ss.second);
futures[j] = engine;
futures[j].run_program(circ, &be, ss.first, gate_threads);
}
for (auto &f : futures)
engine += f;
// C++11 Execution
#else
std::vector<std::future<Engine>> futures;
for (auto &&ss : shotseed)
futures.push_back(async(std::launch::async, [&]() {
Engine eng(engine);
Backend be(backend);
be.set_rng_seed(ss.second);
eng.run_program(circ, &be, ss.first);
return eng;
}));
// collect results
for (auto &&f : futures)
engine += f.get();
#endif
} // end parallel shots
// Return results
ret["data"] = engine; // add engine output to return
if (simulator != "ideal" && JSON::check_key("noise_params", circ.config)) {
ret["noise_params"] = backend.noise;
}
// Add time taken and return result
ret["data"]["time_taken"] =
std::chrono::duration<double>(myclock_t::now() - start).count();
// Add metadata
ret["name"] = circ.name;
ret["shots"] = circ.shots;
ret["seed"] = rng_seed;
if (threads > 1)
ret["threads_shot"] = threads;
// Report success
ret["success"] = true;
ret["status"] = std::string("DONE");
} catch (std::exception &e) {
ret["success"] = false;
ret["status"] = std::string("ERROR: ") + e.what();
}
return ret;
}
//------------------------------------------------------------------------------
inline bool check_qobj(const json_t &qobj) {
std::vector<std::string> qobj_keys{"id", "circuits"}; // optional: "config"
std::vector<std::string> compiled_keys{"header", "operations"};
std::vector<std::string> header_keys{"clbit_labels", "number_of_clbits",
"number_of_qubits", "qubit_labels"};
bool pass = JSON::check_keys(qobj_keys, qobj);
if (pass) {
for (auto &c : qobj["circuits"]) {
pass &= JSON::check_key("compiled_circuit", c);
if (pass) {
pass &= JSON::check_keys(compiled_keys, c["compiled_circuit"]);
if (pass)
pass &=
JSON::check_keys(header_keys, c["compiled_circuit"]["header"]);
}
}
}
return pass;
}
//------------------------------------------------------------------------------
inline void from_json(const json_t &js, Simulator &qobj) {
try {
if (check_qobj(js)) { // check valid qobj
qobj = Simulator();
JSON::get_value(qobj.id, "id", js);
json_t config;
JSON::get_value(config, "config", js);
// Multithreading Parameters
JSON::get_value(qobj.max_memory_gb, "max_memory", config);
JSON::get_value(qobj.max_threads_shot, "max_threads_shot", config);
JSON::get_value(qobj.max_threads_gate, "max_threads_gate", config);
// Override with user simulator backend specification
JSON::get_value(qobj.simulator, "simulator", config);
to_lowercase(qobj.simulator);
// Set simulator gateset
gateset_t gateset;
if (qobj.simulator == "qubit") {
gateset = QubitBackend::gateset;
} else if (qobj.simulator == "ideal") {
gateset = IdealBackend::gateset;
} else if (qobj.simulator == "clifford") {
gateset = CliffordBackend::gateset;
} else {
throw std::runtime_error(std::string("invalid simulator."));
}
// Load unrolled qasm circuits
const json_t &circs = js["circuits"];
for (auto it = circs.cbegin(); it != circs.cend(); ++it)
qobj.circuits.push_back(Circuit(*it, config, gateset));
} else {
throw std::runtime_error(std::string("invalid qobj file."));
}
} catch (std::exception &e) {
std::stringstream msg;
msg << "unable to parse qobj, " << e.what();
throw std::runtime_error(msg.str());
}
}
//------------------------------------------------------------------------------
} // end namespace QISKIT
//------------------------------------------------------------------------------
#endif | [
"cjwood@us.ibm.com"
] | cjwood@us.ibm.com |
ca577c099d33eb16636a159195b87c318dda4309 | a7f0fdadbf539857f57b2b1120268d7c93b76083 | /tests/funcexample.cpp | 25581ba128f19ad67fef7de20c7664c235de36b2 | [] | no_license | SethForrest/Compilers_HW_1 | bf8579b8cb380107aef493170a8f9c359417939d | 17696280cd133a49039ca272d66f7461d4314e1e | refs/heads/master | 2021-01-19T20:03:00.381455 | 2017-09-08T03:35:17 | 2017-09-08T03:35:17 | 101,217,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 397 | cpp | #include <iostream>
using namespace std;
double myfunc(double, double);
double goof(double);
int main()
{
double x, y;
double z;
z = myfunc(x, y);
cout << "zed was " << z << endl;
return 0;
}
double myfunc(double x, double y)
{
x = goof(2.0);
return x;
}
double goof(double branflakes)
{
double bf2 = branflakes + 2.0;
cout << "bf2 is " << bf2 << endl;
return goof(bf2);
}
| [
"Seth.Forrest@gmail.com"
] | Seth.Forrest@gmail.com |
5fff3d8945c65a16d2d350234039d1c747894d0c | 341fbbaa6d7e9b8cf5beba68bde5c8c1090cf3ef | /按 OJ 分类/HDU/f-HDU-2017 多校训练赛10-1002-Array Challenge/f-HDU-2017 多校训练赛10-1002-Array Challenge/main.cpp | f5dea350f5140ca4d86ecb4ff945c695b5c77a88 | [] | no_license | webturing/ACM-1 | 0ceb79e5439a95315234ae1e8bee93b353305459 | 7fcf14d1ff2ae42b001139d04bde01378fb4f5c4 | refs/heads/master | 2020-03-19T17:33:37.098619 | 2018-06-09T17:07:14 | 2018-06-09T17:07:14 | 136,766,339 | 3 | 0 | null | 2018-06-09T23:59:30 | 2018-06-09T23:59:30 | null | UTF-8 | C++ | false | false | 1,933 | cpp | //
// main.cpp
// f-HDU-2017 多校训练赛10-1002-Array Challenge
//
// Created by ZYJ on 2017/8/29.
// Copyright © 2017年 ZYJ. All rights reserved.
//
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const int MAGIC_1 = 31;
const int MAGIC_2 = 197;
const int MAGIC_3 = 1255;
struct matrix
{
ll v[3][3];
matrix()
{
memset(v, 0, sizeof(v));
}
};
ll n;
matrix M, E, ans;
void init()
{
for (int i = 0; i < 3; i++)
{
E.v[i][i] = 1;
}
M.v[0][0] = 4, M.v[0][1] = 17, M.v[0][2] = -12;
M.v[1][0] = 1, M.v[1][1] = 0, M.v[1][2] = 0;
M.v[2][0] = 0, M.v[2][1] = 1, M.v[2][2] = 0;
}
matrix mul(matrix a, matrix b)
{
matrix c;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
c.v[i][j] = (c.v[i][j] % MOD + a.v[i][k] * b.v[k][j] % MOD + MOD) % MOD;
}
}
}
return c;
}
matrix pow(matrix p, ll k)
{
matrix tmp = E;
while (k)
{
if (k & 1)
{
tmp = mul(tmp, p);
k--;
}
k >>= 1;
p = mul(p, p);
}
return tmp;
}
int main()
{
init();
int T;
scanf("%d", &T);
while (T--)
{
scanf("%lld", &n);
if (n == 2)
{
printf("%d\n", MAGIC_1);
}
else if (n == 3)
{
printf("%d\n", MAGIC_2);
}
else if (n == 4)
{
printf("%d\n", MAGIC_3);
}
else
{
ans = pow(M, n - 4);
ll res = (ans.v[0][0] * MAGIC_3 % MOD
+ ans.v[0][1] * MAGIC_2 % MOD
+ ans.v[0][2] * MAGIC_1 % MOD + MOD) % MOD;
printf("%lld\n", res);
}
}
return 0;
}
| [
"1179754741@qq.com"
] | 1179754741@qq.com |
3eae6d7623528c220db63a64acb20a3b5b0bdff5 | 01eef489b10bf76a920b0227a1ded1c7cb1e2cce | /New_Game_3D_2/KeyInput.cpp | 50626d556e7c7ed599953f757f1c15c2d253ca99 | [] | no_license | syogo1903x/Protect-The-Tower | 295beba154a8abe7053d2f8afe67353f617ab32c | a0559a128e59b0ea44ebff801469d0d00c9b8b04 | refs/heads/master | 2020-05-21T13:26:29.319076 | 2019-05-11T01:18:25 | 2019-05-11T01:18:25 | 182,363,239 | 0 | 0 | null | 2019-04-20T07:17:21 | 2019-04-20T05:14:09 | RPC | SHIFT_JIS | C++ | false | false | 1,413 | cpp | #include "KeyInput.h"
KeyInput::KeyInput()
{
}
KeyInput::~KeyInput()
{
}
void KeyInput::Init_Key()
{
int i, j;
for(i = 0; i < 2; i++)
{
for (j = 0; j < 256; j++)
{
keyState[i][j] = 0;
key[j] = KEY_OFF;
}
}
nowKey = 0; prevKey = 1;
}
void KeyInput::Update_Key()
{
// 現在のキーと一つ前のフレームのキー状態を入れ替える
nowKey ^= 1;
prevKey = nowKey ^ 1;
// キー状態取得
GetHitKeyStateAll(keyState[nowKey]);
//
for (int i = 0; i < 256; i++)
{
char nowInput = keyState[nowKey][i];
char prevInput = keyState[prevKey][i];
if (nowInput)
{
//現在押されている
//前のフレームも押されていた?
if (prevInput)
{
key[i] = KEY_PRESSED; // 押されっぱなし
}
else {
key[i] = KEY_ON;// 今押された
}
}
else
{
// 現在キーは押されていない
// 前のフレームで押されていた?
if (prevInput)
{
key[i] = KEY_RELEASE;
}
else {
key[i] = KEY_OFF;
}
}
}
}
KEY_STATE KeyInput::GetKey(unsigned char _keyCode)
{
return key[_keyCode];
}
| [
"ooyamasyogo@icloud.com"
] | ooyamasyogo@icloud.com |
db20e44d081fd8045703ba4dfb6dad7c506e887d | 9b25f9cf63e0bee6654ebdbc8b067a2d3c393a25 | /App/ios/Pods/Flipper-Folly/folly/experimental/coro/BlockingWait.h | f621faeb2c92b8d4bdeb19ff2a41528faf6e8e49 | [
"MIT",
"Apache-2.0"
] | permissive | camhinton/How_Much_Workout_App | 89092a629f59269b683d564d9f330b24ff613704 | 785defb76e57253d968a0173248b3706feccc78a | refs/heads/main | 2023-07-18T04:28:23.925481 | 2021-08-30T17:40:25 | 2021-08-30T17:40:25 | 401,179,472 | 0 | 0 | MIT | 2021-08-30T17:34:09 | 2021-08-30T01:15:40 | JavaScript | UTF-8 | C++ | false | false | 12,859 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <folly/Try.h>
#include <folly/executors/ManualExecutor.h>
#include <folly/experimental/coro/Coroutine.h>
#include <folly/experimental/coro/Task.h>
#include <folly/experimental/coro/Traits.h>
#include <folly/experimental/coro/ViaIfAsync.h>
#include <folly/experimental/coro/WithAsyncStack.h>
#include <folly/experimental/coro/detail/Malloc.h>
#include <folly/experimental/coro/detail/Traits.h>
#include <folly/fibers/Baton.h>
#include <folly/synchronization/Baton.h>
#include <folly/tracing/AsyncStack.h>
#include <cassert>
#include <exception>
#include <type_traits>
#include <utility>
#if FOLLY_HAS_COROUTINES
namespace folly {
namespace coro {
namespace detail {
template <typename T>
class BlockingWaitTask;
class BlockingWaitPromiseBase {
struct FinalAwaiter {
bool await_ready() noexcept { return false; }
template <typename Promise>
void await_suspend(coroutine_handle<Promise> coro) noexcept {
BlockingWaitPromiseBase& promise = coro.promise();
folly::deactivateAsyncStackFrame(promise.getAsyncFrame());
promise.baton_.post();
}
void await_resume() noexcept {}
};
public:
BlockingWaitPromiseBase() noexcept = default;
static void* operator new(std::size_t size) {
return ::folly_coro_async_malloc(size);
}
static void operator delete(void* ptr, std::size_t size) {
::folly_coro_async_free(ptr, size);
}
suspend_always initial_suspend() { return {}; }
FinalAwaiter final_suspend() noexcept { return {}; }
template <typename Awaitable>
decltype(auto) await_transform(Awaitable&& awaitable) {
return folly::coro::co_withAsyncStack(static_cast<Awaitable&&>(awaitable));
}
bool done() const noexcept { return baton_.ready(); }
void wait() noexcept { baton_.wait(); }
folly::AsyncStackFrame& getAsyncFrame() noexcept { return asyncFrame_; }
private:
folly::fibers::Baton baton_;
folly::AsyncStackFrame asyncFrame_;
};
template <typename T>
class BlockingWaitPromise final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() noexcept = default;
~BlockingWaitPromise() = default;
BlockingWaitTask<T> get_return_object() noexcept;
void unhandled_exception() noexcept {
result_->emplaceException(
folly::exception_wrapper::from_exception_ptr(std::current_exception()));
}
template <
typename U = T,
std::enable_if_t<std::is_convertible<U, T>::value, int> = 0>
void return_value(U&& value) noexcept(
std::is_nothrow_constructible<T, U&&>::value) {
result_->emplace(static_cast<U&&>(value));
}
void setTry(folly::Try<T>* result) noexcept { result_ = &result; }
private:
folly::Try<T>* result_;
};
template <typename T>
class BlockingWaitPromise<T&> final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() noexcept = default;
~BlockingWaitPromise() = default;
BlockingWaitTask<T&> get_return_object() noexcept;
void unhandled_exception() noexcept {
result_->emplaceException(
folly::exception_wrapper::from_exception_ptr(std::current_exception()));
}
auto yield_value(T&& value) noexcept {
result_->emplace(std::ref(value));
return final_suspend();
}
auto yield_value(T& value) noexcept {
result_->emplace(std::ref(value));
return final_suspend();
}
#if 0
void return_value(T& value) noexcept {
result_->emplace(std::ref(value));
}
#endif
void return_void() {
// This should never be reachable.
// The coroutine should either have suspended at co_yield or should have
// thrown an exception and skipped over the implicit co_return and
// gone straight to unhandled_exception().
std::abort();
}
void setTry(folly::Try<std::reference_wrapper<T>>* result) noexcept {
result_ = result;
}
private:
folly::Try<std::reference_wrapper<T>>* result_;
};
template <>
class BlockingWaitPromise<void> final : public BlockingWaitPromiseBase {
public:
BlockingWaitPromise() = default;
BlockingWaitTask<void> get_return_object() noexcept;
void return_void() noexcept {}
void unhandled_exception() noexcept {
result_->emplaceException(
exception_wrapper::from_exception_ptr(std::current_exception()));
}
void setTry(folly::Try<void>* result) noexcept { result_ = result; }
private:
folly::Try<void>* result_;
};
template <typename T>
class BlockingWaitTask {
public:
using promise_type = BlockingWaitPromise<T>;
using handle_t = coroutine_handle<promise_type>;
explicit BlockingWaitTask(handle_t coro) noexcept : coro_(coro) {}
BlockingWaitTask(BlockingWaitTask&& other) noexcept
: coro_(std::exchange(other.coro_, {})) {}
BlockingWaitTask& operator=(BlockingWaitTask&& other) noexcept = delete;
~BlockingWaitTask() {
if (coro_) {
coro_.destroy();
}
}
FOLLY_NOINLINE T get(folly::AsyncStackFrame& parentFrame) && {
folly::Try<detail::lift_lvalue_reference_t<T>> result;
auto& promise = coro_.promise();
promise.setTry(&result);
auto& asyncFrame = promise.getAsyncFrame();
asyncFrame.setParentFrame(parentFrame);
asyncFrame.setReturnAddress();
{
RequestContextScopeGuard guard{RequestContext::saveContext()};
folly::resumeCoroutineWithNewAsyncStackRoot(coro_);
}
promise.wait();
return std::move(result).value();
}
FOLLY_NOINLINE T getVia(
folly::DrivableExecutor* executor,
folly::AsyncStackFrame& parentFrame) && {
folly::Try<detail::lift_lvalue_reference_t<T>> result;
auto& promise = coro_.promise();
promise.setTry(&result);
auto& asyncFrame = promise.getAsyncFrame();
asyncFrame.setReturnAddress();
asyncFrame.setParentFrame(parentFrame);
executor->add(
[coro = coro_, rctx = RequestContext::saveContext()]() mutable {
RequestContextScopeGuard guard{std::move(rctx)};
folly::resumeCoroutineWithNewAsyncStackRoot(coro);
});
while (!promise.done()) {
executor->drive();
}
return std::move(result).value();
}
private:
handle_t coro_;
};
template <typename T>
inline BlockingWaitTask<T>
BlockingWaitPromise<T>::get_return_object() noexcept {
return BlockingWaitTask<T>{
coroutine_handle<BlockingWaitPromise<T>>::from_promise(*this)};
}
template <typename T>
inline BlockingWaitTask<T&>
BlockingWaitPromise<T&>::get_return_object() noexcept {
return BlockingWaitTask<T&>{
coroutine_handle<BlockingWaitPromise<T&>>::from_promise(*this)};
}
inline BlockingWaitTask<void>
BlockingWaitPromise<void>::get_return_object() noexcept {
return BlockingWaitTask<void>{
coroutine_handle<BlockingWaitPromise<void>>::from_promise(*this)};
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<!std::is_lvalue_reference<Result>::value, int> = 0>
auto makeBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<detail::decay_rvalue_reference_t<Result>> {
co_return co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<std::is_lvalue_reference<Result>::value, int> = 0>
auto makeBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<detail::decay_rvalue_reference_t<Result>> {
co_yield co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<std::is_void<Result>::value, int> = 0>
BlockingWaitTask<void> makeRefBlockingWaitTask(Awaitable&& awaitable) {
co_await static_cast<Awaitable&&>(awaitable);
}
template <
typename Awaitable,
typename Result = await_result_t<Awaitable>,
std::enable_if_t<!std::is_void<Result>::value, int> = 0>
auto makeRefBlockingWaitTask(Awaitable&& awaitable)
-> BlockingWaitTask<std::add_lvalue_reference_t<Result>> {
co_yield co_await static_cast<Awaitable&&>(awaitable);
}
class BlockingWaitExecutor final : public folly::DrivableExecutor {
public:
~BlockingWaitExecutor() {
while (keepAliveCount_.load() > 0) {
drive();
}
}
void add(Func func) override {
bool empty;
{
auto wQueue = queue_.wlock();
empty = wQueue->empty();
wQueue->push_back(std::move(func));
}
if (empty) {
baton_.post();
}
}
void drive() override {
baton_.wait();
baton_.reset();
folly::fibers::runInMainContext([&]() {
std::vector<Func> funcs;
queue_.swap(funcs);
for (auto& func : funcs) {
std::exchange(func, nullptr)();
}
});
}
private:
bool keepAliveAcquire() noexcept override {
auto keepAliveCount =
keepAliveCount_.fetch_add(1, std::memory_order_relaxed);
DCHECK(keepAliveCount >= 0);
return true;
}
void keepAliveRelease() noexcept override {
auto keepAliveCount = keepAliveCount_.load(std::memory_order_relaxed);
do {
DCHECK(keepAliveCount > 0);
if (keepAliveCount == 1) {
add([this] {
// the final count *must* be released from this executor or else if we
// are mid-destructor we have a data race
keepAliveCount_.fetch_sub(1, std::memory_order_relaxed);
});
return;
}
} while (!keepAliveCount_.compare_exchange_weak(
keepAliveCount,
keepAliveCount - 1,
std::memory_order_release,
std::memory_order_relaxed));
}
folly::Synchronized<std::vector<Func>> queue_;
fibers::Baton baton_;
std::atomic<ssize_t> keepAliveCount_{0};
};
} // namespace detail
/// blocking_wait_fn
///
/// Awaits co_awaits the passed awaitable and blocks the current thread until
/// the await operation completes.
///
/// Useful for launching an asynchronous operation from the top-level main()
/// function or from unit-tests.
///
/// WARNING:
/// Avoid using this function within any code that might run on the thread
/// of an executor as this can potentially lead to deadlock if the operation
/// you are waiting on needs to do some work on that executor in order to
/// complete.
struct blocking_wait_fn {
template <typename Awaitable>
FOLLY_NOINLINE auto operator()(Awaitable&& awaitable) const
-> detail::decay_rvalue_reference_t<await_result_t<Awaitable>> {
folly::AsyncStackFrame frame;
frame.setReturnAddress();
folly::AsyncStackRoot stackRoot;
stackRoot.setNextRoot(folly::tryGetCurrentAsyncStackRoot());
stackRoot.setStackFrameContext();
stackRoot.setTopFrame(frame);
return static_cast<std::add_rvalue_reference_t<await_result_t<Awaitable>>>(
detail::makeRefBlockingWaitTask(static_cast<Awaitable&&>(awaitable))
.get(frame));
}
template <typename SemiAwaitable>
FOLLY_NOINLINE auto operator()(
SemiAwaitable&& awaitable, folly::DrivableExecutor* executor) const
-> detail::decay_rvalue_reference_t<semi_await_result_t<SemiAwaitable>> {
folly::AsyncStackFrame frame;
frame.setReturnAddress();
folly::AsyncStackRoot stackRoot;
stackRoot.setNextRoot(folly::tryGetCurrentAsyncStackRoot());
stackRoot.setStackFrameContext();
stackRoot.setTopFrame(frame);
return static_cast<
std::add_rvalue_reference_t<semi_await_result_t<SemiAwaitable>>>(
detail::makeRefBlockingWaitTask(
folly::coro::co_viaIfAsync(
folly::getKeepAliveToken(executor),
static_cast<SemiAwaitable&&>(awaitable)))
.getVia(executor, frame));
}
template <
typename SemiAwaitable,
std::enable_if_t<!is_awaitable_v<SemiAwaitable>, int> = 0>
auto operator()(SemiAwaitable&& awaitable) const
-> detail::decay_rvalue_reference_t<semi_await_result_t<SemiAwaitable>> {
std::exception_ptr eptr;
{
detail::BlockingWaitExecutor executor;
try {
return operator()(static_cast<SemiAwaitable&&>(awaitable), &executor);
} catch (...) {
eptr = std::current_exception();
}
}
std::rethrow_exception(eptr);
}
};
inline constexpr blocking_wait_fn blocking_wait{};
static constexpr blocking_wait_fn const& blockingWait =
blocking_wait; // backcompat
} // namespace coro
} // namespace folly
#endif // FOLLY_HAS_COROUTINES
| [
"minchanhan5@gmail.com"
] | minchanhan5@gmail.com |
8ea42dc7fe6fbda1f287515a2ec1c3d3d27af0aa | 34541ea972c7e8fae951d3ba053be9af35a572cc | /record/mySLL.h | 2e7192a1ee3988649e7a66676539559c7d6bcdb1 | [
"MIT"
] | permissive | dakshayh/Data-Structures | 0d48da88cea9a4f2a72ca05b4773c14c1c025baf | 042e0e66578efdba3369a140537ed1567c89d216 | refs/heads/master | 2021-04-15T13:11:35.110967 | 2018-01-29T08:35:55 | 2018-01-29T08:35:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,500 | h | #include<iostream>
using namespace std;
template<class T>
class SLL;
template<class T>
class CNode
{
T data;
CNode<T>*link;
friend class SLL<T>;
};
template<class T>
class SLL
{
CNode<T> *first,*last;
public:
bool isempty(){return first==NULL;}
SLL(){first=NULL;}
void LInsert(T &ele);
void display();
class chainiterator
{
CNode<T>*current;
public:
chainiterator(CNode<T>*cn)
{
current=cn;
}
T *operator->()
{
return ¤t->data;
}
chainiterator & operator++()
{
current=current->link;
return *this;
}
bool operator!=(chainiterator right)
{
return current!=right.current;
}
};
chainiterator begin()
{
return chainiterator(first);
}
chainiterator end()
{
return chainiterator(0);
}
};
template<class T>
void SLL<T>::LInsert(T &ele)
{
CNode<T>*ptr=new CNode<T>;
ptr->data=ele;
ptr->link=NULL;
if(first==NULL)
{
first=last=ptr;
}
else
{
last->link=ptr;
last=ptr;
}
}
template<class T>
void SLL<T>::display()
{
if(isempty())
throw "List is empty.Cannot display";
for(CNode<T>*p=first;p!=NULL;p=p->link)
cout<<p->data<<" ";
}
| [
"sekhar.karedla@gmail.com"
] | sekhar.karedla@gmail.com |
14470bb80006441122a783a275cfc7223addacfc | 11fb8d8468f69d5e53aff279e67782b5cf347dbe | /x_table.hpp | c72daebcb2c9cd3746ee36e5182a17f9cce36b81 | [
"Apache-2.0"
] | permissive | da0x/venv | c004e8901a8b6b125d46ceb26228388caafc0145 | 8e2a7ae0cf7c3fd59b43a7dff5c7ad57baaedf80 | refs/heads/master | 2023-05-26T08:02:21.950541 | 2023-05-19T16:49:44 | 2023-05-19T16:49:44 | 114,177,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,022 | hpp | //C++
//////////////////////////////////////////////////////////////////////////////
// //
// Filename : x_table.hpp //
// Created by : Daher Alfawares //
// Created Date : 06/20/2009 //
// License : Apache License 2.0 //
// //
// Copyright 2009 Daher Alfawares //
// //
// 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. //
// //
//////////////////////////////////////////////////////////////////////////////
/*
X Table is a C++ class that allows you to format your data in an ASCII dynamic table structure.
Example:
x::table myTable("Table Title");
myTable ("header 1")("header 2")++;
myTable ("value 11")("value 12")++;
myTable ("value 21")("value 22")++;
std::cout << myTable;
Output:
+---------------------+
|Table Title |
+----------+----------+
| header 1 | header 2 |
+----------+----------+
| value 11 | value 12 |
| value 21 | value 22 |
+----------+----------+
*/
#ifndef _X_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9
#define _X_Table__0a61eabe_d038_4d30_a6fb_e202b2dfd6a9
#include <iostream>
#include <vector>
#include <string>
#include <iomanip>
#include <numeric>
#include <sstream>
namespace x
{
// forward:
// the following allows adding a C style string to an std::string and returns an std::string.
// example:
// std::string a = "abc";
// std::string b = "123" + a;
//
inline std::string operator + ( const char*a, const std::string& b );
inline std::string itoa( const int &i );
inline int atoi( const std::string&s );
// lexical cast.
template<typename _To, typename _From> class lexical_cast;
struct scoped_mute_s;
// formats the output.
std::size_t length( std::string _String);
std::string fill(std::string _Str, std::size_t _Size);
class endl {};
class table
{
public:
std::string title;
size_t column;
std::vector<std::string> columns;
std::vector<std::size_t> column_widths;
std::string comment;
std::string Prefix; // line prefix.
table( std::string t ):title(t),column(0){}
std::vector< std::vector<std::string> > rows;
table & operator<<(std::string t){
return (*this)(t);
}
table & operator<<(int t){
std::stringstream fstr;
fstr << t;
return (*this)<< fstr.str();
}
table & operator()(std::string t)
{
if( column >= columns.size() )
{
columns.push_back("");
column_widths.push_back(0);
}
columns[column] = t;
if( column_widths[column] < length(t) )
column_widths[column] = length(t);
++column;
return *this;
}
table & operator()(int i)
{
return (*this)(itoa(i));
}
void operator ++(int)
{
column = 0;
rows.push_back( columns );
}
std::string prefix(){ return Prefix; }
void prefix( std::string _P ){ Prefix=_P; }
std::string endl(){ return "\r\n" + prefix() + " "; }
};
inline std::ostream& operator << ( std::ostream& _Str, table& T )
{
int width = std::accumulate( T.column_widths.begin(), T.column_widths.end(), 0 );
width += 3*T.columns.size();
_Str << std::setiosflags(std::ios::left);
_Str << T.endl();
// top border.
// _Str
// << ' ';
// for( int b=0; b< width-1; b++ )
// _Str
// << '-';
// _Str
// << ' '
// << T.endl();
// title.
_Str
<< " "
<< std::setw(width-1)
<< T.title
<< ""
<< T.endl();
// middle border
for( size_t i=0; i< T.columns.size(); i++ )
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill('-')
<< ""
<< std::setfill(' ')
<< " ";
_Str
<< " "
<< T.endl();
if( !T.rows.empty() || !T.rows[0].empty() )
{
size_t i=0,j=0;
// first row as header.
for( i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< fill( T.rows[j][i], T.column_widths[i] )
<< " ";
}
_Str
<< " "
<< T.endl();
// middle border
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill(' ')
<< ""
<< std::setfill(' ')
<< " ";
}
_Str
<< " "
<< T.endl();
// comment if available.
if( !T.comment.empty() )
_Str
<< " "
<< std::setw(width-1)
<< T.comment
<< " "
<< T.endl();
// full table.
for( size_t j=1; j< T.rows.size(); j++ )
{
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< fill( T.rows[j][i], T.column_widths[i] )
<< " ";
}
_Str
<< " "
<< T.endl();
}
}
// bottom border.
for( size_t i=0; i< T.columns.size(); i++ )
{
_Str
<< " "
<< std::setw( static_cast<int>(T.column_widths[i]) )
<< std::setfill('-')
<< ""
<< std::setfill(' ')
<< " ";
}
_Str << std::resetiosflags(std::ios::left);
_Str
<< " "
<< std::endl;
return _Str;
}
inline std::string operator + ( const char*a, const std::string& b )
{
std::string c;
c += a;
c += b;
return c;
}
inline std::string itoa( const int &i )
{
std::stringstream Str;
Str << i;
return Str.str();
}
inline int atoi( const std::string&s )
{
int i;
std::istringstream Str(s);
Str >> i;
return i;
}
// lexical cast.
template<typename _To, typename _From> class lexical_cast
{
_From * from;
public:
lexical_cast<_To, _From>( _From From )
{
this->from = & From;
}
operator _To()
{
throw( "Bad lexical cast: " );
}
};
inline
std::size_t length( std::string _String){
std::size_t length = 0;
//while (*s)
for(auto Char:_String)
length += (Char++ & 0xc0) != 0x80;
return length;
}
inline
std::string fill(std::string _Str, std::size_t _Size){
if( length(_Str) < _Size ){
std::size_t Difference = _Size - length(_Str);
std::stringstream _Out;
_Out << _Str;
for(int i=0; i< Difference; i++){
_Out << " ";
}
return _Out.str();
}
return _Str;
}
} /* ascii */
#endif
| [
"daher.alfawares@live.com"
] | daher.alfawares@live.com |
15e3c88f54ba1f4a453bca82ea6127cf945fa057 | bb324b1b7cf95dcb1bbeb7fdae494d9f56b74bda | /game0/vs-2013/GameOver.h | 0b098099bc8e41452adf4873ae3fa62b5f2b4962 | [] | no_license | Sunjiawei58/Drizzle-sjw | 3731eba6b7eaaeead604f0ec723b60b6b6b45f97 | f761beb3f3581cca3621f1409e232065ff1409ab | refs/heads/master | 2020-12-03T04:00:37.935754 | 2017-06-29T17:29:42 | 2017-06-29T17:29:42 | 95,800,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 183 | h | #pragma once
#include "s_Object.h"
class GameOver :
public df::s_Object
{
public:
GameOver();
~GameOver();
int eventHandler(const df::s_Event *p);
GameOver * clone() const;
};
| [
"suninwpi@gmail.com"
] | suninwpi@gmail.com |
3ddb719bbcfcea9d218a9d7c7e1415e1c050fd0c | c66850108afd81720b15333b5fc38b6a1aff4e58 | /src/saber/spectralb/SPNOINTERP_Cov.h | f3c8534836a0eb4fd84d530c5384b67b2199926d | [
"Apache-2.0",
"CECILL-2.0",
"CECILL-C"
] | permissive | JCSDA/saber | e665f962cb856601963409044f9adb6319413ee1 | 67d7451d14d92abd70c23a92f6bc8939d70b1bb1 | refs/heads/master | 2023-09-01T15:17:58.507142 | 2022-10-06T19:43:39 | 2022-10-06T19:43:39 | 304,692,012 | 4 | 8 | Apache-2.0 | 2023-08-18T22:03:34 | 2020-10-16T17:14:36 | C++ | UTF-8 | C++ | false | false | 5,851 | h | /*
* (C) Crown Copyright 2022 Met Office
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#ifndef SABER_SPECTRALB_SPNOINTERP_COV_H_
#define SABER_SPECTRALB_SPNOINTERP_COV_H_
#include <memory>
#include <string>
#include <vector>
#include "atlas/field.h"
#include "oops/base/Geometry.h"
#include "oops/base/Variables.h"
#include "oops/util/abor1_cpp.h"
#include "saber/oops/SaberBlockBase.h"
#include "saber/oops/SaberBlockParametersBase.h"
#include "saber/spectralb/spectralbnointerp.h"
namespace oops {
class Variables;
}
namespace saber {
namespace spectralb {
// -----------------------------------------------------------------------------
template <typename MODEL>
class SPNOINTERP_COVParameters : public SaberBlockParametersBase {
OOPS_CONCRETE_PARAMETERS(SPNOINTERP_COVParameters, SaberBlockParametersBase)
public:
oops::RequiredParameter<spectralbParameters<MODEL>> spectralbParams{"spectralb", this};
};
// -----------------------------------------------------------------------------
template <typename MODEL>
class SPNOINTERP_COV : public SaberBlockBase<MODEL> {
typedef oops::Geometry<MODEL> Geometry_;
typedef oops::State<MODEL> State_;
typedef SpectralBNoInterp<MODEL> SpectralB_;
public:
static const std::string classname() {return "saber::lfricspectralb::SPNOINTERP_COV";}
typedef SPNOINTERP_COVParameters<MODEL> Parameters_;
SPNOINTERP_COV(const Geometry_ &,
const Parameters_ &,
const State_ &,
const State_ &);
virtual ~SPNOINTERP_COV();
void randomize(atlas::FieldSet &) const override;
void multiply(atlas::FieldSet &) const override;
void inverseMultiply(atlas::FieldSet &) const override;
void multiplyAD(atlas::FieldSet &) const override;
void inverseMultiplyAD(atlas::FieldSet &) const override;
private:
void print(std::ostream &) const override;
std::unique_ptr<SpectralB_> spectralb_;
};
// -----------------------------------------------------------------------------
template<typename MODEL>
SPNOINTERP_COV<MODEL>::SPNOINTERP_COV(const Geometry_ & resol, const Parameters_ & params,
const State_ & xb, const State_ & fg)
: SaberBlockBase<MODEL>(params), spectralb_()
{
oops::Log::trace() << classname() << "::SPNOINTERP_COV starting" << std::endl;
// Setup and check input/ouput variables
const oops::Variables inputVars = params.inputVars.value();
const oops::Variables outputVars = params.outputVars.value();
ASSERT(inputVars == outputVars);
// Active variables
const boost::optional<oops::Variables> &activeVarsPtr = params.activeVars.value();
oops::Variables activeVars;
if (activeVarsPtr != boost::none) {
activeVars += *activeVarsPtr;
ASSERT(activeVars <= inputVars);
} else {
activeVars += inputVars;
}
// Initialize SpectralB_
spectralb_.reset(new SpectralB_(resol, activeVars, params.spectralbParams.value()));
oops::Log::trace() << classname() << "::SPNOINTERP_COV done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
SPNOINTERP_COV<MODEL>::~SPNOINTERP_COV() {
oops::Log::trace() << classname() << "::~SPNOINTERP_COV starting" << std::endl;
util::Timer timer(classname(), "~SPNOINTERP_COV");
oops::Log::trace() << classname() << "::~SPNOINTERP_COV done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::randomize(atlas::FieldSet & fset) const {
oops::Log::trace() << classname() << "::randomize starting" << std::endl;
ABORT("SPNOINTERP_COV<MODEL>::randomize: not implemented");
oops::Log::trace() << classname() << "::randomize done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::multiply(atlas::FieldSet & fset) const {
oops::Log::trace() << classname() << "::multiply starting" << std::endl;
spectralb_->multiply(fset);
oops::Log::trace() << classname() << "::multiply done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::inverseMultiply(atlas::FieldSet & fset) const {
oops::Log::trace() << classname() << "::inverseMultiply starting" << std::endl;
ABORT("SPNOINTERP_COV<MODEL>::inverseMultiply: not implemented");
oops::Log::trace() << classname() << "::inverseMultiply done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::multiplyAD(atlas::FieldSet & fset) const {
oops::Log::trace() << classname() << "::multiplyAD starting" << std::endl;
ABORT("SPNOINTERP_COV<MODEL>::multiplyAD: not implemented");
oops::Log::trace() << classname() << "::multiplyAD done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::inverseMultiplyAD(atlas::FieldSet & fset) const {
oops::Log::trace() << classname() << "::inverseMultiplyAD starting" << std::endl;
ABORT("SPNOINTERP_COV<MODEL>::inverseMultiplyAD: not implemented");
oops::Log::trace() << classname() << "::inverseMultiplyAD done" << std::endl;
}
// -----------------------------------------------------------------------------
template<typename MODEL>
void SPNOINTERP_COV<MODEL>::print(std::ostream & os) const {
os << classname();
}
// -----------------------------------------------------------------------------
} // namespace spectralb
} // namespace saber
#endif // SABER_SPECTRALB_SPNOINTERP_COV_H_
| [
"noreply@github.com"
] | JCSDA.noreply@github.com |
a285cba0eda428fb1466365b14b2b18961bef46c | cee86d816f709be28942a19ef5cc5ed9b36fa363 | /libraries/Rtc_by_Makuna/src/RtcDS1307.h | 318c39af88216bfd2f719e56235b7216b43f8ef7 | [] | no_license | nicolalombardi/IoT-Thermostat-ESP8266 | 96bd93331290dda983c74b8ff1e3be4b8a9163f5 | 2f85775d5334ced58d72826a456bb2145cf7ebf1 | refs/heads/master | 2022-01-24T18:44:02.762228 | 2021-12-29T11:35:38 | 2021-12-29T11:35:38 | 94,616,059 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,731 | h |
#ifndef __RTCDS1307_H__
#define __RTCDS1307_H__
#include <Arduino.h>
#include <RtcDateTime.h>
#include "RtcUtility.h"
//I2C Slave Address
const uint8_t DS1307_ADDRESS = 0x68;
//DS1307 Register Addresses
const uint8_t DS1307_REG_TIMEDATE = 0x00;
const uint8_t DS1307_REG_STATUS = 0x00;
const uint8_t DS1307_REG_CONTROL = 0x07;
const uint8_t DS1307_REG_RAMSTART = 0x08;
const uint8_t DS1307_REG_RAMEND = 0x3f;
const uint8_t DS1307_REG_RAMSIZE = DS1307_REG_RAMEND - DS1307_REG_RAMSTART;
//DS1307 Register Data Size if not just 1
const uint8_t DS1307_REG_TIMEDATE_SIZE = 7;
// DS1307 Control Register Bits
const uint8_t DS1307_RS0 = 0;
const uint8_t DS1307_RS1 = 1;
const uint8_t DS1307_SQWE = 4;
const uint8_t DS1307_OUT = 7;
// DS1307 Status Register Bits
const uint8_t DS1307_CH = 7;
enum DS1307SquareWaveOut
{
DS1307SquareWaveOut_1Hz = 0b00010000,
DS1307SquareWaveOut_4kHz = 0b00010001,
DS1307SquareWaveOut_8kHz = 0b00010010,
DS1307SquareWaveOut_32kHz = 0b00010011,
DS1307SquareWaveOut_High = 0b10000000,
DS1307SquareWaveOut_Low = 0b00000000,
};
template<class T_WIRE_METHOD> class RtcDS1307
{
public:
RtcDS1307(T_WIRE_METHOD& wire) :
_wire(wire)
{
}
void Begin()
{
_wire.begin();
}
bool IsDateTimeValid()
{
return GetIsRunning();
}
bool GetIsRunning()
{
uint8_t sreg = getReg(DS1307_REG_STATUS);
return !(sreg & _BV(DS1307_CH));
}
void SetIsRunning(bool isRunning)
{
uint8_t sreg = getReg(DS1307_REG_STATUS);
if (isRunning)
{
sreg &= ~_BV(DS1307_CH);
}
else
{
sreg |= _BV(DS1307_CH);
}
setReg(DS1307_REG_STATUS, sreg);
}
void SetDateTime(const RtcDateTime& dt)
{
// retain running state
uint8_t sreg = getReg(DS1307_REG_STATUS) & _BV(DS1307_CH);
// set the date time
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(DS1307_REG_TIMEDATE);
_wire.write(Uint8ToBcd(dt.Second()) | sreg);
_wire.write(Uint8ToBcd(dt.Minute()));
_wire.write(Uint8ToBcd(dt.Hour())); // 24 hour mode only
_wire.write(Uint8ToBcd(dt.DayOfWeek()));
_wire.write(Uint8ToBcd(dt.Day()));
_wire.write(Uint8ToBcd(dt.Month()));
_wire.write(Uint8ToBcd(dt.Year() - 2000));
_wire.endTransmission();
}
RtcDateTime GetDateTime()
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(DS1307_REG_TIMEDATE);
_wire.endTransmission();
_wire.requestFrom(DS1307_ADDRESS, DS1307_REG_TIMEDATE_SIZE);
uint8_t second = BcdToUint8(_wire.read() & 0x7F);
uint8_t minute = BcdToUint8(_wire.read());
uint8_t hour = BcdToBin24Hour(_wire.read());
_wire.read(); // throwing away day of week as we calculate it
uint8_t dayOfMonth = BcdToUint8(_wire.read());
uint8_t month = BcdToUint8(_wire.read());
uint16_t year = BcdToUint8(_wire.read()) + 2000;
return RtcDateTime(year, month, dayOfMonth, hour, minute, second);
}
void SetMemory(uint8_t memoryAddress, uint8_t value)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
if (address <= DS1307_REG_RAMEND)
{
setReg(address, value);
}
}
uint8_t GetMemory(uint8_t memoryAddress)
{
uint8_t value = 0;
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
if (address <= DS1307_REG_RAMEND)
{
value = getReg(address);
}
return value;
}
uint8_t SetMemory(uint8_t memoryAddress, const uint8_t* pValue, uint8_t countBytes)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
uint8_t countWritten = 0;
if (address <= DS1307_REG_RAMEND)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(address);
while (countBytes > 0 && address <= DS1307_REG_RAMEND)
{
_wire.write(*pValue++);
address++;
countBytes--;
countWritten++;
}
_wire.endTransmission();
}
return countWritten;
}
uint8_t GetMemory(uint8_t memoryAddress, uint8_t* pValue, uint8_t countBytes)
{
uint8_t address = memoryAddress + DS1307_REG_RAMSTART;
uint8_t countRead = 0;
if (address <= DS1307_REG_RAMEND)
{
if (countBytes > DS1307_REG_RAMSIZE)
{
countBytes = DS1307_REG_RAMSIZE;
}
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(address);
_wire.endTransmission();
_wire.requestFrom(DS1307_ADDRESS, countBytes);
while (countBytes-- > 0)
{
*pValue++ = _wire.read();
countRead++;
}
}
return countRead;
}
void SetSquareWavePin(DS1307SquareWaveOut pinMode)
{
setReg(DS1307_REG_CONTROL, pinMode);
}
private:
T_WIRE_METHOD& _wire;
uint8_t getReg(uint8_t regAddress)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(regAddress);
_wire.endTransmission();
// control register
_wire.requestFrom(DS1307_ADDRESS, (uint8_t)1);
uint8_t regValue = _wire.read();
return regValue;
}
void setReg(uint8_t regAddress, uint8_t regValue)
{
_wire.beginTransmission(DS1307_ADDRESS);
_wire.write(regAddress);
_wire.write(regValue);
_wire.endTransmission();
}
};
#endif // __RTCDS1307_H__ | [
"lombardi.nicola23@gmail.com"
] | lombardi.nicola23@gmail.com |
6b13561c7b167feccdf9348c493d5314ef21fcdb | 282b64c67c299b227e3002535609d4319e248b14 | /TcpClientStruct/client_3.cpp | 3cd32a6f1a923b6a8dbab6f285c0df0e142d20db | [] | no_license | TimingTone/Socket | f95ab01f21bb446c16fe1038bcb06cd263777aa4 | a8f937f87479455cb6c9bd4f3909f635d4f297a2 | refs/heads/master | 2021-02-27T20:31:36.108078 | 2020-03-17T16:16:34 | 2020-03-17T16:16:34 | 245,628,295 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,225 | cpp | #define WIN32_LEAN_AND_MEAN //引入宏去避免早期的会引起冲突的一些库,减少其他依赖库的引用
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#include <WinSock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
//用Socket API建立简易的TCP客户端
struct DataPackage {
int age;
char name[32];
};
int main() {
//启动windows socket 2.x环境
WORD wVersionRequested = MAKEWORD(2, 2);
//The WSADATA structure is used to save the Windows Sockets
// initialization information returned by the function WSAStartup
WSADATA wsadata;
//调用winSocket的启动函数WSAStartup
//wVersionRequested :WORD的版本号
//&wsadata :WSADATA的数据结构(struct)
WSAStartup(wVersionRequested, &wsadata);
//用Socket API建立简易的TCP客户端
// 1. 建立一个socket
SOCKET _sock = socket(AF_INET, SOCK_STREAM, 0); //_sock是服务端socket
if (INVALID_SOCKET == _sock) {
printf("Failed to establish socket client...\n");
}
else {
printf("Succeed to establish the client...\n");
}
// 2. 连接服务器 connect
sockaddr_in _sin = {};
_sin.sin_family = AF_INET;
_sin.sin_port = htons(4567);
_sin.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
if (SOCKET_ERROR == ret) {
printf("Failed to establish socket client...\n");
}
else {
printf("Succeed to establish the client...\n");
}
// 3, Input request command
while (true) {
char cmdBuf[128] = {};
scanf("%s", cmdBuf);
// 4, Deal with request command
if (0 == strcmp(cmdBuf, "exit")) {
printf("Received quit command!");
break;
}
else {
// 5, send request command to server.
send(_sock, cmdBuf, strlen(cmdBuf) + 1, 0);
}
// 6. 接收服务器信息recv
char recvBuf[128] = {};
int nlen = recv(_sock, recvBuf, 128, 0);
if (nlen > 0) {
DataPackage* dp = (DataPackage*)recvBuf;
printf("Age: %d \nName = %s\n", dp->age, dp->name);
}
}
// 7. 关闭socket closesocket
closesocket(_sock);
WSACleanup();
printf("quit!, mission completed.");
getchar();
return 0;
} | [
"1725491705@qq.com"
] | 1725491705@qq.com |
e0119de809b298a11cb74a27cbbf8b44957cb950 | 0939698f486c4d8162c677ae3b92694a8711b172 | /client/src/conversationmodel.h | 18f86b5ff4940d21fb026b450425b2337828d438 | [
"WTFPL"
] | permissive | SunRain/mitakuuluu2 | 03edc4d25a99a4bfb82e40b4e250a58797621f86 | b27244e2a880c00665b5faad48cb07af1d2fce89 | refs/heads/master | 2021-01-18T01:47:09.136635 | 2014-09-21T09:34:24 | 2014-09-21T09:34:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,795 | h | #ifndef CONVERSATIONMODEL_H
#define CONVERSATIONMODEL_H
#include <QObject>
#include <QHash>
#include <QVariantMap>
#include <QStringList>
#include <QAbstractListModel>
#include <QtSql/QtSql>
#include <QtDBus/QtDBus>
#include <QTimer>
#include <QDebug>
#include "../threadworker/queryexecutor.h"
class TimestampMsgidPair
{
public:
TimestampMsgidPair(int timestamp, const QString &msgId) {
_timestamp = timestamp;
_msgid = msgId;
}
bool operator <(const TimestampMsgidPair &target) const {
bool result = _timestamp > target._timestamp;
return result;
}
TimestampMsgidPair& operator =(const TimestampMsgidPair &from) {
_timestamp = from._timestamp;
_msgid = from._msgid;
return *this;
}
friend QDebug operator<< (QDebug d, const TimestampMsgidPair &data) {
d << "{" << data._timestamp << ":" << data._msgid << ")";
return d;
}
int _timestamp;
QString _msgid;
};
class ConversationModel : public QAbstractListModel
{
Q_OBJECT
Q_PROPERTY(QString jid READ getJid WRITE loadLastConversation FINAL)
Q_PROPERTY(int count READ count NOTIFY countChanged)
Q_PROPERTY(int allCount READ allCount NOTIFY allCountChanged)
public:
ConversationModel(QObject *parent = 0);
~ConversationModel();
void loadLastConversation(QString newjid);
int rowCount(const QModelIndex &parent = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
virtual QHash<int, QByteArray> roleNames() const { return _roles; }
QString getJid() { return jid; }
QString jid;
QString table;
public slots:
void setPropertyByMsgId(const QString &msgId, const QString &name, const QVariant &value);
void loadOldConversation(int count = 20);
void deleteMessage(const QString &msgId, const QString &myJid, bool deleteMediaFiles = false);
QVariantMap get(int index);
QVariantMap getModelByIndex(int index);
QVariantMap getModelByMsgId(const QString &msgId);
void copyToClipboard(const QString &msgId);
void forwardMessage(const QStringList &jids, const QString &msgId);
void resendMessage(const QString &jid, const QString& msgId);
void removeConversation(const QString &rjid);
int count();
void requestContactMedia(const QString &sjid);
private:
int getIndexByMsgId(const QString &msgId);
QStringList _keys;
QHash<int, QByteArray> _roles;
QList<TimestampMsgidPair> _sortedTimestampMsgidList;
QHash<QString, QVariantMap> _modelData;
QVariantMap _downloadData;
QSqlDatabase db;
QDBusInterface *iface;
QueryExecutor *dbExecutor;
bool _loadingBusy;
QString uuid;
int _allCount;
int allCount();
void getAllCount();
QString makeTimestampDate(int timestamp);
private slots:
void onLoadingFree();
void onMessageReceived(const QVariantMap &data);
void onMessageStatusUpdated(const QString &mjid, const QString &msgId, int msgstatus);
void onMediaProgress(const QString &mjid, const QString &msgId, int progress);
void onMediaFinished(const QString &mjid, const QString &msgId, const QString &path);
void onMediaFailed(const QString &mjid, const QString &msgId);
void onMediaTitleReceived(const QString &msgid, const QString &title, const QString &mjid);
void onMediaUploadFinished(const QString &mjid, const QString &msgid, const QString &url);
void dbResults(const QVariant &result);
signals:
void lastMessageToBeChanged(const QString &mjid);
void lastMessageChanged(const QString &mjid, bool force);
void mediaListReceived(const QString &pjid, const QVariantList &mediaList);
void countChanged();
void allCountChanged();
};
#endif // CONVERSATIONMODEL_H
| [
"coderusinbox@gmail.com"
] | coderusinbox@gmail.com |
9d018269c1a28f7e2da45825fd14d554552fbf40 | 1ab3637074364cf0eba4ee5833361535b9fdc260 | /RFID_YY/leds.cpp | 6e128429d39997873a9f5651469e05d3e5b86668 | [] | no_license | robatz-network/RFID-race | 199bc82bf024926fec75f1d0efb9f127946c24ae | 9460d67aefc0cd511cebde4df192981cd193a02d | refs/heads/master | 2020-06-24T01:35:54.260871 | 2019-09-08T13:55:40 | 2019-09-08T13:55:40 | 198,810,278 | 0 | 1 | null | 2019-08-06T20:12:23 | 2019-07-25T10:28:11 | C++ | UTF-8 | C++ | false | false | 489 | cpp | #include <Arduino.h>
void onLed(const uint8_t pin)
{
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
void offLed(const uint8_t pin)
{
digitalWrite(pin, HIGH);
pinMode(pin, INPUT);
}
void blinkLed(const uint8_t pin, const uint32_t ms, int num)
{
for (int i = 0; i < num; i++)
{
onLed(pin);
delay(ms);
offLed(pin);
if (i < num - 1)
{
delay(ms);
}
}
}
void setupLed(const uint8_t pin)
{
pinMode(pin, INPUT);
}
| [
"noreply@github.com"
] | robatz-network.noreply@github.com |
3b1332438366b01df5a1a978a1d579aee1e0ab81 | 0764add6abfe89ea455502ba4c5cf010dc41d117 | /stream_pusher/Ffmpeg_stream_pusher.h | bb9fc07c6d193fb4d22d1cdc82b9acfe279ade81 | [
"MIT"
] | permissive | WangLCG/LiveStream | 22cb1b4e6bf73712de1234fdedd28dacaf08f7c7 | 9afb50d8e14c277c800d5b13d34adce31866520f | refs/heads/master | 2020-11-23T18:54:37.613768 | 2020-08-31T06:57:35 | 2020-08-31T06:57:35 | 227,776,771 | 20 | 23 | null | null | null | null | UTF-8 | C++ | false | false | 5,979 | h | /*
* Car eye 车辆管理平台: www.car-eye.cn
* Car eye 开源网址: https://github.com/Car-eye-team
* MP4Muxer.h
*
* Author: Wgj
* Date: 2019-03-04 22:21
* Copyright 2019
*
* MP4混流器类声明文件
*/
#ifndef __MP4_MUXER_H__
#define __MP4_MUXER_H__
#define _TIMESPEC_DEFINED
#include <thread>
#include <string>
#include <mutex>
#include <iostream>
#include <sys/time.h>
#include <unistd.h>
#include "RecvMulticastDataModule.h"
using namespace std;
#ifdef __cplusplus
extern "C" {
#endif
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#ifdef __cplusplus
}
#endif
#define ENABLE_MULTICAST_QUEUE (1)
/* ffmpeg 数据读取回调函数 */
typedef struct FFMPEG_READ_PACK_CALL_BACK
{
void *ptr;
int (*read_buffer) (void *opaque, uint8_t *buf, int buf_size);
}FFMPEG_READ_PACK_CB;
// 用于存储流数据的队列项结构
typedef struct _CE_QUEUE_ITEM_T_
{
// 申请的缓冲区指针
uint8_t* Bytes;
// 申请的缓冲区大小
int TotalSize;
// 入队填充的数据字节数
int EnqueueSize;
// 出队读取的数据字节数
int DequeueSize;
}CEQueueItem;
// 一个简单的队列结构, 用于暂存流数据
typedef struct _CE_QUEUE_T_
{
// 队列项指针
CEQueueItem *Items;
// 队列的标识, 使用者可以自定义标识进行队列区分
uint8_t Flag;
// 队列项个数
int Count;
// 出队计数索引
int DequeueIndex;
// 入队索引
int EnqueueIndex;
}CESimpleQueue;
/*!
* \class MP4Muxer
*
* \brief MP4混流器, 合成H264与AAC音视频
*
* \author Wgj
* \date 2019-02-24
*/
class MP4Muxer
{
public:
MP4Muxer(RecvMulticastDataModule* MultiCastModule = NULL);
~MP4Muxer();
/*
* Comments: 混流器初始化 实例化后首先调用该方法进行内部参数的初始化
* Param aFileName: 要保存的文件名
* @Return 是否成功
*/
bool Start(std::string aFileName);
/*
* Comments: 追加一帧AAC数据到混流器
* Param aBytes: 要追加的字节数据
* Param aSize: 追加的字节数
* @Return 成功与否
*/
bool AppendAudio(uint8_t* aBytes, int aSize);
/*
* Comments: 追加一帧H264视频数据到混流器
* Param aBytes: 要追加的字节数据
* Param aSize: 追加的字节数
* @Return 成功与否
*/
bool AppendVideo(uint8_t* aBytes, int aSize);
/*
* Comments: 关闭并释放输出格式上下文
* Param : None
* @Return None
*/
void Stop(void);
void SetVideoCB(FFMPEG_READ_PACK_CB& videoCB);
void SetAudioCB(FFMPEG_READ_PACK_CB& audioCB);
//////////////////////////////////////////////////////////////////////////
/// \brief ffmpeg读取视频数据包回调
/// \details ffmpeg读取视频数据包回调
/// \param[in] opaque 实例句柄
/// \param[in/out] buf 数据填充buf
/// \param[in] buf_size buf大小
/// \return 实际读取数据大小
//////////////////////////////////////////////////////////////////////////
static int ReadVideoFrameCallback(void *opaque, uint8_t *buf, int buf_size);
//////////////////////////////////////////////////////////////////////////
/// \brief ffmpeg读取音频数据包回调
/// \details ffmpeg读取音频数据包回调
/// \param[in] opaque 实例句柄
/// \param[in/out] buf 数据填充buf
/// \param[in] buf_size buf大小
/// \return 实际读取数据大小
//////////////////////////////////////////////////////////////////////////
static int ReadAudioFrameCallback(void *opaque, uint8_t *buf, int buf_size);
/*
* Comments: 写入AAC数据帧到文件
* Param : None
* @Return int
*/
int WriteAudioFrame(void);
/*
* Comments: 写入H264视频帧到文件
* Param : None
* @Return int
*/
int WriteVideoFrame(void);
private:
/*
* Comments: 打开AAC输入上下文
* Param : None
* @Return 0成功, 其他失败
*/
int OpenAudio(bool aNew = false);
/*
* Comments: 打开H264视频流
* Param : None
* @Return 0成功, 其他失败
*/
int OpenVideo(void);
private:
// 要保存的MP4文件路径
std::string mFileName;
// 输入AAC音频上下文
AVFormatContext* mInputAudioContext;
// 输入H264视频上下文
AVFormatContext* mInputVideoContext;
// 输出媒体格式上下文
AVFormatContext* mOutputFrmtContext;
// AAC音频位流筛选上下文
AVBitStreamFilterContext* mAudioFilter;
// H264视频位流筛选上下文
AVBitStreamFilterContext* mVideoFilter;
// 流媒体数据包
AVPacket mPacket;
// AAC数据缓存区
uint8_t* mAudioBuffer;
// AAC数据读写队列
CESimpleQueue* mAudioQueue;
// H264数据缓冲区
uint8_t* mVideoBuffer;
// H264数据读写队列
CESimpleQueue* mVideoQueue;
// AAC的回调读取是否启动成功
bool mIsStartAudio;
// H264的回调读取是否启动成功
bool mIsStartVideo;
// 音频在mInputAudioContext->streams流中的索引
int mAudioIndex;
// 视频在mInputVideoContext->streams流中的索引
int mVideoIndex;
// 输出流中音频帧的索引
int mAudioOutIndex;
// 输出流视频帧的索引
int mVideoOutIndex;
// 输出帧索引计数
int mFrameIndex;
int mAudioFrameIndex;
// 线程操作互斥锁
std::mutex mLock;
FFMPEG_READ_PACK_CB mVideoCB; /* 视频数据读取回调函数 */
FFMPEG_READ_PACK_CB mAudioCB; /* 音频数据读取回调函数 */
RecvMulticastDataModule* mMultiCastModule;
};
#endif
| [
"20123200044@m.scnu.edu.cn"
] | 20123200044@m.scnu.edu.cn |
a32acb84f8d56582b887eae0e3c78dc10b7ba017 | be9e723c405521846ca12425da989c0cb15006f1 | /1040/main.cpp | 0b8e81bfad7907c19cba7c7bced7c1b63f49d2c1 | [] | no_license | mhayk/uri | 21edfc2dfc28afb909cd7b82d0a0dcc6869a1d42 | ecfd6e67b8c5fb962c4eaad8b85fee1accc9d3d5 | refs/heads/master | 2021-01-20T00:13:20.181812 | 2020-01-21T21:36:11 | 2020-01-21T21:36:11 | 89,097,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 914 | cpp | #include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double n1,n2,n3,n4,average;
cin >> n1 >> n2 >> n3 >> n4;
average = (n1*0.2)+(n2*0.3)+(n3*0.4)+(n4*0.1);
cout << "Media: " << fixed << setprecision(1) << average << endl;
if(average > 7.0)
{
cout << "Aluno aprovado." << endl;
return 0;
}
if(average < 5.0)
{
cout << "Aluno reprovado." << endl;
return 0;
}
if(average >= 5.0 && average <= 6.9)
{
cout << "Aluno em exame." << endl;
cin >> n1;
cout << "Nota do exame: " << fixed << setprecision(1) << n1 << endl;
average = (average+n1)/2;
if(average >= 5.0)
cout << "Aluno aprovado." << endl;
else
cout << "Aluno reprovado." << endl;
cout << "Media final: " << fixed << setprecision(1) << average << endl;
}
return 0;
}
| [
"eu@mhayk.com.br"
] | eu@mhayk.com.br |
a7a5990e8b71a25b7037651b64b02acf95d1cf3e | 49fac4986eb2c78a7b2dc15eb5bf4471bd29d3ae | /tags/FRAMEWAVE_1.1_BETA/UnitTest/UnitTestCollection/ColorModelConversion/CMC_FunctionObjects.h | 98f7d515d9a14990b3200b428b401d6a1c161977 | [
"Apache-2.0"
] | permissive | imazen/framewave | 1f2f427cc8a4ff3a4d02b619c2f32fe7693039d8 | e6390439955a103d5a97d1568a99d3e02a11376d | refs/heads/master | 2021-01-24T14:56:16.069570 | 2014-10-23T21:55:58 | 2014-10-23T21:55:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,260 | h | /*
Copyright (c) 2006-2008 Advanced Micro Devices, Inc. All Rights Reserved.
This software is subject to the Apache v2.0 License.
*/
#ifndef __CMC_FUNCTION_OBJECTS_H__
#define __CMC_FUNCTION_OBJECTS_H__
#include "Object.h"
#include "FunctionSignatures.h"
// --------------------
// Channel to Channel
// --------------------
// Even numbered width buffer (422 Sampling)
template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
class SrcDstRoiEvenWidth : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >
{
typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth > BaseClass;
public:
SrcDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
: BaseClass( parent, name, fn )
{
}
};
template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
class SrcDstRoiEven : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidthEvenHeight >
{
typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidthEvenHeight > BaseClass;
public:
SrcDstRoiEven( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
: BaseClass( parent, name, fn )
{
}
};
// --------------------
// Channel to Planar
// --------------------
// --------------------
// Planar to Channel
// --------------------
// --------------------
// Planar to Planar
// --------------------
//
//// Planar to Planar
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiEvenWidth : public PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >
//{
// typedef PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth > BaseClass;
//public:
// PSrcPDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >( parent, name ), m_fn(fn)
// {
// }
//};
//
//// --------------------------------
//// Buffer width and height are even
//// --------------------------------
//// Channel to Channel
//template< typename TS, U32 srcChannels, typename TD, U32 dstChannels >
//class SrcDstRoiEvenWidth : public SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >
//{
// typedef SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth > BaseClass;
//public:
// SrcDstRoiEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : SrcDstRoiGeneric< TS, srcChannels, TD, dstChannels, AdviceRoiEvenWidth >( parent, name, fn )
// {
// }
//};
//
//// Planar to Planar
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiEven : public PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidthEvenHeight >
//{
// typedef PSrcPDstRoiGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidthEvenHeight > BaseClass;
//public:
// PSrcPDstRoiEven( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name ), m_fn(fn)
// {
// }
//};
//// --------------------------------
//// Function Signature: (const TS* const[], int, TS*[], int[], FwiSize)
//// --------------------------------
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes, class Advice >
//class PSrcPDstRoiMultipleDstStepGeneric : public PDstRoiBase< TD, dstPlanes, Advice >
//{
//public:
// typedef FwStatus (STDCALL *Fn)( const TS * const [], int, TD *[], int[], FwiSize );
// const char ** m_srcInit;
// Fn m_fn;
//
// PSrcPDstRoiMultipleDstStepGeneric( UnitTestCatalogBase & parent, const char *name, Fn fn )
// : PDstRoiBase< TD, dstPlanes, Advice >( parent, name ), m_fn(fn)
// {
// }
//
// void RunTest( const char **srcInit, const char **dstExpected, TD errorMargin = MemOps<TD>::Zero(), const FwStatus expectedReturn = fwStsNoErr )
// {
// m_srcInit = srcInit;
// ExecuteTest( NULL, dstExpected, errorMargin, expectedReturn );
// }
//
// virtual void CallFn( const Advice & adv,
// FwStatus & stat,
// PlanarBuffer< TD, dstPlanes >& dst )
// {
// int dstStep[dstPlanes];
// U32 srcAlignments[srcPlanes];
// for( int plane = 0; plane < srcPlanes; plane++ )
// {
// srcAlignments[plane] = adv.Alignment();
// }
// for( int plane = 0; plane < dstPlanes; plane++ )
// {
// dstStep[plane] = dst.StepBytes();
// }
//
// PlanarBuffer< TS, srcPlanes > src( m_srcInit, adv.BufferWidth(), adv.BufferHeight(), srcAlignments );
// try
// {
// this->timer.Start();
// stat = m_fn( src.Ptr(), src.StepBytes(), dst.Ptr(), dstStep, adv.Roi() );
// this->timer.Stop();
// }
// catch( ... )
// {
// this->timer.Stop();
// stat = (FwStatus)EXCEPTION_ERR;
// }
// }
//};
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiMultipleDstStep : public PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoi >
//{
// typedef PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoi > BaseClass;
//public:
// PSrcPDstRoiMultipleDstStep( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name, fn )
// {}
//};
//template< typename TS, U32 srcPlanes, typename TD, U32 dstPlanes >
//class PSrcPDstRoiMultipleDstStepEvenWidth : public PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth >
//{
// typedef PSrcPDstRoiMultipleDstStepGeneric< TS, srcPlanes, TD, dstPlanes, AdviceRoiEvenWidth > BaseClass;
//public:
// PSrcPDstRoiMultipleDstStepEvenWidth( UnitTestCatalogBase & parent, const char *name, typename BaseClass::Fn fn )
// : BaseClass( parent, name, fn )
// {}
//};
#endif // __CMC_FUNCTION_OBJECTS_H__
| [
"jalby@f364fc6c-7e41-0410-b16c-eb8c68fe7df8"
] | jalby@f364fc6c-7e41-0410-b16c-eb8c68fe7df8 |
ff1fb8f1dfa4b6f86bfd7be221fbe3e1af5a040d | 7055d6418bf3e15258e4874641d7b785aaefd520 | /Text chat application/grajasek/src/common.cpp | cf21446fc86061c32a92e1e1c4b24d4d6e356b2d | [] | no_license | gowthamrajasekaranus/Text-chat-application-client-server- | 57c75ec5383f5911b4aa03a55cb28fc4483aaacd | b506b75c86f252f02eee892939e95359bb4926e1 | refs/heads/main | 2023-07-31T13:34:27.580298 | 2021-09-15T03:30:24 | 2021-09-15T03:30:24 | 406,601,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 875 | cpp | #include "../include/logger.h"
#include "../include/common.h"
#include <iostream>
#include <string.h>
using namespace std;
common::common(){
}
void common::print_error(const char* command_str){
cse4589_print_and_log("[%s:ERROR]\n",command_str);
cse4589_print_and_log("[%s:END]\n",command_str);
}
void common::print_author(){
cse4589_print_and_log("[AUTHOR:SUCCESS]\n");
cse4589_print_and_log("I, grajasek, have read and understood the course academic integrity policy.\n");
cse4589_print_and_log("[AUTHOR:END]\n");
}
void common::print_ip(){
cse4589_print_and_log("[IP:SUCCESS]\n");
cse4589_print_and_log("IP:%s\n",information.ip_address);
cse4589_print_and_log("[IP:END]\n");
}
void common::print_port(){
cse4589_print_and_log("[PORT:SUCCESS]\n");
cse4589_print_and_log("PORT:%s\n",information.port_number);
cse4589_print_and_log("[PORT:END]\n");
}
| [
"noreply@github.com"
] | gowthamrajasekaranus.noreply@github.com |
8cc2df3d4fc12f7fec2c57ba7b1c7d0086d93f02 | 81b2279b2b24636ccaebb091d7543537142a9272 | /leetcode原生/942_增减字符串匹配_easy/借鉴思想.cpp | 4b5d3b8073a5209693f769a6f77ce3736488d3f7 | [] | no_license | gwtak/My_Leetcode | be6a8d5a050bcd378ae8cfd38ea5b0e5d6f4f70d | bcbebcc8e6c9c58237698ab7534aa3718c489f21 | refs/heads/master | 2022-12-31T22:23:20.771120 | 2020-10-20T10:29:19 | 2020-10-20T10:29:19 | 263,764,562 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | cpp | /*给定只含 "I"(增大)或 "D"(减小)的字符串 S ,令 N = S.length。
返回 [0, 1, ..., N] 的任意排列 A 使得对于所有 i = 0, ..., N-1,都有:
如果 S[i] == "I",那么 A[i] < A[i+1]
如果 S[i] == "D",那么 A[i] > A[i+1]
示例 1:
输入:"IDID"
输出:[0,4,1,3,2]
示例 2:
输入:"III"
输出:[0,1,2,3]
示例 3:
输入:"DDI"
输出:[3,2,0,1]
提示:
1 <= S.length <= 10000
S 只包含字符 "I" 或 "D"。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/di-string-match
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/
class Solution {
public:
vector<int> diStringMatch(string S) {
int low=0;
int high=S.size();
vector<int> res;
for(int i=0;i<S.size();i++){
if(S[i]=='I'){
res.push_back(low);
low++;
}
else{
res.push_back(high);
high--;
}
}
res.push_back(low);
return res;
}
}; | [
"1969323198@qq.com"
] | 1969323198@qq.com |
2426a700b84018d1776112d82718ab18bf22ac12 | c031fe63baf74199d0aaabd4c5901258d7ae19c5 | /pat/1080.cpp | 8b8bdda0ddc6220f2654e814e2fbe67f08e29de4 | [] | no_license | xjhqre/PAT | 15eb28b6eec93dbd7624de6ca798bd25898507fc | d7571dddd683bf8068e38ce0c78191b63770247b | refs/heads/master | 2023-05-06T04:43:30.527330 | 2021-05-30T06:23:03 | 2021-05-30T06:23:03 | 372,139,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,088 | cpp | #include <algorithm>
#include <iostream>
#include <map>
#include <set>
#include <cstdio>
#include <string>
#include <string.h>
#include <cctype>
#include <math.h>
#include <vector>
using namespace std;
struct StuInfo{
string xh;
int fs1, fs2, fs3;
double zf;
};
int cmp(StuInfo a, StuInfo b){
return a.zf != b.zf ? a.zf > b.zf : a.xh < b.xh;
}
map<string, int> fs1, fs2, fs3, c, c1, c2;
map<string, double> zf;
int main() {
int p, m, n;
cin >> p >> m >> n;
string xh, stu[10005];
int fs, cnt = 0;
for (int i = 0; i < p; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs1[xh] = fs;
}
for (int i = 0; i < m; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs2[xh] = fs;
c1[xh] = 1;
}
for (int i = 0; i < n; i++){
cin >> xh >> fs;
if (c[xh] == 0){
stu[cnt] = xh;
c[xh] = 1;
cnt++;
}
fs3[xh] = fs;
c2[xh] = 1;
}
for (int i = 0; i < 10005; i++){
if (fs2[stu[i]] > fs3[stu[i]]){
zf[stu[i]] = round(fs2[stu[i]] * 0.4 + fs3[stu[i]] * 0.6);
}
else{
zf[stu[i]] = fs3[stu[i]];
}
}
StuInfo stuinfo[10005];
for (int i = 0; i < 10005; i++){
if (c1[stu[i]] == 0) fs2[stu[i]] = -1;
if (c2[stu[i]] == 0) fs3[stu[i]] = -1;
}
for (int i = 0; i < 10005; i++){
stuinfo[i].xh = stu[i];
stuinfo[i].fs1 = fs1[stu[i]];
stuinfo[i].fs2 = fs2[stu[i]];
stuinfo[i].fs3 = fs3[stu[i]];
stuinfo[i].zf = zf[stu[i]];
}
sort(stuinfo, stuinfo + 10005, cmp);
for (int i = 0; i < 10005; i++){
if (stuinfo[i].fs1 >= 200 && stuinfo[i].zf >= 60){
printf("%s %d %d %d %.0f\n", stuinfo[i].xh.c_str(), stuinfo[i].fs1,
stuinfo[i].fs2, stuinfo[i].fs3, stuinfo[i].zf);
}
}
system("pause");
return 0;
} | [
"859425698@qq.com"
] | 859425698@qq.com |
5027784a783100619ed93f57dae189669e92a954 | 1fb3ab49ef4e56088fb5cdf6a58dfd8f9c332be4 | /1 Array/binary_search.cpp | 77ae6505680b07c7930592f24d3f91e4fee28ab1 | [] | no_license | durgesh0187/Data-Structure | 410afc5967b4c8508b3fbf8f6de9922c4f1a29fc | e8ebdcf32ed96cb61f345ae4fd8aa009c6c66a79 | refs/heads/master | 2023-03-24T14:02:32.813951 | 2021-03-18T16:53:02 | 2021-03-18T16:53:02 | 287,024,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n,key;
cin>>n>>key;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
int start=0;
int end=n-1;
bool flag=false;
while (start<=end)
{
int mid = start + (end-start)/2;
if(a[mid]==key)
{
cout<<"Key present at index "<<mid<<endl;
flag=true;
break;
}
if(a[mid]>key)
{
end = mid-1;
}
else
{
start = mid+1;
}
}
if(flag!=true)
{
cout<<"Key is not present"<<endl;
}
return 0;
} | [
"noreply@github.com"
] | durgesh0187.noreply@github.com |
71a04004ce3597809cef0bf899e7d4fe66de4445 | b7eed481dc4f381b27349ea72ae75f806a4334e0 | /leetcodecpp/leetcodecpp/pra/lookup.cc | 40970917982c2edc8d2d78c4a15166ccd80292dd | [] | no_license | weekenlee/leetcode-cpp | f351da2998a01a077ca010a52629602fca9a1b43 | 25188daa69bdd0891fed7795046c9d250fa106fc | refs/heads/master | 2022-12-14T23:52:17.183426 | 2022-01-20T13:40:55 | 2022-01-20T13:40:55 | 120,147,027 | 0 | 0 | null | 2022-12-08T00:02:30 | 2018-02-04T02:02:56 | C++ | UTF-8 | C++ | false | false | 867 | cc | #include <algorithm>
#include <iostream>
#include <typeinfo>
using std::cout;
using std::endl;
void g() {cout << "global g" <<endl;}
template <class T>
class Y {
public:
void g() { cout << "Y<" << typeid(T).name() << ">::g()" <<endl;}
void h() { cout << "Y<" << typeid(T).name() << ">::h()" <<endl;}
typedef int E;
};
typedef double E;
template<class T>
void swap(T& t1, T& t2) {
cout <<"global swap"<<endl;
T temp = t1;
t1 = t2;
t2 = temp;
}
template<class T> class X: public Y<T> {
public:
E f() {
g();
this->h();
T t1 = T(), t2 = T(1);
cout << t1 <<endl;
swap(t1, t2);
std::swap(t1, t2);
cout << typeid(E).name() <<endl;
return E(t2);
}
};
int main() {
X<int> x;
cout << x.f() <<endl;
}
| [
"lwj1396@163.com"
] | lwj1396@163.com |
41028d9ffbcdcdfa2d4592d3f865b4fc0576e08c | 460455e7990de7257aa223a58e73069f3ef7ff43 | /src/server/game/Achievements/AchievementMgr.cpp | 4acd3580147712a6262b7a0c7b25caa2f765d158 | [] | no_license | Shkipper/wmane | 2ce69adea1eedf866921c857cbc5bd1bc6d037f0 | 2da37e1e758f17b61efb6aae8fa7343b234f3dcd | refs/heads/master | 2020-04-24T19:51:51.897587 | 2019-02-25T06:14:18 | 2019-02-25T06:14:18 | 172,225,859 | 0 | 0 | null | 2019-02-23T14:49:31 | 2019-02-23T14:49:31 | null | UTF-8 | C++ | false | false | 168,459 | cpp | /*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 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, see <http://www.gnu.org/licenses/>.
*/
#include "Common.h"
#include "DBCEnums.h"
#include "ObjectMgr.h"
#include "GuildMgr.h"
#include "World.h"
#include "WorldPacket.h"
#include "DatabaseEnv.h"
#include "AchievementMgr.h"
#include "Arena.h"
#include "CellImpl.h"
#include "GameEventMgr.h"
#include "GridNotifiersImpl.h"
#include "Guild.h"
#include "Language.h"
#include "Player.h"
#include "SpellMgr.h"
#include "DisableMgr.h"
#include "ScriptMgr.h"
#include "MapManager.h"
#include "Battleground.h"
#include "BattlegroundAB.h"
#include "Map.h"
#include "InstanceScript.h"
#include "Group.h"
#include "Chat.h"
#include "LexicalCast.h"
namespace Trinity
{
class AchievementChatBuilder
{
public:
AchievementChatBuilder(Player const& player, ChatMsg msgtype, int32 textId, uint32 ach_id)
: i_player(player), i_msgtype(msgtype), i_textId(textId), i_achievementId(ach_id) {}
void operator()(WorldPacket& data, LocaleConstant loc_idx)
{
auto const &text = sObjectMgr->GetTrinityString(i_textId, loc_idx);
ChatHandler::FillMessageData(&data, i_player.GetSession(), i_msgtype, LANG_UNIVERSAL, NULL, i_player.GetGUID(), text, NULL, NULL, i_achievementId);
}
private:
Player const& i_player;
ChatMsg i_msgtype;
int32 i_textId;
uint32 i_achievementId;
};
} // namespace Trinity
bool AchievementCriteriaData::IsValid(CriteriaEntry const* criteria)
{
if (dataType >= MAX_ACHIEVEMENT_CRITERIA_DATA_TYPE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` for criteria (Entry: %u) has wrong data type (%u), ignored.", criteria->ID, dataType);
return false;
}
switch (criteria->type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST: // Only hardcoded list
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST: // Only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM: // Only Children's Week achievements
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
default:
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-supported criteria type (Entry: %u Type: %u), ignored.", criteria->ID, criteria->type);
return false;
}
break;
}
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!creature.id || !sObjectMgr->GetCreatureTemplate(creature.id))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_CREATURE (%u) has non-existing creature id in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, creature.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (health.percent < 1 || health.percent > 100)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_PLAYER_LESS_HEALTH (%u) has wrong percent value in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, health.percent);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
{
SpellInfo const* spellEntry = sSpellMgr->GetSpellInfo(aura.spell_id);
if (!spellEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell id in value1 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id);
return false;
}
if (aura.effect_idx >= 3)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has wrong spell effect index in value2 (%u), ignored.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.effect_idx);
return false;
}
if (!spellEntry->Effects[aura.effect_idx].ApplyAuraName)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type %s (%u) has non-aura spell effect (ID: %u Effect: %u), ignores.",
criteria->ID, criteria->type, (dataType == ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA?"ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA":"ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA"), dataType, aura.spell_id, aura.effect_idx);
return false;
}
return true;
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (level.minlevel > STRONG_MAX_LEVEL)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL (%u) has wrong minlevel in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, level.minlevel);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (gender.gender > GENDER_NONE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER (%u) has wrong gender in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, gender.gender);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
if (!ScriptId)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT (%u) does not have ScriptName set, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
return true;
/*
@Todo:
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_DIFFICULTY:
*/
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
if (map_players.maxcount <= 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT (%u) has wrong max players count in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, map_players.maxcount);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (team.team != ALLIANCE && team.team != HORDE)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM (%u) has unknown team in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, team.team);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
if (drunk.state >= MAX_DRUNKEN)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK (%u) has unknown drunken state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, drunk.state);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
if (!sHolidaysStore.LookupEntry(holiday.id))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY (%u) has unknown holiday in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, holiday.id);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
return true; // Not check correctness node indexes
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
if (equipped_item.item_quality >= MAX_ITEM_QUALITY)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_requirement` (Entry: %u Type: %u) for requirement ACHIEVEMENT_CRITERIA_REQUIRE_S_EQUIPED_ITEM (%u) has unknown quality state in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, equipped_item.item_quality);
return false;
}
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!classRace.class_id && !classRace.race_id)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) must not have 0 in either value field, ignored.",
criteria->ID, criteria->type, dataType);
return false;
}
if (classRace.class_id && ((1 << (classRace.class_id-1)) & CLASSMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing class in value1 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.class_id);
return false;
}
if (classRace.race_id && ((1 << (classRace.race_id-1)) & RACEMASK_ALL_PLAYABLE) == 0)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) for data type ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE (%u) has non-existing race in value2 (%u), ignored.",
criteria->ID, criteria->type, dataType, classRace.race_id);
return false;
}
return true;
default:
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` (Entry: %u Type: %u) has data for non-supported data type (%u), ignored.", criteria->ID, criteria->type, dataType);
return false;
}
}
bool AchievementCriteriaData::Meets(uint32 criteria_id, Player const* source, Unit const* target, uint64 miscValue1 /*= 0*/) const
{
switch (dataType)
{
case ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE:
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_CREATURE:
if (!target || target->GetTypeId() != TYPEID_UNIT)
return false;
return target->GetEntry() == creature.id;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_CLASS_RACE:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != target->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != target->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_PLAYER_CLASS_RACE:
if (!source || source->GetTypeId() != TYPEID_PLAYER)
return false;
if (classRace.class_id && classRace.class_id != source->ToPlayer()->getClass())
return false;
if (classRace.race_id && classRace.race_id != source->ToPlayer()->getRace())
return false;
return true;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_PLAYER_LESS_HEALTH:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return !target->HealthAbovePct(health.percent);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_AURA:
return source->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_AURA:
return target && target->HasAuraEffect(aura.spell_id, aura.effect_idx);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_VALUE:
return miscValue1 >= value.minvalue;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_LEVEL:
if (!target)
return false;
return target->getLevel() >= level.minlevel;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_GENDER:
if (!target)
return false;
return target->getGender() == gender.gender;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT:
return sScriptMgr->OnCriteriaCheck(ScriptId, criteria_id, miscValue1, const_cast<Player*>(source), const_cast<Unit*>(target));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_MAP_PLAYER_COUNT:
return source->GetMap()->GetPlayersCountExceptGMs() <= map_players.maxcount;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_T_TEAM:
if (!target || target->GetTypeId() != TYPEID_PLAYER)
return false;
return target->ToPlayer()->GetTeam() == team.team;
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_DRUNK:
return Player::GetDrunkenstateByValue(source->GetDrunkValue()) >= DrunkenState(drunk.state);
case ACHIEVEMENT_CRITERIA_DATA_TYPE_HOLIDAY:
return IsHolidayActive(HolidayIds(holiday.id));
case ACHIEVEMENT_CRITERIA_DATA_TYPE_BG_LOSS_TEAM_SCORE:
{
Battleground* bg = source->GetBattleground();
if (!bg)
return false;
uint16 winnerTeamScore = 0;
switch(bg->GetTypeID(true))
{
case BATTLEGROUND_WS:
winnerTeamScore = 3;
break;
case BATTLEGROUND_AB:
case BATTLEGROUND_EY:
winnerTeamScore = 1600;
break;
default:
break;
}
if (winnerTeamScore > 0 && !bg->IsTeamScoreInRange(source->GetTeam(), winnerTeamScore, winnerTeamScore))
return false;
return bg->IsTeamScoreInRange(source->GetTeam() == ALLIANCE ? HORDE : ALLIANCE, bg_loss_team_score.min_score, bg_loss_team_score.max_score);
}
case ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT:
{
if (!source->IsInWorld())
return false;
Map* map = source->GetMap();
if (!map->IsDungeon())
{
TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for non-dungeon/non-raid map %u",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
InstanceScript* instance = ((InstanceMap*)map)->GetInstanceScript();
if (!instance)
{
TC_LOG_ERROR("achievement", "Achievement system call ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT (%u) for achievement criteria %u for map %u but map does not have a instance script",
ACHIEVEMENT_CRITERIA_DATA_INSTANCE_SCRIPT, criteria_id, map->GetId());
return false;
}
return instance->CheckAchievementCriteriaMeet(criteria_id, source, target, miscValue1);
}
case ACHIEVEMENT_CRITERIA_DATA_TYPE_S_EQUIPED_ITEM:
{
ItemTemplate const* pProto = sObjectMgr->GetItemTemplate(miscValue1);
if (!pProto)
return false;
return pProto->ItemLevel >= equipped_item.item_level && pProto->Quality >= equipped_item.item_quality;
}
default:
break;
}
return false;
}
bool AchievementCriteriaDataSet::Meets(Player const* source, Unit const* target, uint64 miscvalue /*= 0*/) const
{
for (Storage::const_iterator itr = storage.begin(); itr != storage.end(); ++itr)
if (!itr->Meets(criteria_id, source, target, miscvalue))
return false;
return true;
}
template<class T>
AchievementMgr<T>::AchievementMgr(T* owner): _owner(owner), _achievementPoints(0)
{
}
template<class T>
AchievementMgr<T>::~AchievementMgr()
{
}
template<class T>
void AchievementMgr<T>::SendPacket(WorldPacket* /*data*/) const
{
}
template<>
void AchievementMgr<Guild>::SendPacket(WorldPacket* data) const
{
GetOwner()->BroadcastPacket(data);
}
template<>
void AchievementMgr<Player>::SendPacket(WorldPacket* data) const
{
GetOwner()->GetSession()->SendPacket(data);
}
template<class T>
void AchievementMgr<T>::RemoveCriteriaProgress(const CriteriaEntry* entry)
{
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
auto const itr = progressMap.find(entry->ID);
if (itr == progressMap.end())
return;
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(entry->ID);
SendPacket(&data);
progressMap.erase(itr);
}
template<>
void AchievementMgr<Guild>::RemoveCriteriaProgress(const CriteriaEntry* entry)
{
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
auto const itr = progressMap.find(entry->ID);
if (itr == progressMap.end())
return;
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8);
data.WriteBitSeq<7, 3, 4, 2, 1, 5, 6, 0>(guid);
data.WriteByteSeq<5, 7, 4, 6, 2, 1, 3>(guid);
data << uint32(entry->ID);
data.WriteByteSeq<0>(guid);
SendPacket(&data);
progressMap.erase(itr);
}
template<class T>
void AchievementMgr<T>::ResetAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1, uint64 miscValue2, bool evenIfCriteriaComplete)
{
// Disable for gamemasters with GM-mode enabled
if (GetOwner()->isGameMaster())
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
CriteriaEntry const* achievementCriteria = (*i);
// don't update already completed criteria if not forced or achievement already complete
if (!IsCompletedCriteria(achievementCriteria))
RemoveCriteriaProgress(achievementCriteria);
}
}
template<>
void AchievementMgr<Guild>::ResetAchievementCriteria(AchievementCriteriaTypes /*type*/, uint64 /*miscValue1*/, uint64 /*miscValue2*/, bool /*evenIfCriteriaComplete*/)
{
// Not needed
}
template<class T>
void AchievementMgr<T>::DeleteFromDB(uint32 /*lowguid*/, uint32 /*accountId*/)
{
}
template<>
void AchievementMgr<Player>::DeleteFromDB(uint32 lowguid, uint32 /*accountId*/)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_CHAR_ACHIEVEMENT);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<>
void AchievementMgr<Guild>::DeleteFromDB(uint32 lowguid, uint32 /*accountId*/)
{
SQLTransaction trans = CharacterDatabase.BeginTransaction();
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENTS);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_ALL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, lowguid);
trans->Append(stmt);
CharacterDatabase.CommitTransaction(trans);
}
template<class T>
void AchievementMgr<T>::SaveToDB(SQLTransaction& /*charTrans*/, SQLTransaction& /*authTrans*/)
{
}
template<>
void AchievementMgr<Player>::SaveToDB(SQLTransaction& charTrans, SQLTransaction& authTrans)
{
uint32 const guidLow = GetOwner()->GetGUIDLow();
uint32 const accountId = GetOwner()->GetSession()->GetAccountId();
if (!m_completedAchievements.empty())
{
bool needCharacterExecute = false;
bool needAccountExecute = false;
std::ostringstream ssAccDel;
std::ostringstream ssAccIns;
std::ostringstream ssCharDel;
std::ostringstream ssCharIns;
std::ostringstream sscount;
for (auto &kvPair : m_completedAchievements)
{
auto const achievementId = kvPair.first;
auto &completionData = kvPair.second;
if (!completionData.changed)
continue;
AchievementEntry const* ach = sAchievementMgr->GetAchievement(achievementId);
if (!ach)
continue;
bool isAccountAchievement = ach->flags & ACHIEVEMENT_FLAG_ACCOUNT;
bool const mustSaveForCharacter = completionData.completedByThisCharacter;
if (!needAccountExecute)
{
if (isAccountAchievement)
{
// First new/changed record prefix
ssAccDel << "DELETE FROM account_achievement WHERE account = " << accountId << " AND achievement IN (";
ssAccIns << "INSERT INTO account_achievement (account, first_guid, achievement, date) VALUES ";
needAccountExecute = true;
}
}
else
{
if (isAccountAchievement)
{
// Next new/changed record prefix
ssAccDel << ',';
ssAccIns << ',';
}
}
if (!needCharacterExecute)
{
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << "DELETE FROM character_achievement WHERE guid = " << guidLow << " AND achievement IN (";
ssCharIns << "INSERT INTO character_achievement (guid, achievement, date) VALUES ";
needCharacterExecute = true;
}
}
else
{
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << ',';
ssCharIns << ',';
}
}
if (isAccountAchievement)
{
// New/changed record data
ssAccDel << achievementId;
ssAccIns << '(' << accountId << ',' << completionData.first_guid << ',' << achievementId << ',' << completionData.date << ')';
}
if (mustSaveForCharacter || !isAccountAchievement)
{
ssCharDel << achievementId;
ssCharIns << '(' << guidLow << ',' << achievementId << "," << completionData.date << ')';
}
/// Mark as saved in db
completionData.changed = false;
}
if (needAccountExecute)
{
ssAccDel << ')';
authTrans->Append(ssAccDel.str().c_str());
authTrans->Append(ssAccIns.str().c_str());
}
if (needCharacterExecute)
{
ssCharDel << ')';
charTrans->Append(ssCharDel.str().c_str());
charTrans->Append(ssCharIns.str().c_str());
}
}
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
if (progressMap.empty())
return;
// Prepare deleting and insert
bool needExecuteDel = false;
bool needExecuteIns = false;
bool needExecuteAccount = false;
bool isAccountAchievement = false;
bool alreadyOneCharDelLine = false;
bool alreadyOneAccDelLine = false;
bool alreadyOneCharInsLine = false;
bool alreadyOneAccInsLine = false;
std::ostringstream ssAccDel;
std::ostringstream ssAccIns;
std::ostringstream ssCharDel;
std::ostringstream ssCharIns;
for (auto &kvPair : progressMap)
{
auto const criteriaId = kvPair.first;
auto &progressData = kvPair.second;
if (!progressData.changed)
continue;
auto const criteria = sAchievementMgr->GetAchievementCriteria(criteriaId);
if (!criteria)
continue;
AchievementEntry const* achievement;
AchievementCriteriaTreeList const& criteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaTreeList.begin(); iter != criteriaTreeList.end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(criteriaTree);
}
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
isAccountAchievement = true;
needExecuteAccount = true;
}
else
isAccountAchievement = false;
// Deleted data (including 0 progress state)
if (!needExecuteDel)
{
// First new/changed record prefix (for any counter value)
ssAccDel << "DELETE FROM account_achievement_progress WHERE account = " << accountId << " AND criteria IN (";
ssCharDel << "DELETE FROM character_achievement_progress WHERE guid = " << guidLow << " AND criteria IN (";
needExecuteDel = true;
}
else
{
// Next new/changed record prefix
if (isAccountAchievement)
{
if (alreadyOneAccDelLine)
ssAccDel << ',';
}
else
{
if (alreadyOneCharDelLine)
ssCharDel << ',';
}
}
// New/changed record data
if (isAccountAchievement)
{
ssAccDel << criteriaId;
alreadyOneAccDelLine = true;
}
else
{
ssCharDel << criteriaId;
alreadyOneCharDelLine = true;
}
// Store data only for real progress
if (progressData.counter != 0)
{
if (!needExecuteIns)
{
// First new/changed record prefix
ssAccIns << "INSERT INTO account_achievement_progress (account, criteria, counter, date) VALUES ";
ssCharIns << "INSERT INTO character_achievement_progress (guid, criteria, counter, date) VALUES ";
needExecuteIns = true;
}
else
{
// Next new/changed record prefix
if (isAccountAchievement)
{
if (alreadyOneAccInsLine)
ssAccIns << ',';
}
else
{
if (alreadyOneCharInsLine)
ssCharIns << ',';
}
}
// New/changed record data
if (isAccountAchievement)
{
ssAccIns << '(' << accountId << ',' << criteriaId << ',' << progressData.counter << ',' << progressData.date << ')';
alreadyOneAccInsLine = true;
}
else
{
ssCharIns << '(' << guidLow << ',' << criteriaId << ',' << progressData.counter << ',' << progressData.date << ')';
alreadyOneCharInsLine = true;
}
}
// Mark as updated in db
progressData.changed = false;
}
// DELETE ... IN (.... _)_
if (needExecuteDel)
{
ssAccDel << ')';
ssCharDel << ')';
}
if (needExecuteDel || needExecuteIns)
{
if (needExecuteDel)
{
if (needExecuteAccount && alreadyOneAccDelLine)
authTrans->Append(ssAccDel.str().c_str());
if (alreadyOneCharDelLine)
charTrans->Append(ssCharDel.str().c_str());
}
if (needExecuteIns)
{
if (needExecuteAccount && alreadyOneAccInsLine)
authTrans->Append(ssAccIns.str().c_str());
if (alreadyOneCharInsLine)
charTrans->Append(ssCharIns.str().c_str());
}
}
}
template<>
void AchievementMgr<Guild>::SaveToDB(SQLTransaction& trans, SQLTransaction& /*trans*/)
{
PreparedStatement* stmt;
std::ostringstream guidstr;
for (auto &kvPair : m_completedAchievements)
{
auto const achievementId = kvPair.first;
auto &completionData = kvPair.second;
if (!completionData.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, achievementId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, achievementId);
stmt->setUInt32(2, completionData.date);
for (auto const &guid : completionData.guids)
guidstr << GUID_LOPART(guid) << ',';
stmt->setString(3, guidstr.str());
trans->Append(stmt);
guidstr.str("");
completionData.changed = false;
}
for (auto &kvPair : GetCriteriaProgressMap())
{
auto const criteriaId = kvPair.first;
auto &progressData = kvPair.second;
if (!progressData.changed)
continue;
stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, criteriaId);
trans->Append(stmt);
stmt = CharacterDatabase.GetPreparedStatement(CHAR_INS_GUILD_ACHIEVEMENT_CRITERIA);
stmt->setUInt32(0, GetOwner()->GetId());
stmt->setUInt16(1, criteriaId);
stmt->setUInt64(2, progressData.counter);
stmt->setUInt32(3, progressData.date);
stmt->setUInt32(4, GUID_LOPART(progressData.CompletedGUID));
trans->Append(stmt);
progressData.changed = false;
}
}
template<class T>
void AchievementMgr<T>::LoadFromDB(PreparedQueryResult /*achievementResult*/, PreparedQueryResult /*criteriaResult*/, PreparedQueryResult /*achievementAccountResult*/, PreparedQueryResult /*criteriaAccountResult*/)
{
}
template<>
void AchievementMgr<Player>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult, PreparedQueryResult achievementAccountResult, PreparedQueryResult criteriaAccountResult)
{
if (achievementAccountResult)
{
do
{
Field* fields = achievementAccountResult->Fetch();
uint32 first_guid = fields[0].GetUInt32();
uint32 achievementid = fields[1].GetUInt16();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_GUILD)
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[2].GetUInt32());
ca.changed = false;
ca.first_guid = MAKE_NEW_GUID(first_guid, 0, HIGHGUID_PLAYER);
ca.completedByThisCharacter = false;
_achievementPoints += achievement->points;
// Title achievement rewards are retroactive
if (AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement))
if (uint32 titleId = reward->titleId[Player::TeamForRace(GetOwner()->getRace()) == ALLIANCE ? 0 : 1])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
}
while (achievementAccountResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all characters
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.changed = false;
}
while (criteriaResult->NextRow());
}
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
uint32 guid = fields[1].GetUInt32();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(achievementid);
if (!achievement)
continue;
if (achievement->flags & ACHIEVEMENT_FLAG_GUILD)
continue;
// Achievement in character_achievement but not in account_achievement, there is a problem.
if (m_completedAchievements.find(achievementid) == m_completedAchievements.end() && achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
TC_LOG_ERROR("achievement", "Account-wide achievement '%u' in character_achievement but not in account_achievement, there is a problem.", achievementid);
continue;
}
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.completedByThisCharacter = true;
ca.date = time_t(fields[2].GetUInt32());
ca.changed = false;
ca.first_guid = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER);
_achievementPoints += achievement->points;
}
while (achievementResult->NextRow());
}
if (criteriaAccountResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaAccountResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all characters
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `character_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgressMap &progressMap = GetCriteriaProgressMap();
// Achievement in both account & characters achievement_progress, problem
if (progressMap.find(id) != progressMap.end())
{
TC_LOG_ERROR("achievement", "Achievement '%u' in both account & characters achievement_progress", id);
continue;
}
CriteriaProgress& progress = progressMap[id];
progress.counter = counter;
progress.date = date;
progress.changed = false;
}
while (criteriaAccountResult->NextRow());
}
}
template<>
void AchievementMgr<Guild>::LoadFromDB(PreparedQueryResult achievementResult, PreparedQueryResult criteriaResult, PreparedQueryResult /*achievementAccountResult*/, PreparedQueryResult /*criteriaAccountResult*/)
{
if (achievementResult)
{
do
{
Field* fields = achievementResult->Fetch();
uint32 achievementid = fields[0].GetUInt16();
// Must not happen: cleanup at server startup in sAchievementMgr->LoadCompletedAchievements()
AchievementEntry const* achievement = sAchievementStore.LookupEntry(achievementid);
if (!achievement)
continue;
if (!(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
continue;
CompletedAchievementData& ca = m_completedAchievements[achievementid];
ca.date = time_t(fields[1].GetUInt32());
Tokenizer guids(fields[2].GetString(), ' ');
for (uint32 i = 0; i < guids.size(); ++i)
ca.guids.insert(MAKE_NEW_GUID(Trinity::lexicalCast<uint32>(guids[i]), 0, HIGHGUID_PLAYER));
ca.changed = false;
_achievementPoints += achievement->points;
}
while (achievementResult->NextRow());
}
if (criteriaResult)
{
time_t now = time(NULL);
do
{
Field* fields = criteriaResult->Fetch();
uint32 id = fields[0].GetUInt16();
uint64 counter = fields[1].GetUInt64();
time_t date = time_t(fields[2].GetUInt32());
uint64 guid = MAKE_NEW_GUID(fields[3].GetUInt32(), 0, HIGHGUID_PLAYER);
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(id);
if (!criteria)
{
// We will remove not existed criteria for all guilds
TC_LOG_ERROR("achievement", "Non-existing achievement criteria %u data removed from table `guild_achievement_progress`.", id);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEV_PROGRESS_CRITERIA_GUILD);
stmt->setUInt16(0, uint16(id));
CharacterDatabase.Execute(stmt);
continue;
}
if (criteria->timeLimit && time_t(date + criteria->timeLimit) < now)
continue;
CriteriaProgress& progress = m_criteriaProgress[id];
progress.counter = counter;
progress.date = date;
progress.CompletedGUID = MAKE_NEW_GUID(guid, 0, HIGHGUID_PLAYER);
progress.changed = false;
}
while (criteriaResult->NextRow());
}
}
template<class T>
void AchievementMgr<T>::Reset()
{
}
template<>
void AchievementMgr<Player>::Reset()
{
for (auto const &kvPair : m_completedAchievements)
{
WorldPacket data(SMSG_ACHIEVEMENT_DELETED, 4);
data << uint32(kvPair.first);
SendPacket(&data);
}
m_completedAchievements.clear();
for (auto const &kvPair : GetCriteriaProgressMap())
{
WorldPacket data(SMSG_CRITERIA_DELETED, 4);
data << uint32(kvPair.first);
SendPacket(&data);
}
GetCriteriaProgressMap().clear();
_achievementPoints = 0;
DeleteFromDB(GetOwner()->GetGUIDLow());
// re-fill data
GetOwner()->CheckAllAchievementCriteria();
}
template<>
void AchievementMgr<Guild>::Reset()
{
ObjectGuid const guid = GetOwner()->GetGUID();
for (auto const &kvPair : m_completedAchievements)
{
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DELETED, 4);
data.WriteBitSeq<4, 1, 2, 3, 0, 7, 5, 6>(guid);
data << uint32(kvPair.first);
data.WriteByteSeq<5, 1, 3, 6, 0, 7>(guid);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<4, 2>(guid);
SendPacket(&data);
}
m_completedAchievements.clear();
for (auto const &kvPair : GetCriteriaProgressMap())
{
WorldPacket data(SMSG_GUILD_CRITERIA_DELETED, 4 + 8);
data.WriteBitSeq<7, 3, 4, 2, 1, 5, 6, 0>(guid);
data.WriteByteSeq<5, 7, 4, 6, 2, 1, 3>(guid);
data << uint32(kvPair.first);
data.WriteByteSeq<0>(guid);
SendPacket(&data);
}
GetCriteriaProgressMap().clear();
_achievementPoints = 0;
DeleteFromDB(GetOwner()->GetId());
}
template<class T>
void AchievementMgr<T>::SendAchievementEarned(AchievementEntry const* achievement) const
{
// Don't send for achievements with ACHIEVEMENT_FLAG_HIDDEN
if (achievement->flags & ACHIEVEMENT_FLAG_HIDDEN)
return;
if (Guild* guild = sGuildMgr->GetGuildById(GetOwner()->GetGuildId()))
{
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_GUILD_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
guild->BroadcastWorker(say_do);
}
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_KILL | ACHIEVEMENT_FLAG_REALM_FIRST_REACH))
{
if (WorldSession* session = GetOwner()->GetSession())
{
WorldPacket data;
auto const &text = session->GetTrinityString(LANG_ACHIEVEMENT_EARNED);
ChatHandler::FillMessageData(&data, session, CHAT_MSG_ACHIEVEMENT, LANG_UNIVERSAL, NULL, session->GetPlayer()->GetGUID(), text, NULL, NULL, achievement->ID);
sWorld->SendGlobalMessage(&data);
}
// Broadcast realm first reached
/*WorldPacket data(SMSG_SERVER_FIRST_ACHIEVEMENT, GetOwner()->GetName().length() + 1 + 8 + 4 + 4);
data << GetOwner()->GetName();
data << uint64(GetOwner()->GetGUID());
data << uint32(achievement->ID);
data << uint32(0); // 1=link supplied string as player name, 0=display plain string
sWorld->SendGlobalMessage(&data);*/
}
// If player is in world he can tell his friends about new achievement
else if (GetOwner()->IsInWorld())
{
CellCoord p = Trinity::ComputeCellCoord(GetOwner()->GetPositionX(), GetOwner()->GetPositionY());
Cell cell(p);
cell.SetNoCreate();
Trinity::AchievementChatBuilder say_builder(*GetOwner(), CHAT_MSG_ACHIEVEMENT, LANG_ACHIEVEMENT_EARNED, achievement->ID);
Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> say_do(say_builder);
Trinity::PlayerDistWorker<Trinity::LocalizedPacketDo<Trinity::AchievementChatBuilder> > say_worker(GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), say_do);
cell.Visit(p, Trinity::makeWorldVisitor(say_worker), *GetOwner()->GetMap(), *GetOwner(), sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY));
}
WorldPacket data(SMSG_ACHIEVEMENT_EARNED);
ObjectGuid thisPlayerGuid = GetOwner()->GetGUID();
ObjectGuid firstPlayerOnAccountGuid = GetOwner()->GetGUID();
if (HasAccountAchieved(achievement->ID))
firstPlayerOnAccountGuid = GetFirstAchievedCharacterOnAccount(achievement->ID);
data << uint32(secsToTimeBitFields(time(NULL)));
data << uint32(50724905);
data << uint32(achievement->ID);
data << uint32(50724905);
data.WriteBitSeq<6>(thisPlayerGuid);
data.WriteBitSeq<5, 3, 0, 1, 6>(firstPlayerOnAccountGuid);
data.WriteBitSeq<2>(thisPlayerGuid);
data.WriteBitSeq<2>(firstPlayerOnAccountGuid);
data.WriteBitSeq<1, 4, 5, 7>(thisPlayerGuid);
data.WriteBitSeq<7>(firstPlayerOnAccountGuid);
data.WriteBitSeq<0>(thisPlayerGuid);
data.WriteBitSeq<4>(firstPlayerOnAccountGuid);
data.WriteBit(0);
data.WriteBitSeq<3>(thisPlayerGuid);
data.WriteByteSeq<4>(firstPlayerOnAccountGuid);
data.WriteByteSeq<0, 2, 6, 1>(thisPlayerGuid);
data.WriteByteSeq<1, 5, 0>(firstPlayerOnAccountGuid);
data.WriteByteSeq<7, 3, 5>(thisPlayerGuid);
data.WriteByteSeq<6>(firstPlayerOnAccountGuid);
data.WriteByteSeq<4>(thisPlayerGuid);
data.WriteByteSeq<3, 7, 2>(firstPlayerOnAccountGuid);
GetOwner()->SendMessageToSetInRange(&data, sWorld->getFloatConfig(CONFIG_LISTEN_RANGE_SAY), true);
}
template<>
void AchievementMgr<Guild>::SendAchievementEarned(AchievementEntry const* achievement) const
{
ObjectGuid guid = GetOwner()->GetGUID();
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_EARNED, 8+4+8);
data.WriteBitSeq<6, 1, 5, 0, 3, 4, 2, 7>(guid);
data.WriteByteSeq<7>(guid);
data << uint32(achievement->ID);
data.WriteByteSeq<4, 3, 1, 6, 5>(guid);
data << uint32(secsToTimeBitFields(time(NULL)));
data.WriteByteSeq<0, 2>(guid);
SendPacket(&data);
}
template<class T>
void AchievementMgr<T>::SendCriteriaUpdate(CriteriaEntry const* /*entry*/, CriteriaProgress const* /*progress*/, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
}
template<>
void AchievementMgr<Player>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 timeElapsed, bool timedCompleted) const
{
WorldPacket data(SMSG_CRITERIA_UPDATE, 4 + 4 + 4 + 4 + 8 + 4);
ObjectGuid playerGuid = GetOwner()->GetGUID();
data << uint32(entry->ID);
// This are some flags, 1 is for keeping the counter at 0 in client
if (!entry->timeLimit)
data << uint32(0);
else
data << uint32(timedCompleted ? 0 : 1);
data << uint32(timeElapsed); // Time elapsed in seconds
data.AppendPackedTime(progress->date);
data << (uint64)progress->counter;
data << uint32(timeElapsed);
data.WriteBitSeq<2, 4, 1, 5, 3, 6, 7, 0>(playerGuid);
data.WriteByteSeq<7, 0, 6, 5, 2, 1, 4, 3>(playerGuid);
SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendCriteriaUpdate(CriteriaEntry const* entry, CriteriaProgress const* progress, uint32 /*timeElapsed*/, bool /*timedCompleted*/) const
{
// Will send response to criteria progress request
WorldPacket data(SMSG_GUILD_CRITERIA_DATA);
ObjectGuid counter = progress->counter; // For accessing every byte individually
ObjectGuid guid = progress->CompletedGUID;
data.WriteBits(1, 19);
data.WriteBitSeq<3, 6>(counter);
data.WriteBitSeq<5, 4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6, 7, 3>(guid);
data.WriteBitSeq<5, 0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<1, 4>(counter);
data.WriteBitSeq<1>(guid);
data.FlushBits();
data.WriteByteSeq<4>(guid);
data << uint32(progress->date); // Unknown date
data.WriteByteSeq<2, 0>(counter);
data << uint32(progress->changed);
data.WriteByteSeq<7, 1>(guid);
data << uint32(entry->ID);
data << uint32(progress->date); // Last update time (not packed!)
data.WriteByteSeq<6>(guid);
data.WriteByteSeq<1>(counter);
data.WriteByteSeq<3>(guid);
data.WriteByteSeq<4>(counter);
data << uint32(progress->date); // Unknown date
data.WriteByteSeq<5, 3>(counter);
data.WriteByteSeq<0>(guid);
data.WriteByteSeq<6, 7>(counter);
data.WriteByteSeq<2, 5>(guid);
SendPacket(&data);
}
template<class T>
CriteriaProgressMap & AchievementMgr<T>::GetCriteriaProgressMap()
{
return m_criteriaProgress;
}
static const uint32 achievIdByArenaSlot[MAX_ARENA_SLOT] = {1057, 1107, 1108};
static const uint32 achievIdForDungeon[][4] =
{
// ach_cr_id, is_dungeon, is_raid, is_heroic_dungeon
{ 321, true, true, true },
{ 916, false, true, false },
{ 917, false, true, false },
{ 918, true, false, false },
{ 2219, false, false, true },
{ 0, false, false, false }
};
// Helper function to avoid having to specialize template for a 800 line long function
template <typename T> static bool IsGuild() { return false; }
template<> bool IsGuild<Guild>() { return true; }
/**
* This function will be called whenever the user might have done a criteria relevant action
*/
template<class T>
void AchievementMgr<T>::UpdateAchievementCriteria(AchievementCriteriaTypes type, uint64 miscValue1 /*= 0*/, uint64 miscValue2 /*= 0*/, uint64 miscValue3 /*= 0*/, Unit const* unit /*= NULL*/, Player* referencePlayer /*= NULL*/)
{
if (type >= ACHIEVEMENT_CRITERIA_TYPE_TOTAL)
return;
if (!IsGuild<T>() && !referencePlayer)
return;
// disable for gamemasters with GM-mode enabled
if (referencePlayer)
if (referencePlayer->isGameMaster())
return;
// Lua_GetGuildLevelEnabled() is checked in achievement UI to display guild tab
if (IsGuild<T>() && !sWorld->getBoolConfig(CONFIG_GUILD_LEVELING_ENABLED))
return;
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetAchievementCriteriaByType(type, IsGuild<T>());
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
CriteriaEntry const* achievementCriteria = (*i);
if (!CanUpdateCriteria(achievementCriteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
continue;
// Requirements not found in the dbc
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit, miscValue1))
continue;
switch (type)
{
// std. case: increment at 1
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS: // @TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: increment at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS: //@TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: increment at miscValue2
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE);
break;
// std case: high value at miscValue1
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD: //@TODO : for online player only currently
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
SetCriteriaProgress(achievementCriteria, referencePlayer->getLevel(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
if (uint32 skillvalue = referencePlayer->GetBaseSkillValue(achievementCriteria->reach_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, skillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
if (uint32 maxSkillvalue = referencePlayer->GetPureMaxSkillValue(achievementCriteria->learn_skill_level.skillID))
SetCriteriaProgress(achievementCriteria, maxSkillvalue, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetRewardedQuestCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
{
time_t nextDailyResetTime = sWorld->GetNextDailyQuestsResetTime();
CriteriaProgress *progress = GetCriteriaProgress(achievementCriteria);
if (!miscValue1) // Login case.
{
// Reset if player missed one day.
if (progress && progress->date < (nextDailyResetTime - 2 * DAY))
SetCriteriaProgress(achievementCriteria, 0, referencePlayer, PROGRESS_SET);
continue;
}
ProgressType progressType;
if (!progress)
// 1st time. Start count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - 2 * DAY))
// Last progress is older than 2 days. Player missed 1 day => Restart count.
progressType = PROGRESS_SET;
else if (progress->date < (nextDailyResetTime - DAY))
// Last progress is between 1 and 2 days. => 1st time of the day.
progressType = PROGRESS_ACCUMULATE;
else
// Last progress is within the day before the reset => Already counted today.
continue;
SetCriteriaProgress(achievementCriteria, 1, referencePlayer, progressType);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
{
uint32 counter = 0;
const RewardedQuestSet &rewQuests = referencePlayer->getRewardedQuests();
for (RewardedQuestSet::const_iterator itr = rewQuests.begin(); itr != rewQuests.end(); ++itr)
{
Quest const* quest = sObjectMgr->GetQuestTemplate(*itr);
if (quest && quest->GetZoneOrSort() >= 0 && uint32(quest->GetZoneOrSort()) == achievementCriteria->complete_quests_in_zone.zoneID)
++counter;
}
SetCriteriaProgress(achievementCriteria, counter, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
// miscValue1 is the ingame fallheight*100 as stored in dbc
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
SetCriteriaProgress(achievementCriteria, 1, referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetBankBagSlotCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
{
int32 reputation = referencePlayer->GetReputationMgr().GetReputation(achievementCriteria->gain_reputation.factionID);
if (reputation > 0)
SetCriteriaProgress(achievementCriteria, reputation, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetExaltedFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
{
uint32 spellCount = 0;
for (auto const &kvPair : referencePlayer->GetSpellMap())
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(kvPair.first);
for (auto skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
{
if (skillIter->second->skillId == achievementCriteria->learn_skillline_spell.skillLine)
++spellCount;
}
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetReveredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetHonoredFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetReputationMgr().GetVisibleFactionCount(), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
{
uint32 spellCount = 0;
for (auto const &kvPair : referencePlayer->GetSpellMap())
{
SkillLineAbilityMapBounds bounds = sSpellMgr->GetSkillLineAbilityMapBounds(kvPair.first);
for (auto skillIter = bounds.first; skillIter != bounds.second; ++skillIter)
if (skillIter->second->skillId == achievementCriteria->learn_skill_line.skillLine)
++spellCount;
}
SetCriteriaProgress(achievementCriteria, spellCount, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetUInt32Value(PLAYER_FIELD_LIFETIME_HONORABLE_KILLS), referencePlayer);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
SetCriteriaProgress(achievementCriteria, referencePlayer->GetMoney(), referencePlayer, PROGRESS_HIGHEST);
break;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
if (!miscValue1)
SetCriteriaProgress(achievementCriteria, _achievementPoints, referencePlayer, PROGRESS_SET);
else
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_team_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // Login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
SetCriteriaProgress(achievementCriteria, referencePlayer->GetArenaPersonalRating(arena_slot), referencePlayer, PROGRESS_HIGHEST);
}
}
break;
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
{
uint32 reqTeamType = achievementCriteria->highest_personal_rating.teamtype;
if (miscValue1)
{
if (miscValue2 != reqTeamType)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_HIGHEST);
}
else // Login case
{
for (uint32 arena_slot = 0; arena_slot < MAX_ARENA_SLOT; ++arena_slot)
SetCriteriaProgress(achievementCriteria, referencePlayer->GetArenaPersonalRating(arena_slot), referencePlayer, PROGRESS_HIGHEST);
}
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
{
if (!miscValue1)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer, PROGRESS_ACCUMULATE);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
{
if (!miscValue1)
continue;
SetCriteriaProgress(achievementCriteria, miscValue1, referencePlayer);
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
{
if (!miscValue1 || !miscValue2)
continue;
SetCriteriaProgress(achievementCriteria, miscValue2, referencePlayer, PROGRESS_ACCUMULATE);
break;
}
// FIXME: not triggered in code as result, need to implement
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
break; // Not implemented yet :(
default:
break;
}
std::list<uint32> achivEntries;
AchievementCriteriaTreeList achievementCriteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(achievementCriteria);
for (AchievementCriteriaTreeList::const_iterator iter = achievementCriteriaTreeList.begin(); iter != achievementCriteriaTreeList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
if ((IsGuild<T>() && !(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
|| (achievement->flags & ACHIEVEMENT_FLAG_GUILD && !IsGuild<T>()))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Non-guild achievement",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID, achievement->parentAchievement);
continue;
}
if (achievement->mapID != -1 && referencePlayer->GetMapId() != uint32(achievement->mapID))
{
if (type == ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS)
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Wrong map",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID);
continue;
}
}
if ((achievement->requiredFaction == ACHIEVEMENT_FACTION_HORDE && referencePlayer->GetTeam() != HORDE) ||
(achievement->requiredFaction == ACHIEVEMENT_FACTION_ALLIANCE && referencePlayer->GetTeam() != ALLIANCE))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Wrong faction",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID);
continue;
}
achivEntries.push_back(achievement->ID);
}
achivEntries.sort();
for (auto x : achivEntries)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(x);
if (!achievement)
continue;
if (referencePlayer)
{
if (achievement->parentAchievement != 0 &&
((!(achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT) && !HasAchieved(achievement->parentAchievement))
|| (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT && !HasAccountAchieved(achievement->parentAchievement))))
{
TC_LOG_DEBUG("achievement", "CanUpdateCriteria: (Id: %u Type %s Achievement %u) Not completed parent achievement %u (Guild: %u)",
achievementCriteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(achievementCriteria->type), achievement->ID, achievement->parentAchievement, IsGuild<T>() ? 1 : 0);
continue;
}
}
if (IsCompletedCriteriaForAchievement(achievementCriteria, achievement))
CompletedCriteriaFor(achievement, referencePlayer);
// check again the completeness for SUMM and REQ COUNT achievements,
// as they don't depend on the completed criteria but on the sum of the progress of each individual criteria
if (achievement->flags & ACHIEVEMENT_FLAG_SUMM)
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
if (AchievementEntryList const* achRefList = sAchievementMgr->GetAchievementByReferencedId(achievement->ID))
for (AchievementEntryList::const_iterator itr = achRefList->begin(); itr != achRefList->end(); ++itr)
if (IsCompletedAchievement(*itr))
CompletedAchievement(*itr, referencePlayer);
}
}
}
template<class T>
bool AchievementMgr<T>::CanCompleteCriteria(CriteriaEntry const* /*achievementCriteria*/, AchievementEntry const* /*achievement*/)
{
return true;
}
template<>
bool AchievementMgr<Player>::CanCompleteCriteria(CriteriaEntry const* /*achievementCriteria*/, AchievementEntry const* achievement)
{
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
{
// Someone on this realm has already completed that achievement
if (sAchievementMgr->IsRealmCompleted(achievement))
return false;
if (GetOwner())
if (GetOwner()->GetSession())
if (GetOwner()->GetSession()->GetSecurity())
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::IsCompletedCriteria(CriteriaEntry const* criteria)
{
AchievementCriteriaTreeList const& criteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaTreeList.begin(); iter != criteriaTreeList.end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(criteriaTree);
if (!achievement)
return false;
if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->criteriaID))
if (!IsCompletedCriteriaForAchievement(criteria, achievement))
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::IsCompletedCriteriaForAchievement(CriteriaEntry const* criteria, AchievementEntry const* achievement)
{
if (!criteria || !achievement)
return false;
CriteriaTreeEntry const* criteriaTree = NULL;
AchievementCriteriaTreeList const* treeList = sAchievementMgr->GetSubCriteriaTreeById(achievement->criteriaTreeID);
if (treeList)
{
for (AchievementCriteriaTreeList::const_iterator iter = treeList->begin(); iter != treeList->end(); iter++)
{
if ((*iter)->criteriaID == criteria->ID)
{
criteriaTree = *iter;
break;
}
}
}
if (!criteriaTree)
return false;
// counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
{
// someone on this realm has already completed that achievement
if (sAchievementMgr->IsRealmCompleted(achievement))
return false;
}
CriteriaProgress const* progress = GetCriteriaProgress(criteria);
if (!progress)
return false;
switch (AchievementCriteriaTypes(criteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
return progress->counter >= criteriaTree->criteriaCount;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
return progress->counter >= 1;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return progress->counter >= (criteriaTree->criteriaCount * 75);
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return progress->counter >= 9000;
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
return progress->counter >= 2000;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return criteriaTree->criteriaCount && progress->counter >= criteriaTree->criteriaCount;
// handle all statistic-only criteria here
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
default:
return false;
}
return false;
}
template<class T>
void AchievementMgr<T>::CompletedCriteriaFor(AchievementEntry const* achievement, Player* referencePlayer)
{
// Counter can never complete
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER)
return;
// Already completed and stored
if (HasAchieved(achievement->ID))
return;
if (IsCompletedAchievement(achievement))
CompletedAchievement(achievement, referencePlayer);
}
template<class T>
bool AchievementMgr<T>::IsCompletedAchievement(AchievementEntry const* entry)
{
// Counter can never complete
if (entry->flags & ACHIEVEMENT_FLAG_COUNTER)
return false;
// For achievement with referenced achievement criterias get from referenced and counter from self
uint32 achievementForTestId = entry->refAchievement ? entry->refAchievement : entry->ID;
uint32 achievementForTestCount = entry->count;
if (CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID))
achievementForTestCount = criteriaTree->criteriaCount;
AchievementCriteriaEntryList cList;
AchievementCriteriaTreeList const* list = sAchievementMgr->GetSubCriteriaTreeById(entry->criteriaTreeID);
for (AchievementCriteriaTreeList::const_iterator iter = list->begin(); iter != list->end(); iter++)
{
CriteriaTreeEntry const* criteriaTree = *iter;
if (CriteriaEntry const* criteria = sCriteriaStore.LookupEntry(criteriaTree->criteriaID))
cList.push_back(criteria);
}
if (!cList.size())
return false;
uint64 count = 0;
// For SUMM achievements, we have to count the progress of each criteria of the achievement.
// Oddly, the target count is NOT contained in the achievement, but in each individual criteria
if (entry->flags & ACHIEVEMENT_FLAG_SUMM)
{
for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr)
{
CriteriaEntry const* criteria = *itr;
CriteriaProgress const* progress = GetCriteriaProgress(criteria);
if (!progress)
continue;
count += progress->counter;
// For counters, field4 contains the main count requirement
if (count >= sCriteriaTreeStore.LookupEntry(entry->criteriaTreeID)->criteriaCount)
return true;
}
return false;
}
// Default case - need complete all or
bool completed_all = true;
for (AchievementCriteriaEntryList::const_iterator itr = cList.begin(); itr != cList.end(); ++itr)
{
CriteriaEntry const* criteria = *itr;
bool completed = IsCompletedCriteriaForAchievement(criteria, entry);
// Found an uncompleted criteria, but DONT return false yet - there might be a completed criteria with ACHIEVEMENT_CRITERIA_COMPLETE_FLAG_ALL
if (completed)
++count;
else
completed_all = false;
// Completed as have req. count of completed criterias
if (achievementForTestCount > 0 && achievementForTestCount <= count)
return true;
}
// All criterias completed requirement
if (completed_all && achievementForTestCount == 0)
return true;
return false;
}
template<class T>
CriteriaProgress* AchievementMgr<T>::GetCriteriaProgress(uint32 criteriaId)
{
CriteriaProgressMap::iterator iter = m_criteriaProgress.find(criteriaId);
if (iter == m_criteriaProgress.end())
return NULL;
return &(iter->second);
}
template<class T>
void AchievementMgr<T>::SetCriteriaProgress(CriteriaEntry const* entry, uint64 changeValue, Player* referencePlayer, ProgressType ptype)
{
// Don't allow to cheat - doing timed achievements without timer active
TimedAchievementMap::iterator timedIter = m_timedAchievements.find(entry->ID);
if (entry->timeLimit && timedIter == m_timedAchievements.end())
return;
TC_LOG_DEBUG("achievement", "SetCriteriaProgress(%u, " UI64FMTD ") for (%s GUID: %u)",
entry->ID, changeValue, GetLogNameForGuid(GetOwner()->GetGUID()), GUID_LOPART(GetOwner()->GetGUID()));
CriteriaProgress* progress = GetCriteriaProgress(entry);
if (!progress)
{
// Not create record for 0 counter but allow it for timed achievements
// We will need to send 0 progress to client to start the timer
if (changeValue == 0 && !entry->timeLimit)
return;
progress = &m_criteriaProgress[entry->ID];
progress->counter = changeValue;
}
else
{
uint64 newValue = 0;
switch (ptype)
{
case PROGRESS_SET:
newValue = changeValue;
break;
case PROGRESS_ACCUMULATE:
{
// Avoid overflow
uint64 max_value = std::numeric_limits<uint64>::max();
newValue = max_value - progress->counter > changeValue ? progress->counter + changeValue : max_value;
break;
}
case PROGRESS_HIGHEST:
newValue = progress->counter < changeValue ? changeValue : progress->counter;
break;
}
// Not update (not mark as changed) if counter will have same value
if (progress->counter == newValue && !entry->timeLimit && (!IsGuild<T>() || !IsCompletedCriteria(entry) || progress->CompletedGUID))
return;
progress->counter = newValue;
}
progress->changed = true;
progress->date = time(NULL); // Set the date to the latest update.
uint32 timeElapsed = 0;
AchievementCriteriaTreeList criteriaList = sAchievementMgr->GetAchievementCriteriaTreeList(entry);
for (AchievementCriteriaTreeList::const_iterator iter = criteriaList.begin(); iter != criteriaList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
bool criteriaComplete = IsCompletedCriteriaForAchievement(entry, achievement);
if (entry->timeLimit)
{
// Client expects this in packet
timeElapsed = entry->timeLimit - (timedIter->second / IN_MILLISECONDS);
// Remove the timer, we wont need it anymore
if (criteriaComplete)
m_timedAchievements.erase(timedIter);
}
if (criteriaComplete && achievement->flags & ACHIEVEMENT_FLAG_SHOW_CRITERIA_MEMBERS && !progress->CompletedGUID)
progress->CompletedGUID = referencePlayer->GetGUID();
if (achievement->flags & ACHIEVEMENT_FLAG_ACCOUNT)
{
WorldPacket data(SMSG_ACCOUNT_CRITERIA_UPDATE, 4 + 4 + 4 + 4 + 8 + 4);
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter = progress->counter;
data.WriteBitSeq<5>(counter);
data.WriteBits(0, 4);
data.WriteBitSeq<3, 1>(counter);
data.WriteBitSeq<0, 1>(guid);
data.WriteBitSeq<4, 2>(counter);
data.WriteBitSeq<3, 7, 4>(guid);
data.WriteBitSeq<6>(counter);
data.WriteBitSeq<6, 5>(guid);
data.WriteBitSeq<0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<7>(counter);
data.FlushBits();
data.WriteByteSeq<5, 6>(guid);
data.WriteByteSeq<6>(counter);
data.WriteByteSeq<1>(guid);
data << uint32(timeElapsed);
data.WriteByteSeq<2>(counter);
data << uint32(entry->ID);
data.WriteByteSeq<2, 0>(guid);
data.WriteByteSeq<0, 5>(counter);
data.AppendPackedTime(progress->date);
data.WriteByteSeq<4>(counter);
data.WriteByteSeq<3, 7>(guid);
data << uint32(timeElapsed);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<7, 3, 1>(counter);
SendPacket(&data);
return;
}
}
SendCriteriaUpdate(entry, progress, timeElapsed, false);
}
template<class T>
void AchievementMgr<T>::UpdateTimedAchievements(uint32 timeDiff)
{
if (!m_timedAchievements.empty())
{
for (TimedAchievementMap::iterator itr = m_timedAchievements.begin(); itr != m_timedAchievements.end();)
{
// Time is up, remove timer and reset progress
if (itr->second <= timeDiff)
{
CriteriaEntry const* entry = sAchievementMgr->GetAchievementCriteria(itr->first);
RemoveCriteriaProgress(entry);
m_timedAchievements.erase(itr++);
}
else
{
itr->second -= timeDiff;
++itr;
}
}
}
}
template<class T>
void AchievementMgr<T>::StartTimedAchievement(AchievementCriteriaTimedTypes /*type*/, uint32 /*entry*/, uint32 /*timeLost = 0*/)
{
}
template<>
void AchievementMgr<Player>::StartTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry, uint32 timeLost /* = 0 */)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entry);
if (m_timedAchievements.find((*i)->ID) == m_timedAchievements.end() && !IsCompletedCriteriaForAchievement(*i, achievement))
{
// Start the timer
if ((*i)->timeLimit * IN_MILLISECONDS > timeLost)
{
m_timedAchievements[(*i)->ID] = (*i)->timeLimit * IN_MILLISECONDS - timeLost;
// And at client too
SetCriteriaProgress(*i, 0, GetOwner(), PROGRESS_SET);
}
}
}
}
template<class T>
void AchievementMgr<T>::RemoveTimedAchievement(AchievementCriteriaTimedTypes type, uint32 entry)
{
AchievementCriteriaEntryList const& achievementCriteriaList = sAchievementMgr->GetTimedAchievementCriteriaByType(type);
for (AchievementCriteriaEntryList::const_iterator i = achievementCriteriaList.begin(); i != achievementCriteriaList.end(); ++i)
{
if ((*i)->timedCriteriaMiscId != entry)
continue;
TimedAchievementMap::iterator timedIter = m_timedAchievements.find((*i)->ID);
// We don't have timer for this achievement
if (timedIter == m_timedAchievements.end())
continue;
// Remove progress
RemoveCriteriaProgress(*i);
// Remove the timer
m_timedAchievements.erase(timedIter);
}
}
template<class T>
void AchievementMgr<T>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
// Disable for gamemasters with GM-mode enabled
if (GetOwner()->isGameMaster())
return;
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
/*if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = sGuildMgr->GetGuildById(referencePlayer->GetGuildId()))
guild->GetNewsLog().AddNewEvent(GUILD_NEWS_PLAYER_ACHIEVEMENT, time(NULL), referencePlayer->GetGUID(), achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);*/
if (HasAccountAchieved(achievement->ID))
{
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.completedByThisCharacter = true;
return;
}
if (!GetOwner()->GetSession()->PlayerLoading())
SendAchievementEarned(achievement);
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.completedByThisCharacter = true;
ca.date = time(NULL);
ca.first_guid = GetOwner()->GetGUIDLow();
ca.changed = true;
// Don't insert for ACHIEVEMENT_FLAG_REALM_FIRST_KILL since otherwise only the first group member would reach that achievement
// @TODO: where do set this instead?
if (!(achievement->flags & ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
// Reward items and titles if any
AchievementReward const* reward = sAchievementMgr->GetAchievementReward(achievement);
// No rewards
if (!reward)
return;
// Titles
//! Currently there's only one achievement that deals with gender-specific titles.
//! Since no common attributes were found, (not even in titleRewardFlags field)
//! we explicitly check by ID. Maybe in the future we could move the achievement_reward
//! condition fields to the condition system.
if (uint32 titleId = reward->titleId[achievement->ID == 1793 ? GetOwner()->getGender() : (GetOwner()->GetTeam() == ALLIANCE ? 0 : 1)])
if (CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(titleId))
GetOwner()->SetTitle(titleEntry);
// Mail
if (reward->sender)
{
Item* item = reward->itemId ? Item::CreateItem(reward->itemId, 1, GetOwner()) : NULL;
int loc_idx = GetOwner()->GetSession()->GetSessionDbLocaleIndex();
// Subject and text
std::string subject = reward->subject;
std::string text = reward->text;
if (loc_idx >= 0)
{
if (AchievementRewardLocale const* loc = sAchievementMgr->GetAchievementRewardLocale(achievement))
{
ObjectMgr::GetLocaleString(loc->subject, loc_idx, subject);
ObjectMgr::GetLocaleString(loc->text, loc_idx, text);
}
}
MailDraft draft(subject, text);
SQLTransaction trans = CharacterDatabase.BeginTransaction();
if (item)
{
item->SetOwnerGUID(0);
// Save new item before send
item->SaveToDB(trans); // Save for prevent lost at next mail load, if send fail then item will deleted
// Item
draft.AddItem(item);
}
draft.SendMailTo(trans, GetOwner(), MailSender(MAIL_CREATURE, reward->sender));
CharacterDatabase.CommitTransaction(trans);
}
}
template<>
void AchievementMgr<Guild>::CompletedAchievement(AchievementEntry const* achievement, Player* referencePlayer)
{
if (achievement->flags & ACHIEVEMENT_FLAG_COUNTER || HasAchieved(achievement->ID))
return;
/*if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_NEWS)
if (Guild* guild = sGuildMgr->GetGuildById(referencePlayer->GetGuildId()))
guild->GetNewsLog().AddNewEvent(GUILD_NEWS_GUILD_ACHIEVEMENT, time(NULL), 0, achievement->flags & ACHIEVEMENT_FLAG_SHOW_IN_GUILD_HEADER, achievement->ID);*/
SendAchievementEarned(achievement);
CompletedAchievementData& ca = m_completedAchievements[achievement->ID];
ca.date = time(NULL);
ca.changed = true;
if (achievement->flags & ACHIEVEMENT_FLAG_SHOW_GUILD_MEMBERS)
{
if (referencePlayer->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(referencePlayer->GetGUID());
if (Group const* group = referencePlayer->GetGroup())
for (GroupReference const* ref = group->GetFirstMember(); ref != NULL; ref = ref->next())
if (Player const* groupMember = ref->GetSource())
if (groupMember->GetGuildId() == GetOwner()->GetId())
ca.guids.insert(groupMember->GetGUID());
}
sAchievementMgr->SetRealmCompleted(achievement);
_achievementPoints += achievement->points;
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT, 0, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS, achievement->points, 0, 0, NULL, referencePlayer);
}
struct VisibleAchievementPred final
{
bool operator()(CompletedAchievementMap::value_type const& val) const
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(val.first);
return achievement && !(achievement->flags & ACHIEVEMENT_FLAG_HIDDEN);
}
};
template<class T>
void AchievementMgr<T>::SendAllAchievementData(Player* /*receiver*/)
{
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
VisibleAchievementPred isVisible;
size_t numCriteria = progressMap.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
WorldPacket data(SMSG_ALL_ACHIEVEMENT_DATA);
data.WriteBits(numAchievements, 20);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstAccountGuid = kvPair.second.first_guid;
data.WriteBitSeq<6, 1, 5, 3, 2, 7, 0, 4>(firstAccountGuid);
}
data.WriteBits(numCriteria, 19);
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data.WriteBitSeq<5>(counter);
data.WriteBitSeq<2, 4>(guid);
data.WriteBitSeq<1, 7>(counter);
data.WriteBitSeq<0, 1>(guid);
data.WriteBitSeq<3>(counter);
data.WriteBitSeq<5>(guid);
data.WriteBits(0, 4);
data.WriteBitSeq<0, 6, 4>(counter);
data.WriteBitSeq<7, 3, 6>(guid);
data.WriteBitSeq<2>(counter);
}
data.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data.WriteByteSeq<1>(guid);
data << uint32(kvPair.first); // Criteria id
data.WriteByteSeq<7>(guid);
data.WriteByteSeq<5>(counter);
data << uint32(0); // Unk value from 5.4.0, always 0
data.WriteByteSeq<6>(guid);
data.WriteByteSeq<0>(counter);
data << uint32(227545947); // Unk value from 5.4.0, always 227545947
data.WriteByteSeq<2>(guid);
data.WriteByteSeq<2, 1>(counter);
data << uint32(0); // Unk value from 5.4.0, always 0
data.WriteByteSeq<3, 5>(guid);
data.WriteByteSeq<3>(counter);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<4, 7, 6>(counter);
data.WriteByteSeq<0>(guid);
}
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid firstAccountGuid = kvPair.second.first_guid;
data.WriteByteSeq<4, 6, 3, 0>(firstAccountGuid);
data << uint32(realmID); // Unk timer from 5.4.0 17399, sometimes 50724907
data.WriteByteSeq<1, 2>(firstAccountGuid);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<7, 5>(firstAccountGuid);
data << uint32(realmID); // Unk timer from 5.4.0 17399, sometimes 50724907
data << uint32(kvPair.first);
}
SendPacket(&data);
WorldPacket data2(SMSG_ACCOUNT_CRITERIA_UPDATE_ALL);
ObjectGuid acc = GetOwner()->GetSession()->GetAccountId();
data2.WriteBits(numCriteria, 19);
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data2.WriteBitSeq<6, 3>(counter);
data2.WriteBitSeq<6, 1, 2, 3>(acc);
data2.WriteBits(0, 4);
data2.WriteBitSeq<5, 0, 7>(acc);
data2.WriteBitSeq<0, 7, 5>(counter);
data2.WriteBitSeq<4>(acc);
data2.WriteBitSeq<1, 4, 2>(counter);
}
data2.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = uint64(kvPair.second.counter);
data2.WriteByteSeq<1>(acc);
data2 << uint32(0);
data2.WriteByteSeq<2>(acc);
data2.WriteByteSeq<6>(counter);
data2.WriteByteSeq<4>(acc);
data2.WriteByteSeq<7>(counter);
data2.WriteByteSeq<6, 7>(acc);
data2 << uint32(0);
data2.WriteByteSeq<5>(counter);
data2.WriteByteSeq<5>(acc);
data2.WriteByteSeq<2>(counter);
data2 << uint32(227545947);
data2 << uint32(kvPair.first);
data2.WriteByteSeq<0>(counter);
data2.WriteByteSeq<3>(acc);
data2.WriteByteSeq<1>(counter);
data2.WriteByteSeq<0>(acc);
data2.WriteByteSeq<4, 3>(counter);
}
SendPacket(&data2);
}
template<>
void AchievementMgr<Guild>::SendAllAchievementData(Player* receiver)
{
WorldPacket data(SMSG_GUILD_ACHIEVEMENT_DATA, m_completedAchievements.size() * (4 + 4) + 3);
data.WriteBits(m_completedAchievements.size(), 20);
ObjectGuid achievementee;
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
data.WriteBit(0);
}
data.FlushBits();
for (CompletedAchievementMap::const_iterator itr = m_completedAchievements.begin(); itr != m_completedAchievements.end(); ++itr)
{
data.WriteByte(0);
data << uint32(itr->first);
data << uint32(0); //0 or time ?
data.WriteByte(0);
data.WriteByte(0);
data.WriteByte(0);
data.WriteByte(0);
data << uint32(0);
data.WriteByte(0);
data.WriteByte(0);
data.AppendPackedTime(itr->second.date);
data.WriteByte(0);
}
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Player>::SendAchievementInfo(Player* receiver, uint32 /*achievementId = 0 */)
{
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
ObjectGuid guid = GetOwner()->GetGUID();
ObjectGuid counter;
VisibleAchievementPred isVisible;
size_t numCriteria = progressMap.size();
size_t numAchievements = std::count_if(m_completedAchievements.begin(), m_completedAchievements.end(), isVisible);
WorldPacket data(SMSG_RESPOND_INSPECT_ACHIEVEMENTS);
data.WriteBits(numCriteria, 19);
data.WriteBits(numAchievements, 20);
for (auto const &kvPair : progressMap)
{
counter = kvPair.second.counter;
data.WriteBitSeq<4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<4, 5, 1, 0>(counter);
data.WriteBitSeq<5>(guid);
data.WriteBitSeq<6, 3>(counter);
data.WriteBits(1, 4); // Criteria progress flags
data.WriteBitSeq<1, 7, 2, 3>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6>(guid);
}
data.WriteBitSeq<6, 2>(guid);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstGuid = kvPair.second.first_guid;
data.WriteBitSeq<2, 3, 7, 5, 4, 6, 0, 1>(firstGuid);
}
data.WriteBitSeq<4, 7, 3, 0, 5, 1>(guid);
data.FlushBits();
for (auto const &kvPair : progressMap)
{
counter = kvPair.second.counter;
data.WriteByteSeq<5>(counter);
data.WriteByteSeq<0, 1>(guid);
data.WriteByteSeq<6>(counter);
data.WriteByteSeq<4>(guid);
data.WriteByteSeq<7, 0, 1>(counter);
data << uint32(0);
data.WriteByteSeq<4, 3>(counter);
data << uint32(kvPair.first); // criteria id
data << uint32(secsToTimeBitFields(kvPair.second.date));
data << uint32(227545947);
data.WriteByteSeq<2, 5, 6>(guid);
data.WriteByteSeq<2>(counter);
data.WriteByteSeq<7, 3>(guid);
}
data.WriteByteSeq<5, 3>(guid);
for (auto const &kvPair : m_completedAchievements)
{
if (!isVisible(kvPair))
continue;
ObjectGuid const firstGuid = kvPair.second.first_guid;
data.WriteByteSeq<0, 7, 6>(firstGuid);
data << uint32(0);
data << uint32(kvPair.first);
data << uint32(50397223);
data << uint32(secsToTimeBitFields(kvPair.second.date));
data.WriteByteSeq<4, 5, 1, 3, 2>(firstGuid);
}
data.WriteByteSeq<6, 7, 2, 1, 4, 0>(guid);
receiver->GetSession()->SendPacket(&data);
}
template<>
void AchievementMgr<Guild>::SendAchievementInfo(Player* receiver, uint32 achievementId /*= 0*/)
{
// Will send response to criteria progress request
AchievementCriteriaEntryList const* criteria = sAchievementMgr->GetAchievementCriteriaByAchievement(achievementId);
if (!criteria)
{
// Send empty packet
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3);
data.WriteBits(0, 19);
data.FlushBits();
receiver->SendDirectMessage(&data);
return;
}
ObjectGuid counter, guid;
ByteBuffer criteriaData;
CriteriaProgressMap const &progressMap = GetCriteriaProgressMap();
WorldPacket data(SMSG_GUILD_CRITERIA_DATA, 3 + (2 + 8 + 5 * 4) * progressMap.size());
data.WriteBits(progressMap.size(), 19);
for (auto const &kvPair : progressMap)
{
auto const &criteriaId = kvPair.first;
auto const &progressData = kvPair.second;
counter = progressData.counter;
guid = progressData.CompletedGUID;
data.WriteBitSeq<3, 6>(counter);
data.WriteBitSeq<5, 4>(guid);
data.WriteBitSeq<2>(counter);
data.WriteBitSeq<0>(guid);
data.WriteBitSeq<7>(counter);
data.WriteBitSeq<6, 7, 3>(guid);
data.WriteBitSeq<5, 0>(counter);
data.WriteBitSeq<2>(guid);
data.WriteBitSeq<1, 4>(counter);
data.WriteBitSeq<1>(guid);
criteriaData.WriteByteSeq<4>(guid);
criteriaData << uint32(progressData.date); // Unknown date
criteriaData.WriteByteSeq<2, 0>(counter);
criteriaData << uint32(progressData.changed);
criteriaData.WriteByteSeq<7, 1>(guid);
criteriaData << uint32(criteriaId);
criteriaData << uint32(progressData.date); // Last update time (not packed!)
criteriaData.WriteByteSeq<6>(guid);
criteriaData.WriteByteSeq<1>(counter);
criteriaData.WriteByteSeq<3>(guid);
criteriaData.WriteByteSeq<4>(counter);
criteriaData << uint32(progressData.date); // Unknown date
criteriaData.WriteByteSeq<5, 3>(counter);
criteriaData.WriteByteSeq<0>(guid);
criteriaData.WriteByteSeq<6, 7>(counter);
criteriaData.WriteByteSeq<2, 5>(guid);
}
data.FlushBits();
data.append(criteriaData);
receiver->SendDirectMessage(&data);
}
template<class T>
bool AchievementMgr<T>::HasAchieved(uint32 achievementId) const
{
return m_completedAchievements.find(achievementId) != m_completedAchievements.end();
}
template<>
bool AchievementMgr<Player>::HasAchieved(uint32 achievementId) const
{
CompletedAchievementMap::const_iterator itr = m_completedAchievements.find(achievementId);
if (itr == m_completedAchievements.end())
return false;
return (*itr).second.completedByThisCharacter;
}
template<class T>
bool AchievementMgr<T>::HasAccountAchieved(uint32 achievementId) const
{
return m_completedAchievements.find(achievementId) != m_completedAchievements.end();
}
template<class T>
uint64 AchievementMgr<T>::GetFirstAchievedCharacterOnAccount(uint32 achievementId) const
{
CompletedAchievementMap::const_iterator itr = m_completedAchievements.find(achievementId);
if (itr == m_completedAchievements.end())
return 0LL;
return (*itr).second.first_guid;
}
template<class T>
bool AchievementMgr<T>::CanUpdateCriteria(CriteriaEntry const* criteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const* unit, Player* referencePlayer)
{
if (DisableMgr::IsDisabledFor(DISABLE_TYPE_ACHIEVEMENT_CRITERIA, criteria->ID, NULL))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Disabled",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (IsCompletedCriteria(criteria))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Is Completed",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!RequirementsSatisfied(criteria, miscValue1, miscValue2, miscValue3, unit, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Requirements not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!AdditionalRequirementsSatisfied(criteria, miscValue1, miscValue2, unit, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Additional requirements not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
if (!ConditionsSatisfied(criteria, referencePlayer))
{
TC_LOG_TRACE("achievement", "CanUpdateCriteria: (Id: %u Type %s) Conditions not satisfied",
criteria->ID, AchievementGlobalMgr::GetCriteriaTypeString(criteria->type));
return false;
}
return true;
}
template<class T>
bool AchievementMgr<T>::ConditionsSatisfied(CriteriaEntry const *criteria, Player* referencePlayer) const
{
/*
for (uint32 i = 0; i < MAX_CRITERIA_REQUIREMENTS; ++i)
{
if (!criteria->additionalRequirements[i].additionalRequirement_type)
continue;
switch (criteria->additionalRequirements[i].additionalRequirement_type)
{
case ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP:
if (referencePlayer->GetMapId() != criteria->additionalRequirements[i].additionalRequirement_value)
return false;
break;
case ACHIEVEMENT_CRITERIA_CONDITION_NOT_IN_GROUP:
if (referencePlayer->GetGroup())
return false;
break;
case ACHIEVEMENT_CRITERIA_CONDITION_SERVER_SIDE_CHECK:
// FIXME: return criteria->scriptId != 0;
default:
break;
}
}
*/
return true;
}
template<class T>
bool AchievementMgr<T>::RequirementsSatisfied(CriteriaEntry const *achievementCriteria, uint64 miscValue1, uint64 miscValue2, uint64 miscValue3, Unit const *unit, Player* referencePlayer) const
{
switch (AchievementCriteriaTypes(achievementCriteria->type))
{
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
if (!miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
if (m_completedAchievements.find(achievementCriteria->complete_achievement.linkedAchievement) == m_completedAchievements.end())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
if (!miscValue1 || !referencePlayer || achievementCriteria->win_bg.bgMapID != referencePlayer->GetMapId())
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
if (!miscValue1 || achievementCriteria->kill_creature.creatureID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->reach_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
// update at loading or specific skill update
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_level.skillID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
if (miscValue1 && miscValue1 != achievementCriteria->complete_quests_in_zone.zoneID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
if (!miscValue1 || !referencePlayer || referencePlayer->GetMapId() != achievementCriteria->complete_battleground.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
if (!miscValue1 || !referencePlayer ||referencePlayer->GetMapId() != achievementCriteria->death_at_map.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
{
if (!miscValue1)
return false;
/*if (!referencePlayer)
return false;
// skip wrong arena achievements, if not achievIdByArenaSlot then normal total death counter
bool notfit = false;
for (int j = 0; j < MAX_ARENA_SLOT; ++j)
{
if (achievIdByArenaSlot[j] == achievementCriteria->achievement)
{
Battleground* bg = referencePlayer->GetBattleground();
if (!bg || !bg->isArena() || Arena::GetSlotByType(bg->GetArenaType()) != j)
notfit = true;
break;
}
}
if (notfit)
return false;*/
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
{
if (!miscValue1)
return false;
/*
if (!referencePlayer)
return false;
Map const* map = referencePlayer->IsInWorld() ? referencePlayer->GetMap() : sMapMgr->FindMap(referencePlayer->GetMapId(), referencePlayer->GetInstanceId());
if (!map || !map->IsDungeon())
return false;
// search case
bool found = false;
for (int j = 0; achievIdForDungeon[j][0]; ++j)
{
if (achievIdForDungeon[j][0] == achievementCriteria->achievement)
{
if (map->IsRaid())
{
// if raid accepted (ignore difficulty)
if (!achievIdForDungeon[j][2])
break; // for
}
else if (referencePlayer->GetDungeonDifficulty() == REGULAR_DIFFICULTY)
{
// dungeon in normal mode accepted
if (!achievIdForDungeon[j][1])
break; // for
}
else
{
// dungeon in heroic mode accepted
if (!achievIdForDungeon[j][3])
break; // for
}
found = true;
break; // for
}
}
if (!found)
return false;
//FIXME: work only for instances where max == min for players
if (((InstanceMap*)map)->GetMaxPlayers() != achievementCriteria->death_in_dungeon.manLimit)
return false;*/
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
if (!miscValue1 || miscValue1 != achievementCriteria->killed_by_creature.creatureEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
if (!miscValue1 || !unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
if (!miscValue1 || miscValue2 != achievementCriteria->death_from.type)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
{
// if miscValues != 0, it contains the questID.
if (miscValue1)
{
if (miscValue1 != achievementCriteria->complete_quest.questID)
return false;
}
else
{
// login case.
if (!referencePlayer || !referencePlayer->GetQuestRewardStatus(achievementCriteria->complete_quest.questID))
return false;
}
if (AchievementCriteriaDataSet const* data = sAchievementMgr->GetCriteriaDataSet(achievementCriteria))
if (!data->Meets(referencePlayer, unit))
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
if (!miscValue1 || miscValue1 != achievementCriteria->be_spell_target.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
if (!miscValue1 || miscValue1 != achievementCriteria->cast_spell.spellID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
if (miscValue1 && miscValue1 != achievementCriteria->learn_spell.spellID)
return false;
if (!referencePlayer || !referencePlayer->HasSpell(achievementCriteria->learn_spell.spellID))
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
// miscValue1 = itemId - miscValue2 = count of item loot
// miscValue3 = loot_type (note: 0 = LOOT_CORPSE and then it ignored)
if (!miscValue1 || !miscValue2 || !miscValue3 || miscValue3 != achievementCriteria->loot_type.lootType)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
if (miscValue1 && achievementCriteria->own_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
if (!miscValue1 || achievementCriteria->use_item.itemID != miscValue1)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
if (!miscValue1 || miscValue1 != achievementCriteria->own_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
{
if (!referencePlayer)
return false;
WorldMapOverlayEntry const* worldOverlayEntry = sWorldMapOverlayStore.LookupEntry(achievementCriteria->explore_area.areaReference);
if (!worldOverlayEntry)
break;
bool matchFound = false;
for (int j = 0; j < MAX_WORLD_MAP_OVERLAY_AREA_IDX; ++j)
{
uint32 area_id = worldOverlayEntry->areatableID[j];
if (!area_id) // array have 0 only in empty tail
break;
int32 exploreFlag = GetAreaFlagByAreaID(area_id);
// Hack: Explore Southern Barrens
if (achievementCriteria->explore_area.areaReference == 3009)
exploreFlag = 515;
if (exploreFlag < 0)
continue;
uint32 playerIndexOffset = uint32(exploreFlag) / 32;
uint32 mask = 1 << (uint32(exploreFlag) % 32);
if (referencePlayer->GetUInt32Value(PLAYER_EXPLORED_ZONES_1 + playerIndexOffset) & mask)
{
matchFound = true;
break;
}
}
if (!matchFound)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
if (miscValue1 && miscValue1 != achievementCriteria->gain_reputation.factionID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
// miscValue1 = itemid miscValue2 = itemSlot
if (!miscValue1 || miscValue2 != achievementCriteria->equip_epic_item.itemSlot)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
{
// miscValue1 = itemid miscValue2 = diced value
if (!miscValue1 || miscValue2 != achievementCriteria->roll_greed_on_loot.rollValue)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
if (!miscValue1 || miscValue1 != achievementCriteria->do_emote.emoteID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
if (!miscValue1)
return false;
/*if (!referencePlayer)
return false;
if (achievementCriteria->additionalRequirements[0].additionalRequirement_type == ACHIEVEMENT_CRITERIA_CONDITION_BG_MAP)
{
if (referencePlayer->GetMapId() != achievementCriteria->additionalRequirements[0].additionalRequirement_value)
return false;
*/
// map specific case (BG in fact) expected player targeted damage/heal
if (!unit || unit->GetTypeId() != TYPEID_PLAYER)
return false;
//}
break;
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
// miscValue1 = item_id
if (!miscValue1 || miscValue1 != achievementCriteria->equip_item.itemID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->use_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
if (!miscValue1 || miscValue1 != achievementCriteria->fish_in_gameobject.goEntry)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skillline_spell.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
{
if (!miscValue1)
return false;
ItemTemplate const* proto = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!proto)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
if (miscValue1 && miscValue1 != achievementCriteria->learn_skill_line.skillLine)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_class.classID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
if (!miscValue1 || miscValue1 != achievementCriteria->hk_race.raceID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
if (!miscValue1 || miscValue1 != achievementCriteria->bg_objective.objectiveId)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
if (!miscValue1 || miscValue1 != achievementCriteria->honorable_kill_at_area.areaID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
if (!miscValue1 || !miscValue2 || int64(miscValue2) < 0
|| miscValue1 != achievementCriteria->currencyGain.currency)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
if (miscValue1 != achievementCriteria->win_arena.mapID)
return false;
break;
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
//if (miscValue1 != achievementCriteria->guild_challenge_complete_type.challenge_type)
// return false;
break;
default:
break;
}
return true;
}
template<class T>
bool AchievementMgr<T>::AdditionalRequirementsSatisfied(CriteriaEntry const *criteria, uint64 miscValue1, uint64 /*miscValue2*/, Unit const* unit, Player* referencePlayer) const
{
ModifierTreeEntry const* condition = sModifierTreeStore.LookupEntry(criteria->modifierTreeId);
if (!condition)
return true;
ModifierTreeEntryList const* list = sAchievementMgr->GetModifierTreeByModifierId(condition->ID);
if (!list)
return true;
for (ModifierTreeEntryList::const_iterator iter = list->begin(); iter != list->end(); iter++)
{
ModifierTreeEntry const* tree = (*iter);
uint32 reqType = tree->conditionType;
uint32 reqValue = tree->conditionValue[0];
switch (AchievementCriteriaAdditionalCondition(reqType))
{
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_DRUNK_VALUE: // 1
{
if (!referencePlayer || (referencePlayer->GetDrunkValue() < reqValue))
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SERVER_SIDE_CHECK:
{
#if 0
if (!referencePlayer)
return criteria->scriptId != 0;
#endif
switch (reqValue)
{
case 924: // Alliance faction
case 11835: // Alliance faction
return referencePlayer->GetTeam() == ALLIANCE;
case 923: // Horde faction
case 11836: // Horde faction
return referencePlayer->GetTeam() == HORDE;
#if 0
default:
return criteria->scriptId != 0;
#endif
}
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_LEVEL: // 3
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->ItemLevel < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_ENTRY: // 4
if (!unit || unit->GetEntry() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_PLAYER: // 5
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_DEAD: // 6
if (!unit || !unit->IsInWorld() || unit->IsAlive())
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_MUST_BE_ENEMY: // 7
if (!referencePlayer)
return false;
if (!unit || !unit->IsInWorld() || !referencePlayer->IsHostileTo(unit))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_HAS_AURA: // 8
if (!referencePlayer->HasAura(reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA: // 10
if (!unit || !unit->HasAura(reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HAS_AURA_TYPE: // 11
if (!unit || !unit->HasAuraType(AuraType(reqValue)))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_MIN: // 14
{
// miscValue1 is itemid
ItemTemplate const * const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_QUALITY_EQUALS: // 15
{
// miscValue1 is itemid
ItemTemplate const * const item = sObjectMgr->GetItemTemplate(uint32(miscValue1));
if (!item || item->Quality < reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_AREA_OR_ZONE: // 17
{
if (!referencePlayer)
return false;
uint32 zoneId, areaId;
referencePlayer->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_AREA_OR_ZONE: // 18
{
if (!unit)
return false;
uint32 zoneId, areaId;
unit->GetZoneAndAreaId(zoneId, areaId);
if (zoneId != reqValue && areaId != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAP_DIFFICULTY: // 20
{
if (!referencePlayer)
return false;
if (Map* pMap = referencePlayer->GetMap())
{
if (pMap->IsNonRaidDungeon()
|| pMap->IsRaid())
{
if (pMap->GetDifficulty() < Difficulty(reqValue))
return false;
}
else
return false;
}
else
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_YIELDS_XP: // 21
if (!unit || unit->GetTypeId() != TYPEID_UNIT || !referencePlayer || !referencePlayer->isHonorOrXPTarget(unit))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ARENA_TYPE: // 24
{
if (!referencePlayer)
return false;
Battleground const * const bg = referencePlayer->GetBattleground();
if (!bg || !bg->isArena() || bg->GetArenaType() != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_RACE: // 25
if (!referencePlayer || (referencePlayer->getRace() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_CLASS: // 26
if (!referencePlayer || (referencePlayer->getClass() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_RACE: // 27
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER || unit->getRace() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CLASS: // 28
if (!unit || !unit->IsInWorld() || unit->GetTypeId() != TYPEID_PLAYER || unit->getClass() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MAX_GROUP_MEMBERS: // 29
if (!referencePlayer || (referencePlayer->GetGroup() && referencePlayer->GetGroup()->GetMembersCount() >= reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_CREATURE_TYPE: // 30
{
if (!unit)
return false;
Creature const * const creature = unit->ToCreature();
if (!creature || creature->GetCreatureType() != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_MAP: // 32
if (!referencePlayer || (referencePlayer->GetMapId() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_CLASS: // 33
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->Class != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_ITEM_SUBCLASS: // 34
{
ItemTemplate const* pItem = sObjectMgr->GetItemTemplate(miscValue1);
if (!pItem)
return false;
if (pItem->SubClass != reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_COMPLETE_QUEST_NOT_IN_GROUP: // 35
// miscValue is questid
if (!referencePlayer || !referencePlayer->IsQuestRewarded(uint32(miscValue1)) || referencePlayer->GetGroup())
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_PERSONAL_RATING: // 37
{
if (miscValue1 <= reqValue)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TITLE_BIT_INDEX: // 38
// miscValue1 is title's bit index
if (miscValue1 != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_LEVEL: // 39
if (!referencePlayer || (referencePlayer->getLevel() != reqValue))
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_LEVEL: // 40
if (!unit || !unit->IsInWorld() || unit->getLevel() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_SOURCE_ZONE: // 41
if (!referencePlayer || referencePlayer->GetZoneId() != reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_TARGET_HEALTH_PERCENT_BELOW: // 46
if (!unit || !unit->IsInWorld() || unit->GetHealthPct() >= reqValue)
return false;
break;
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_MIN_ACHIEVEMENT_POINTS: // 56
if (!referencePlayer || (referencePlayer->GetAchievementMgr().GetAchievementPoints() < reqValue))
return false;
break;
#if 0
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_LFG_GROUP: // 58
if (!referencePlayer || !referencePlayer->inRandomLfgDungeon())
return false;
break;
#endif
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_REQUIRES_GUILD_GROUP: // 61
{
if (!referencePlayer)
return false;
Group* pGroup = referencePlayer->GetGroup();
if (!pGroup)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_GUILD_REPUTATION: // 62
{
if (!referencePlayer)
return false;
if (uint32(referencePlayer->GetReputationMgr().GetReputation(1168)) < reqValue) // 1168 = Guild faction
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_RATED_BATTLEGROUND: // 63
{
if (!referencePlayer)
return false;
Battleground const * const bg = referencePlayer->GetBattleground();
if (!bg || !bg->isRated())
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RARITY: // 65
{
if (!miscValue1)
return false;
break;
}
case ACHIEVEMENT_CRITERIA_ADDITIONAL_CONDITION_PROJECT_RACE: // 66
{
if (!miscValue1)
return false;
break;
}
default:
break;
}
}
return true;
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(uint32 type)
{
return GetCriteriaTypeString(AchievementCriteriaTypes(type));
}
char const* AchievementGlobalMgr::GetCriteriaTypeString(AchievementCriteriaTypes type)
{
switch (type)
{
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE:
return "KILL_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_BG:
return "TYPE_WIN_BG";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ARCHAEOLOGY_PROJECTS:
return "COMPLETE_RESEARCH";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_LEVEL:
return "REACH_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_SKILL_LEVEL:
return "REACH_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_ACHIEVEMENT:
return "COMPLETE_ACHIEVEMENT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST_COUNT:
return "COMPLETE_QUEST_COUNT";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST_DAILY:
return "COMPLETE_DAILY_QUEST_DAILY";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_IN_ZONE:
return "COMPLETE_QUESTS_IN_ZONE";
case ACHIEVEMENT_CRITERIA_TYPE_CURRENCY:
return "CURRENCY";
case ACHIEVEMENT_CRITERIA_TYPE_DAMAGE_DONE:
return "DAMAGE_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_DAILY_QUEST:
return "COMPLETE_DAILY_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_BATTLEGROUND:
return "COMPLETE_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_AT_MAP:
return "DEATH_AT_MAP";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH:
return "DEATH";
case ACHIEVEMENT_CRITERIA_TYPE_DEATH_IN_DUNGEON:
return "DEATH_IN_DUNGEON";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_RAID:
return "COMPLETE_RAID";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_CREATURE:
return "KILLED_BY_CREATURE";
case ACHIEVEMENT_CRITERIA_TYPE_KILLED_BY_PLAYER:
return "KILLED_BY_PLAYER";
case ACHIEVEMENT_CRITERIA_TYPE_FALL_WITHOUT_DYING:
return "FALL_WITHOUT_DYING";
case ACHIEVEMENT_CRITERIA_TYPE_DEATHS_FROM:
return "DEATHS_FROM";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUEST:
return "COMPLETE_QUEST";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET:
return "BE_SPELL_TARGET";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL:
return "CAST_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_BG_OBJECTIVE_CAPTURE:
return "BG_OBJECTIVE_CAPTURE";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL_AT_AREA:
return "HONORABLE_KILL_AT_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_ARENA:
return "WIN_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_PLAY_ARENA:
return "PLAY_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SPELL:
return "LEARN_SPELL";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILL:
return "HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_ITEM:
return "OWN_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_ARENA:
return "WIN_RATED_ARENA";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_TEAM_RATING:
return "HIGHEST_TEAM_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_PERSONAL_RATING:
return "HIGHEST_PERSONAL_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LEVEL:
return "LEARN_SKILL_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_USE_ITEM:
return "USE_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_ITEM:
return "LOOT_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_EXPLORE_AREA:
return "EXPLORE_AREA";
case ACHIEVEMENT_CRITERIA_TYPE_OWN_RANK:
return "OWN_RANK";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT:
return "BUY_BANK_SLOT";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REPUTATION:
return "GAIN_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_EXALTED_REPUTATION:
return "GAIN_EXALTED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_VISIT_BARBER_SHOP:
return "VISIT_BARBER_SHOP";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_EPIC_ITEM:
return "EQUIP_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED_ON_LOOT:
return "ROLL_NEED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED_ON_LOOT:
return "GREED_ON_LOOT";
case ACHIEVEMENT_CRITERIA_TYPE_HK_CLASS:
return "HK_CLASS";
case ACHIEVEMENT_CRITERIA_TYPE_HK_RACE:
return "HK_RACE";
case ACHIEVEMENT_CRITERIA_TYPE_DO_EMOTE:
return "DO_EMOTE";
case ACHIEVEMENT_CRITERIA_TYPE_HEALING_DONE:
return "HEALING_DONE";
case ACHIEVEMENT_CRITERIA_TYPE_GET_KILLING_BLOWS:
return "GET_KILLING_BLOWS";
case ACHIEVEMENT_CRITERIA_TYPE_EQUIP_ITEM:
return "EQUIP_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS:
return "MONEY_FROM_VENDORS";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TALENTS:
return "GOLD_SPENT_FOR_TALENTS";
case ACHIEVEMENT_CRITERIA_TYPE_NUMBER_OF_TALENT_RESETS:
return "NUMBER_OF_TALENT_RESETS";
case ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_QUEST_REWARD:
return "MONEY_FROM_QUEST_REWARD";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_TRAVELLING:
return "GOLD_SPENT_FOR_TRAVELLING";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_AT_BARBER:
return "GOLD_SPENT_AT_BARBER";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_SPENT_FOR_MAIL:
return "GOLD_SPENT_FOR_MAIL";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_MONEY:
return "LOOT_MONEY";
case ACHIEVEMENT_CRITERIA_TYPE_USE_GAMEOBJECT:
return "USE_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_BE_SPELL_TARGET2:
return "BE_SPELL_TARGET2";
case ACHIEVEMENT_CRITERIA_TYPE_SPECIAL_PVP_KILL:
return "SPECIAL_PVP_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_FISH_IN_GAMEOBJECT:
return "FISH_IN_GAMEOBJECT";
case ACHIEVEMENT_CRITERIA_TYPE_EARNED_PVP_TITLE:
return "EARNED_PVP_TITLE";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILLLINE_SPELLS:
return "LEARN_SKILLLINE_SPELLS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_DUEL:
return "WIN_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_LOSE_DUEL:
return "LOSE_DUEL";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE:
return "KILL_CREATURE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_GOLD_EARNED_BY_AUCTIONS:
return "GOLD_EARNED_BY_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_CREATE_AUCTION:
return "CREATE_AUCTION";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_BID:
return "HIGHEST_AUCTION_BID";
case ACHIEVEMENT_CRITERIA_TYPE_WON_AUCTIONS:
return "WON_AUCTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_AUCTION_SOLD:
return "HIGHEST_AUCTION_SOLD";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_GOLD_VALUE_OWNED:
return "HIGHEST_GOLD_VALUE_OWNED";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_REVERED_REPUTATION:
return "GAIN_REVERED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_GAIN_HONORED_REPUTATION:
return "GAIN_HONORED_REPUTATION";
case ACHIEVEMENT_CRITERIA_TYPE_KNOWN_FACTIONS:
return "KNOWN_FACTIONS";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_EPIC_ITEM:
return "LOOT_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM:
return "RECEIVE_EPIC_ITEM";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_NEED:
return "ROLL_NEED";
case ACHIEVEMENT_CRITERIA_TYPE_ROLL_GREED:
return "ROLL_GREED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_DEALT:
return "HIT_DEALT";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HIT_RECEIVED:
return "HIT_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_DAMAGE_RECEIVED:
return "TOTAL_DAMAGE_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEAL_CASTED:
return "HIGHEST_HEAL_CASTED";
case ACHIEVEMENT_CRITERIA_TYPE_TOTAL_HEALING_RECEIVED:
return "TOTAL_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_HIGHEST_HEALING_RECEIVED:
return "HIGHEST_HEALING_RECEIVED";
case ACHIEVEMENT_CRITERIA_TYPE_QUEST_ABANDONED:
return "QUEST_ABANDONED";
case ACHIEVEMENT_CRITERIA_TYPE_FLIGHT_PATHS_TAKEN:
return "FLIGHT_PATHS_TAKEN";
case ACHIEVEMENT_CRITERIA_TYPE_LOOT_TYPE:
return "LOOT_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_CAST_SPELL2:
return "CAST_SPELL2";
case ACHIEVEMENT_CRITERIA_TYPE_LEARN_SKILL_LINE:
return "LEARN_SKILL_LINE";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_HONORABLE_KILL:
return "EARN_HONORABLE_KILL";
case ACHIEVEMENT_CRITERIA_TYPE_ACCEPTED_SUMMONINGS:
return "ACCEPTED_SUMMONINGS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_ACHIEVEMENT_POINTS:
return "EARN_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_USE_LFD_TO_GROUP_WITH_PLAYERS:
return "USE_LFD_TO_GROUP_WITH_PLAYERS";
case ACHIEVEMENT_CRITERIA_TYPE_SPENT_GOLD_GUILD_REPAIRS:
return "SPENT_GOLD_GUILD_REPAIRS";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_GUILD_LEVEL:
return "REACH_GUILD_LEVEL";
case ACHIEVEMENT_CRITERIA_TYPE_CRAFT_ITEMS_GUILD:
return "CRAFT_ITEMS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_CATCH_FROM_POOL:
return "CATCH_FROM_POOL";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_BANK_SLOTS:
return "BUY_GUILD_BANK_SLOTS";
case ACHIEVEMENT_CRITERIA_TYPE_EARN_GUILD_ACHIEVEMENT_POINTS:
return "EARN_GUILD_ACHIEVEMENT_POINTS";
case ACHIEVEMENT_CRITERIA_TYPE_WIN_RATED_BATTLEGROUND:
return "WIN_RATED_BATTLEGROUND";
case ACHIEVEMENT_CRITERIA_TYPE_REACH_BG_RATING:
return "REACH_BG_RATING";
case ACHIEVEMENT_CRITERIA_TYPE_BUY_GUILD_TABARD:
return "BUY_GUILD_TABARD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_QUESTS_GUILD:
return "COMPLETE_QUESTS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_HONORABLE_KILLS_GUILD:
return "HONORABLE_KILLS_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_KILL_CREATURE_TYPE_GUILD:
return "KILL_CREATURE_TYPE_GUILD";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE_TYPE:
return "GUILD_CHALLENGE_TYPE";
case ACHIEVEMENT_CRITERIA_TYPE_COMPLETE_GUILD_CHALLENGE:
return "GUILD_CHALLENGE";
default:
return "MISSING_TYPE";
}
}
template class AchievementMgr<Guild>;
template class AchievementMgr<Player>;
//==========================================================
void AchievementGlobalMgr::LoadAchievementCriteriaList()
{
uint32 oldMSTime = getMSTime();
if (sCriteriaStore.GetNumRows() == 0)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement criteria.");
return;
}
for (uint32 entryId = 0; entryId < sCriteriaTreeStore.GetNumRows(); entryId++)
{
CriteriaTreeEntry const* criteriaTree = sCriteriaTreeStore.LookupEntry(entryId);
if (!criteriaTree)
continue;
if (CriteriaTreeEntry const* parent = sCriteriaTreeStore.LookupEntry(criteriaTree->parentID))
m_SubCriteriaTreeListById[parent->ID].push_back(criteriaTree);
ModifierTreeEntryByTreeId m_ModifierTreeEntryByTreeId;
CriteriaEntry const* criteriaEntry = sCriteriaStore.LookupEntry(criteriaTree->criteriaID);
if (!criteriaEntry)
continue;
m_AchievementCriteriaTreeByCriteriaId[criteriaEntry->ID].push_back(criteriaTree);
}
for (uint32 entryId = 0; entryId < sModifierTreeStore.GetNumRows(); entryId++)
{
ModifierTreeEntry const* modifier = sModifierTreeStore.LookupEntry(entryId);
if (!modifier)
continue;
if (modifier->parent)
m_ModifierTreeEntryByTreeId[modifier->parent].push_back(modifier);
}
uint32 criterias = 0;
for (uint32 entryId = 0; entryId < sCriteriaStore.GetNumRows(); entryId++)
{
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId);
if (!criteria)
continue;
m_AchievementCriteriasByType[criteria->type].push_back(criteria);
if (criteria->timeLimit)
m_AchievementCriteriasByTimedType[criteria->timedCriteriaStartType].push_back(criteria);
++criterias;
}
for (uint32 entryId = 0; entryId < sCriteriaStore.GetNumRows(); entryId++)
{
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(entryId);
if (!criteria)
continue;
AchievementCriteriaTreeList achievementCriteriaTreeList = sAchievementMgr->GetAchievementCriteriaTreeList(criteria);
for (AchievementCriteriaTreeList::const_iterator iter = achievementCriteriaTreeList.begin(); iter != achievementCriteriaTreeList.end(); iter++)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievementEntryByCriteriaTree(*iter);
if (!achievement)
continue;
if (!(achievement->flags & ACHIEVEMENT_FLAG_GUILD))
continue;
m_GuildAchievementCriteriasByType[criteria->type].push_back(criteria);
++criterias;
}
}
TC_LOG_INFO("server.loading", ">> Loaded %u achievement criteria in %u ms", criterias, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementReferenceList()
{
uint32 oldMSTime = getMSTime();
if (sAchievementStore.GetNumRows() == 0)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 achievement references.");
return;
}
uint32 count = 0;
for (uint32 entryId = 0; entryId < sAchievementStore.GetNumRows(); ++entryId)
{
AchievementEntry const* achievement = sAchievementMgr->GetAchievement(entryId);
if (!achievement)
continue;
m_AchievementEntryByCriteriaTree[achievement->criteriaTreeID] = achievement;
if (!achievement->refAchievement)
continue;
m_AchievementListByReferencedId[achievement->refAchievement].push_back(achievement);
++count;
}
// Once Bitten, Twice Shy (10 player) - Icecrown Citadel
if (AchievementEntry const* achievement = sAchievementMgr->GetAchievement(4539))
const_cast<AchievementEntry*>(achievement)->mapID = 631; // Correct map requirement (currently has Ulduar)
TC_LOG_INFO("server.loading", ">> Loaded %u achievement references in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadAchievementCriteriaData()
{
uint32 oldMSTime = getMSTime();
m_criteriaDataMap.clear(); // Need for reload case
QueryResult result = WorldDatabase.Query("SELECT criteria_id, type, value1, value2, ScriptName FROM achievement_criteria_data");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 additional achievement criteria data. DB table `achievement_criteria_data` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 criteria_id = fields[0].GetUInt32();
CriteriaEntry const* criteria = sAchievementMgr->GetAchievementCriteria(criteria_id);
if (!criteria)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has data for non-existing criteria (Entry: %u), ignore.", criteria_id);
continue;
}
uint32 dataType = fields[1].GetUInt8();
const char* scriptName = fields[4].GetCString();
uint32 scriptId = 0;
if (strcmp(scriptName, "")) // Not empty
{
if (dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_SCRIPT)
TC_LOG_ERROR("sql.sql", "Table `achievement_criteria_data` has ScriptName set for non-scripted data type (Entry: %u, type %u), useless data.", criteria_id, dataType);
else
scriptId = sObjectMgr->GetScriptId(scriptName);
}
AchievementCriteriaData data(dataType, fields[2].GetUInt32(), fields[3].GetUInt32(), scriptId);
if (!data.IsValid(criteria))
continue;
// This will allocate empty data set storage
AchievementCriteriaDataSet& dataSet = m_criteriaDataMap[criteria_id];
dataSet.SetCriteriaId(criteria_id);
// Add real data only for not NONE data types
if (data.dataType != ACHIEVEMENT_CRITERIA_DATA_TYPE_NONE)
dataSet.Add(data);
// Counting data by and data types
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u additional achievement criteria data in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadCompletedAchievements()
{
uint32 oldMSTime = getMSTime();
QueryResult result = CharacterDatabase.Query("SELECT achievement FROM character_achievement GROUP BY achievement");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 completed achievements. DB table `character_achievement` is empty.");
return;
}
do
{
Field* fields = result->Fetch();
uint16 achievementId = fields[0].GetUInt16();
const AchievementEntry* achievement = sAchievementMgr->GetAchievement(achievementId);
if (!achievement)
{
// Remove non existent achievements from all characters
TC_LOG_ERROR("achievement", "Non-existing achievement %u data removed from table `character_achievement`.", achievementId);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_INVALID_ACHIEVMENT);
stmt->setUInt16(0, uint16(achievementId));
CharacterDatabase.Execute(stmt);
continue;
}
else if (achievement->flags & (ACHIEVEMENT_FLAG_REALM_FIRST_REACH | ACHIEVEMENT_FLAG_REALM_FIRST_KILL))
m_allCompletedAchievements.insert(achievementId);
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %lu completed achievements in %u ms", (unsigned long)m_allCompletedAchievements.size(), GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewards()
{
uint32 oldMSTime = getMSTime();
m_achievementRewards.clear(); // Need for reload case
// 0 1 2 3 4 5 6
QueryResult result = WorldDatabase.Query("SELECT entry, title_A, title_H, item, sender, subject, text FROM achievement_reward");
if (!result)
{
TC_LOG_ERROR("server.loading", ">> Loaded 0 achievement rewards. DB table `achievement_reward` is empty.");
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
const AchievementEntry* pAchievement = GetAchievement(entry);
if (!pAchievement)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` has wrong achievement (Entry: %u), ignored.", entry);
continue;
}
AchievementReward reward;
reward.titleId[0] = fields[1].GetUInt32();
reward.titleId[1] = fields[2].GetUInt32();
reward.itemId = fields[3].GetUInt32();
reward.sender = fields[4].GetUInt32();
reward.subject = fields[5].GetString();
reward.text = fields[6].GetString();
// Must be title or mail at least
if (!reward.titleId[0] && !reward.titleId[1] && !reward.sender)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have title or item reward data, ignored.", entry);
continue;
}
if (pAchievement->requiredFaction == ACHIEVEMENT_FACTION_ANY && ((reward.titleId[0] == 0) != (reward.titleId[1] == 0)))
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has title (A: %u H: %u) for only one team.", entry, reward.titleId[0], reward.titleId[1]);
if (reward.titleId[0])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[0]);
if (!titleEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_A`, set to 0", entry, reward.titleId[0]);
reward.titleId[0] = 0;
}
}
if (reward.titleId[1])
{
CharTitlesEntry const* titleEntry = sCharTitlesStore.LookupEntry(reward.titleId[1]);
if (!titleEntry)
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid title id (%u) in `title_H`, set to 0", entry, reward.titleId[1]);
reward.titleId[1] = 0;
}
}
// Check mail data before item for report including wrong item case
if (reward.sender)
{
if (!sObjectMgr->GetCreatureTemplate(reward.sender))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid creature entry %u as sender, mail reward skipped.", entry, reward.sender);
reward.sender = 0;
}
}
else
{
if (reward.itemId)
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has item reward, item will not be rewarded.", entry);
if (!reward.subject.empty())
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail subject.", entry);
if (!reward.text.empty())
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) does not have sender data but has mail text.", entry);
}
if (reward.itemId)
{
if (!sObjectMgr->GetItemTemplate(reward.itemId))
{
TC_LOG_ERROR("sql.sql", "Table `achievement_reward` (Entry: %u) has invalid item id %u, reward mail will not contain item.", entry, reward.itemId);
reward.itemId = 0;
}
}
m_achievementRewards[entry] = reward;
++count;
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %u achievement rewards in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
}
void AchievementGlobalMgr::LoadRewardLocales()
{
uint32 oldMSTime = getMSTime();
m_achievementRewardLocales.clear(); // Need for reload case
QueryResult result = WorldDatabase.Query("SELECT entry, subject_loc1, text_loc1, subject_loc2, text_loc2, subject_loc3, text_loc3, subject_loc4, text_loc4, "
"subject_loc5, text_loc5, subject_loc6, text_loc6, subject_loc7, text_loc7, subject_loc8, text_loc8, subject_loc9, text_loc9,"
"subject_loc10, text_loc10 FROM locales_achievement_reward");
if (!result)
{
TC_LOG_INFO("server.loading", ">> Loaded 0 achievement reward locale strings. DB table `locales_achievement_reward` is empty");
return;
}
do
{
Field* fields = result->Fetch();
uint32 entry = fields[0].GetUInt32();
if (m_achievementRewards.find(entry) == m_achievementRewards.end())
{
TC_LOG_ERROR("sql.sql", "Table `locales_achievement_reward` (Entry: %u) has locale strings for non-existing achievement reward.", entry);
continue;
}
AchievementRewardLocale& data = m_achievementRewardLocales[entry];
for (int i = 1; i < TOTAL_LOCALES; ++i)
{
LocaleConstant locale = (LocaleConstant) i;
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1)].GetString(), locale, data.subject);
ObjectMgr::AddLocaleString(fields[1 + 2 * (i - 1) + 1].GetString(), locale, data.text);
}
}
while (result->NextRow());
TC_LOG_INFO("server.loading", ">> Loaded %lu achievement reward locale strings in %u ms", (unsigned long)m_achievementRewardLocales.size(), GetMSTimeDiffToNow(oldMSTime));
}
AchievementEntry const* AchievementGlobalMgr::GetAchievement(uint32 achievementId) const
{
return sAchievementStore.LookupEntry(achievementId);
}
CriteriaEntry const* AchievementGlobalMgr::GetAchievementCriteria(uint32 criteriaId) const
{
return sCriteriaStore.LookupEntry(criteriaId);
}
| [
"felianther15@gmail.com"
] | felianther15@gmail.com |
ef366a8827db21299642e3b78ed897c11681ddf2 | d09f25e7b28f14024c3e3d4e46ee1e400db9f19e | /c++-test/Programming_with_c++/cpt16_exception/AbstractGeometricObject.h | b5e37923f478596bd0d74b8d0db826a69c02cfef | [] | no_license | gj-sq/program_language_test | c6fc02aed1a43b78380b6b32a4e7b34adfdbc63e | 07218f82f5c5a9e98e2b3ed98dcd82d702291b29 | refs/heads/main | 2023-08-16T22:16:59.731207 | 2021-09-29T14:35:27 | 2021-09-29T14:35:27 | 405,794,259 | 0 | 0 | null | 2021-09-13T01:20:51 | 2021-09-13T01:20:50 | null | UTF-8 | C++ | false | false | 509 | h | #ifndef GEOMETICOBJECT_H
#define GEOMETICOBJECT_H
#include <string>
using namespace std;
class GeometricObject
{
private:
string color;
bool filled;
protected:
GeometricObject();
GeometricObject(const string& color, bool filled);
public:
string getColor() const;
void setColor(const string& color);
bool isFilled() const;
void setFilled(bool filled);
string toString() const;
virtual double getArea() const = 0;
virtual double getPerimeter() const = 0;
};
#endif
| [
"GuangJiHuang@qq.com"
] | GuangJiHuang@qq.com |
bb9a88c6516ca58df75c7db5116be3de35ffa6b0 | a0966c0b5ea3c736e325b929fe86fe7907d2eb04 | /c002.cpp | 8979140b103dc7b7e264e66d6b35def518716289 | [] | no_license | hchs910739/zerojudge_c | ec58afb71c1193e6b2d573ed50e22f5ccdb0a5d3 | 95a85dd1991bf2e81223d95590c9cc3277631200 | refs/heads/master | 2020-03-22T07:56:31.689581 | 2018-07-04T14:42:28 | 2018-07-04T14:42:28 | 139,734,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | cpp | #include<iostream>
using namespace std;
main(){
int n[250000];
int ans[250000];
int x,i,j;
for(i=0;;i++)
{
cin>>n[i];
if(n[i]==0)
{
break;
}
if(n[i]>=101)
{
ans[i]=n[i]-10;
}
else if(n[i]<=100)
{
ans[i]=91;
}
}
for(j=0;j<i;j++)
{
cout<<"f91("<<n[j]<<") = "<<ans[j]<<endl;
}
system("pause");
return 0;
}
| [
"40828533+hchs910739@users.noreply.github.com"
] | 40828533+hchs910739@users.noreply.github.com |
71b64fb477f9666e726a9baea9d9504331184a7c | 6ea9796da14f3ee7880d04a51c6bff25713b3206 | /hackerrank/contests/week1-challenge/maximizing-xor/main.cc | fd5cc6393ec35355932b167b9d9d35d96c88da4b | [] | no_license | vguerra/programming_contests | 79def4d0a864811a48038b270cebda3fbdc0f000 | 025b064ae0675f015e61cb3066d099b814cd3871 | refs/heads/master | 2021-01-22T11:36:30.364021 | 2015-03-30T19:28:25 | 2015-03-30T19:28:25 | 25,770,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | cc | // Victor Guerra <vguerra@gmail.com>
// 2014-04-21
// https://www.hackerrank.com/contests/w1/challenges/maximizing-xor
#include <iostream>
#include <cmath>
#include <cstdint>
using namespace std;
uint32_t maxXor(uint32_t L, uint32_t R) {
uint32_t mask = 0;
uint32_t extra_bits = 0;
uint32_t bitsL = floor(log2(L) + 1);
uint32_t bitsR = floor(log2(R) + 1);
if (bitsL == bitsR) {
uint32_t bitsDiff = floor(log2(L ^ R) + 1);
uint32_t filter = ~(~0 << bitsDiff);
L &= filter;
R &= filter;
extra_bits = bitsL - bitsDiff;
}
for (int i = 0; i < floor(log2(R - L) + 1) + extra_bits; ++i) {
mask = (mask << 1) | 1;
}
return mask;
}
int main() {
uint32_t L, R;
cin >> L >> R;
cout << maxXor(L, R) << "\n";
return 0;
}
| [
"vguerra@gmail.com"
] | vguerra@gmail.com |
10eca59e7aec6810e88a90682d9b4037cfb2afa7 | bc1ba6cd743692e82682a7a999d2de74ab4966c7 | /Computer programming with C++/2ndASSG_3160119_3150251/ppm/Image.cpp | 399674d925a31f9fdf9b9a79076d50fc4203a724 | [] | no_license | ntogka/Aueb-projects | 01ac6fc804759b7f5fbb8a9cc06a2b64962f1edd | d2a07552eb5a1f33d65e127adc388683549a5fc5 | refs/heads/master | 2023-08-30T21:52:38.816787 | 2021-10-04T15:25:50 | 2021-10-04T15:25:50 | 299,969,145 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,248 | cpp | #include "Array.h"
#include <string>
#include "ppm/ppm.h"
using namespace imaging;
namespace math {
bool checkPPM(std::string filename);
bool checkFormat(const std::string& filename_format, const std::string& true_format);
Image::~Image() {}
Image & Image::operator = (const Image & right) {
width = right.width;
height = right.height;
buffer = right.buffer;
return *this;
}
bool Image::load(const std::string & filename, const std::string & format) {
if (checkFormat(format, "ppm")) {
unsigned int * W = &width;
unsigned int * H = &height;
const char * initial_filename = filename.c_str();
float * loadedData = ReadPPM(initial_filename, (int*)W, (int*)H);
/*width = *w;
height = *h;
int size = width * height;
for (int i = 0; i < size; i++) {
Vec3<float> * newColor = new Vec3<float>(loadedData[3 * i], loadedData[3 * i + 1], loadedData[3 * i + 2]);
buffer.push_back(*newColor);
}*/
width = *W;
height = *H;
buffer.insert(buffer.begin(), (Color*)loadedData, (Color*)loadedData + (width*height));
delete loadedData;
return true;
}
return false;
}
bool Image::save(const std::string & filename, const std::string & format) {
if (buffer.empty()) {
return false;
}
if (checkFormat(format, "ppm")) {
int triplexSize = 3 * height * width;
int colorSize = height * width;
float * savedData = new float[triplexSize];
for (unsigned int i = 0; i < colorSize; i++) {
savedData[3 * i] = buffer[i].r;
savedData[3 * i + 1] = buffer[i].g;
savedData[3 * i + 2] = buffer[i].b;
}
return WritePPM(savedData, width, height, filename.c_str());
}
return false;
}
bool checkPPM(std::string filename) {
if (checkFormat(filename.substr(filename.find_last_of(".") + 1), "ppm")) {
return true;
}
return false;
}
bool checkFormat(const std::string& filename_format, const std::string& true_format){
unsigned int format_size = filename_format.size();
if (true_format.size() != format_size)
return false;
for (unsigned int i = 0; i < format_size; ++i)
if (tolower(filename_format[i]) != tolower(true_format[i]))
return false;
return true;
}
} | [
"noreply@github.com"
] | ntogka.noreply@github.com |
4704995dde0b34c455faeca8b62a6a6104edb8ab | 48591e6fe907d1d1c15ea671db3ab32b6d60f5a6 | /dizuo/Tutorial3_src/src/MainWindow.h | 6fc21dac8c198aef77382e9fc194c7b63f99e7ab | [] | no_license | dizuo/dizuo | 17a2da81c0ad39d77e904012cb9fbb8f6681df1b | 6083ca9969d9d45b72859d9795544ccdf2d13b1c | refs/heads/master | 2021-10-24T21:16:19.910030 | 2021-10-23T07:17:30 | 2021-10-23T07:17:30 | 1,253,554 | 7 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,527 | h | #ifndef _MAINWINDOW_H_
#define _MAINWINDOW_H_
#include <Windows.h>
#include "GL/gl.h"
#include "StateManager.h"
// The main window class. It wraps the HANDLE of the window and initializes the
// openGL rendering context. It is also in charge of processing the different
// event messages.
class CMainWindow
{
public:
CMainWindow(int iWidth, int iHeight, bool bFullScreen);
~CMainWindow();
// Called by the application class to update the game logic
void Update(DWORD dwCurrentTime);
// Called by the application class when the window need to be redrawn.
void Draw();
private:
// Register the window class with the correct window procedure (OnEvent)
void RegisterWindowClass();
// Create the rendering context used by OpenGL
void CreateContext();
// Initialize openGL
void InitGL();
// Called when a WM_SIZE message is received
void OnSize(GLsizei width, GLsizei height);
// Static function which will be the window procedure callback
static LRESULT CALLBACK OnEvent(HWND Handle, UINT Message, WPARAM wParam, LPARAM lParam);
// Processes the messages that were received in OnEvent.
void ProcessEvent(UINT Message, WPARAM wParam, LPARAM lParam);
// The window handle
HWND m_hWindow;
// The window device context
HDC m_hDeviceContext;
// The openGL context.
HGLRC m_hGLContext;
// Specifies if the window is fullscreen.
bool m_bFullScreen;
// The state manager
CStateManager* m_pStateManager;
};
#endif // _MAINWINDOW_H_ | [
"ren.yafee@gmail.com@107d8d70-eac7-11de-9d05-050bbbc75a16"
] | ren.yafee@gmail.com@107d8d70-eac7-11de-9d05-050bbbc75a16 |
b9b9976db6ae67611b1b8744fe8ed07c32577a71 | 017d653b1a4d9ed3f5d2b36315dc3a131dd3b601 | /Az_Tools/Textline.h | c0b771d9b56b745702ff9174214c90a233443a2e | [] | no_license | cwoll87/code | c03e5cd2b9603c27a6397364bf6fee9a62f3c5eb | b584b4248a5f979237f1b9d3664b30b8c4ca8a4d | refs/heads/master | 2016-08-04T07:03:16.013414 | 2015-01-06T22:55:32 | 2015-01-06T22:55:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 541 | h | #pragma once
#include "SFML\Graphics.hpp"
namespace az
{
class Textline : public sf::Drawable
{
public:
sf::Text text;
std::string stringName;
sf::Font *font;
Textline(void);
Textline(std::string name, int size, int xpos, int ypos, const sf::Color &color);
~Textline(void);
std::string getString()const;
void setString(std::string temp);
void setColor(sf::Color color);
sf::FloatRect getFloatRect();
void setPosition(int x, int y);
void draw(sf::RenderTarget& target, sf::RenderStates states) const;
};
}
| [
"Hybra@hotmail.de"
] | Hybra@hotmail.de |
9bd246dd78eb4611f7adc826cfe1969c54819401 | c2252f1526c624f88885240ef4e07ca6f27cae69 | /Solutions/101170 - 2016-2017 ACM-ICPC Northwestern European Regional Programming Contest (NWERC 2016)/J(greedy).cpp | 64911435b88b443890b5fcfbbd0aa61734233feb | [] | no_license | shubhansujee9/Codeforces-Gyms-Solutions | 201529a75db9abe9b5dfa693ee1fedca93416823 | 785b69956c9b8afd31f4ebd0b24fe10362dc9d84 | refs/heads/master | 2020-03-24T13:00:38.421420 | 2018-07-22T09:05:52 | 2018-07-22T09:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,733 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef vector<ll> vll;
typedef vector<vi> vvi;
typedef pair<ll, ll> pii;
typedef vector<pii> vii;
typedef vector<bool> vb;
typedef vector<string> vs;
const int di[] = { -1, 0, 1, 0 };
const int dj[] = { 0, 1, 0, -1 };
const ll MOD = 5e6;
const ll INF = 1e8;
const double EPS = 1e-12;
#define mp make_pair
#define all(x) x.begin(),x.end()
int main() {
ios::sync_with_stdio(false), cin.tie(0);
ll n, q, s; cin >> n >> q >> s;
vi sen(s);
for (int i = 0; i < s; i++) {
cin >> sen[i]; sen[i]--;
}
vi sz(q);
for (int i = 0; i < q; i++) {
cin >> sz[i];
}
vi d(n);
vvi qinc(n, vi(q));
for (int i = 0; i < n; i++) {
cin >> d[i];
for (int j = 0; j < s; j++) {
ll x; cin >> x;
qinc[i][sen[j]] += x;
}
}
ll cur = 0; bool w = false;
vi qcur(q);
vector<queue<pii>> qp(q);
for (int i = 0; i < n && !w; i++) {
for (int j = 0; j < q && !w; j++) {
while (qcur[j] + qinc[i][j] > sz[j]) {
if (qp[j].empty()) {
w = true; break;
}
ll rm = qcur[j] + qinc[i][j] - sz[j];//min(qcur[j] + qinc[i][j] - sz[j], d[qp[j].front().second]);
//if (rm == 0) {
// ll x = qp[j].front().first;
// qp[j].pop();
// if (!qp[j].empty())
// qp[j].front().first += x;
//}
if (rm >= qp[j].front().first) {
if (qp[j].front().first <= d[qp[j].front().second]) {
rm -= qp[j].front().first;
qcur[j] -= qp[j].front().first;
d[qp[j].front().second] -= qp[j].front().first;
qp[j].pop();
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
else {
if (rm <= d[qp[j].front().second]) {
qp[j].front().first -= rm;
qcur[j] -= rm;
d[qp[j].front().second] -= rm;
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
}
qcur[j] += qinc[i][j];
qp[j].push({ qinc[i][j],i });
}
}
for (int j = 0; j < q && !w; j++) {
while (qcur[j] > 0) {
if (qp[j].empty()) {
w = true; break;
}
ll rm = qcur[j];//min(qcur[j], d[qp[j].front().second]);
//if (rm == 0) {
// ll x = qp[j].front().first;
// qp[j].pop();
// if (!qp[j].empty())
// qp[j].front().first += x;
//}
if (rm >= qp[j].front().first) {
if (qp[j].front().first <= d[qp[j].front().second]) {
rm -= qp[j].front().first;
qcur[j] -= qp[j].front().first;
d[qp[j].front().second] -= qp[j].front().first;
qp[j].pop();
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
else {
if (rm <= d[qp[j].front().second]) {
qp[j].front().first -= rm;
qcur[j] -= rm;
d[qp[j].front().second] -= rm;
}
else {
rm -= d[qp[j].front().second];
qcur[j] -= d[qp[j].front().second];
ll x = qp[j].front().first - d[qp[j].front().second];
d[qp[j].front().second] -= d[qp[j].front().second];
qp[j].pop();
if (!qp[j].empty())
qp[j].front().first += x;
}
}
}
}
cout << (w ? "impossible" : "possible") << endl;
cin.ignore(), cin.get();
}
| [
"khaled.hamedt@gmail.com"
] | khaled.hamedt@gmail.com |
579763f1ba366750d2a81245654aa2d1bfcd1031 | 3e92edd742d419f6abc4ba17ae90d40f0d59413b | /firmware/firmware/firmware.ino | a1dae519f929f974a5f64a85206e43d91c2f6a7f | [] | no_license | NimraZeeshan/WeatherMonitoringSystem-Iot | 2938ac87d5051c7cbcec5e77b96572c18f388a45 | e9db84a71a090ff85d8b62465c227955163d1c71 | refs/heads/master | 2023-06-03T05:35:09.775806 | 2020-07-09T06:40:38 | 2020-07-09T06:40:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,674 | ino | #include <ESP8266WiFi.h> //Including the ESP8266 WiFi library in order to usm them
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
//FOR SOIL MOISTURE
int soil_pin = D0; // Soil Sensor input at PIN D0
int soil_value = 0;
//FOR DHT11
#include <Adafruit_Sensor.h> //In order to use DHT sensor we have to include this library first
#include <DHT.h> //Including the DHT library
char dstmp[20], btmp[20], bprs[20], balt[20];
bool bmp085_present = true;
#define DHTPIN 2 //Connect the DHT11 sensor's data pin to GPIO2(D4) of Nodemcu
#define DHTTYPE DHT11 //Mention the type of sensor we are using, Here it it DHT11, for DHT22 just replace DHT11 with DHT22
float temp = 0.000 ;
float humidity = 0.000 ;
DHT dht(DHTPIN, DHTTYPE); //Defining the pin and the dhttype
//FOR BMP180
//For using I2C connection of BMP180 in order to connect it to the board
#include <Adafruit_BMP085.h> //Including the library for BMP180
Adafruit_BMP085 bmp; //Defining the object bmp
#define I2C_SCL 12 //Connect SCL pin of BMP180 to GPIO12(D6) of Nodemcu
#define I2C_SDA 13 //Connect SDA pin of BMP180 to GPIO13(D7) of Nodemcu
float pressure = 0.000;
//FOR RAIN SENSOR
int rain_sensor = A0;
int rain_sensor_value = 0; //variable to store RainDrop Sensor Module's output value
//________________________Mention the SSID and Password____________________________________________________
const char* ssid = "shresthas_wlink";//SSID of the WiFi hotspot available
const char* password = "alumanchor"; //Password of the WiFi
void setup() {
Serial.begin(9600);
//Connecting nodemcu with wifi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting...");
}
//starting DTH & BMP 180
dht.begin(); //Initializing the DHT sensor
Wire.begin(I2C_SDA, I2C_SCL); //Initializing the I2C connection BMP180
}
//MAIN
void loop() {
//FOR SOIL MOISTURE
startReadingSoilMoisture();
startReadingDHT();
startReadingRainSensor();
startReadingBMPSensor();
Serial.println("Sending data to cloud....... ");
// apiCall();
}
//FOR SOIL MOISTURE
void startReadingSoilMoisture() {
Serial.println("Started Reading SoilMoisture : ");
soil_value = analogRead(soil_pin); //Takes reading from soil moisture sensor
Serial.print("MOISTURE LEVEL : ");
Serial.println(soil_value);
}
//FOR DHT
void startReadingDHT() {
//______________________Getting the Humidity and temperature value from DHT11____________________________
Serial.println("Started Reading Humidity : ");
humidity = dht.readHumidity();
Serial.print("Humidity : ");
Serial.println(humidity);
Serial.println("Started Reading Temperature : ");
temp = dht.readTemperature(); // or dht.readTemperature(true) for Fahrenheit
Serial.print("Temperature : ");
Serial.println(temp);
}
//FOR RAINSENSOR
void startReadingRainSensor() {
//_____________________________________Checking for Rain______________________________________________________
Serial.println("Started RAINSENSOR : ");
rain_sensor_value = analogRead(rain_sensor);
Serial.print("RAINSENSOR : ");
Serial.println(rain_sensor_value);
rain_sensor_value = constrain(rain_sensor, 150, 440);
rain_sensor_value = map(rain_sensor, 150, 440, 1023, 0);
}
//FOR BMP180 Sensor
void startReadingBMPSensor()
{
Serial.println("Started Reading Pressure : ");
if (bmp.begin())
{
//BMP180 is working
//______________________Reading the value of Pressure from the BMP180__________________
pressure = bmp.readPressure() / 100; // Division by 100 makes it in millibars
Serial.print("Pressure : ");
Serial.println(pressure);
}
}
//SENDING DATA TO SERVER THROUGHT API CALL
void apiCall() {
String deviceKey = "123456";
String postbody = "";
postbody += "{\"device_key\":";
postbody += deviceKey;
postbody += ",\"temperature\":";
postbody += temp;
postbody += ",\"pressure\":";
postbody += pressure;
postbody += ",\"rain\":";
postbody += rain_sensor_value;
postbody += ",\"humidity\":";
postbody += humidity;
postbody += ",\"soil_moisture\":";
postbody += soil_value;
postbody += "}";
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http; //Object of class HTTPClient
http.begin("http://localhost:3000/api/update-stats");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST(postbody);
if (httpCode > 0) {
}
http.end(); //Close connection
}
delay(10000); //10sec delay
}
| [
"winneecreztha@gmail.com"
] | winneecreztha@gmail.com |
025e4f7d3b61b28ed257dc04f45695184ed2058f | 39b5fe34f34fdf1d25b5904b79647893379867a3 | /ClientSide/Handmade/Player.cpp | 14d06e4733341c625cf0b3ae43ccea38793965e9 | [
"MIT"
] | permissive | kakol20/Networking-For-Games---2D-Game | 2e6d2981b14c2c41728f779aecb114905f5f2fe1 | bf76aa4be9fbb05653d650f662db16594fcd28d2 | refs/heads/master | 2020-12-21T18:26:10.872686 | 2020-01-31T17:51:22 | 2020-01-31T17:51:22 | 236,521,700 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,707 | cpp | #include "Player.h"
#include <cmath>
#include <sstream>
#include "InputManager.h"
#include "ScreenManager.h"
#include "TextureManager.h"
Player::Player()
{
TheTexture::Instance()->LoadTextureFromFile("Assets/Sprites/Player.png", "PlayerSprite");
TheTexture::Instance()->LoadFontFromFile("Assets/Fonts/Formula1-Regular.ttf", 100, "MainFont");
m_taggedT.SetFont("MainFont");
m_scoreT.SetFont("MainFont");
m_sprite.SetTexture("PlayerSprite");
m_sprite.SetSpriteDimension(30, 30);
m_sprite.SetTextureDimension(1, 1, 30, 30);
m_taggedT.SetText("T");
m_taggedT.SetSize(15, 30);
m_position.x = TheScreen::Instance()->GetScreenSize().x / 2;
m_position.y = TheScreen::Instance()->GetScreenSize().y / 2;
}
Player::~Player()
{
}
void Player::Update()
{
KeyState keys = TheInput::Instance()->GetKeyStates();
if (keys[SDL_SCANCODE_W])
{
m_position.y -= 1;
}
if (keys[SDL_SCANCODE_S])
{
m_position.y += 1;
}
if (keys[SDL_SCANCODE_D])
{
m_position.x += 1;
}
if (keys[SDL_SCANCODE_A])
{
m_position.x -= 1;
}
if (m_tagged)
{
m_score = 0.0f;
}
else
{
m_score += 0.5f;;
}
std::stringstream str;
char scoreChar[10] = { '\0' };
str << m_score;
str >> scoreChar;
String score = "Score: ";
score += scoreChar;
m_scoreT.SetText(score.GetString());
m_scoreT.SetSize(score.Length() * 15, 30);
}
bool Player::Draw()
{
m_sprite.Draw(m_position.x - 15, m_position.y - 15);
if (m_tagged)
{
m_taggedT.Draw(m_position.x - 7, m_position.y - 15);
}
m_scoreT.Draw();
return true;
}
bool Player::IsTagged() const
{
return m_tagged;
}
void Player::SetTagged(const bool flag)
{
m_tagged = flag;
}
int Player::GetScore() const
{
return (int)floor(m_score);
}
| [
"adrianaquino.aquino33@gmail.com"
] | adrianaquino.aquino33@gmail.com |
6cb45a9ac8527d9c191ed7c0c6a491ca3429808e | d7bdd8789ebd7fdf7a4a181b24d8c922cc457fa7 | /Shuffle/List.cpp | 8fa0adfd46a7adadb4d9d7e4c2030317838964f9 | [] | no_license | daringh10/C-Programming-Projects | 2e114f339780c3c9a970578a08b4ee30a3a80f6c | 8a030d6490db0f7a1a36dba38926626acf19a88e | refs/heads/main | 2023-08-05T08:04:22.707187 | 2021-09-19T22:00:55 | 2021-09-19T22:00:55 | 408,241,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,533 | cpp | #include <iostream>
#include <string>
#include <climits>
#include "List.h"
using namespace std;
// Private Constructor ---------------------------------------------------
//Node constructor
List::Node::Node(int x){
data = x;
next = nullptr;
prev = nullptr;
}
// Class Constructors & Destructors -------------------------------------------
// Creates a new List in the empty state.
List::List(){
frontDummy = new Node(INT_MIN);
backDummy = new Node(INT_MAX);
frontDummy->next = backDummy;
backDummy->prev = frontDummy;
beforeCursor = frontDummy;
afterCursor = backDummy;
pos_cursor = 0;
num_elements = 0;
}
//Copy Constructor
List::List(const List& L){
frontDummy = new Node(INT_MIN);
backDummy = new Node(INT_MAX);
frontDummy->next = backDummy;
backDummy->prev = frontDummy;
beforeCursor = frontDummy;
afterCursor = backDummy;
pos_cursor = 0;
num_elements = 0;
Node *n = L.frontDummy->next;
for (int i = 0; i < L.num_elements; i++){
this->insertBefore(n->data);
n = n->next;
}
}
//Destructor
List::~List(){
clear();
delete frontDummy;
delete backDummy;
}
// Access functions --------------------------------------------------------
// isEmpty()
// Returns true if this List is empty, false otherwise.
bool List::isEmpty(){
return (num_elements == 0);
}
// size()
// Returns the size of this List.
int List::size(){
return num_elements;
}
// position()
// Returns the position of the cursor in this List. The value returned
// will be in the range 0 to size().
int List::position(){
return pos_cursor;
}
// Manipulation procedures -------------------------------------------------
// moveFront()
// Moves cursor to position 0 in this List.
void List::moveFront(){
beforeCursor = frontDummy;
afterCursor = frontDummy->next;
pos_cursor = 0;
}
// moveBack()
// Moves cursor to position size() in this List.
void List::moveBack(){
beforeCursor = backDummy->prev;
afterCursor = backDummy;
pos_cursor = num_elements;
}
// peekNext()
// Returns the element after the cursor.
// pre: position()<size()
int List::peekNext(){
if( position() < size() ){
return afterCursor->data;
}
return INT_MIN;
}
// peekPrev()
// Returns the element before the cursor.
// pre: position()>0
int List::peekPrev(){
if( position() > 0 ){
return beforeCursor->data;
}
return INT_MIN;
}
// moveNext()
// Advances cursor to next higher position. Returns the List element that
// was passed over.
// pre: position()<size()
int List::moveNext(){
if( position() < size() ){
afterCursor = afterCursor->next;
beforeCursor = beforeCursor->next;
pos_cursor += 1;
return beforeCursor->data;
}
return INT_MIN;
}
// movePrev()
// Advances cursor to next lower position. Returns the List element that
// was passed over.
// pre: position()>0
int List::movePrev(){
if( position() > 0 ){
afterCursor = afterCursor->prev;
beforeCursor = beforeCursor->prev;
pos_cursor -=1;
return afterCursor->data;
}
return INT_MIN;
}
// insertAfter()
// Inserts x after cursor.
void List::insertAfter(int x){
Node *n = new Node(x);
n->next = afterCursor;
n->prev = beforeCursor;
beforeCursor->next = n;
afterCursor->prev = n;
afterCursor = n;
num_elements +=1;
}
// insertBefore()
// Inserts x before cursor.
void List::insertBefore(int x){
Node *n = new Node(x);
n->prev = beforeCursor;
n->next = afterCursor;
beforeCursor->next = n;
afterCursor->prev = n;
beforeCursor = n;
pos_cursor +=1;
num_elements +=1;
}
// eraseAfter()
// Deletes element after cursor.
// pre: position()<size()
void List::eraseAfter(){
if( position() < size() ){
Node *temp = afterCursor->next;
delete afterCursor;
afterCursor = temp;
temp->prev = beforeCursor;
beforeCursor->next = temp;
num_elements -=1;
}
}
// eraseBefore()
// Deletes element before cursor.
// pre: position()>0
void List::eraseBefore(){
if( position() > 0 ){
Node *temp = beforeCursor->prev;
delete beforeCursor;
beforeCursor = temp;
temp->next = afterCursor;
afterCursor->prev = temp;
num_elements -=1;
pos_cursor -=1;
}
}
// findNext()
// Starting from the current cursor position, performs a linear search (in
// the direction front-to-back) for the first occurrence of the element x.
// If x is found, places the cursor immediately after the found element (so
// eraseBefore() would remove the found element), and returns the final
// cursor position. If x is not found, places the cursor at position size(),
// and returns -1.
int List::findNext(int x){
while(pos_cursor != num_elements){
moveNext();
if(peekPrev() == x){
return pos_cursor;
}
}
return -1;
}
// findPrev()
// Starting from the current cursor position, performs a linear search (in
// the direction back-to-front) for the first occurrence of the element x.
// If x is found, places the cursor immediately before the found element (so
// eraseAfter() would remove the found element), and returns the final
// cursor position. If x is not found, places the cursor at position 0, and
// returns -1.
int List::findPrev(int x){
while(pos_cursor != 0){
movePrev();
if(peekNext() == x){
return pos_cursor;
}
}
return -1;
}
// cleanup()
// Removes any repeated elements in this List, leaving only unique data
// values. The order of the remaining elements is obtained by retaining
// the frontmost occurrance of each element, and removing all other
// occurances. The cursor is not moved with respect to the retained
// elements, i.e. it lies between the same two retained elements that it
// did before cleanup() was called.
void List::cleanup(){
int current_pos = pos_cursor;
moveFront();
moveNext();
Node *temp1 = frontDummy->next;
int x = 1;
while (pos_cursor != num_elements){
while(pos_cursor != num_elements){
if (temp1->data == afterCursor->data){
eraseAfter();
if (pos_cursor <= current_pos - 1){
current_pos -=1;
}
}
else{
moveNext();
continue;
}
}
x++;
moveFront();
for (int i =0; i < x; i++){
moveNext();
}
temp1 = temp1->next;
}
moveFront();
for (int i =0; i <current_pos; i++){
moveNext();
}
}
// clear()
// Deletes all elements in this List, setting it to the empty state.
void List::clear(){
moveFront();
while (size() != 0){
eraseAfter();
}
}
// concat()
// Returns a new List consisting of the elements of this List, followed
// the elements of L. The returned List's cursor will be at its front
// (position 0).
List List::concat(const List& L){
List New;
Node *N = L.frontDummy->next;
Node *M = this->frontDummy->next;
for (int i = 0; i < this->num_elements; i++){
New.insertBefore(M->data);
M = M->next;
}
for (int i = 0; i < L.num_elements; i++){
New.insertBefore(N->data);
N = N->next;
}
New.moveFront();
cout << New.position() << endl;
return New;
}
// Other Functions ---------------------------------------------------------
// to_string()
// Returns a string representation of this List consisting of a comma
// separated sequence of elements, surrounded by parentheses.
std::string List::to_string(){
Node *N = frontDummy->next;
string s = "(";
for (int i = 0; i < size(); i++){
s += std::to_string(N->data);
if (i != size() - 1){
s+=", ";
}
N = N->next;
}
s+=")";
return s;
}
// equals()
// Returns true if and only if this List is the same integer sequence as R.
// The cursors in this List and in R are unchanged.
bool List::equals(const List& R){
if(this->num_elements != R.num_elements){
return false;
}
Node *M = this->frontDummy->next;
Node *N = R.frontDummy->next;
for(int i = 0; i< R.num_elements; i++){
if(M->data == N->data){
M = M->next;
N = N->next;
continue;
}
else{
return false;
}
}
return true;
}
// Overriden Operators -----------------------------------------------------
// operator=()
// Overwrites the state of this List with state of L.
List& List::operator=( const List& L ){
if (this != &L){
List temp = L;
std::swap(frontDummy, temp.frontDummy);
std::swap(backDummy, temp.backDummy);
std::swap(afterCursor, temp.afterCursor);
std::swap(beforeCursor,temp.beforeCursor);
std::swap(pos_cursor, temp.pos_cursor);
std::swap(num_elements,temp.num_elements);
}
return *this;
}
// operator<<()
// Inserts string representation of L into stream.
std::ostream& operator<<( std::ostream& stream, List& L ){
return stream << L.List::to_string();
}
bool operator==( List& A, const List& B ){
return A.List::equals(B);
}
| [
"dgharib@ucsc.edu"
] | dgharib@ucsc.edu |
6a0299f9b190e8e1e94deee28fd3b19af4cfe7bc | 1baf140693e66029e97b044bedbcb227cce4be22 | /arduino/LC/Garaland.ino | 2d6d14bfd8b8d31fc9f63e7e83dbd7c6b3d47407 | [] | no_license | zholdak/arduino-lights-controller | 88be11e7d7f3634cb85c0d7e064911440fd07bc8 | b260fce45adcc572216b6ddfa43bda7631fd3cb7 | refs/heads/master | 2020-04-09T03:10:45.131751 | 2018-12-01T18:00:58 | 2018-12-01T18:00:58 | 159,972,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,426 | ino | #include "Leds.h"
#include "Garaland.h"
#include "Sd.h"
CRGB garalandLeds[NUM_LEDS];
void garalandInit() {
#ifdef DEBUG
Serial.println(F("All leds off"));
#endif
#ifdef LED_GARLAND
FastLED.addLeds<WS2812B, LED_GARLAND, GRB>(garalandLeds, NUM_LEDS);
FastLED.setBrightness(128);
FastLED.setDither(0);
allBulbsOff();
#endif
}
void allBulbsOff() {
#ifdef LED_GARLAND
for(int i = 0; i < NUM_LEDS; i++)
garalandLeds[i].setRGB(0, 0, 0);
FastLED.show();
#endif
}
boolean checkForInterrupt() {
return Serial.available() > 0;
}
boolean checkForButton() {
if( isOkButtonPressed() ) {
consumeOkButtonPress();
delay(100);
return true;
}
else
return false;
}
void readAndPlayProgsRecursively() {
#ifdef DEBUG
Serial.println(F("Reading and play progs"));
#endif
File root;
uint8_t currProg = 0;
uint8_t totalProgs = 0;
if( beginSD() ) {
root = openProgsRoot();
if( root ) {
File prog;
while( true ) {
prog = root.openNextFile();
if( prog ) {
prog.close();
totalProgs ++;
} else
break;
}
root.rewindDirectory();
volatile boolean repeatAllProgs = true;
volatile boolean nextProg = false;
boolean isMustBeFirstProg = true;
while( true ) {
if( checkForInterrupt() )
break;
gheartbeat();
if( repeatAllProgs || (!repeatAllProgs && !prog) || nextProg ) {
nextProg = false;
if( prog )
prog.close();
prog = root.openNextFile();
currProg ++;
if( !prog ) {
if( isMustBeFirstProg ) {
#ifdef DEBUG
Serial.println(F("Problem with SD?"));
#endif
stopAndShowError(SD_ERROR_WHILE_READING);
}
#ifdef DEBUG
Serial.println(F("Reopen SD, from 1st prog"));
#endif
root.close();
endSD();
if( !beginSD() )
stopAndShowError(CANNT_REBEGIN_SD);
root = openProgsRoot();
if( !root )
stopAndShowError(CANNT_REOPEN_ROOT);
currProg = 0;
isMustBeFirstProg = true;
repeatAllProgs = true;
continue;
}
isMustBeFirstProg = false;
} else {
if( !prog.seek(0) )
stopAndShowError(SD_ERROR_WHILE_SEEK);
}
#ifdef DEBUG
Serial.print(F("# Prog '"));
Serial.print(prog.name());
Serial.println(F("'"));
#endif
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" no data"));
#endif
prog.close();
continue;
}
displayPlay(currProg, totalProgs, prog.name(), !repeatAllProgs);
initButtons();
//
// read prog
//
uint8_t count, delayMsHi, delayMsLo, n, r, g, b;
uint16_t delayMs;
while( true ) {
if( checkForInterrupt() )
break;
if( !prog.available() ) {
#ifdef DEBUG
//Serial.println(F(" no more data"));
#endif
break;
}
//
// first byte, should be zero
//
uint8_t zero = prog.read();
if( zero != 0 ) {
#ifdef DEBUG
Serial.println(F(" PE01"));
#endif
stopAndShowError(PROG_FORMAT_ERROR);
}
//
// second byte, should be number of bulbs
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE02"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
count = prog.read();
if( count == 0 ) {
#ifdef DEBUG
Serial.println(F(" PE03"));
#endif
stopAndShowError(PROG_FORMAT_ERROR);
}
#ifdef DEBUG
//Serial.print(F(" bulbs "));
//Serial.println(count, DEC);
#endif
//
// third and fourth bytes, should be the delay
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE04"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
delayMsHi = prog.read();
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE05"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
delayMsLo = prog.read();
delayMs = delayMsHi << 8 | delayMsLo;
#ifdef DEBUG
//Serial.print(F(" delay "));
//Serial.println(delayMs, DEC);
#endif
volatile boolean frameOk = true;
volatile boolean breakProg = false;
//
// read frames
//
for(uint8_t i=0; i<count; i++) {
if( checkForButton() ) {
if( repeatAllProgs )
repeatAllProgs = false;
else
nextProg = true;
breakProg = true;
break;
}
//
// should be the number of bulb
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE06"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
n = prog.read();
//
// should be the red
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE07"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
r = prog.read();
//
// should be the green
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE08"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
g = prog.read();
//
// should be the blue
//
if( !prog.available() ) {
#ifdef DEBUG
Serial.println(F(" PE09"));
#endif
stopAndShowError(UNEXPECTED_END_OF_PROG);
}
b = prog.read();
#ifdef LED_GARLAND
garalandLeds[n].setRGB(r, g, b);
#endif
}
if( !breakProg ) {
#ifdef LED_GARLAND
FastLED.show();
#endif
gheartbeat();
delay(delayMs);
} else {
allBulbsOff();
break;
}
} // while( true ) // read prog
//prog.close();
deinitButtons();
} // while(true) // read progs recursively
if( prog )
prog.close();
deinitButtons();
allBulbsOff();
allLedsOff();
root.close();
} // if( root )
endSD();
} // if( beginSD() )
} // readAndPlayProgsRecursively()
| [
"aleksey@zholdak.com"
] | aleksey@zholdak.com |
d14e78b89fab554f5b583a605e40e5a04e211606 | 7771130ea6eb1f076a7d18e672d3d82d5996e957 | /src/qt/winshutdownmonitor.cpp | 81c6c853d960cd4816be31d2068b4a222fe10b51 | [
"MIT"
] | permissive | gdrcoin/gdrcoin | 49707508dfc1b14ace3817854416355a925539df | f9f2137b3d9069bfc8e3c69c90a684a061dfb6aa | refs/heads/master | 2020-03-10T18:01:49.563615 | 2018-04-14T12:36:52 | 2018-04-14T12:36:52 | 129,511,260 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,457 | cpp | // Copyright (c) 2014-2016 The Gdrcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "winshutdownmonitor.h"
#if defined(Q_OS_WIN) && QT_VERSION >= 0x050000
#include "init.h"
#include "util.h"
#include <windows.h>
#include <QDebug>
#include <openssl/rand.h>
// If we don't want a message to be processed by Qt, return true and set result to
// the value that the window procedure should return. Otherwise return false.
bool WinShutdownMonitor::nativeEventFilter(const QByteArray &eventType, void *pMessage, long *pnResult)
{
Q_UNUSED(eventType);
MSG *pMsg = static_cast<MSG *>(pMessage);
// Seed OpenSSL PRNG with Windows event data (e.g. mouse movements and other user interactions)
if (RAND_event(pMsg->message, pMsg->wParam, pMsg->lParam) == 0) {
// Warn only once as this is performance-critical
static bool warned = false;
if (!warned) {
LogPrintf("%s: OpenSSL RAND_event() failed to seed OpenSSL PRNG with enough data.\n", __func__);
warned = true;
}
}
switch(pMsg->message)
{
case WM_QUERYENDSESSION:
{
// Initiate a client shutdown after receiving a WM_QUERYENDSESSION and block
// Windows session end until we have finished client shutdown.
StartShutdown();
*pnResult = FALSE;
return true;
}
case WM_ENDSESSION:
{
*pnResult = FALSE;
return true;
}
}
return false;
}
void WinShutdownMonitor::registerShutdownBlockReason(const QString& strReason, const HWND& mainWinId)
{
typedef BOOL (WINAPI *PSHUTDOWNBRCREATE)(HWND, LPCWSTR);
PSHUTDOWNBRCREATE shutdownBRCreate = (PSHUTDOWNBRCREATE)GetProcAddress(GetModuleHandleA("User32.dll"), "ShutdownBlockReasonCreate");
if (shutdownBRCreate == nullptr) {
qWarning() << "registerShutdownBlockReason: GetProcAddress for ShutdownBlockReasonCreate failed";
return;
}
if (shutdownBRCreate(mainWinId, strReason.toStdWString().c_str()))
qWarning() << "registerShutdownBlockReason: Successfully registered: " + strReason;
else
qWarning() << "registerShutdownBlockReason: Failed to register: " + strReason;
}
#endif
| [
"37983255+spineinhalb@users.noreply.github.com"
] | 37983255+spineinhalb@users.noreply.github.com |
e863a920565d41d2b70ec8d94ad3766d4120fd28 | ad06b2e7544e0c67ff20a94b7be605f4cce6f6a9 | /reverse/reverse.cpp | 6890c086d8ca98b045d338c3e68301542e531b78 | [] | no_license | blackxhat24/clanguagevjudgepart2 | 379526c464556483bcbbc897320c047beee36d7d | 514c141b2804a00eaf39adb35b612347a2115498 | refs/heads/master | 2022-12-24T05:25:03.988734 | 2020-09-26T06:44:42 | 2020-09-26T06:44:42 | 298,753,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 369 | cpp | #include <stdio.h>
#include <string.h>
int main ()
{
int kasus;
int i,j;
char input[1000];
scanf("%d",&kasus);
for ( i = 1; i <= kasus ; i++ )
{
scanf("%s", input);
printf("Case #%d : ",i);
for (j = strlen(input)-1; j >=0 ; j--)
{
printf("%c", input[j]);
}
printf("\n");
}
return 0;
}
| [
"noreply@github.com"
] | blackxhat24.noreply@github.com |
b60140d2a3566bd53f7552d67f43b9dc05e6769e | 826c0537b0d11865ca5c67782f853cef950430cb | /JFEngine/WinMain.cpp | 07ed5edb39e8048a5461ea353065781d75e7fbac | [
"MIT"
] | permissive | jeffery1994/JFEngine | 1e0aa67fa761ab8698eacd8e94573f2f64a1806d | 76222e0c34f40088577506322a361cc822cf2591 | refs/heads/main | 2023-02-28T07:15:10.319921 | 2021-02-07T01:56:36 | 2021-02-07T01:56:36 | 335,144,597 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | cpp | /******************************************************************************************
* Chili Direct3D Engine *
* Copyright 2018 PlanetChili <http://www.planetchili.net> *
* *
* This file is part of Chili Direct3D Engine. *
* *
* Chili Direct3D Engine is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* The Chili Direct3D Engine 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 The Chili Direct3D Engine. If not, see <http://www.gnu.org/licenses/>. *
******************************************************************************************/
//#include "Window.h"
#include "App.h"
//int CALLBACK WinMain(
// HINSTANCE hInstance,
// HINSTANCE hPrevInstance,
// LPSTR lpCmdLine,
// int nCmdShow)
//{
// try
// {
// return App{}.Go();
// }
// catch (const ChiliException& e)
// {
// MessageBox(nullptr, e.what(), e.GetType(), MB_OK | MB_ICONEXCLAMATION);
// }
// catch (const std::exception& e)
// {
// return -1;
// MessageBox(nullptr, e.what(), "Standard Exception", MB_OK | MB_ICONEXCLAMATION);
// }
// catch (...)
// {
// MessageBox(nullptr, "No details available", "Unknown Exception", MB_OK | MB_ICONEXCLAMATION);
// }
// return -1;
//} | [
"xiaotabing1994@126.com"
] | xiaotabing1994@126.com |
057775b6eaffcb33b8f573921eefd752cf33fe7d | 6c8ab6c4680c08e707fe262ef6ef9c0de8e726dd | /miabot_commands.h | 52d49961a2e3d6ae4aac45ebe96ca90082e58dd5 | [] | no_license | drjosephbaxter/miabot-player | 934ee4866e1843bc9d3c74d9eb51cbf0729e23f5 | a494bcc447c15e18f322e15f8c05bc78c877f888 | refs/heads/main | 2023-04-30T21:20:02.683128 | 2021-05-08T09:26:32 | 2021-05-08T09:26:32 | 365,471,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,389 | h | /* miabot_commands.h
* Miabot Plugin for Player
* Copyright (C) - Joseph Baxter {joseph.lee.baxter@gmail.com}
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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
*
*/
#ifndef _MIABOT_COMMANDS_H
#define _MIABOT_COMMANDS_H
#include <string>
#include <libplayercore/playercore.h>
#include "miabot.h"
#include <bluetooth/bluetooth.h>
using namespace std;
void bluetooth_dongle(string bluetooth_mac);
void bluetooth(string bluetooth_router, string bluetooth_port);
int rfcomm_connect_dongle(bdaddr_t *src, bdaddr_t *dst, uint8_t channel);
int rfcomm_connect(string bluetooth_router, string bluetooth_port);
string hexbyte2str(int n);
string hexbyte2strB(int n);
int str2hexdig(char s);
int str2hexbyte(string s);
double ticks2m(int ticks);
int m2speed(double m);
int m2ticks(double m);
int deg2ticks(double d);
void stop();
void encoder();
void defaults();
int bin2int();
void seq(int f, int t, int r, bool b, bool l, bool forw);
int value2index(int value);
void stopped();
double time();
void p(int ping);
void rec();
void DoScan(player_miabot_data_t* d, int photodiode, int sonar, bool buffer);
void ToggleSonar(bool b, int ping);
void parseSonar();
void odom(string inp_odom);
void set_odometry(float m_x, float m_y, float rad_theta);
void ToggleOdom(bool b, int enc);
void updateOdom(player_miabot_data_t* d);
void HandlePositionCommand(player_position2d_cmd_vel_t position2d_cmd);
void HandlePositionCommand_pos(player_position2d_cmd_pos_t position2d_cmd);
void CloseGripper(int close_arg);
void OpenGripper(int open_arg);
void UpGripper(int up_arg);
void DownGripper(int down_arg);
void compass(player_miabot_data_t* d);
void updateGripper(player_miabot_data_t* d);
int rgb(int rmin, int rmax,int gmin, int gmax,int bmin, int bmax);
void blob(player_miabot_data_t* d);
void camTrack(int set_cam,int num_blobs, int redmin,int redmax, int redmin1,int redmax1, int redmin2,int redmax2,int redmin3,int redmax3, int redmin4,int redmax4, int redmin5,int redmax5,int redmin6,int redmax6, int redmin7,int redmax7, int greenmin,int greenmax, int greenmin1,int greenmax1,int greenmin2,int greenmax2, int greenmin3,int greenmax3, int greenmin4,int greenmax4,int greenmin5,int greenmax5, int greenmin6,int greenmax6, int greenmin7,int greenmax7, int bluemin,int bluemax,int bluemin1,int bluemax1, int bluemin2,int bluemax2, int bluemin3,int bluemax3,int bluemin4,int bluemax4, int bluemin5,int bluemax5, int bluemin6,int bluemax6,int bluemin7,int bluemax7);
void camStopTracking();
void parseBlob(string inp_blob);
void Track();
void camera_settings(int white,int adj,int filt);
void readData(int wait);
void voltage(string bluetooth_router, string bluetooth_port);
void TogglePill(bool set, int rate);
#endif
| [
"joseph.baxter@nottingham.ac.uk"
] | joseph.baxter@nottingham.ac.uk |
ca217f495a4fe5059c2f087cbf0c7eaa54176d7f | 221e8fd8c12d916a847af856ae0667dc14511833 | /CDrawTool.hpp | eadb7ea7db917f726980ec5af62988c9e5834421 | [] | no_license | LikeSnooker/Sokoban | 6cb47ad79a3bdd4021447752aa14a3dd199175b7 | a95eacaa2e9eea793a07e45daf889aa11ece338f | refs/heads/master | 2021-04-15T05:58:17.732477 | 2018-03-22T13:02:10 | 2018-03-22T13:02:10 | 126,334,920 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,930 | hpp | //
// CDrawer.hpp
// sokoban
//
// Created by 张雨 on 15/9/22.
// Copyright © 2015年 张雨. All rights reserved.
//
#ifndef CDrawTool_hpp
#define CDrawTool_hpp
#import <UIKit/UIKit.h>
#include <stdio.h>
#include "CSokoban.hpp"
#include "ISokobanDatasource.hpp"
#define MATH_PAI 3.1415926
//石板灰
#define WALL_COLOR [[UIColor colorWithRed:112/255.0 green:118/255.0 blue:144/255.0 alpha:1.0] CGColor]
#define BOX_COLOR [[UIColor colorWithRed:255/255.0 green:235/255.0 blue:205/255.0 alpha:1.0] CGColor]
#define TARGET_COLOR [[UIColor colorWithRed:2220/255.0 green:20/255.0 blue:60/255.0 alpha:1.0] CGColor]
#define FILL_COLOR [[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0] CGColor]
#define MAN_COLOR [[UIColor colorWithRed:218/255.0 green:165/255.0 blue:105/255.0 alpha:1.0] CGColor]
#define GUIDE_COLOR [[UIColor colorWithRed:220/255.0 green:220/255.0 blue:220/255.0 alpha:1.0] CGColor]
class CDrawTool
{
public:
static void DrawWall (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawBox (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawMan (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawTarget (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawBoxOnTarget(CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawFloor (CGContextRef _context ,CGRect _rect,bool _selectedStyle = false);
static void DrawCoordinate (CGContextRef _context ,CGRect _rect,int _row,int _line);
static void DrawGuide(CGContextRef _context,CGRect _rect);
private:
static float _lineWidth;
static void DrawEdge (CGContextRef _context ,CGRect _rect);
static void DrawSelectStyle(CGContextRef _context ,CGRect _rect);
};
#endif /* CDrawer_hpp */
| [
"yuzhang@yuzhangdeMacBook-Pro.local"
] | yuzhang@yuzhangdeMacBook-Pro.local |
6475f29292b925778d2be22d3660d1c44304e9f2 | c9b06761b0b43a5a06b765fed6a9b4f8e6c1f1d1 | /Lecture_24/graph.cpp | 8b7caa9cb4151fdd11522d37526ac4581779ee14 | [] | no_license | utkarshnath/Launchpad_Sept_18 | 5fba2eb69ffa380b46e198b1b9a27fa603e86909 | c4ec3c542d5c1e2b81741e62697608eeaa96982a | refs/heads/master | 2020-03-30T06:45:08.487753 | 2019-01-13T17:31:46 | 2019-01-13T17:31:46 | 150,886,207 | 10 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,735 | cpp | #include<iostream>
#include<list>
#include<queue>
#include<stack>
using namespace std;
class graph{
int V; // count of vertex
list<int>* l;
public:
graph(int v){
V = v;
l = new list<int> [v];
}
void addEdge(int u,int v, bool bidir = true){
l[u].push_back(v);
if(bidir){
l[v].push_back(u);
}
}
void bfs(int vertex){
//bool * visited = new bool[100];
bool visited[100] = {0};
for(int i=0;i<V;i++){
visited[i] = false;
}
queue<int> q;
q.push(vertex);
visited[vertex] = true;
while(!q.empty()){
int top = q.front();
q.pop();
cout<<top<<" ";
list<int>:: iterator it;
for(it=l[top].begin();it!=l[top].end();it++){
if(visited[*it]==false){
q.push(*it);
visited[*it] = true;
}
}
}
}
void bfsDist(int vertex){
bool visited[100] = {0};
int dist[100];
for(int i=0;i<V;i++){
dist[i] = INT_MAX;
}
queue<int> q;
q.push(vertex);
visited[vertex] = true;
dist[vertex] = 0;
while(!q.empty()){
int top = q.front();
q.pop();
list<int>::iterator it;
for(it =l[top].begin();it!=l[top].end();it++){
if(visited[*it]==false){
dist[*it] = dist[top] + 1;
q.push(*it);
visited[*it] = true;
}
}
}
}
void dfsDriver(int vertex,bool visited[100]){
if(visited[vertex]){
return;
}
cout<<vertex<<" ";
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
dfsDriver(*it,visited);
}
return;
}
void dfs(){
bool visited[100] = {0};
for(int i=0;i<V;i++){
dfsDriver(i,visited);
}
}
void topoDriver(int vertex,bool visited[100],stack<int>&s){
if(visited[vertex]){
return;
}
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
topoDriver(v,visited,s);
}
s.push(vertex);
}
void topologicalSort(){
bool visited[100] = {0};
stack<int>s;
for(int i=0;i<V;i++){
topoDriver(i,visited,s);
}
while(!s.empty()){
cout<<s.top();
s.pop();
}
}
bool cycleDriver(int vertex,bool visited[100],int parent){
if(visited[vertex]){
return true;
}
visited[vertex] = true;
list<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
if(v!=parent){
bool cycle = cycleDriver(v,visited,vertex);
if(cycle){
return true;
}
}
}
return false;
}
bool isCycle(){
bool visited[100] = {0};
for(int i=0;i<V;i++){
if(!visited[i]){
bool cycle = cycleDriver(i,visited,i);
if(cycle){
return true;
}
}
}
return false;
}
bool cycleDriverDir(int vertex,bool visited[]bool recstack[]){
if(visited[vertex]==false){
visited[vertex] = true;
recstack[vertex] = true;
ist<int>:: iterator it;
for(it=l[vertex].begin();it!=l[vertex].end();it++){
int v = *it;
if(!visited[v] && cycleDriverDir(v,visited,recstack)){
return true;
}
if(recstack[v]){
return true;
}
}
recstack[vertex] = false;
return false;
}
}
bool isCycleDir(){
bool visited[100] = {0};
bool recstack[100] = {0};
for(int i=0;i<V;i++){
if(cycleDriverDir(i,visited,recstack)){
return true;
}
}
return false;
}
void print(){
for(int i=0;i<V;i++){
cout<<i<<" => ";
list<int>:: iterator it;
for(it=l[i].begin();it!=l[i].end();it++){
cout<<*it<<" ";
}
cout<<endl;
}
}
};
int main(){
graph g(7);
g.addEdge(0,1,0);
g.addEdge(0,2,0);
g.addEdge(0,3,0);
g.addEdge(1,4,0);
g.addEdge(2,3,0);
g.addEdge(2,4,0);
g.addEdge(3,4,0);
g.addEdge(5,6,0);
g.topologicalSort();
//g.print();
}
| [
"nath.utkarsh1@gmail.com"
] | nath.utkarsh1@gmail.com |
d1f5ea87eaab3437224d192433b85776a38b69ed | 03e92eca1c566dc5621d70f6b9e700f7ea4fa04e | /core_war/jmz_command.cpp | 3e1f0d6352593a9d56ef684c5e7610415b589e9f | [] | no_license | ankutalev/16208_kutalev | 15610a5075bb9dd50c37998a06ce8ee5996e081e | e36ecdc14960175074bb0a6a62c31bddb77db1bf | refs/heads/master | 2021-09-16T07:19:36.850113 | 2018-06-18T12:35:01 | 2018-06-18T12:35:01 | 103,538,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,893 | cpp | #include "factory.hpp"
class Jmz_command : public Instruction {
public:
explicit Jmz_command(Modifiers x) { Fields.OpcodeMod = x;Name = "JMZ"; }
void Execution(ExecutionContext &Executor) override {
if (Fields.AOperandMod == Mods::Lattice &&
Fields.BOperandMod == Mods::Lattice) {
Fields.AOffset = Fields.AOperand;
Fields.BOffset = Fields.BOperand;
} else {
Executor.SetOffsets(Fields);
}
switch (Fields.OpcodeMod) {
case (Modifiers::A):
case (Modifiers::BA):
if (!Executor.getA(Fields.BOffset))
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
else
Executor.ForwardQueue();
break;
case (Modifiers::Not):
case (Modifiers::B):
case (Modifiers::AB):
if (!Executor.getB(Fields.BOffset)) {
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
std::cout << Executor.getCurrentWarriorName() << " jump to "
<< Executor.getCurrentAddress() << " address" << std::endl;
} else {
Executor.ForwardQueue();
std::cout << Executor.getCurrentWarriorName()
<< " will execute next command in "
<< Executor.getCurrentAddress() << " adress" << std::endl;
}
break;
case (Modifiers::I):
case (Modifiers::F):
case (Modifiers::X):
if (!Executor.getA(Fields.BOffset) && !Executor.getB(Fields.BOffset)) {
Executor.ChangeCurrentFlowAddress(Fields.AOffset);
std::cout << Executor.getCurrentWarriorName() << " jump to "
<< Executor.getCurrentAddress() << " address" << std::endl;
} else {
Executor.ForwardQueue();
std::cout << Executor.getCurrentWarriorName()
<< " will execute next command in "
<< Executor.getCurrentAddress() << " adress" << std::endl;
}
break;
}
}
Jmz_command *Clone() override { return new Jmz_command(*this); }
};
namespace {
Instruction *Jmzab() { return new Jmz_command(Modifiers::AB); }
Instruction *Jmzba() { return new Jmz_command(Modifiers::BA); }
Instruction *Jmzta() { return new Jmz_command(Modifiers::A); }
Instruction *Jmztb() { return new Jmz_command(Modifiers::B); }
Instruction *Jmztf() { return new Jmz_command(Modifiers::F); }
Instruction *Jmzx() { return new Jmz_command(Modifiers::X); }
Instruction *Jmzi() { return new Jmz_command(Modifiers::I); }
bool a = Factory::get_instance()->regist3r("JMZ.AB", &Jmzab);
bool b = Factory::get_instance()->regist3r("JMZ.BA", &Jmzba);
bool c = Factory::get_instance()->regist3r("JMZ.A", &Jmzta);
bool d = Factory::get_instance()->regist3r("JMZ.B", &Jmztb);
bool f = Factory::get_instance()->regist3r("JMZ.F", &Jmztf);
bool e = Factory::get_instance()->regist3r("JMZ.X", &Jmzx);
bool g = Factory::get_instance()->regist3r("JMZ.I", &Jmzi);
bool w = Factory::get_instance()->nameRegister("JMZ","JMZ");
} | [
"a.kutalev@g.nsu.ru"
] | a.kutalev@g.nsu.ru |
a6ddefdf8b515fca14e7dfed951471e6cc210849 | 0f5780cdf99c4b4568d8550f2bdfb3a1fa71126d | /src/FastDC.cpp | b678ed3f75c95c11225917ddcc5b9c3b0bc59310 | [] | no_license | lenoval/e | 3136e04e5cbfc140368f0ec32c6e500e9773d113 | 52f3c09282ddbf5c53fe75c1d4395a9bc134f52d | refs/heads/master | 2021-01-18T03:51:50.353760 | 2009-05-08T21:57:49 | 2009-05-08T21:57:49 | 196,945 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,092 | cpp | /*******************************************************************************
*
* Copyright (C) 2009, Alexander Stigsen, e-texteditor.com
*
* This software is licensed under the Open Company License as described
* in the file license.txt, which you should have received as part of this
* distribution. The terms are also available at http://opencompany.org/license.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
******************************************************************************/
#ifdef __WXMSW__
#pragma warning(disable:4786)
#endif
#include "FastDC.h"
void FastDC::SetFontStyles(int fontStyles, map<int,wxFont>& fontMap) {
const int fontStyle = (fontStyles & wxFONTFLAG_ITALIC) ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL;
const int fontWeight = (fontStyles & wxFONTFLAG_BOLD) ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL;
const bool fontUnderline = (fontStyles & wxFONTFLAG_UNDERLINED) ? true : false;
// Check if we need to change font style
// (changing the font can be expensive, so we want to avoid it if possible)
const bool styleChanged = (m_font.GetStyle() != fontStyle);
const bool widthChanged = (m_font.GetWeight() != fontWeight);
const bool underlineChanged = (m_font.GetUnderlined() != fontUnderline);
if (!styleChanged && !widthChanged && !underlineChanged) return;
// Check if we have font in cache
map<int,wxFont>::const_iterator p = fontMap.find(fontStyles);
if (p == fontMap.end()) {
m_font.SetStyle(fontStyle);
m_font.SetWeight(fontWeight);
m_font.SetUnderlined(fontUnderline);
fontMap[fontStyles] = m_font;
}
else m_font = p->second;
/*m_font.SetStyle(fontStyle);
m_font.SetWeight(fontWeight);
m_font.SetUnderlined(fontUnderline);*/
#ifdef __WXMSW__
HGDIOBJ hfont = ::SelectObject(GetHdc(), GetHfontOf(m_font));
if ( hfont == HGDI_ERROR )
{
wxLogLastError(_T("SelectObject(font)"));
}
else // selected ok
{
if ( !m_oldFont )
m_oldFont = (WXHPEN)hfont;
}
#else
SetFont(m_font);
#endif
}
| [
"stigsen@e-texteditor.com"
] | stigsen@e-texteditor.com |
eaca1e58dba15691e3f832fa2f00e4410820253e | 6b30258040708b6a691b0620d4aaa64e98d2e0d0 | /zjutOJ/倒置排序.cpp | 869b9df76327e30d4c58559f5cd5766e9e40d06d | [] | no_license | shenxs/ACM | 74e94b250b23468b1f88dcccf1c4ca9d55aa6937 | bea2ea559e1e3375cec3def59cab718a180db98e | refs/heads/master | 2020-05-09T21:22:57.880227 | 2019-12-22T14:43:42 | 2019-12-22T14:43:42 | 27,082,818 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,031 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<cmath>
#include<algorithm>
using namespace std;
bool bijiao(string s1,string s2)
{
string a1,a2,b1,b2;
a1=s1;
a2=s2;
reverse(a1.begin(),a1.end());
reverse(a2.begin(),a2.end());
string::iterator it;
for (it =a1.begin(); it != a1.end(); ++it)
{
if( *it == '0')
{
a1.erase(it);
}
if(*it!='0') break;
}
for (it =a2.begin(); it != a2.end(); ++it)
{
if( *it == '0')
{
a2.erase(it);
}
if(*it!='0') break;
}
if(a1.length()<a2.length()) return true;
else if(a1.length()==a2.length()&& a1<a2) return true;
else return false;
}
int main()
{
int n,m,a,e;
string s1;
vector<string>s;
for(;cin>>n;)
{
for(;n--;)
{
cin>>m;
a=m;
s.clear();
for(;m--;)
{
cin>>s1;
s.push_back(s1);
}
sort(s.begin(),s.end(),bijiao);
e=0;
for(;a--;e++)
{
if(a==0) cout<<s[e];
else cout<<s[e]<<' ';
}
cout<<endl;
}
cout<<endl;
}
return 0;
}
| [
"a247820400@gmail.com"
] | a247820400@gmail.com |
259e7d42c7270780d6c57abbe1c1514abbfc841d | 7c17e5606be4ad8d1785226deb3fe5677e04d099 | /stuff/urho3d/Source/Samples/00_ignition/relative_pose/_zzz/pioneer_src/ui/CellSpec.cpp | ed1ed360b6338523893f0394d24286020baca353 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | z80/ignition | a4fa4adb32fed843ee41bcdc83e41ba3d70f048b | 629c9d998d53de33f3b123910770f73c9e783234 | refs/heads/master | 2023-07-21T17:46:52.510964 | 2023-04-04T17:18:41 | 2023-04-04T17:18:41 | 206,724,558 | 14 | 3 | null | 2022-06-23T00:02:44 | 2019-09-06T06:06:22 | C++ | UTF-8 | C++ | false | false | 606 | cpp | // Copyright © 2008-2020 Pioneer Developers. See AUTHORS.txt for details
// Licensed under the terms of the GPL v3. See licenses/GPL-3.txt
#include "CellSpec.h"
#include "LuaObject.h"
namespace UI {
CellSpec CellSpec::FromLuaTable(lua_State *l, int idx)
{
const int table = lua_absindex(l, idx);
assert(lua_istable(l, table));
const int len = lua_rawlen(l, table);
std::vector<float> cellPercent(len);
for (int i = 0; i < len; i++) {
lua_rawgeti(l, table, i + 1);
cellPercent[i] = luaL_checknumber(l, -1);
lua_pop(l, 1);
}
return CellSpec(cellPercent);
}
} // namespace UI
| [
"bashkirov.sergey@gmail.com"
] | bashkirov.sergey@gmail.com |
b2430c30e5077303c504050cd1fa9b58fc506100 | ff5cc8a70efa3967b4d94932b9282d7152693a89 | /201903-3-损坏的RAID5.cpp | 3194ea382e603faf6419ddf50a19101e87e5ea23 | [] | no_license | WHUQFCC/CCF | 28b1956cadc41f91850631e2d204ea6ddd63112c | 9722df2d4bd772ead7bdb98ee2d368cae16cda7d | refs/heads/master | 2020-08-09T14:30:49.890757 | 2019-10-16T10:21:19 | 2019-10-16T10:21:19 | 214,107,365 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,780 | cpp | #include <iostream>
#include <string>
using namespace std;
typedef struct Disk
{
int disknum;
string content;
}Disk;
typedef struct
{
int disknum;
int posi;
}Block;
int n,s,l,m,disklenth;
Disk disk[1005];//用于存储存在的磁盘的磁盘号和该磁盘上的内容
int block[1005];//用于存储待查询的块的块号
Block getPosition(int blknum);//获取块在磁盘上的位置
int sixteenPower(int power);//计算16的power次幂
int hextoDec(char c);//将16进制字符c转化成十进制数字
int stringtoInt(string str);//将16进制字符串str转化成十进制整型数字
void print(int blknum);//打印块号为blknum的块的内容
int main()
{
std::ios::sync_with_stdio(false);
cin>>n>>s>>l;
for(int i=0;i<l;i++)//存现存的磁盘
{
cin>>disk[i].disknum;
cin>>disk[i].content;
}
disklenth=disk[0].content.size()/8;
cin>>m;
for(int i=0;i<m;i++)
cin>>block[i];
for(int i=0;i<m;i++)
print(block[i]);
return 0;
}
Block getPosition(int blknum)
{
int bandnum,diskn,pos,b;
bandnum=blknum/(s*(n-1));//该块所在的行号
b=blknum%(s*(n-1));
int db=n-1-bandnum%n;//db为一行中该行校验条带所在的磁盘号
int i=0;
diskn=(db+1+blknum%(s*(n-1))/s)%n;//该块所在的磁盘号
pos=bandnum*s+blknum%s;//该块在磁盘上的位置
Block block;
block.disknum=diskn;
block.posi=pos;
return block;
}
int sixteenPower(int power)
{
if(power==0)
return 1;
int res=1;
for(int i=0;i<power;i++)
res*=16;
return res;
}
int hextoDec(char c)
{
int ans;
switch(c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':ans=c-'0';break;
case 'a':
case 'A':ans=10;break;
case 'b':
case 'B':ans=11;break;
case 'c':
case 'C':ans=12;break;
case 'd':
case 'D':ans=13;break;
case 'e':
case 'E':ans=14;break;
case 'f':
case 'F':ans=15;break;
}
return ans;
}
int stringtoInt(string str)
{
int ans=0;
for(int i=str.size()-1,j=0;i>=0;i--,j++)//从低位到高位依次转化
ans+=hextoDec(str[i])*sixteenPower(j);
return ans;
}
void print(int blknum)
{
if(blknum>=disklenth*(n-1))//检验块号是否超过阵列的最大容量
{
cout<<"-"<<endl;
return;
}
Block bl=getPosition(blknum);
for(int j=0;j<l;j++)//检验该块是否存在于已知磁盘上
{
if(disk[j].disknum==bl.disknum)
{
string s=disk[j].content.substr(bl.posi*8,8);
cout<<s<<endl;
return;
}
}
if(n-1>l)//若不能推导出输出"-"
{
cout<<"-"<<endl;
return;
}
int res=0,b=0;
string str;
for(int i=0;i<l;i++)//可以推导出
{
str=disk[i].content.substr(bl.posi*8,8);
if(b==0)
{
b++;
res=stringtoInt(str);
continue;
}
res=res^stringtoInt(str);
}
cout<<hex<<uppercase<<res<<endl;
}
| [
"noreply@github.com"
] | WHUQFCC.noreply@github.com |
d3eea6e5469efd3c266df8b48a235bb05ed347e0 | 0f73c722e85ee23fcf7d276041a2dd3c2f8c36f4 | /helloworld.cpp | 8b998912ad8dcd8b0e7ee298a37f86763122c026 | [] | no_license | BohemianHacks/Programming-1 | 7be28c92c14464a9f1cdad144f22c9a8f541db57 | b83fdcb1770038fb0535b4a2dae18134e5fe4c45 | refs/heads/master | 2021-01-01T18:38:07.630437 | 2013-11-26T09:10:12 | 2013-11-26T09:10:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 269 | cpp | //Hello world program
//Built to introduce me to C++
//by Jeff Blecha
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void print(string words){
cout << words << endl;
}
int main(){
print("Hello World!");
cin.ignore();
return 0;
}
| [
"jeff.blecha@gmail.com"
] | jeff.blecha@gmail.com |
2e8245afa88bcc31394c90934f63b39a1b2bbda1 | eb7047d5a8c00d4370a55c2806a2f051287b452d | /modulesrc/topology/ReverseCuthillMcKee.i | 967c75b2e191b3e4eefa51f3bfd1b7518520188f | [
"MIT"
] | permissive | mousumiroy-unm/pylith | 8361a1c0fbcde99657fd3c4e88678a8b5fc8398b | 9a7b6b4ee8e1b89bc441bcedc5ed28a3318e2468 | refs/heads/main | 2023-05-27T18:40:57.145323 | 2021-06-09T19:32:19 | 2021-06-09T19:32:19 | 373,931,160 | 0 | 0 | MIT | 2021-06-04T18:40:09 | 2021-06-04T18:40:09 | null | UTF-8 | C++ | false | false | 1,242 | i | // -*- C++ -*-
//
// ======================================================================
//
// Brad T. Aagaard, U.S. Geological Survey
// Charles A. Williams, GNS Science
// Matthew G. Knepley, University of Chicago
//
// This code was developed as part of the Computational Infrastructure
// for Geodynamics (http://geodynamics.org).
//
// Copyright (c) 2010-2017 University of California, Davis
//
// See COPYING for license information.
//
// ======================================================================
//
/**
* @file modulesrc/topology/ReverseCuthillMcKee.hh
*
* @brief Python interface to C++ PyLith ReverseCuthillMcKee object.
*/
namespace pylith {
namespace topology {
// ReverseCuthillMcKee ----------------------------------------------
class ReverseCuthillMcKee
{ // ReverseCuthillMcKee
// PUBLIC METHODS /////////////////////////////////////////////////
public :
/** Reorder vertices and cells of mesh using PETSc routines
* implementing reverse Cuthill-McKee algorithm.
*
* @param mesh PyLith finite-element mesh.
*/
static
void reorder(topology::Mesh* mesh);
}; // ReverseCuthillMcKee
} // topology
} // pylith
// End of file
| [
"baagaard@usgs.gov"
] | baagaard@usgs.gov |
c05148e7073ac569d389bd0b137c72ab87718d62 | fcc4e5e6c7ade243bd9fce6a3b7561a4d262e206 | /pwmLight/pwmLight.ino | a74d1df77a36fc12269f4658cf2cbb605eb0fd57 | [] | no_license | brucetsao/arduino_Programming | 48fd7e4e93035107fd46eb036161441a42030dcc | fbd44a0ba59fa4002d0879d7ad4182524894619b | refs/heads/master | 2021-01-15T16:17:34.427866 | 2015-06-29T05:17:49 | 2015-06-29T05:17:49 | 29,160,262 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 587 | ino | int val;//定義變數val
int ledpin=8 ;//定義Led pin8
int potpin=1;//定義可便電組類比介面0
void setup()
{
Serial.begin(9600);//設置串列傳輸速率為9600
pinMode(ledpin,OUTPUT);
//設置數位接腳13為輸出介面,Arduino 上我們用到的I/O 口都要進行類似這樣的定義。
}
void loop()
{
val=analogRead(potpin);// 讀取感測器的模擬值並賦值給val
Serial.println(val);//顯示val 變數
analogWrite(ledpin,map(val,0,1023,0,255));// 打開LED 並設置亮度(PWM 輸__________出最大值255)
delay(10);//延時0.01 秒
}
| [
"prgbruce@gmail.com"
] | prgbruce@gmail.com |
a5d6724daac9d9f8b6bce9c20ee54a937a6c9f54 | a211bff67d4a1904cd1268ede8cdd5bad519d7a1 | /src/frameworks/naiad_dispatcher.cc | 8ca517cc6bacd0f0bbf8c84edb89b870659ec630 | [
"Apache-2.0"
] | permissive | ingomueller-net/Musketeer | c00144b45c35980979149cc4f41922588b92277a | 3ed41d93b0a61f00aa8a0b8ec084973b20956b3d | refs/heads/master | 2020-04-03T15:24:28.385684 | 2018-10-30T09:49:13 | 2018-10-30T09:49:13 | 155,361,431 | 0 | 0 | Apache-2.0 | 2018-10-30T09:51:29 | 2018-10-30T09:51:28 | null | UTF-8 | C++ | false | false | 2,327 | cc | // Copyright (c) 2015 Ionel Gog <ionel.gog@cl.cam.ac.uk>
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR
* A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
#include "frameworks/naiad_dispatcher.h"
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
#include "base/common.h"
#include "base/flags.h"
namespace musketeer {
NaiadDispatcher::NaiadDispatcher() {
}
void NaiadDispatcher::Execute(string job_path, string job_options) {
LOG(INFO) << "naiad run started for: " << job_path;
LOG(INFO) << "naiad copy input started for: " << job_path;
string copy_input_cmd = "parallel-ssh -h " + FLAGS_naiad_hosts_file +
" -t 10000 -p 100 -i 'START_TIME=`date +%s` ; sh " +
FLAGS_generated_code_dir + "Musketeer/hdfs_get.sh ; END_TIME=`date +%s` ; " +
"PULL_TIME=`expr $END_TIME - $START_TIME` ; echo \"PULLING DATA: \"$PULL_TIME'";
system(copy_input_cmd.c_str());
LOG(INFO) << "naiad copy input ended for: " << job_path;
string run_cmd = "parallel-ssh -h " + FLAGS_naiad_hosts_file +
" -t 10000 -p 100 -i 'PROCID=`" + FLAGS_generated_code_dir +
"Musketeer/get_proc_id.sh` ; cd " + FLAGS_generated_code_dir + " ; mono-sgen " +
job_path + " -p $PROCID -n " +
boost::lexical_cast<string>(FLAGS_naiad_num_workers) + " -t " +
boost::lexical_cast<string>(FLAGS_naiad_num_threads) + " -h @" +
FLAGS_naiad_hosts_file +
" --inlineserializer ; START_TIME=`date +%s` ; sh Musketeer/hdfs_put.sh ; " +
"END_TIME=`date +%s` ; PUSH_TIME=`expr $END_TIME - $START_TIME` ; " +
"echo \"PUSHING DATA: \"$PUSH_TIME'";
LOG(INFO) << "Running: " << run_cmd;
system(run_cmd.c_str());
LOG(INFO) << "naiad run ended for: " << job_path;
}
} // namespace musketeer
| [
"gogionel@gmail.com"
] | gogionel@gmail.com |
0a82745e7632c6585929b0be613f491880aa56c5 | 5a1fddd1b5b317476d280b4536c5f38a7b1c1b9e | /ThunderFox/ThunderFox/TFGizmo.h | c65682a670f8c48840af2f009aff6ab09401c6f3 | [] | no_license | o-tantk/ThunderfoxEngine | 0c991fcb8b675f4f9d1620fb78bf6f7ddaef3840 | 7504d05faab8f4bc718d7d2951978b464279322f | refs/heads/master | 2021-01-15T09:42:41.904444 | 2016-05-06T20:46:04 | 2016-05-06T20:46:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,351 | h | #ifndef _TFGIZMO_H_
#define _TFGIZMO_H_
#include "gl\glew.h"
#include "glm\glm.hpp"
#include "TFShader.h"
#include "TFHandle.h"
#include <vector>
struct GizmoPoint{
glm::vec3 vertex;
glm::vec3 color;
};
enum {
MAX_GIZMO_LINES = 100,
MAX_GIZMO_POINTS = 100,
};
//class TFGizmo{
//private:
// TFGizmo(TFGizmo const&);
// void operator = (TFGizmo const&);
//
// static std::vector<TFGizmo *> m_instances;
//protected:
// TFGizmo(){
// m_instances.push_back(this);
// }
//
// virtual void drawGizmo() = 0;
//public:
// static void draw(){
//
// }
//};
class TFGizmo{
private:
GLuint m_vertexBuffer;
GizmoPoint m_lines[MAX_GIZMO_LINES];
GizmoPoint m_points[MAX_GIZMO_POINTS];
int m_lineCount, m_pointCount;
public:
TFGizmo() {
glGenBuffers(1, &m_vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
int sss = sizeof(m_lines);
glBufferData(GL_ARRAY_BUFFER, sizeof(m_lines), nullptr, GL_DYNAMIC_DRAW);
m_lineCount = 0;
m_pointCount = 0;
}
~TFGizmo(){
glDeleteBuffers(1, &m_vertexBuffer);
}
void drawLine(glm::vec3 color, glm::vec3 p1, glm::vec3 p2){
//m_lines.push_back({ p1, color });
//m_lines.push_back({ p2, color });
if (m_lineCount == MAX_GIZMO_LINES - 1){
return;
}
m_lines[m_lineCount++] = { p1, color };
m_lines[m_lineCount++] = { p2, color };
}
void drawPoint(glm::vec3 color, glm::vec3 p){
if (m_pointCount == MAX_GIZMO_POINTS - 1){
return;
}
m_points[m_pointCount++] = { p, color };
}
void flush(){
glBindBuffer(GL_ARRAY_BUFFER, m_vertexBuffer);
GLvoid *vbo_buffer = glMapBuffer(GL_ARRAY_BUFFER, GL_WRITE_ONLY);
memcpy(vbo_buffer, m_lines, m_lineCount * sizeof(GizmoPoint));
glUnmapBuffer(GL_ARRAY_BUFFER);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(glm::vec3), (void *)0);
TFHandle::checkOpenGL(__FILE__, __LINE__);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 2 * sizeof(glm::vec3), (void *)(sizeof(glm::vec3)));
TFHandle::checkOpenGL(__FILE__, __LINE__);
TFHandle::checkOpenGL(__FILE__, __LINE__);
//glDrawArrays(GL_LINES, 0, m_lines.size() * 6);
glDrawArrays(GL_LINES, 0, 6 * m_lineCount);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
TFHandle::checkOpenGL(__FILE__, __LINE__);
m_lineCount = 0;
m_pointCount = 0;
}
};
#endif | [
"tantk90@hotmail.com"
] | tantk90@hotmail.com |
9349fc19bf2ddc311d41c401928c01e3bb7c0ee7 | de24652a9c94a974c92eb6cca1edcf04f465aa4f | /Ground.h | 8877f20e7518f868b219e5ba231dc0ca883968ef | [] | no_license | dencorg/Robot_vehicles_simulation | abbc9ee4f3525d71c0a2f3d2fd6189e9ce74baa5 | 062d9a3652731be6b67f441748758083cf822970 | refs/heads/master | 2020-06-08T00:34:25.716584 | 2015-06-10T19:25:10 | 2015-06-10T19:25:10 | 37,216,968 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,393 | h | #ifndef GROUND_H
#define GROUND_H
#include <iostream>
#include <cstdlib>
// class gia ena simeio sto edafos tou kosmou
class Ground {
private:
int ground_units; // monades sto edafos
// periektikotites sistatikwn
float palladio_content;
float iridio_content;
float leukoxriso_content;
// monades gia kathe sistatiko
int palladio_units;
int iridio_units;
int leukoxriso_units;
float access_danger; // epikindinotita prosvasis
bool flag; // simaia kindinou
bool base; // true an to simeio einai i basi
public:
// constructor
Ground();
// dwse tis posotites twn sistatikwn sto edafos
int getpalladiounits();
int getiridiounits();
int getleukoxrisounits();
// dwse tis periektikotites sistatikwn
float get_palladio_content();
float get_iridio_content();
float get_leukoxriso_content();
// thetoun tis posotites sistatikwn sto edafos
void setpalladiounits(int);
void setiridiounits(int);
void setleukoxrisounits(int);
float getaccessdanger(); // epistrefei tin epikindinotita
bool hasflag(); // true an ehei simaia kindinou
bool isbase(); // true an to simeio einai vasi
void info(); // plirofories gia to simeio sto edafos
// thetei simaia kindinou
void setflag();
// kanei to simeio vasi gia tin eksomoiwsi
void setbase();
};
#endif | [
"dencorg@gmail.com"
] | dencorg@gmail.com |
36bc23cfe57e99bc71a6b87be592b4eab5034627 | 3f0f439d57f2185cb484f8faad78d49bab648627 | /external/rocksdb/table/iter_heap.h | 763d5f98c1eb1f44d00f3d5843e9032874e8c1b1 | [
"Apache-2.0",
"BSD-3-Clause",
"GPL-2.0-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | b2n-project/bitcoin2network | f0f0d8c67e901004c9def6b39906c9edbc241554 | 0861d44ca8efd2c34c63acabe5468a094593d25d | refs/heads/master | 2020-03-18T04:40:53.034521 | 2019-02-16T07:32:31 | 2019-02-16T07:32:31 | 134,300,206 | 0 | 7 | MIT | 2019-02-16T07:32:32 | 2018-05-21T17:09:54 | C++ | UTF-8 | C++ | false | false | 1,273 | h | // Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under both the GPLv2 (found in the
// COPYING file in the root directory) and Apache 2.0 License
// (found in the LICENSE.Apache file in the root directory).
//
#pragma once
#include "rocksdb/comparator.h"
#include "table/iterator_wrapper.h"
namespace rocksdb {
// When used with std::priority_queue, this comparison functor puts the
// iterator with the max/largest key on top.
class MaxIteratorComparator {
public:
MaxIteratorComparator(const Comparator* comparator) :
comparator_(comparator) {}
bool operator()(IteratorWrapper* a, IteratorWrapper* b) const {
return comparator_->Compare(a->key(), b->key()) < 0;
}
private:
const Comparator* comparator_;
};
// When used with std::priority_queue, this comparison functor puts the
// iterator with the min/smallest key on top.
class MinIteratorComparator {
public:
MinIteratorComparator(const Comparator* comparator) :
comparator_(comparator) {}
bool operator()(IteratorWrapper* a, IteratorWrapper* b) const {
return comparator_->Compare(a->key(), b->key()) > 0;
}
private:
const Comparator* comparator_;
};
} // namespace rocksdb
| [
"devs@bitcoin2.network"
] | devs@bitcoin2.network |
d15887d1919604162b8b9c4b7df627706d68d7af | d1ad68da0d7d3a71c2d43d297d6fd3cffbbf75c2 | /yukicoder/430/AhoCrasick.cpp | f452b37c607638e5372f475f20d7d9d5813ab3ec | [] | no_license | hamko/procon | 2a0a685b88a69951be7a9217dd32955f9500df57 | a822f8089a3063a158d47ea48c54aca89934f855 | refs/heads/master | 2021-01-17T00:00:10.915298 | 2020-02-24T06:24:33 | 2020-02-24T06:24:33 | 55,990,248 | 7 | 1 | null | 2020-02-24T06:24:34 | 2016-04-11T16:49:50 | C++ | UTF-8 | C++ | false | false | 10,267 | cpp | #include <bits/stdc++.h>
#include <sys/time.h>
using namespace std;
#define rep(i,n) for(long long i = 0; i < (long long)(n); i++)
#define repi(i,a,b) for(long long i = (long long)(a); i < (long long)(b); i++)
#define pb push_back
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second
#define mt make_tuple
#define mp make_pair
template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); }
template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
#define exists find_if
#define forall all_of
using ll = long long; using vll = vector<ll>; using vvll = vector<vll>; using P = pair<ll, ll>;
using ld = long double; using vld = vector<ld>;
using vi = vector<int>; using vvi = vector<vi>; vll conv(vi& v) { vll r(v.size()); rep(i, v.size()) r[i] = v[i]; return r; }
using Pos = complex<double>;
template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) { o << "(" << v.first << ", " << v.second << ")"; return o; }
template<size_t...> struct seq{}; template<size_t N, size_t... Is> struct gen_seq : gen_seq<N-1, N-1, Is...>{}; template<size_t... Is> struct gen_seq<0, Is...> : seq<Is...>{};
template<class Ch, class Tr, class Tuple, size_t... Is>
void print_tuple(basic_ostream<Ch,Tr>& os, Tuple const& t, seq<Is...>){ using s = int[]; (void)s{0, (void(os << (Is == 0? "" : ", ") << get<Is>(t)), 0)...}; }
template<class Ch, class Tr, class... Args>
auto operator<<(basic_ostream<Ch, Tr>& os, tuple<Args...> const& t) -> basic_ostream<Ch, Tr>& { os << "("; print_tuple(os, t, gen_seq<sizeof...(Args)>()); return os << ")"; }
ostream &operator<<(ostream &o, const vvll &v) { rep(i, v.size()) { rep(j, v[i].size()) o << v[i][j] << " "; o << endl; } return o; }
template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { o << '['; rep(i, v.size()) o << v[i] << (i != v.size()-1 ? ", " : ""); o << "]"; return o; }
template <typename T> ostream &operator<<(ostream &o, const set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T> ostream &operator<<(ostream &o, const unordered_set<T> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T, typename U> ostream &operator<<(ostream &o, const map<T, U> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it << (next(it) != m.end() ? ", " : ""); o << "]"; return o; }
template <typename T, typename U, typename V> ostream &operator<<(ostream &o, const unordered_map<T, U, V> &m) { o << '['; for (auto it = m.begin(); it != m.end(); it++) o << *it; o << "]"; return o; }
vector<int> range(const int x, const int y) { vector<int> v(y - x + 1); iota(v.begin(), v.end(), x); return v; }
template <typename T> istream& operator>>(istream& i, vector<T>& o) { rep(j, o.size()) i >> o[j]; return i;}
string bits_to_string(ll input, ll n=64) { string s; rep(i, n) s += '0' + !!(input & (1ll << i)); reverse(all(s)); return s; }
template <typename T> unordered_map<T, ll> counter(vector<T> vec){unordered_map<T, ll> ret; for (auto&& x : vec) ret[x]++; return ret;};
string substr(string s, P x) {return s.substr(x.fi, x.se - x.fi); }
struct ci : public iterator<forward_iterator_tag, ll> { ll n; ci(const ll n) : n(n) { } bool operator==(const ci& x) { return n == x.n; } bool operator!=(const ci& x) { return !(*this == x); } ci &operator++() { n++; return *this; } ll operator*() const { return n; } };
size_t random_seed; namespace std { using argument_type = P; template<> struct hash<argument_type> { size_t operator()(argument_type const& x) const { size_t seed = random_seed; seed ^= hash<ll>{}(x.fi); seed ^= (hash<ll>{}(x.se) << 1); return seed; } }; }; // hash for various class
namespace myhash{ const int Bsizes[]={3,9,13,17,21,25,29,33,37,41,45,49,53,57,61,65,69,73,77,81}; const int xor_nums[]={0x100007d1,0x5ff049c9,0x14560859,0x07087fef,0x3e277d49,0x4dba1f17,0x709c5988,0x05904258,0x1aa71872,0x238819b3,0x7b002bb7,0x1cf91302,0x0012290a,0x1083576b,0x76473e49,0x3d86295b,0x20536814,0x08634f4d,0x115405e8,0x0e6359f2}; const int hash_key=xor_nums[rand()%20]; const int mod_key=xor_nums[rand()%20]; template <typename T> struct myhash{ std::size_t operator()(const T& val) const { return (hash<T>{}(val)%mod_key)^hash_key; } }; };
template <typename T> class uset:public std::unordered_set<T,myhash::myhash<T>> { using SET=std::unordered_set<T,myhash::myhash<T>>; public: uset():SET(){SET::rehash(myhash::Bsizes[rand()%20]);} };
template <typename T,typename U> class umap:public std::unordered_map<T,U,myhash::myhash<T>> { public: using MAP=std::unordered_map<T,U,myhash::myhash<T>>; umap():MAP(){MAP::rehash(myhash::Bsizes[rand()%20]);} };
struct timeval start; double sec() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec - start.tv_sec) + (tv.tv_usec - start.tv_usec) * 1e-6; }
struct init_{init_(){ gettimeofday(&start, NULL); ios::sync_with_stdio(false); cin.tie(0); srand((unsigned int)time(NULL)); random_seed = RAND_MAX / 2 + rand() / 2; }} init__;
static const double EPS = 1e-14;
static const long long INF = 1e18;
static const long long mo = 1e9+7;
#define ldout fixed << setprecision(40)
// 簡単な挙動
//
// (a)
// p = transite(p, c)
// cが成功なら p = p->next[c]
// cが失敗なら p = p->p[fail]->next[c]
//
// (b)
// 各pで、マッチングしている辞書番号集合が保持されている。
//
// (c)
// 複数マッチング。"aaaa"には"aa"が3回マッチングする。
// もしcoveringマッチングにしたいなら、マッチングするノードの失敗辺を全てrootに張り替えれば良い
const int fail = 0;
// パターンマッチングの頂点
// 256個の子を持つ多分木
struct pma {
// trie木では、非0ならば遷移可能
//
// Aho-Crasickでは、
// next[0]が、failure辺として特別扱いとなる。fail = 0である。
// (1) thisがrootなら、next[fail]はNULLとなる。
// (2) thisがrootでないなら、next[fail]は失敗辺の行き先となる。
//
// next[i]は、rootの時のみ特別扱いとなる。
// (3) thisがrootなら、next[i]がない時は自己ループになる。
pma* next[256] = {};
unordered_set<ll> matched; // 正にこの頂点を表す文字列パターンの集合(昇順)
pma() {}
~pma() { rep(i, 256) if (next[i]) delete next[i]; }
};
unordered_map<pma*, ll> name; // ネームサーバ
// rootに文字列sをパターンsiとして登録する。
void add(pma* root, string& s, ll si) {
pma* now = root;
for (int c : s) {
if (!now->next[c]) {
now->next[c] = new pma;
ll name_size = name.size(); name[now->next[c]] = name_size; // for name server
}
now = now->next[c];
}
now->matched.insert(si);
}
// パターン集合pによってtrie木を構築する。
pma* buildTrie(vector<string> p) {
name.clear();
pma* root = new pma;
name[root] = 0; // for name server
ll pn = p.size();
rep(si, pn)
add(root, p[si], si);
return root;
}
// 今のTrie木に対して、AhoCrasickによって失敗辺を構築する。
//
// 頂点iのマッチング失敗辺failure(i)を既知とする。
//
// この時、頂点iの次の頂点j=goto(i, c)での失敗辺は、
// cで遷移可能になるまで戻る関数failure(i)に対して、goto(failure(i), c)である。
void buildAhoCrasick(pma* root) {
queue<pma*> q;
// rootの失敗辺と、rootに直接つながっている成功辺の失敗辺の初期化
repi(i, 1, 256)
if (root->next[i])
root->next[i]->next[fail] = root, q.push(root->next[i]); // rootの直後で失敗したらrootに戻る
else
root->next[i] = root; // (3)
while (q.size()) {
auto now = q.front(); q.pop();
// 以下が(2)
repi(i, 1, 256) if (now->next[i]) {
// iでの遷移が成功するところまで、失敗辺をたどってから進んだところが、新たな失敗辺
auto now_f = now->next[fail];
while (!now_f->next[i]) now_f = now_f->next[fail];
now->next[i]->next[fail] = now_f->next[i];
for (auto x : now_f->next[i]->matched) // 失敗辺の先のマッチングを継承する。パターンが互いに含まないなら不要
now->next[i]->matched.insert(x);
q.push(now->next[i]);
}
}
}
// Aho-Corasickをcoveringマッチングにする
// 破壊的
//
// 内部でやってることは、マッチングするノードの失敗辺を全てrootに張り替えている
void changeToCoveringMode(pma* root) {
unordered_set<pma*> memo;
function<void(pma*)> f = [&](pma* p) {
if (memo.count(p)) return;
memo.insert(p);
if (p->matched.size())
p->next[0] = root;
rep(i, 256) if (p->next[i]) {
f(p->next[i]);
}
};
f(root);
}
// 頂点pから遷移cによって、次の頂点へと遷移する。
// 1回の遷移によるマッチング増加は、transite(p, c)->matchingによって計算できる。
pma* transite(pma* p, int c) {
while (!p->next[c]) p = p->next[fail];
p = p->next[c];
return p;
}
// AhoCrasick pを構築したパターンが、sに何個入っているかをresに副作用で返す。
// 注意!!これはデフォルトで複数マッチング。coveringマッチングにしたいなら、changeToCoveringMode(root)を読ぶこと。
void match(pma* &p, string s, vll& res) {
rep(i, s.length()) {
p = transite(p, s[i]);
for (auto x : p->matched)
res[x]++;
}
}
int main(void) {
string s; cin >> s;
ll n; cin >> n;
vector<string> dict;
rep(i, n) {
string tmp; cin >> tmp;
dict.pb(tmp);
}
auto root = buildTrie(dict);
buildAhoCrasick(root);
vll res(dict.size());
match(root, s, res); // 重複マッチングで何個ある?
cout << accumulate(all(res), 0ll) << endl;
return 0;
}
| [
"wakataberyo@gmail.com"
] | wakataberyo@gmail.com |
0080998542d6451528769c360f09fcbca1af9499 | 93c66e44e6ae7e654aefc42cad10706a44aa2377 | /concurrency/then_19_25_2_2_1.cpp | d4b9b9e975246387c487e2f1502c1e1a04f05b11 | [] | no_license | dcampora/cpp11 | 11a61227522baa5d83a8f0d81300c84553a923ca | db3e2830d2eed370134e6d25193d0f22e8dbd605 | refs/heads/master | 2020-05-17T18:38:38.325947 | 2016-01-20T08:47:41 | 2016-01-20T08:47:41 | 32,726,789 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,638 | cpp | #include <iostream> // cout, endl
#include <future> // async, future
#include <thread> // thread, sleep_for
#include <vector> // vector
#include <random> // random_device, uniform_int_distribution
#include <chrono> // chrono (system_clock, sleep_for)
#include <utility> // declval
using std::cout; using std::endl;
//////////////////////////////////////////////////////////////////////////////////
// Some very important work that needs to be done. //
// Do not change the code in this box. //
void work(int t) { std::this_thread::sleep_for(std::chrono::milliseconds(t)); } //
//
int work_hard(int n) { //
std::random_device rd; //
std::uniform_int_distribution<int> choose(0, n); //
int m = choose(rd); //
work(m); //
return n - m; //
} //
//
int step_1(int n) { return work_hard(n); } //
int step_2(int n) { return work_hard(n); } //
int step_3(int n) { return work_hard(n); } //
int step_4(int n) { return work_hard(n); } //
int step_5(int n) { return work_hard(n); } //
int step_F(int n) { //
// Ensure that all remaining work is done //
int m = n; //
work(m); //
return n - m; //
} //
//////////////////////////////////////////////////////////////////////////////////
template <typename Future, typename Continuation>
auto then(Future f, Continuation continue_) -> std::future<decltype(continue_(f.get()))> {
return async(std::launch::async,
// In C++1y, [f = std::move(f)] should work
[continue_] (Future f) { return continue_(f.get()); },
std::move(f) ); // Faking capture by move
}
int main() {
int how_many = 10;
auto job_size = 300;
std::vector<int> jobs(how_many, job_size);
auto start = std::chrono::system_clock::now();
{
std::vector<std::future<void>> fs;
fs.reserve(how_many);
for (auto job: jobs) {
auto f1 = std::async(std::launch::async, step_1, job);
auto f2 = then(std::move(f1), step_2);
auto f3 = then(std::move(f2), step_3);
auto f4 = then(std::move(f3), step_4);
auto f5 = then(std::move(f4), step_5);
auto fF = then(std::move(f5), step_F);
fs.push_back(then(std::move(fF), [] (int r) { cout << "Remaining = " << r << endl; }));
}
}
auto stop = std::chrono::system_clock::now();
cout << "Completed in "
<< std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count()/1000.0
<< "s\n";
} | [
"danielcampora@gmail.com"
] | danielcampora@gmail.com |
b633310855d8a04618da56f3c99e1bf19d349331 | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/External (Offsets Only)/SDK/BP_FishingFish_StormFish_03_Colour_03_Wild_classes.h | 91b01995a131cfbf7464aedf26c2d17f31890fb4 | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 955 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_FishingFish_StormFish_03_Colour_03_Wild.BP_FishingFish_StormFish_03_Colour_03_Wild_C
// 0x0000 (FullSize[0x0910] - InheritedSize[0x0910])
class ABP_FishingFish_StormFish_03_Colour_03_Wild_C : public ABP_FishingFish_StormFish_03_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_FishingFish_StormFish_03_Colour_03_Wild.BP_FishingFish_StormFish_03_Colour_03_Wild_C");
return ptr;
}
void UserConstructionScript();
void AfterRead();
void BeforeDelete();
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
adbcb47923beed921e909cf617eccb56dbdd3fd1 | 6fc9a543ab23fb8d1253f7d073d864f41c2b9067 | /src/controller/ShowController.cpp | dc286e212c260c04e19f3143a837a286217ad5e4 | [] | no_license | MarcoCaballero/klondike-cpp | 73fa7e5c4a3974f47500259e9f1bb988202fd72c | 3b3a6acc5851c5fbe2cc86401951f7f9e3653189 | refs/heads/master | 2021-05-07T15:06:16.858655 | 2017-11-16T07:48:19 | 2017-11-16T07:48:19 | 109,833,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 132 | cpp | #include <controller/ShowController.h>
namespace controller {
ShowController::~ShowController() {
}
} /* namespace controller */
| [
"marco.caballero.d@gmail.com"
] | marco.caballero.d@gmail.com |
eb24ba0a471d8cd6bc0fb0d6e0592a0c7d0c9131 | fa7a76c7646ced5f8ffbd009d4a21f05e187495a | /Live Archive/Live Archive/Triangle.cpp | fb5e05190cdb4e523b2510b9aaadbbdcfc827dac | [] | no_license | osama-afifi/Online-Judges-Solutions | 5273018f8373f377b9dafa85521c97beaa6574a0 | f49130f8ccbe8abc062f1b51a204edb819699b3a | refs/heads/master | 2021-01-10T19:54:34.488053 | 2015-04-23T21:42:54 | 2015-04-23T21:42:54 | 21,754,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,240 | cpp | //// NOT AC YET
//
//#include <vector>
//#include <list>
//#include <map>
//#include <set>
//#include <queue>
//#include <deque>
//#include <stack>
//#include <bitset>
//#include <algorithm>
//#include <functional>
//#include <numeric>
//#include <utility>
//#include <sstream>
//#include <iostream>
//#include <iomanip>
//#include <cstdio>
//#include <cmath>
//#include <cstdlib>
//#include <ctime>
//#include <cstring>
//
//using namespace std;
//#define FOR(i, a, b) for( int i = (a); i < (b); i++ )
//#define Fore(it, x) for(typeof (x.begin()) it = x.begin(); it != x.end (); it++)
//#define Set(a, s) memset(a, s, sizeof (a))
//#define mp make_pair
//
//long long M = 1000000007;
//inline long long app(double x)
//{
// if(abs(x-floor(x))>=abs(x-ceil(x)))
// return (long long)ceil(x);
// return (long long)floor(x);
//}
//
//inline int long long F(long long n)
//{
// if(n&1LL)
// app((double)((n+3.0)*(n+3.0))/48.0);
// else
// app((double)(n*n)/48.0);
//}
//
//
//int main()
//{
// freopen("input.in","r",stdin);
//
// int n;
// string text;
// int kase=0;
// while(cin>>n)
// {
// long long res=0;
// FOR(i,3,n+1)
// if(n%i==0)
// {
// long long x= F(i);
// long long z = n/i;
//
// }
// }
//
// return 0;
//} | [
"osama.egt@gmail.com"
] | osama.egt@gmail.com |
eb391b455196a087f01e6cdf0a28a94241988aab | 70f8491a27470287090d3c2be061d5fce23f07a9 | /algorithms/p397/397.hpp | 5464a0998ca1bb21d9942a15724a940f824e2900 | [
"Apache-2.0"
] | permissive | baishuai/leetcode | 44094a91e95c0557394cf15324008f79fc2d6688 | 440ff08cf15e03ee64b3aa18370af1f75e958d18 | refs/heads/master | 2021-09-01T01:02:33.335046 | 2017-12-24T01:01:47 | 2017-12-24T01:01:47 | 84,698,557 | 10 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,069 | hpp |
#ifndef LEETCODE_397_HPP
#define LEETCODE_397_HPP
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <unordered_set>
#include <set>
#include <numeric>
#include <stack>
#include <string>
using namespace std;
/*
Given a positive integer n and you can do operations as follow:
If n is even, replace n with n/2.
If n is odd, you can replace n with either n + 1 or n - 1.
What is the minimum number of replacements needed for n to become 1?
Example 1:
Input:
8
Output:
3
Explanation:
8 -> 4 -> 2 -> 1
Example 2:
Input:
7
Output:
4
Explanation:
7 -> 8 -> 4 -> 2 -> 1
or
7 -> 6 -> 3 -> 2 -> 1
*/
class Solution {
public:
int integerReplacement(int n) {
int cnt = 0;
uint un = static_cast<uint>(n);
while (un != 1) {
if ((un & 1) == 0)
un >>= 1;
else if (un != 3 && ((un >> 1) & 1) == 1)
un++;
else
un--;
cnt++;
}
return cnt;
}
};
#endif //LEETCODE_397_HPP
| [
"baishuai.io@gmail.com"
] | baishuai.io@gmail.com |
575c4010bd4da1324ebdb2aeb91703b2b8a48b43 | f8573941754a429f481c18b46ad5337d1bb55609 | /PhysX 3.3.1/Source/foundation/include/PsFoundation.h | 1b92105453bc32144d0835f72e760fa9c5f5b2ac | [] | no_license | frbyles/ExcavatorSimulator | 409fa4ad56ba3d786dedfffb5d981db86d89f4f5 | c4be4ea60cd1c62c0d0207af31dfed4a47ef6124 | refs/heads/master | 2021-01-19T11:38:04.166440 | 2015-11-12T17:45:52 | 2015-11-12T17:45:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,805 | h | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#ifndef PX_FOUNDATION_PSFOUNDATION_H
#define PX_FOUNDATION_PSFOUNDATION_H
#include "Ps.h"
#include "PsInlineArray.h"
#include "foundation/PxFoundation.h"
#include "foundation/PxErrors.h"
#include "PsMutex.h"
#include "foundation/PxBroadcastingAllocator.h"
#include "PsPAEventSrc.h"
#include <stdarg.h>
#include "PsHashMap.h"
#include "PsErrorHandler.h"
namespace physx
{
namespace shdfnd
{
union TempAllocatorChunk;
class PxAllocatorListenerManager;
class PX_FOUNDATION_API Foundation : public PxFoundation
{
PX_NOCOPY(Foundation)
public:
#ifdef PX_CHECKED
typedef MutexT<Allocator> Mutex;
#else
typedef MutexT<> Mutex;
#endif
private:
typedef HashMap<const NamedAllocator*, const char*,
Hash<const NamedAllocator*>, NonTrackingAllocator> AllocNameMap;
typedef Array<TempAllocatorChunk*, Allocator> AllocFreeTable;
Foundation(PxErrorCallback& errc, PxAllocatorCallback& alloc);
~Foundation();
public:
void release();
// factory
static Foundation* createInstance(PxU32 version, PxErrorCallback& errc, PxAllocatorCallback& alloc);
// note, you MUST call destroyInstance iff createInstance returned true!
static void destroyInstance();
static Foundation& getInstance();
static void incRefCount(); // this call requires a foundation object to exist already
static void decRefCount(); // this call requires a foundation object to exist already
virtual PxErrorCallback& getErrorCallback() const;
virtual void setErrorLevel(PxErrorCode::Enum mask);
virtual PxErrorCode::Enum getErrorLevel() const;
virtual PxBroadcastingAllocator& getAllocator() const { return mAllocator; }
virtual PxAllocatorCallback& getAllocatorCallback() const;
PxAllocatorCallback& getCheckedAllocator() { return mAllocator; }
virtual bool getReportAllocationNames() const { return mReportAllocationNames; }
virtual void setReportAllocationNames(bool value) { mReportAllocationNames = value; }
//! error reporting function
void error(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, ...);
void errorImpl(PxErrorCode::Enum, const char* file, int line, const char* messageFmt, va_list );
PxI32 getWarnOnceTimestamp();
PX_INLINE Mutex& getErrorMutex() { return mErrorMutex; }
PX_INLINE AllocNameMap& getNamedAllocMap() { return mNamedAllocMap; }
PX_INLINE Mutex& getNamedAllocMutex() { return mNamedAllocMutex; }
PX_INLINE AllocFreeTable& getTempAllocFreeTable() { return mTempAllocFreeTable; }
PX_INLINE Mutex& getTempAllocMutex() { return mTempAllocMutex; }
PX_INLINE PAUtils& getPAUtils() { return mPAUtils; }
PX_INLINE ErrorHandler& getErrorHandler() { return mInteralErrorHandler; }
private:
class AlignCheckAllocator: public PxBroadcastingAllocator
{
static const PxU32 MAX_LISTENER_COUNT = 5;
public:
AlignCheckAllocator(PxAllocatorCallback& originalAllocator)
: mAllocator(originalAllocator)
, mListenerCount( 0 ){}
void deallocate(void* ptr)
{
//So here, for performance reasons I don't grab the mutex.
//The listener array is very rarely changing; for most situations
//only at startup. So it is unlikely that using the mutex
//will help a lot but it could have serious perf implications.
PxU32 theCount = mListenerCount;
for( PxU32 idx = 0; idx < theCount; ++idx )
mListeners[idx]->onDeallocation( ptr );
mAllocator.deallocate(ptr);
}
void* allocate(size_t size, const char* typeName, const char* filename, int line);
PxAllocatorCallback& getBaseAllocator() const { return mAllocator; }
void registerAllocationListener( PxAllocationListener& inListener )
{
PX_ASSERT( mListenerCount < MAX_LISTENER_COUNT );
if ( mListenerCount < MAX_LISTENER_COUNT )
{
mListeners[mListenerCount] = &inListener;
++mListenerCount;
}
}
void deregisterAllocationListener( PxAllocationListener& inListener )
{
for( PxU32 idx = 0; idx < mListenerCount; ++idx )
{
if ( mListeners[idx] == &inListener )
{
mListeners[idx] = mListeners[mListenerCount-1];
--mListenerCount;
break;
}
}
}
protected:
AlignCheckAllocator& operator=(const AlignCheckAllocator&);
private:
PxAllocatorCallback& mAllocator;
//I am not sure about using a PxArray here.
//For now, this is fine.
PxAllocationListener* mListeners[MAX_LISTENER_COUNT];
volatile PxU32 mListenerCount;
};
// init order is tricky here: the mutexes require the allocator, the allocator may require the error stream
PxErrorCallback& mErrorCallback;
mutable AlignCheckAllocator mAllocator;
bool mReportAllocationNames;
PxErrorCode::Enum mErrorMask;
Mutex mErrorMutex;
AllocNameMap mNamedAllocMap;
Mutex mNamedAllocMutex;
AllocFreeTable mTempAllocFreeTable;
Mutex mTempAllocMutex;
PAUtils mPAUtils;
ErrorHandler mInteralErrorHandler;
static Foundation* mInstance;
static PxU32 mRefCount;
};
PX_INLINE Foundation& getFoundation()
{
return Foundation::getInstance();
}
} // namespace shdfnd
} // namespace physx
//shortcut macros:
//usage: Foundation::error(PX_WARN, "static friction %f is is lower than dynamic friction %d", sfr, dfr);
#define PX_WARN ::physx::PxErrorCode::eDEBUG_WARNING, __FILE__, __LINE__
#define PX_INFO ::physx::PxErrorCode::eDEBUG_INFO, __FILE__, __LINE__
#if defined(PX_DEBUG) || defined(PX_CHECKED)
#ifdef __SPU__ // SCS: used in CCD from SPU. how can we fix that correctly?
#define PX_WARN_ONCE(condition, string) ((void)0)
#else
#define PX_WARN_ONCE(condition, string) \
if (condition) { \
static PxI32 timestap = 0; \
if (timestap != Ps::getFoundation().getWarnOnceTimestamp()) { \
timestap = Ps::getFoundation().getWarnOnceTimestamp(); \
Ps::getFoundation().error(PX_WARN, string); \
} \
}
#endif
#else
#define PX_WARN_ONCE(condition, string) ((void)0)
#endif
#endif
| [
"seifes1@gmail.com"
] | seifes1@gmail.com |
f3d81605dd407e3b51d2e523200a7bf5cd61ee65 | 1bbf0f087abe2a2c1522f7a5aa422cb75bb6d319 | /Tecnicas de programação 1/trabforcabrabo/mainwindow.cpp | 7505cfa720d39a7f5fe9db77ee81f6aaf876bbc1 | [] | no_license | xfelipealves/SecondSemester | 0f0839a40e08319f454d3e5f414df581b2614e25 | 0777d76dbbf7b6369963b09996d37f5a614cb101 | refs/heads/main | 2023-06-21T19:26:09.783376 | 2021-07-21T03:10:29 | 2021-07-21T03:10:29 | 387,977,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,092 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
btns(nullptr),
jogo(nullptr)
{
ui->setupUi(this);
jogo=new Jogo;
btns=new QPushButton*[26]; //inicializar vetor de botoes
criarBotoes();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::btnClicked()
{
QPushButton *btn=qobject_cast<QPushButton*>(sender()); //converter Qobjetc para QPushButton
QString letra = btn->text();
btn->setEnabled(false); //desabilitar botao
QMessageBox::information(this, "Tecla pressionada", "A tecla "+letra+" foi pressionado");
}
void MainWindow::criarBotoes()
{
int tb=35; //tamanho da largura e altura
QHBoxLayout *caxinha1H=new QHBoxLayout[2];
QVBoxLayout *vertizin=new QVBoxLayout;
QString Letras= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int l = 0, x=0 ; l < 2; ++l) {
for (int i = 0; i < 13; ++i,x++) {
QPushButton *btn=new QPushButton;
btn->setText(Letras.at(x));
btn->setMinimumWidth(tb); //largura minima
btn->setMinimumHeight(tb); //altura minima
btn->setMaximumWidth(tb); //largura max
btn->setMaximumHeight(tb); //altura max
(caxinha1H+l)->addWidget(btn);
btns[x]=btn;
connect(btn,SIGNAL(clicked()),this,SLOT(btnClicked()));
}
vertizin->addLayout(caxinha1H+l); //adicionar o layout horizonatal no vertical
}
ui->botoesArea->setLayout(vertizin);
}
void MainWindow::habilitarBotoes()
{
for (int i = 0; i < 26; ++i) {
btns[i]->setEnabled(true); //habilitar botoes
}
}
void MainWindow::desabilitarBotoes()
{
for (int i = 0; i < 26; ++i) {
btns[i]->setEnabled(false); //desabilitar botoes
}
}
void MainWindow::inicioJogo()
{
habilitarBotoes();
if (jogo) delete jogo;
jogo=new Jogo;
QString nome=QInputDialog::getText(this,"Game Start","Type your name");
}
void MainWindow::on_actionNew_Game_triggered()
{
inicioJogo();
}
| [
"felipecamiloalves04@gmail.com"
] | felipecamiloalves04@gmail.com |
56b5ee1d7c79f64cad2e6e9d794fe36725f9e75e | 1b8db6b3991c7f49ac180dca30c0f1e42069ab72 | /common/NetworkMessageParser.h | 67b02a08fb19cfc1730d12b32f74a3955fff43d7 | [] | no_license | jsandersr/Hydra | cf27de6c5fad35c1b49faa2b51320dcde453a15a | 0fd5f7b2e24a3ca75f3c135d996510d896330390 | refs/heads/master | 2020-06-29T04:47:27.474351 | 2020-01-01T11:35:39 | 2020-01-01T11:39:05 | 200,444,574 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | h | //---------------------------------------------------------------
//
// Parser.cpp
//
#pragma once
#include <memory>
#include <vector>
#include <string>
namespace Common {
//===============================================================================
struct MessageHeader;
struct NetworkMessage;
class NetworkMessageParser
{
public:
NetworkMessageParser();
~NetworkMessageParser();
// Will attempt to extract NetworkMessages out of a stream.
void ExtractMessages(const std::string& stream, std::vector<NetworkMessage>& messages);
private:
void Parse(const std::string& stream);
void SwapBuffer();
void TransitionState();
void WriteToBuffer(const std::string& data, int size);
std::string* Buffer() { return m_activeBuffer; }
private:
enum class State : uint32_t
{
Header,
Content,
Finalizing
};
// Local cache of the header we're looking for.
std::unique_ptr<NetworkMessage> m_messageCache = std::make_unique<NetworkMessage>();
// To ensure smooth writes, buffers are swapped after successful header or content reads.
std::string m_firstBuffer;
std::string m_secondBuffer;
// Points to whichever buffer is being written to.
std::string* m_activeBuffer;
// We're either parsing a header, or content.
State m_state = State::Header;
// Resets on state change.
uint32_t m_bytesParsedThisState = 0;
// Keep track of where we are in the stream overall.
uint32_t m_totalBytesParsed = 0;
};
//===============================================================================
} // namespace Tests
| [
"joshua.sandersr@gmail.com"
] | joshua.sandersr@gmail.com |
fc586fa32bfa1a484c4b32d0b030a3849e51ce9f | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/net/mmc/wins/delrcdlg.cpp | b32346f253c5e82377c7a2f11d963feee5fedea6 | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,408 | cpp | /**********************************************************************/
/** Microsoft Windows/NT **/
/** Copyright(c) Microsoft Corporation, 1997 - 1999 -99 **/
/**********************************************************************/
/*
delrcdlg.cpp
The delete/tombstone record(s) dialog
FILE HISTORY:
*/
#include "stdafx.h"
#include "winssnap.h"
#include "delrcdlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDeleteRecordDlg dialog
CDeleteRecordDlg::CDeleteRecordDlg(CWnd* pParent /*=NULL*/)
: CBaseDialog(CDeleteRecordDlg::IDD, pParent)
{
//{{AFX_DATA_INIT(CDeleteRecordDlg)
m_nDeleteRecord = 0;
//}}AFX_DATA_INIT
m_fMultiple = FALSE;
}
void CDeleteRecordDlg::DoDataExchange(CDataExchange* pDX)
{
CBaseDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDeleteRecordDlg)
DDX_Radio(pDX, IDC_RADIO_DELETE, m_nDeleteRecord);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDeleteRecordDlg, CBaseDialog)
//{{AFX_MSG_MAP(CDeleteRecordDlg)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDeleteRecordDlg message handlers
void CDeleteRecordDlg::OnOK()
{
UpdateData();
// warn the user
if (m_nDeleteRecord != 0)
{
if (AfxMessageBox(IDS_WARN_TOMBSTONE, MB_YESNO) == IDNO)
{
return;
}
}
CBaseDialog::OnOK();
}
BOOL CDeleteRecordDlg::OnInitDialog()
{
CBaseDialog::OnInitDialog();
if (m_fMultiple)
{
CString strText;
// update the strings, title first
strText.LoadString(IDS_DELETE_MULTIPLE_TITLE);
SetWindowText(strText);
// now the static text
strText.LoadString(IDS_DELETE_MULTIPLE_STATIC);
GetDlgItem(IDC_STATIC_DELETE_DESC)->SetWindowText(strText);
// now the radio buttons
strText.LoadString(IDS_DELETE_MULTIPLE_THIS_SERVER);
GetDlgItem(IDC_RADIO_DELETE)->SetWindowText(strText);
strText.LoadString(IDS_DELETE_MULTIPLE_TOMBSTONE);
GetDlgItem(IDC_RADIO_TOMBSTONE)->SetWindowText(strText);
}
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
| [
"support@cryptoalgo.cf"
] | support@cryptoalgo.cf |
beb60a3ba0569627f5f392dfba7b39d8366b9f9f | efa055b4d902b79a729e133f061975b73120c1de | /Playground/QWidgetMultiFileChooser/MainWindow.cpp | d19e2619a5f89e5727aa2e3658808f595662446f | [] | no_license | dellambrogio/learning-qml | 2c4f1a8a7a07d67fd92bc0799968d5be0a4b12cc | 05b8dcfb0052028278ffbdd8db15727acfffd641 | refs/heads/master | 2021-07-17T07:36:10.504767 | 2016-07-29T14:38:18 | 2016-07-29T14:38:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | cpp | // ============================================================================
// Copyright (c) 2016 Nextcode
// Nextcode, Zurich. All rights reserved.
//
// Authors: Michele Dell'Ambrogio (m@nextcode.ch)
// ============================================================================
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include "FileItem.h"
#include <QDebug>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
QWidget* widget = new QWidget(ui->scrollArea);
widget->setGeometry(0, 0, ui->scrollArea->width(), 0);
ui->scrollArea->setWidget(widget);
}
MainWindow::~MainWindow()
{
Q_FOREACH(FileItem* item, m_fileItems)
{
qDebug() << item->filename();
}
delete ui;
}
void MainWindow::slotRemoveFileItem(FileItem *item)
{
if (item)
{
m_fileItems.removeAll(item);
delete item;
doLayout();
}
}
void MainWindow::slotAddFileItemAfter(FileItem *item)
{
if (item)
{
int index = m_fileItems.indexOf(item);
addFileItemAtIndex(++index);
}
}
void MainWindow::on_actionNewFile_triggered()
{
addFileItemAtIndex(m_fileItems.count());
}
void MainWindow::addFileItemAtIndex(int index)
{
QWidget* widget = ui->scrollArea->takeWidget();
FileItem* newFileItem = new FileItem(widget);
connect(newFileItem, SIGNAL(signalAddFileItemAfter(FileItem*)), this, SLOT(slotAddFileItemAfter(FileItem*)));
connect(newFileItem, SIGNAL(signalRemoveItem(FileItem*)), this, SLOT(slotRemoveFileItem(FileItem*)));
m_fileItems.insert(index, newFileItem);
ui->scrollArea->setWidget(widget);
doLayout();
}
void MainWindow::doLayout()
{
const int scrollWidth = ui->scrollArea->width();
QWidget* widget = ui->scrollArea->takeWidget();
int itemHeight = 0;
for(int idx = 0; idx < m_fileItems.size(); ++idx)
{
itemHeight = m_fileItems[idx]->height();
m_fileItems[idx]->setGeometry(0, idx*itemHeight, scrollWidth, itemHeight);
}
int scrollHeight = m_fileItems.count() * itemHeight;
widget->resize(scrollWidth, scrollHeight);
ui->scrollArea->setWidget(widget);
}
| [
"mda@disneyresearch.com"
] | mda@disneyresearch.com |
410f2c922973578229a4fc53b2c0a11790546a21 | 6218cb47da451a41270c86fbd61382c8a8b7a635 | /NTRIP/venus8.cpp | fe97c4e2d39f2f21e778d6333df419df312e5754 | [
"MIT"
] | permissive | ollax452/Qt | a7ea3a6a6378409ef4bfa62c1dc6f1183f893f4d | 85f29279e70121d5108c6d9295b2ba09826fba85 | refs/heads/master | 2021-12-25T06:31:57.097999 | 2017-06-12T01:13:28 | 2017-06-12T01:13:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,562 | cpp | #include "venus8.h"
#define VENUS8WAIT 3000
QByteArray Venus8::messagestart=QByteArray::fromHex("A0A1");
QByteArray Venus8::messageend=QByteArray::fromHex("0D0A");
Venus8::Venus8()
: QSerialPort(Q_NULLPTR)
{
receiveflag=false;
sendflag=false;
thread=new QThread();
this->moveToThread(thread);
connect(this,SIGNAL(signalLoadPortList()),this,SLOT(slotLoadPortList()),Qt::QueuedConnection);
connect(this,SIGNAL(signalStartVenus8(int)),this,SLOT(slotStartVenus8(int)),Qt::QueuedConnection);
thread->start();
baudrate=QSerialPort::Baud9600;
nmea_zero_INFO(&info);
nmea_parser_init(&parser);
qRegisterMetaType<nmeaINFO>("nmeaINFO");
}
Venus8::~Venus8()
{
if(receiveflag)
{
mutex.lock();
receiveflag=false;
mutex.unlock();
}
thread->exit();
thread->wait();
delete thread;
nmea_parser_destroy(&parser);
}
void Venus8::loadPortList()
{
emit signalLoadPortList();
}
void Venus8::slotLoadPortList()
{
portlist=QSerialPortInfo::availablePorts();
emit signalPortListLoaded();
}
void Venus8::startReceiveNmea(int portId)
{
mutex.lock();
receiveflag=true;
mutex.unlock();
emit signalStartVenus8(portId);
}
void Venus8::stopReceiveNmea()
{
mutex.lock();
receiveflag=false;
mutex.unlock();
}
void Venus8::sendMessage(QByteArray hexMessage)
{
message.clear();
message.append(messagestart);
QByteArray raw=QByteArray::fromHex(hexMessage);
int n=raw.size();
message.append(char(n/0x100));
message.append(char(n%0x100));
message.append(raw);
char cs=0;
for(int i=0;i<n;i++)
{
char m=raw.at(i);
cs=cs^m;
}
message.append(cs);
message.append(messageend);
mutex.lock();
sendflag=true;
mutex.unlock();
}
bool Venus8::checkReceiveFlag()
{
bool result;
mutex.lock();
result=receiveflag;
mutex.unlock();
return result;
}
bool Venus8::checkSendFlag()
{
bool result;
mutex.lock();
result=sendflag;
mutex.unlock();
return result;
}
void Venus8::slotStartVenus8(int portId)
{
this->setPort(portlist[portId]);
this->setBaudRate(baudrate);
if(this->open(QIODevice::ReadWrite))
{
while(checkReceiveFlag()&&this->waitForReadyRead(VENUS8WAIT))
{
while(this->canReadLine())
{
QByteArray message=this->readLine();
if(message.startsWith(messagestart))
{
emit signalMessageReceived(message);
}
else
{
emit signalNmeaReceived(message);
nmea_parse(&parser,message.data(),message.size(),&info);
emit signalNmeaParsed(info);
}
}
if(checkSendFlag())
{
this->write(message);
if(this->waitForBytesWritten(VENUS8WAIT))
{
emit signalMessageSent();
}
else
{
emit signalMessageNotSent();
}
mutex.lock();
sendflag=false;
mutex.unlock();
}
}
this->close();
if(checkReceiveFlag())
{
emit signalVenus8Stopped();
}
}
else
{
mutex.lock();
receiveflag=false;
mutex.unlock();
emit signalVenus8ConnectionError();
}
}
Venus8Logger::Venus8Logger()
: QObject(Q_NULLPTR)
{
stream.setDevice(&file);
thread=new QThread();
this->moveToThread(thread);
connect(this,SIGNAL(signalSetLogFilename(QString)),this,SLOT(slotSetLogFilename(QString)),Qt::QueuedConnection);
thread->start(QThread::HighestPriority);
}
Venus8Logger::~Venus8Logger()
{
if(file.isOpen())
{
mutex.lock();
file.close();
mutex.unlock();
}
thread->exit();
thread->wait();
delete thread;
}
void Venus8Logger::setLogFilename()
{
QString filename=QFileDialog::getSaveFileName();
if(filename.isEmpty())
{
return;
}
emit signalSetLogFilename(filename);
}
void Venus8Logger::slotSetLogFilename(QString filename)
{
mutex.lock();
this->filename=filename;
if(file.fileName()!=this->filename)
{
if(file.isOpen())
{
file.close();
}
file.setFileName(this->filename);
emit signalLogFilenameSet();
}
mutex.unlock();
}
void Venus8Logger::startLogNmea()
{
mutex.lock();
if(!this->filename.isEmpty()&&!file.isOpen())
{
file.open(QIODevice::WriteOnly|QIODevice::Text);
}
mutex.unlock();
}
void Venus8Logger::stopLogNmea()
{
mutex.lock();
if(file.isOpen())
{
file.close();
}
mutex.unlock();
}
bool Venus8Logger::checkFileOpenFlagAndWriteData(QByteArray nmea)
{
bool result;
mutex.lock();
result=file.isOpen();
if(result)
{
stream<<nmea;
}
mutex.unlock();
return result;
}
void Venus8Logger::slotLogNmea(QByteArray nmea)
{
if(checkFileOpenFlagAndWriteData(nmea))
{
emit signalNmeaLogged();
}
else
{
emit signalNmeaLogStopped();
}
}
| [
"alexanderhmw@gmail.com"
] | alexanderhmw@gmail.com |
f54d0f86508ae5763ad8ee0468b3ad481da0e08d | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /vm/include/tencentcloud/vm/v20210922/model/DescribeTasksResponse.h | 621ce1227b6dd4016d832c5b546f3ea7d668bd74 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 5,265 | 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_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
#define TENCENTCLOUD_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/vm/v20210922/model/TaskData.h>
namespace TencentCloud
{
namespace Vm
{
namespace V20210922
{
namespace Model
{
/**
* DescribeTasks返回参数结构体
*/
class DescribeTasksResponse : public AbstractModel
{
public:
DescribeTasksResponse();
~DescribeTasksResponse() = default;
CoreInternalOutcome Deserialize(const std::string &payload);
std::string ToJsonString() const;
/**
* 获取该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
* @return Total 该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetTotal() const;
/**
* 判断参数 Total 是否已赋值
* @return Total 是否已赋值
*
*/
bool TotalHasBeenSet() const;
/**
* 获取该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
* @return Data 该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::vector<TaskData> GetData() const;
/**
* 判断参数 Data 是否已赋值
* @return Data 是否已赋值
*
*/
bool DataHasBeenSet() const;
/**
* 获取该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
* @return PageToken 该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
*
*/
std::string GetPageToken() const;
/**
* 判断参数 PageToken 是否已赋值
* @return PageToken 是否已赋值
*
*/
bool PageTokenHasBeenSet() const;
private:
/**
* 该字段用于返回当前查询的任务总量,格式为int字符串。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_total;
bool m_totalHasBeenSet;
/**
* 该字段用于返回当前页的任务详细数据,具体输出内容请参见TaskData数据结构的详细描述。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<TaskData> m_data;
bool m_dataHasBeenSet;
/**
* 该字段用于返回翻页时使用的Token信息,由系统自动生成,并在翻页时向下一个生成的页面传递此参数,以方便快速翻页功能的实现。当到最后一页时,该字段为空。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::string m_pageToken;
bool m_pageTokenHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_VM_V20210922_MODEL_DESCRIBETASKSRESPONSE_H_
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
6be874fb39a9bdebf01527696999c34e447f0265 | 6a69d57c782e0b1b993e876ad4ca2927a5f2e863 | /vendor/samsung/common/packages/apps/SBrowser/src/components/autofill/core/browser/autofill_manager.cc | 8398b53095cff00fe2b99f74a81e8dd4c5ddcb11 | [
"BSD-3-Clause"
] | permissive | duki994/G900H-Platform-XXU1BOA7 | c8411ef51f5f01defa96b3381f15ea741aa5bce2 | 4f9307e6ef21893c9a791c96a500dfad36e3b202 | refs/heads/master | 2020-05-16T20:57:07.585212 | 2015-05-11T11:03:16 | 2015-05-11T11:03:16 | 35,418,464 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 45,455 | cc | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/autofill/core/browser/autofill_manager.h"
#include <stddef.h>
#include <limits>
#include <map>
#include <set>
#include <utility>
#ifdef SAMSUNG_EDM
#include <string.h> //WTL_EDM
#endif //SAMSUNG_EDM
#include "base/bind.h"
#include "base/command_line.h"
#include "base/guid.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/sequenced_worker_pool.h"
#include "components/autofill/core/browser/autocomplete_history_manager.h"
#include "components/autofill/core/browser/autofill_data_model.h"
#include "components/autofill/core/browser/autofill_driver.h"
#include "components/autofill/core/browser/autofill_external_delegate.h"
#include "components/autofill/core/browser/autofill_field.h"
#include "components/autofill/core/browser/autofill_manager_delegate.h"
#include "components/autofill/core/browser/autofill_manager_test_delegate.h"
#include "components/autofill/core/browser/autofill_metrics.h"
#include "components/autofill/core/browser/autofill_profile.h"
#include "components/autofill/core/browser/autofill_type.h"
#include "components/autofill/core/browser/credit_card.h"
#include "components/autofill/core/browser/form_structure.h"
#include "components/autofill/core/browser/personal_data_manager.h"
#include "components/autofill/core/browser/phone_number.h"
#include "components/autofill/core/browser/phone_number_i18n.h"
#include "components/autofill/core/common/autofill_data_validation.h"
#include "components/autofill/core/common/autofill_pref_names.h"
#include "components/autofill/core/common/autofill_switches.h"
#include "components/autofill/core/common/form_data.h"
#include "components/autofill/core/common/form_data_predictions.h"
#include "components/autofill/core/common/form_field_data.h"
#include "components/autofill/core/common/password_form_fill_data.h"
#include "components/user_prefs/pref_registry_syncable.h"
#ifdef SAMSUNG_EDM
#include "edmnativehelper/EDMNativeHelper.h" //WTL_EDM
#endif //SAMSUNG_EDM
#include "grit/component_strings.h"
#include "third_party/WebKit/public/web/WebAutofillClient.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/rect.h"
#include "url/gurl.h"
namespace autofill {
typedef PersonalDataManager::GUIDPair GUIDPair;
using base::TimeTicks;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
#define AUDITLOG_MSG_SIZE 34 // Size of header msg
extern "C" void c_auditLog(int severityGrade, int moduleGroup, bool outcome, int uid,
const char* swComponent, const char* logMessage) {
android::EDMNativeHelper::nativeLogger(severityGrade, moduleGroup, (int)outcome, uid,
swComponent, logMessage);
}
extern "C" bool c_isAuditLogEnabled() {
return android::EDMNativeHelper::isAuditLogEnabled();
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
namespace {
// We only send a fraction of the forms to upload server.
// The rate for positive/negative matches potentially could be different.
const double kAutofillPositiveUploadRateDefaultValue = 0.20;
const double kAutofillNegativeUploadRateDefaultValue = 0.20;
const size_t kMaxRecentFormSignaturesToRemember = 3;
// Set a conservative upper bound on the number of forms we are willing to
// cache, simply to prevent unbounded memory consumption.
const size_t kMaxFormCacheSize = 100;
// Removes duplicate suggestions whilst preserving their original order.
void RemoveDuplicateSuggestions(std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) {
DCHECK_EQ(values->size(), labels->size());
DCHECK_EQ(values->size(), icons->size());
DCHECK_EQ(values->size(), unique_ids->size());
std::set<std::pair<base::string16, base::string16> > seen_suggestions;
std::vector<base::string16> values_copy;
std::vector<base::string16> labels_copy;
std::vector<base::string16> icons_copy;
std::vector<int> unique_ids_copy;
for (size_t i = 0; i < values->size(); ++i) {
const std::pair<base::string16, base::string16> suggestion(
(*values)[i], (*labels)[i]);
if (seen_suggestions.insert(suggestion).second) {
values_copy.push_back((*values)[i]);
labels_copy.push_back((*labels)[i]);
icons_copy.push_back((*icons)[i]);
unique_ids_copy.push_back((*unique_ids)[i]);
}
}
values->swap(values_copy);
labels->swap(labels_copy);
icons->swap(icons_copy);
unique_ids->swap(unique_ids_copy);
}
// Precondition: |form_structure| and |form| should correspond to the same
// logical form. Returns true if any field in the given |section| within |form|
// is auto-filled.
bool SectionIsAutofilled(const FormStructure& form_structure,
const FormData& form,
const std::string& section) {
DCHECK_EQ(form_structure.field_count(), form.fields.size());
for (size_t i = 0; i < form_structure.field_count(); ++i) {
if (form_structure.field(i)->section() == section &&
form.fields[i].is_autofilled) {
return true;
}
}
return false;
}
bool FormIsHTTPS(const FormStructure& form) {
// TODO(blundell): Change this to use a constant once crbug.com/306258 is
// fixed.
return form.source_url().SchemeIs("https");
}
// Uses the existing personal data in |profiles| and |credit_cards| to determine
// possible field types for the |submitted_form|. This is potentially
// expensive -- on the order of 50ms even for a small set of |stored_data|.
// Hence, it should not run on the UI thread -- to avoid locking up the UI --
// nor on the IO thread -- to avoid blocking IPC calls.
void DeterminePossibleFieldTypesForUpload(
const std::vector<AutofillProfile>& profiles,
const std::vector<CreditCard>& credit_cards,
const std::string& app_locale,
FormStructure* submitted_form) {
// For each field in the |submitted_form|, extract the value. Then for each
// profile or credit card, identify any stored types that match the value.
for (size_t i = 0; i < submitted_form->field_count(); ++i) {
AutofillField* field = submitted_form->field(i);
ServerFieldTypeSet matching_types;
// If it's a password field, set the type directly.
if (field->form_control_type == "password") {
matching_types.insert(autofill::PASSWORD);
} else {
base::string16 value;
TrimWhitespace(field->value, TRIM_ALL, &value);
for (std::vector<AutofillProfile>::const_iterator it = profiles.begin();
it != profiles.end(); ++it) {
it->GetMatchingTypes(value, app_locale, &matching_types);
}
for (std::vector<CreditCard>::const_iterator it = credit_cards.begin();
it != credit_cards.end(); ++it) {
it->GetMatchingTypes(value, app_locale, &matching_types);
}
}
if (matching_types.empty())
matching_types.insert(UNKNOWN_TYPE);
field->set_possible_types(matching_types);
}
}
} // namespace
AutofillManager::AutofillManager(
AutofillDriver* driver,
autofill::AutofillManagerDelegate* delegate,
const std::string& app_locale,
AutofillDownloadManagerState enable_download_manager)
: driver_(driver),
manager_delegate_(delegate),
app_locale_(app_locale),
personal_data_(delegate->GetPersonalDataManager()),
autocomplete_history_manager_(
new AutocompleteHistoryManager(driver, delegate)),
metric_logger_(new AutofillMetrics),
has_logged_autofill_enabled_(false),
has_logged_address_suggestions_count_(false),
did_show_suggestions_(false),
user_did_type_(false),
user_did_autofill_(false),
user_did_edit_autofilled_field_(false),
external_delegate_(NULL),
test_delegate_(NULL),
weak_ptr_factory_(this) {
if (enable_download_manager == ENABLE_AUTOFILL_DOWNLOAD_MANAGER) {
download_manager_.reset(
new AutofillDownloadManager(driver,
manager_delegate_->GetPrefs(),
this));
}
}
AutofillManager::~AutofillManager() {}
// static
void AutofillManager::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* registry) {
#if defined(S_AUTOFILL_REMEMBER_FORM_FILL_DATA)
registry->RegisterBooleanPref(
prefs::kRememberFormDataEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#endif
registry->RegisterBooleanPref(
prefs::kAutofillEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#if defined(OS_MACOSX) || defined(OS_ANDROID)
registry->RegisterBooleanPref(
prefs::kAutofillAuxiliaryProfilesEnabled,
true,
user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
#else
registry->RegisterBooleanPref(
prefs::kAutofillAuxiliaryProfilesEnabled,
false,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
#endif
registry->RegisterDoublePref(
prefs::kAutofillPositiveUploadRate,
kAutofillPositiveUploadRateDefaultValue,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
registry->RegisterDoublePref(
prefs::kAutofillNegativeUploadRate,
kAutofillNegativeUploadRateDefaultValue,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
void AutofillManager::SetExternalDelegate(AutofillExternalDelegate* delegate) {
// TODO(jrg): consider passing delegate into the ctor. That won't
// work if the delegate has a pointer to the AutofillManager, but
// future directions may not need such a pointer.
external_delegate_ = delegate;
autocomplete_history_manager_->SetExternalDelegate(delegate);
}
void AutofillManager::ShowAutofillSettings() {
manager_delegate_->ShowAutofillSettings();
}
#if defined(S_HIDE_AUTOFILL_OPTIMIZATION)
void AutofillManager::ShowAutofillPopupCalled(bool showing) {
driver_->ShowAutofillPopupCalled(showing);
}
#endif
bool AutofillManager::OnFormSubmitted(const FormData& form,
const TimeTicks& timestamp) {
if (!IsValidFormData(form))
return false;
// Let Autocomplete know as well.
autocomplete_history_manager_->OnFormSubmitted(form);
// Grab a copy of the form data.
scoped_ptr<FormStructure> submitted_form(new FormStructure(form));
if (!ShouldUploadForm(*submitted_form))
return false;
// Don't save data that was submitted through JavaScript.
if (!form.user_submitted)
return false;
// Ignore forms not present in our cache. These are typically forms with
// wonky JavaScript that also makes them not auto-fillable.
FormStructure* cached_submitted_form;
if (!FindCachedForm(form, &cached_submitted_form))
return false;
submitted_form->UpdateFromCache(*cached_submitted_form);
if (submitted_form->IsAutofillable(true))
ImportFormData(*submitted_form);
// Only upload server statistics and UMA metrics if at least some local data
// is available to use as a baseline.
const std::vector<AutofillProfile*>& profiles = personal_data_->GetProfiles();
const std::vector<CreditCard*>& credit_cards =
personal_data_->GetCreditCards();
if (!profiles.empty() || !credit_cards.empty()) {
// Copy the profile and credit card data, so that it can be accessed on a
// separate thread.
std::vector<AutofillProfile> copied_profiles;
copied_profiles.reserve(profiles.size());
for (std::vector<AutofillProfile*>::const_iterator it = profiles.begin();
it != profiles.end(); ++it) {
copied_profiles.push_back(**it);
}
std::vector<CreditCard> copied_credit_cards;
copied_credit_cards.reserve(credit_cards.size());
for (std::vector<CreditCard*>::const_iterator it = credit_cards.begin();
it != credit_cards.end(); ++it) {
copied_credit_cards.push_back(**it);
}
// Note that ownership of |submitted_form| is passed to the second task,
// using |base::Owned|.
FormStructure* raw_submitted_form = submitted_form.get();
driver_->GetBlockingPool()->PostTaskAndReply(
FROM_HERE,
base::Bind(&DeterminePossibleFieldTypesForUpload,
copied_profiles,
copied_credit_cards,
app_locale_,
raw_submitted_form),
base::Bind(&AutofillManager::UploadFormDataAsyncCallback,
weak_ptr_factory_.GetWeakPtr(),
base::Owned(submitted_form.release()),
forms_loaded_timestamp_,
initial_interaction_timestamp_,
timestamp));
}
return true;
}
void AutofillManager::OnFormsSeen(const std::vector<FormData>& forms,
const TimeTicks& timestamp,
autofill::FormsSeenState state) {
if (!IsValidFormDataVector(forms))
return;
bool is_post_document_load = state == autofill::DYNAMIC_FORMS_SEEN;
// If new forms were added dynamically, treat as a new page.
if (is_post_document_load)
Reset();
if (!driver_->RendererIsAvailable())
return;
bool enabled = IsAutofillEnabled();
if (!has_logged_autofill_enabled_) {
metric_logger_->LogIsAutofillEnabledAtPageLoad(enabled);
has_logged_autofill_enabled_ = true;
}
if (!enabled)
return;
forms_loaded_timestamp_ = timestamp;
ParseForms(forms);
}
void AutofillManager::OnTextFieldDidChange(const FormData& form,
const FormFieldData& field,
const TimeTicks& timestamp) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
if (!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
return;
if (!user_did_type_) {
user_did_type_ = true;
metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_TYPE);
}
if (autofill_field->is_autofilled) {
autofill_field->is_autofilled = false;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD);
if (!user_did_edit_autofilled_field_) {
user_did_edit_autofilled_field_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_EDIT_AUTOFILLED_FIELD_ONCE);
}
}
UpdateInitialInteractionTimestamp(timestamp);
}
void AutofillManager::OnQueryFormFieldAutofill(int query_id,
const FormData& form,
const FormFieldData& field,
const gfx::RectF& bounding_box,
bool display_warning) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
std::vector<base::string16> values;
std::vector<base::string16> labels;
std::vector<base::string16> icons;
std::vector<int> unique_ids;
external_delegate_->OnQuery(query_id,
form,
field,
bounding_box,
display_warning);
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
if (RefreshDataModels() &&
driver_->RendererIsAvailable() &&
GetCachedFormAndField(form, field, &form_structure, &autofill_field) &&
// Don't send suggestions for forms that aren't auto-fillable.
form_structure->IsAutofillable(false)) {
AutofillType type = autofill_field->Type();
bool is_filling_credit_card = (type.group() == CREDIT_CARD);
if (is_filling_credit_card) {
GetCreditCardSuggestions(
field, type, &values, &labels, &icons, &unique_ids);
} else {
GetProfileSuggestions(
form_structure, field, type, &values, &labels, &icons, &unique_ids);
}
DCHECK_EQ(values.size(), labels.size());
DCHECK_EQ(values.size(), icons.size());
DCHECK_EQ(values.size(), unique_ids.size());
if (!values.empty()) {
// Don't provide Autofill suggestions when Autofill is disabled, and don't
// provide credit card suggestions for non-HTTPS pages. However, provide a
// warning to the user in these cases.
int warning = 0;
if (!form_structure->IsAutofillable(true))
warning = IDS_AUTOFILL_WARNING_FORM_DISABLED;
else if (is_filling_credit_card && !FormIsHTTPS(*form_structure))
warning = IDS_AUTOFILL_WARNING_INSECURE_CONNECTION;
if (warning) {
values.assign(1, l10n_util::GetStringUTF16(warning));
labels.assign(1, base::string16());
icons.assign(1, base::string16());
unique_ids.assign(1,
blink::WebAutofillClient::MenuItemIDWarningMessage);
} else {
bool section_is_autofilled =
SectionIsAutofilled(*form_structure, form,
autofill_field->section());
if (section_is_autofilled) {
// If the relevant section is auto-filled and the renderer is querying
// for suggestions, then the user is editing the value of a field.
// In this case, mimic autocomplete: don't display labels or icons,
// as that information is redundant.
labels.assign(labels.size(), base::string16());
icons.assign(icons.size(), base::string16());
}
// When filling credit card suggestions, the values and labels are
// typically obfuscated, which makes detecting duplicates hard. Since
// duplicates only tend to be a problem when filling address forms
// anyway, only don't de-dup credit card suggestions.
if (!is_filling_credit_card)
RemoveDuplicateSuggestions(&values, &labels, &icons, &unique_ids);
// The first time we show suggestions on this page, log the number of
// suggestions shown.
if (!has_logged_address_suggestions_count_ && !section_is_autofilled) {
metric_logger_->LogAddressSuggestionsCount(values.size());
has_logged_address_suggestions_count_ = true;
}
}
}
}
// Add the results from AutoComplete. They come back asynchronously, so we
// hand off what we generated and they will send the results back to the
// renderer.
autocomplete_history_manager_->OnGetAutocompleteSuggestions(
query_id, field.name, field.value, values, labels, icons, unique_ids);
}
void AutofillManager::OnFillAutofillFormData(int query_id,
const FormData& form,
const FormFieldData& field,
int unique_id) {
if (!IsValidFormData(form) || !IsValidFormFieldData(field))
return;
const AutofillDataModel* data_model = NULL;
size_t variant = 0;
FormStructure* form_structure = NULL;
AutofillField* autofill_field = NULL;
// NOTE: RefreshDataModels may invalidate |data_model| because it causes the
// PersonalDataManager to reload Mac address book entries. Thus it must come
// before GetProfileOrCreditCard.
if (!RefreshDataModels() ||
!driver_->RendererIsAvailable() ||
!GetProfileOrCreditCard(unique_id, &data_model, &variant) ||
!GetCachedFormAndField(form, field, &form_structure, &autofill_field))
return;
DCHECK(form_structure);
DCHECK(autofill_field);
FormData result = form;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
AutofillProfile* profile = NULL;
base::string16 profile_full_name;
char* audit_msg;
int audit_msg_len = 0;
if(c_isAuditLogEnabled()) { // Get profile info if AuditLog is enabled
profile = personal_data_->GetProfileByGUID(data_model->guid());
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
// If the relevant section is auto-filled, we should fill |field| but not the
// rest of the form.
if (SectionIsAutofilled(*form_structure, form, autofill_field->section())) {
for (std::vector<FormFieldData>::iterator iter = result.fields.begin();
iter != result.fields.end(); ++iter) {
if ((*iter) == field) {
base::string16 value = data_model->GetInfoForVariant(
autofill_field->Type(), variant, app_locale_);
AutofillField::FillFormField(*autofill_field, value, app_locale_,
&(*iter));
// Mark the cached field as autofilled, so that we can detect when a
// user edits an autofilled field (for metrics).
autofill_field->is_autofilled = true;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
//send autofill event to KNOX's AuditLog in case of AutofillProfile
if(profile && value != NULL && value.length() > 0) {
profile_full_name = profile->GetRawInfo(NAME_FULL);//, app_locale_);
audit_msg_len = value.length() + profile_full_name.length() + AUDITLOG_MSG_SIZE;
// If msg exists
if (audit_msg_len > AUDITLOG_MSG_SIZE){
audit_msg = (char*)malloc(audit_msg_len*sizeof(char));
if(audit_msg){
sprintf(audit_msg, "Auto-completing data for field %s %s",
UTF16ToUTF8(value).c_str(),UTF16ToUTF8(profile_full_name).c_str());
// Send autofill msg to auditlog
c_auditLog(1,1,1,1,"RequestFormData",audit_msg);
free(audit_msg);
}
}
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
break;
}
}
driver_->SendFormDataToRenderer(query_id, result);
return;
}
// Cache the field type for the field from which the user initiated autofill.
FieldTypeGroup initiating_group_type = autofill_field->Type().group();
DCHECK_EQ(form_structure->field_count(), form.fields.size());
for (size_t i = 0; i < form_structure->field_count(); ++i) {
if (form_structure->field(i)->section() != autofill_field->section())
continue;
DCHECK_EQ(*form_structure->field(i), result.fields[i]);
const AutofillField* cached_field = form_structure->field(i);
FieldTypeGroup field_group_type = cached_field->Type().group();
if (field_group_type != NO_GROUP) {
// If the field being filled is either
// (a) the field that the user initiated the fill from, or
// (b) part of the same logical unit, e.g. name or phone number,
// then take the multi-profile "variant" into account.
// Otherwise fill with the default (zeroth) variant.
size_t use_variant = 0;
if (result.fields[i] == field ||
field_group_type == initiating_group_type) {
use_variant = variant;
}
base::string16 value = data_model->GetInfoForVariant(
cached_field->Type(), use_variant, app_locale_);
AutofillField::FillFormField(*cached_field, value, app_locale_,
&result.fields[i]);
// Mark the cached field as autofilled, so that we can detect when a user
// edits an autofilled field (for metrics).
form_structure->field(i)->is_autofilled = true;
#ifdef SAMSUNG_EDM
//WTL_EDM_START
//send autofill event to KNOX's AuditLog in case of AutofillProfile
if(profile && value != NULL && value.length() > 0) {
profile_full_name = profile->GetRawInfo(NAME_FULL);//, app_locale_);
audit_msg_len = value.length() + profile_full_name.length() + AUDITLOG_MSG_SIZE;
// If msg exists
if (audit_msg_len > AUDITLOG_MSG_SIZE){
audit_msg = (char*)malloc(audit_msg_len*sizeof(char));
if(audit_msg){
sprintf(audit_msg, "Auto-completing data for field %s %s",
UTF16ToUTF8(value).c_str(),UTF16ToUTF8(profile_full_name).c_str());
// Send autofill msg to auditlog
c_auditLog(1,1,1,1,"RequestFormData",audit_msg);
free(audit_msg);
}
}
}
//WTL_EDM_END
#endif //SAMSUNG_EDM
}
}
autofilled_form_signatures_.push_front(form_structure->FormSignature());
// Only remember the last few forms that we've seen, both to avoid false
// positives and to avoid wasting memory.
if (autofilled_form_signatures_.size() > kMaxRecentFormSignaturesToRemember)
autofilled_form_signatures_.pop_back();
driver_->SendFormDataToRenderer(query_id, result);
}
void AutofillManager::OnDidPreviewAutofillFormData() {
if (test_delegate_)
test_delegate_->DidPreviewFormData();
}
void AutofillManager::OnDidFillAutofillFormData(const TimeTicks& timestamp) {
if (test_delegate_)
test_delegate_->DidFillFormData();
metric_logger_->LogUserHappinessMetric(AutofillMetrics::USER_DID_AUTOFILL);
if (!user_did_autofill_) {
user_did_autofill_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::USER_DID_AUTOFILL_ONCE);
}
UpdateInitialInteractionTimestamp(timestamp);
}
void AutofillManager::OnDidShowAutofillSuggestions(bool is_new_popup) {
if (test_delegate_)
test_delegate_->DidShowSuggestions();
if (is_new_popup) {
metric_logger_->LogUserHappinessMetric(AutofillMetrics::SUGGESTIONS_SHOWN);
if (!did_show_suggestions_) {
did_show_suggestions_ = true;
metric_logger_->LogUserHappinessMetric(
AutofillMetrics::SUGGESTIONS_SHOWN_ONCE);
}
}
}
void AutofillManager::OnHideAutofillUI() {
if (!IsAutofillEnabled())
return;
manager_delegate_->HideAutofillPopup();
}
void AutofillManager::RemoveAutofillProfileOrCreditCard(int unique_id) {
const AutofillDataModel* data_model = NULL;
size_t variant = 0;
if (!GetProfileOrCreditCard(unique_id, &data_model, &variant)) {
NOTREACHED();
return;
}
// TODO(csharp): If we are dealing with a variant only the variant should
// be deleted, instead of doing nothing.
// http://crbug.com/124211
if (variant != 0)
return;
personal_data_->RemoveByGUID(data_model->guid());
}
void AutofillManager::RemoveAutocompleteEntry(const base::string16& name,
const base::string16& value) {
autocomplete_history_manager_->OnRemoveAutocompleteEntry(name, value);
}
const std::vector<FormStructure*>& AutofillManager::GetFormStructures() {
return form_structures_.get();
}
void AutofillManager::SetTestDelegate(
autofill::AutofillManagerTestDelegate* delegate) {
test_delegate_ = delegate;
}
void AutofillManager::OnAddPasswordFormMapping(
const FormFieldData& username_field,
const PasswordFormFillData& fill_data) {
if (!IsValidFormFieldData(username_field) ||
!IsValidPasswordFormFillData(fill_data))
return;
external_delegate_->AddPasswordFormMapping(username_field, fill_data);
}
void AutofillManager::OnShowPasswordSuggestions(
const FormFieldData& field,
const gfx::RectF& bounds,
const std::vector<base::string16>& suggestions,
const std::vector<base::string16>& realms) {
if (!IsValidString16Vector(suggestions) ||
!IsValidString16Vector(realms) ||
suggestions.size() != realms.size())
return;
external_delegate_->OnShowPasswordSuggestions(suggestions,
realms,
field,
bounds);
}
void AutofillManager::OnSetDataList(const std::vector<base::string16>& values,
const std::vector<base::string16>& labels) {
if (!IsValidString16Vector(values) ||
!IsValidString16Vector(labels) ||
values.size() != labels.size())
return;
external_delegate_->SetCurrentDataListValues(values, labels);
}
void AutofillManager::OnLoadedServerPredictions(
const std::string& response_xml) {
// Parse and store the server predictions.
FormStructure::ParseQueryResponse(response_xml,
form_structures_.get(),
*metric_logger_);
// Forward form structures to the password generation manager to detect
// account creation forms.
manager_delegate_->DetectAccountCreationForms(form_structures_.get());
// If the corresponding flag is set, annotate forms with the predicted types.
driver_->SendAutofillTypePredictionsToRenderer(form_structures_.get());
}
void AutofillManager::OnDidEndTextFieldEditing() {
external_delegate_->DidEndTextFieldEditing();
}
bool AutofillManager::IsAutofillEnabled() const {
return manager_delegate_->GetPrefs()->GetBoolean(prefs::kAutofillEnabled);
}
void AutofillManager::ImportFormData(const FormStructure& submitted_form) {
scoped_ptr<CreditCard> imported_credit_card;
if (!personal_data_->ImportFormData(submitted_form, &imported_credit_card))
return;
// If credit card information was submitted, we need to confirm whether to
// save it.
if (imported_credit_card) {
manager_delegate_->ConfirmSaveCreditCard(
*metric_logger_,
base::Bind(
base::IgnoreResult(&PersonalDataManager::SaveImportedCreditCard),
base::Unretained(personal_data_), *imported_credit_card));
}
}
// Note that |submitted_form| is passed as a pointer rather than as a reference
// so that we can get memory management right across threads. Note also that we
// explicitly pass in all the time stamps of interest, as the cached ones might
// get reset before this method executes.
void AutofillManager::UploadFormDataAsyncCallback(
const FormStructure* submitted_form,
const TimeTicks& load_time,
const TimeTicks& interaction_time,
const TimeTicks& submission_time) {
submitted_form->LogQualityMetrics(*metric_logger_,
load_time,
interaction_time,
submission_time);
if (submitted_form->ShouldBeCrowdsourced())
UploadFormData(*submitted_form);
}
void AutofillManager::UploadFormData(const FormStructure& submitted_form) {
if (!download_manager_)
return;
// Check if the form is among the forms that were recently auto-filled.
bool was_autofilled = false;
std::string form_signature = submitted_form.FormSignature();
for (std::list<std::string>::const_iterator it =
autofilled_form_signatures_.begin();
it != autofilled_form_signatures_.end() && !was_autofilled;
++it) {
if (*it == form_signature)
was_autofilled = true;
}
ServerFieldTypeSet non_empty_types;
personal_data_->GetNonEmptyTypes(&non_empty_types);
// Always add PASSWORD to |non_empty_types| so that if |submitted_form|
// contains a password field it will be uploaded to the server. If
// |submitted_form| doesn't contain a password field, there is no side
// effect from adding PASSWORD to |non_empty_types|.
non_empty_types.insert(autofill::PASSWORD);
download_manager_->StartUploadRequest(submitted_form, was_autofilled,
non_empty_types);
}
bool AutofillManager::UploadPasswordGenerationForm(const FormData& form) {
FormStructure form_structure(form);
if (!ShouldUploadForm(form_structure))
return false;
if (!form_structure.ShouldBeCrowdsourced())
return false;
// TODO(gcasto): Check that PasswordGeneration is enabled?
// Find the first password field to label. We don't try to label anything
// else.
bool found_password_field = false;
for (size_t i = 0; i < form_structure.field_count(); ++i) {
AutofillField* field = form_structure.field(i);
ServerFieldTypeSet types;
if (!found_password_field && field->form_control_type == "password") {
types.insert(ACCOUNT_CREATION_PASSWORD);
found_password_field = true;
} else {
types.insert(UNKNOWN_TYPE);
}
field->set_possible_types(types);
}
DCHECK(found_password_field);
// Only one field type should be present.
ServerFieldTypeSet available_field_types;
available_field_types.insert(ACCOUNT_CREATION_PASSWORD);
// Force uploading as these events are relatively rare and we want to make
// sure to receive them. It also makes testing easier if these requests
// always pass.
form_structure.set_upload_required(UPLOAD_REQUIRED);
if (!download_manager_)
return false;
return download_manager_->StartUploadRequest(form_structure,
false /* was_autofilled */,
available_field_types);
}
void AutofillManager::Reset() {
form_structures_.clear();
has_logged_autofill_enabled_ = false;
has_logged_address_suggestions_count_ = false;
did_show_suggestions_ = false;
user_did_type_ = false;
user_did_autofill_ = false;
user_did_edit_autofilled_field_ = false;
forms_loaded_timestamp_ = TimeTicks();
initial_interaction_timestamp_ = TimeTicks();
external_delegate_->Reset();
}
AutofillManager::AutofillManager(AutofillDriver* driver,
autofill::AutofillManagerDelegate* delegate,
PersonalDataManager* personal_data)
: driver_(driver),
manager_delegate_(delegate),
app_locale_("en-US"),
personal_data_(personal_data),
autocomplete_history_manager_(
new AutocompleteHistoryManager(driver, delegate)),
metric_logger_(new AutofillMetrics),
has_logged_autofill_enabled_(false),
has_logged_address_suggestions_count_(false),
did_show_suggestions_(false),
user_did_type_(false),
user_did_autofill_(false),
user_did_edit_autofilled_field_(false),
external_delegate_(NULL),
test_delegate_(NULL),
weak_ptr_factory_(this) {
DCHECK(driver_);
DCHECK(manager_delegate_);
}
void AutofillManager::set_metric_logger(const AutofillMetrics* metric_logger) {
metric_logger_.reset(metric_logger);
}
bool AutofillManager::RefreshDataModels() const {
if (!IsAutofillEnabled())
return false;
// No autofill data to return if the profiles are empty.
if (personal_data_->GetProfiles().empty() &&
personal_data_->GetCreditCards().empty()) {
return false;
}
return true;
}
bool AutofillManager::GetProfileOrCreditCard(
int unique_id,
const AutofillDataModel** data_model,
size_t* variant) const {
// Unpack the |unique_id| into component parts.
GUIDPair credit_card_guid;
GUIDPair profile_guid;
UnpackGUIDs(unique_id, &credit_card_guid, &profile_guid);
DCHECK(!base::IsValidGUID(credit_card_guid.first) ||
!base::IsValidGUID(profile_guid.first));
// Find the profile that matches the |profile_guid|, if one is specified.
// Otherwise find the credit card that matches the |credit_card_guid|,
// if specified.
if (base::IsValidGUID(profile_guid.first)) {
*data_model = personal_data_->GetProfileByGUID(profile_guid.first);
*variant = profile_guid.second;
} else if (base::IsValidGUID(credit_card_guid.first)) {
*data_model = personal_data_->GetCreditCardByGUID(credit_card_guid.first);
*variant = credit_card_guid.second;
}
return !!*data_model;
}
bool AutofillManager::FindCachedForm(const FormData& form,
FormStructure** form_structure) const {
// Find the FormStructure that corresponds to |form|.
// Scan backward through the cached |form_structures_|, as updated versions of
// forms are added to the back of the list, whereas original versions of these
// forms might appear toward the beginning of the list. The communication
// protocol with the crowdsourcing server does not permit us to discard the
// original versions of the forms.
*form_structure = NULL;
for (std::vector<FormStructure*>::const_reverse_iterator iter =
form_structures_.rbegin();
iter != form_structures_.rend(); ++iter) {
if (**iter == form) {
*form_structure = *iter;
// The same form might be cached with multiple field counts: in some
// cases, non-autofillable fields are filtered out, whereas in other cases
// they are not. To avoid thrashing the cache, keep scanning until we
// find a cached version with the same number of fields, if there is one.
if ((*iter)->field_count() == form.fields.size())
break;
}
}
if (!(*form_structure))
return false;
return true;
}
bool AutofillManager::GetCachedFormAndField(const FormData& form,
const FormFieldData& field,
FormStructure** form_structure,
AutofillField** autofill_field) {
// Find the FormStructure that corresponds to |form|.
// If we do not have this form in our cache but it is parseable, we'll add it
// in the call to |UpdateCachedForm()|.
if (!FindCachedForm(form, form_structure) &&
!FormStructure(form).ShouldBeParsed(false)) {
return false;
}
// Update the cached form to reflect any dynamic changes to the form data, if
// necessary.
if (!UpdateCachedForm(form, *form_structure, form_structure))
return false;
// No data to return if there are no auto-fillable fields.
if (!(*form_structure)->autofill_count())
return false;
// Find the AutofillField that corresponds to |field|.
*autofill_field = NULL;
for (std::vector<AutofillField*>::const_iterator iter =
(*form_structure)->begin();
iter != (*form_structure)->end(); ++iter) {
if ((**iter) == field) {
*autofill_field = *iter;
break;
}
}
// Even though we always update the cache, the field might not exist if the
// website disables autocomplete while the user is interacting with the form.
// See http://crbug.com/160476
return *autofill_field != NULL;
}
bool AutofillManager::UpdateCachedForm(const FormData& live_form,
const FormStructure* cached_form,
FormStructure** updated_form) {
bool needs_update =
(!cached_form ||
live_form.fields.size() != cached_form->field_count());
for (size_t i = 0; !needs_update && i < cached_form->field_count(); ++i) {
needs_update = *cached_form->field(i) != live_form.fields[i];
}
if (!needs_update)
return true;
if (form_structures_.size() >= kMaxFormCacheSize)
return false;
// Add the new or updated form to our cache.
form_structures_.push_back(new FormStructure(live_form));
*updated_form = *form_structures_.rbegin();
(*updated_form)->DetermineHeuristicTypes(*metric_logger_);
// If we have cached data, propagate it to the updated form.
if (cached_form) {
std::map<base::string16, const AutofillField*> cached_fields;
for (size_t i = 0; i < cached_form->field_count(); ++i) {
const AutofillField* field = cached_form->field(i);
cached_fields[field->unique_name()] = field;
}
for (size_t i = 0; i < (*updated_form)->field_count(); ++i) {
AutofillField* field = (*updated_form)->field(i);
std::map<base::string16, const AutofillField*>::iterator cached_field =
cached_fields.find(field->unique_name());
if (cached_field != cached_fields.end()) {
field->set_server_type(cached_field->second->server_type());
field->is_autofilled = cached_field->second->is_autofilled;
}
}
// Note: We _must not_ remove the original version of the cached form from
// the list of |form_structures_|. Otherwise, we break parsing of the
// crowdsourcing server's response to our query.
}
// Annotate the updated form with its predicted types.
std::vector<FormStructure*> forms(1, *updated_form);
driver_->SendAutofillTypePredictionsToRenderer(forms);
return true;
}
void AutofillManager::GetProfileSuggestions(
FormStructure* form,
const FormFieldData& field,
const AutofillType& type,
std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) const {
std::vector<ServerFieldType> field_types(form->field_count());
for (size_t i = 0; i < form->field_count(); ++i) {
field_types.push_back(form->field(i)->Type().GetStorableType());
}
std::vector<GUIDPair> guid_pairs;
personal_data_->GetProfileSuggestions(
type, field.value, field.is_autofilled, field_types,
values, labels, icons, &guid_pairs);
for (size_t i = 0; i < guid_pairs.size(); ++i) {
unique_ids->push_back(PackGUIDs(GUIDPair(std::string(), 0),
guid_pairs[i]));
}
}
void AutofillManager::GetCreditCardSuggestions(
const FormFieldData& field,
const AutofillType& type,
std::vector<base::string16>* values,
std::vector<base::string16>* labels,
std::vector<base::string16>* icons,
std::vector<int>* unique_ids) const {
std::vector<GUIDPair> guid_pairs;
personal_data_->GetCreditCardSuggestions(
type, field.value, values, labels, icons, &guid_pairs);
for (size_t i = 0; i < guid_pairs.size(); ++i) {
unique_ids->push_back(PackGUIDs(guid_pairs[i], GUIDPair(std::string(), 0)));
}
}
void AutofillManager::ParseForms(const std::vector<FormData>& forms) {
std::vector<FormStructure*> non_queryable_forms;
for (std::vector<FormData>::const_iterator iter = forms.begin();
iter != forms.end(); ++iter) {
scoped_ptr<FormStructure> form_structure(new FormStructure(*iter));
if (!form_structure->ShouldBeParsed(false))
continue;
form_structure->DetermineHeuristicTypes(*metric_logger_);
// Set aside forms with method GET or author-specified types, so that they
// are not included in the query to the server.
if (form_structure->ShouldBeCrowdsourced())
form_structures_.push_back(form_structure.release());
else
non_queryable_forms.push_back(form_structure.release());
}
if (!form_structures_.empty() && download_manager_) {
// Query the server if we have at least one of the forms were parsed.
download_manager_->StartQueryRequest(form_structures_.get(),
*metric_logger_);
}
for (std::vector<FormStructure*>::const_iterator iter =
non_queryable_forms.begin();
iter != non_queryable_forms.end(); ++iter) {
form_structures_.push_back(*iter);
}
if (!form_structures_.empty())
metric_logger_->LogUserHappinessMetric(AutofillMetrics::FORMS_LOADED);
// For the |non_queryable_forms|, we have all the field type info we're ever
// going to get about them. For the other forms, we'll wait until we get a
// response from the server.
driver_->SendAutofillTypePredictionsToRenderer(non_queryable_forms);
}
int AutofillManager::GUIDToID(const GUIDPair& guid) const {
if (!base::IsValidGUID(guid.first))
return 0;
std::map<GUIDPair, int>::const_iterator iter = guid_id_map_.find(guid);
if (iter == guid_id_map_.end()) {
int id = guid_id_map_.size() + 1;
guid_id_map_[guid] = id;
id_guid_map_[id] = guid;
return id;
} else {
return iter->second;
}
}
const GUIDPair AutofillManager::IDToGUID(int id) const {
if (id == 0)
return GUIDPair(std::string(), 0);
std::map<int, GUIDPair>::const_iterator iter = id_guid_map_.find(id);
if (iter == id_guid_map_.end()) {
NOTREACHED();
return GUIDPair(std::string(), 0);
}
return iter->second;
}
// When sending IDs (across processes) to the renderer we pack credit card and
// profile IDs into a single integer. Credit card IDs are sent in the high
// word and profile IDs are sent in the low word.
int AutofillManager::PackGUIDs(const GUIDPair& cc_guid,
const GUIDPair& profile_guid) const {
int cc_id = GUIDToID(cc_guid);
int profile_id = GUIDToID(profile_guid);
DCHECK(cc_id <= std::numeric_limits<unsigned short>::max());
DCHECK(profile_id <= std::numeric_limits<unsigned short>::max());
return cc_id << std::numeric_limits<unsigned short>::digits | profile_id;
}
// When receiving IDs (across processes) from the renderer we unpack credit card
// and profile IDs from a single integer. Credit card IDs are stored in the
// high word and profile IDs are stored in the low word.
void AutofillManager::UnpackGUIDs(int id,
GUIDPair* cc_guid,
GUIDPair* profile_guid) const {
int cc_id = id >> std::numeric_limits<unsigned short>::digits &
std::numeric_limits<unsigned short>::max();
int profile_id = id & std::numeric_limits<unsigned short>::max();
*cc_guid = IDToGUID(cc_id);
*profile_guid = IDToGUID(profile_id);
}
void AutofillManager::UpdateInitialInteractionTimestamp(
const TimeTicks& interaction_timestamp) {
if (initial_interaction_timestamp_.is_null() ||
interaction_timestamp < initial_interaction_timestamp_) {
initial_interaction_timestamp_ = interaction_timestamp;
}
}
bool AutofillManager::ShouldUploadForm(const FormStructure& form) {
if (!IsAutofillEnabled())
return false;
if (driver_->IsOffTheRecord())
return false;
// Disregard forms that we wouldn't ever autofill in the first place.
if (!form.ShouldBeParsed(true))
return false;
return true;
}
} // namespace autofill
| [
"duki994@gmail.com"
] | duki994@gmail.com |
c8e919a5b376a96e806c4df689dbb6a6089a11b2 | c85635e522f8075ebf2fff39c60627c246a670e3 | /Experimentation/Investigations/Cryptography/DataEncryptionStandard/plans/Sboxes/Sbox_2.hpp | f0787d5768103e2cdc1f8109074b0127f37f40e6 | [] | no_license | MGwynne/oklibrary | 31fcccc5bb6a07cef1b18b937589d63336ee0b53 | 8087ca23d0855ccfd9a6ce29f4799f890afba6f1 | refs/heads/master | 2020-12-25T06:22:57.181997 | 2012-04-26T00:23:40 | 2012-04-26T00:23:40 | 38,967 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,588 | hpp | // Matthew Gwynne, 16.5.2011 (Swansea)
/* Copyright 2011 Oliver Kullmann
This file is part of the OKlibrary. OKlibrary 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 and included in this library; either version 3 of the
License, or any later version. */
/*!
\file Investigations/Cryptography/DataEncryptionStandard/plans/Sboxes/Sbox_2.hpp
\brief On investigations into Sbox two of the Data Encryption Standard
\todo Basic data
<ul>
<li> Generating the full CNF representation:
<ol>
<li> The CNF-file "DES_Sbox_2_fullCNF.cnf" is created by the Maxima-function
output_dessbox_fullcnf_stdname(2) in
ComputerAlgebra/Cryptology/Lisp/Cryptanalysis/DataEncryptionStandard/Sboxes.mac,
which is a full clause-set with 10
variables and 2^10 - 2^6 = 960 clauses:
\verbatim
> cat DES_Sbox_2_fullCNF.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 960 9600 0 9600 1 1
length count
10 960
\endverbatim
</li>
<li> This clause-set is also computed by
bf2relation_fullcnf_fcs(des_sbox_bf(2),6). </li>
</ol>
</li>
<li> The minimum CNF representation has at most 67 clauses. See
"Using weighted MaxSAT to compute small CNFs". </li>
</ul>
\todo Using weighted MaxSAT to compute small CNFs (mincl_rinf <= 67)
<ul>
<li> Computing the weighted MaxSAT problem:
\verbatim
shell> QuineMcCluskeySubsumptionHypergraph-n16-O3-DNDEBUG DES_Sbox_2_fullCNF.cnf > DES_Sbox_2_shg.cnf
shell> cat DES_Sbox_2_shg.cnf | MinOnes2WeightedMaxSAT-O3-DNDEBUG > DES_Sbox_2_shg.wcnf
\endverbatim
</li>
<li> Running then:
\verbatim
shell> ubcsat-okl -alg gsat -w -runs 100 -cutoff 400000 -wtarget 67 -solve 1 -seed 2521057446 -i DES_Sbox_2_shg.wcnf -r model DES_Sbox_2_s67.ass;
shell> cat DES_Sbox_2_fullCNF.cnf_primes | FilterDimacs DES_Sbox_2_s67.ass > DES_Sbox_2_s67.cnf
shell> cat DES_Sbox_2_s67.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 67 374 0 374 1 1
length count
5 30
6 35
7 2
\endverbatim
</li>
<li> The hardness of this "minimum" representation is 3:
<ul>
<li> See "Hardness of boolean function representations" in
Experimentation/Investigations/BooleanFunctions/plans/general.hpp
for a description of the notion of hardness, and method of computation.
</li>
<li> Computing the hardness:
\verbatim
maxima> Sbox_min_F : read_fcl_f("DES_Sbox_2_s67.cnf")$
maxima> Sbox_primes_F : read_fcl_f("DES_Sbox_2_fullCNF.cnf_primes")$
maxima> hardness_wpi_cs(setify(Sbox_min_F[2]), setify(Sbox_primes_F[2]));
3
\endverbatim
</li>
</ul>
</li>
</ul>
\todo 1-base : mincl_r1 <= 129
<ul>
<li> Computing an 1-base
\verbatim
shell> QuineMcCluskey-n16-O3-DNDEBUG DES_Sbox_2_fullCNF.cnf > DES_Sbox_2_pi.cnf
shell> RandomShuffleDimacs-O3-DNDEBUG 71 < DES_Sbox_2_pi.cnf | SortByClauseLength-O3-DNDEBUG > DES_Sbox_2_sortedpi.cnf
shell> RUcpGen-O3-DNDEBUG DES_Sbox_2_sortedpi.cnf > DES_Sbox_2_gen.cnf
shell> RandomShuffleDimacs-O3-DNDEBUG 1 < DES_Sbox_2_gen.cnf | SortByClauseLengthDescending-O3-DNDEBUG | RUcpBase-O3-DNDEBUG > DES_Sbox_2_1base.cnf
shell> cat DES_Sbox_2_1base.cnf | ExtendedDimacsFullStatistics-O3-DNDEBUG n
n non_taut_c red_l taut_c orig_l comment_count finished_bool
10 129 699 0 699 0 1
length count
5 75
6 54
\endverbatim
</li>
</ul>
\todo Move Sbox-1-specific investigations here
*/
| [
"360678@swan.ac.uk"
] | 360678@swan.ac.uk |
0eae995c3b3e4a08034826b49f98436928cb4d32 | ce6fd0670484b3fd7d7969240a032c4edca32a67 | /Editor/Editor/stb_image.cpp | eda4f283335d9eaabc52ae8edbd890900c36ade1 | [] | no_license | M0hammadx/C_Sharp_Apps | b96c30e06a7c5f615d53d3adc54b0486e8b1948e | e0f7987e3bd8c367ef56bedc98bd6e0e61d633c3 | refs/heads/master | 2020-03-24T18:30:46.477173 | 2019-01-25T02:35:54 | 2019-01-25T02:35:54 | 142,893,987 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | cpp | /*
* stb_image.cpp
*
* Created on: Oct 22, 2018
* Author: mh-sh
*/
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
| [
"mh-sherbini@hotmail.com"
] | mh-sherbini@hotmail.com |
1d11dc71461a26cfba5e51174fe2680f9e24c7a9 | 0a1252a1bbc41925d41ad7fc91b619f528ce817e | /lib/arduino/QuadEncoderSensor.cpp | 89c743f43105e52c4cfd94fadadf88a2b969345c | [] | no_license | IkonOne/invpend | b845c7018779c6bb8d8137f3911f95ece3bc76c8 | 7b9f9769812e8c2542bad6e6190cacb791e383cd | refs/heads/master | 2021-05-20T12:52:03.616356 | 2020-04-30T20:46:07 | 2020-04-30T20:46:07 | 252,304,634 | 0 | 1 | null | 2020-04-27T20:18:00 | 2020-04-01T22:57:05 | C++ | UTF-8 | C++ | false | false | 1,309 | cpp | #include "QuadEncoderSensor.h"
#include "Arduino.h"
// Core iplib libraries
#include "../MathHelpers.h"
/**
* QuadEncoderSensor Class Definition
*/
namespace iplib {
namespace arduino {
QuadEncoderSensor::QuadEncoderSensor(uint8_t emitterPin, uint8_t sensorPin0, uint8_t sensorPin1)
: _mapMin(-1.0f), _mapMax(1.0f)
{
_sensorPins[0] = sensorPin0;
_sensorPins[1] = sensorPin1;
_qtr.setTypeAnalog();
_qtr.setSensorPins(_sensorPins, 2);
_qtr.setEmitterPin(emitterPin);
_qtr.setSamplesPerSensor(1);
}
void QuadEncoderSensor::Calibrate(uint16_t duration_ms) {
// analogRead() takes about 0.1ms on avg
// 0.1ms * 1 sample per sensor * 2 sensors
// * 10 reads per calibrate() call = ~20ms per calibrate()
for (uint16_t i = 0; i < duration_ms / 20; ++i)
_qtr.calibrate();
}
void QuadEncoderSensor::Update() {
_qtr.read(_values);
}
void QuadEncoderSensor::SetMapRange(float min, float max) {
_mapMin = min;
_mapMax = max;
}
float QuadEncoderSensor::ReadMappedValue(int pin) {
return iplib::fmap(
_values[pin],
_qtr.calibrationOn.minimum[pin], _qtr.calibrationOn.maximum[pin],
_mapMin, _mapMax
);
}
uint16_t QuadEncoderSensor::ReadCalibratedValue(int pin) {
return _values[pin];
}
} // arduino
} // iplib | [
"ikonone@gmail.com"
] | ikonone@gmail.com |
2a778bc3ede5cd27064db7c1a3901af10c2f7356 | 0769f23da655feb037dc895251e074850e60be02 | /plugin_III/game_III/CPopulation.h | 54da93d8bfe8c385c6f4b6ae2cb437a7e9d87483 | [
"Zlib"
] | permissive | Aleksandr-Belousov/plugin-sdk | 8f3f8d5a51fe60cce3536d19803bf869378a57ae | 5ca5f7d5575ae4138a4f165410a1acf0ae922260 | refs/heads/master | 2020-09-16T10:31:41.400580 | 2019-11-24T13:29:22 | 2019-11-24T13:29:22 | 223,742,780 | 0 | 0 | Zlib | 2019-11-24T12:45:46 | 2019-11-24T12:45:46 | null | UTF-8 | C++ | false | false | 4,519 | h | /*
Plugin-SDK (Grand Theft Auto 3) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#pragma once
#include "PluginBase.h"
#include "CDummyObject.h"
#include "CObject.h"
#include "CPed.h"
#include "ePedType.h"
#include "CVector.h"
#include "eCopType.h"
#include "CVehicle.h"
#include "eLevelName.h"
#include "CColPoint.h"
class PLUGIN_API CPopulation {
public:
SUPPORTED_10EN_11EN_STEAM static float &PedDensityMultiplier;
SUPPORTED_10EN_11EN_STEAM static int &m_AllRandomPedsThisType;
SUPPORTED_10EN_11EN_STEAM static int &MaxNumberOfPedsInUse;
SUPPORTED_10EN_11EN_STEAM static CColPoint(&aTempColPoints)[32]; // static CColPoint aTempColPoints[32]
SUPPORTED_10EN_11EN_STEAM static int(&ms_pPedGroups)[31][8]; // static int ms_pPedGroups[31][8]
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalGangPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCop;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationPoint_b;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationPoint_a;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumDummy;
SUPPORTED_10EN_11EN_STEAM static CVector &RegenerationFront;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang8;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang9;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang2;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang3;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang1;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang6;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang7;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang4;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumGang5;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCivMale;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalCivPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumCivFemale;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalMissionPeds;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nNumEmergency;
SUPPORTED_10EN_11EN_STEAM static unsigned int &ms_nTotalPeds;
SUPPORTED_10EN_11EN_STEAM static bool &ms_bGivePedsWeapons;
SUPPORTED_10EN_11EN_STEAM static char &m_CountDownToPedsAtStart;
SUPPORTED_10EN_11EN_STEAM static bool &bZoneChangeHasHappened;
SUPPORTED_10EN_11EN_STEAM static CPed *AddPed(ePedType pedType, unsigned int modelIndex, CVector *posn);
SUPPORTED_10EN_11EN_STEAM static CPed *AddPedInCar(CVehicle *vehicle);
SUPPORTED_10EN_11EN_STEAM static void AddToPopulation(float z1, float x2, float y2, float z2);
SUPPORTED_10EN_11EN_STEAM static int ChooseCivilianOccupation(int index);
SUPPORTED_10EN_11EN_STEAM static int ChooseGangOccupation(int gangType);
SUPPORTED_10EN_11EN_STEAM static eCopType ChoosePolicePedOccupation();
SUPPORTED_10EN_11EN_STEAM static void ConvertAllObjectsToDummyObjects();
SUPPORTED_10EN_11EN_STEAM static void ConvertToDummyObject(CObject *object);
SUPPORTED_10EN_11EN_STEAM static void ConvertToRealObject(CDummyObject *dummyObject);
SUPPORTED_10EN_11EN_STEAM static void DealWithZoneChange(eLevelName levelName, eLevelName levelNameTwo, bool a3);
SUPPORTED_10EN_11EN_STEAM static void FindClosestZoneForCoors(CVector *point, int *a2, eLevelName levelName, eLevelName _levelName);
SUPPORTED_10EN_11EN_STEAM static void FindCollisionZoneForCoors(CVector *point, int *a2, eLevelName *levelName);
SUPPORTED_10EN_11EN_STEAM static void GeneratePedsAtStartOfGame();
SUPPORTED_10EN_11EN_STEAM static void Initialise();
SUPPORTED_10EN_11EN_STEAM static bool IsPointInSafeZone(CVector *point);
SUPPORTED_10EN_11EN_STEAM static void LoadPedGroups();
SUPPORTED_10EN_11EN_STEAM static void ManagePopulation();
SUPPORTED_10EN_11EN_STEAM static void MoveCarsAndPedsOutOfAbandonedZones();
SUPPORTED_10EN_11EN_STEAM static float PedCreationDistMultiplier();
SUPPORTED_10EN_11EN_STEAM static void RemovePed(CPed *ped);
SUPPORTED_10EN_11EN_STEAM static bool TestRoomForDummyObject(CObject *object);
SUPPORTED_10EN_11EN_STEAM static bool TestSafeForRealObject(CDummyObject *dummyObject);
SUPPORTED_10EN_11EN_STEAM static void Update();
SUPPORTED_10EN_11EN_STEAM static void UpdatePedCount(ePedType pedType, unsigned char updateState);
};
#include "meta/meta.CPopulation.h"
| [
"kenking@rambler.ru"
] | kenking@rambler.ru |
7ed3362cdc0d6c66261f8fdd301127f526dc0a36 | 440d8b37103bc3534089f8a65dc87870698dc828 | /src/codegen.cpp | 6dd8153e773a6210dc69ace158a36621efb9c568 | [] | no_license | sugu24/self-made-programming-language | 8946fa181c8767f16bc9624c7b72d6cdf606c3f3 | c00d450727b7d52e7cb76b22e93e85394d338af1 | refs/heads/master | 2023-08-27T22:39:59.041663 | 2021-11-06T04:14:23 | 2021-11-06T04:14:23 | 385,790,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 43,119 | cpp | #include "codegen.hpp"
/**
* コンストラクタ
*/
CodeGen::CodeGen(){
Builder = new llvm::IRBuilder<>(llvm::getGlobalContext());
Mod = NULL;
}
/**
* デストラクタ
*/
CodeGen::~CodeGen(){
SAFE_DELETE(Builder);
SAFE_DELETE(Mod);
}
/**
* コード生成実行
* @param TranslationUnitAST Module名(入力ファイル名)
* @return 成功時:true 失敗時:false
*/
bool CodeGen::doCodeGen(TranslationUnitAST &tunit, std::string name, std::string link_file, bool with_jit = false){
// Module生成に失敗したら終了
if(!generateTranslationUnit(tunit, name))
return false;
// LinkFileの指定があったらModuleをリンク
if(!link_file.empty() && !linkModule(Mod, link_file))
return false;
// JITのフラグふぁ立っていたらJIT
if(with_jit){
// ExecutionEngine生成
llvm::ExecutionEngine *EE = llvm::EngineBuilder(Mod).create();
// 実行したいFunctionのポインタを渡す(main関数へのポインタを取得)
llvm::Function *F;
if(!(F = Mod->getFunction("main")))
return false;
// JIT済みのmain関数のポインタを取得
int (*fp)() = (int (*)())EE->getPointerToFunction(F);
fprintf(stderr,"%d\n",fp());
}
return true;
}
/**
* Module取得
*/
llvm::Module &CodeGen::getModule(){
if(Mod)
return *Mod;
else
return *(new llvm::Module("null", llvm::getGlobalContext()));
}
/**
* Module生成メソッド
* @param TranslationUnitAST Module名(入力ファイル)
* @return 成功時:true 失敗時:false
*/
bool CodeGen::generateTranslationUnit(TranslationUnitAST &tunit, std::string name){
// Moduleを生成
Mod = new llvm::Module(name, llvm::getGlobalContext());
// printのFunction/////////////////////////////////////////////////
std::vector<llvm::Type*> printFuncArgs;
printFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *printFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
printFuncArgs,
true
);
llvm::Function *printFunc = llvm::Function::Create(
printFuncType,
llvm::GlobalValue::ExternalLinkage,
"printf",
Mod
);
printFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// scanfのFunction//////////////////////////////////////////////////
std::vector<llvm::Type*> scanFuncArgs;
scanFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *scanFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
scanFuncArgs,
true
);
llvm::Function *scanFunc = llvm::Function::Create(
scanFuncType,
llvm::GlobalValue::ExternalLinkage,
"__isoc99_scanf",
Mod
);
scanFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// sprintfのfunction ///////////////////////////////////////////////
std::vector<llvm::Type*> sprintFuncArgs;
sprintFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
sprintFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
llvm::FunctionType *sprintFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
sprintFuncArgs,
true
);
llvm::Function *sprintFunc = llvm::Function::Create(
sprintFuncType,
llvm::GlobalValue::ExternalLinkage,
"sprintf",
Mod
);
sprintFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// memsetのfunction ////////////////////////////////////////////////
std::vector<llvm::Type*> memsetFuncArgs;
memsetFuncArgs.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt8Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt64Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
memsetFuncArgs.push_back(llvm::Type::getInt1Ty(llvm::getGlobalContext()));
llvm::FunctionType *memsetFuncType = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),
memsetFuncArgs,
false
);
llvm::Function *memsetFunc = llvm::Function::Create(
memsetFuncType,
llvm::GlobalValue::ExternalLinkage,
"llvm.memset.p0i8.i64",
Mod
);
memsetFunc->setCallingConv(llvm::CallingConv::C);
////////////////////////////////////////////////////////////////////
// function declaration
for(int i = 0; ; i++){
PrototypeAST *proto = tunit.getPrototype(i);
if(!proto){
break;
}else if(!generatePrototype(proto, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
// function definition
// main最初
for(int i = 0; ;i++){
FunctionAST *func = tunit.getFunction(i);
if(!func)
break;
if(func->getPrototype()->getName() == "main"){
if(!generateFunctionDefinition(func, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
}
for(int i = 0; ;i++){
FunctionAST *func = tunit.getFunction(i);
if(!func)
break;
if(func->getPrototype()->getName() != "main"){
if(!generateFunctionDefinition(func, Mod)){
SAFE_DELETE(Mod);
return false;
}
}
}
return true;
}
/**
* 関数宣言生成メソッド
* @param PrototypeAST, Module
* @return 生成したFunctionのポインタ
*/
llvm::Function *CodeGen::generatePrototype(PrototypeAST *proto, llvm::Module *mod){
// already declared?
llvm::Function *func = mod->getFunction(proto->getName());
if(func){
if(func->arg_size() == proto->getParamNum() && func->empty()){
return func;
}else{
fprintf(stderr, "error::function %s is redefined", proto->getName().c_str());
return NULL;
}
}
// create arg_types
std::vector<llvm::Type*> arg_types;
for(int i=0; i < proto->getParamNum(); i++){
if(proto->getParamIdentify(i) == "int")
arg_types.push_back(llvm::Type::getInt32Ty(llvm::getGlobalContext()));
else if(proto->getParamIdentify(i) == "double")
arg_types.push_back(llvm::Type::getDoubleTy(llvm::getGlobalContext()));
else if(proto->getParamIdentify(i) == "string")
arg_types.push_back(llvm::Type::getInt8PtrTy(llvm::getGlobalContext()));
else
return NULL;
}
// create func type
llvm::FunctionType *func_type;
if(proto->getIdentify() == "double")
func_type = llvm::FunctionType::get(
llvm::Type::getDoubleTy(llvm::getGlobalContext()),arg_types,false);
else if(proto->getIdentify() == "int")
func_type = llvm::FunctionType::get(
llvm::Type::getInt32Ty(llvm::getGlobalContext()),arg_types,false);
// create function
func = llvm::Function::Create(func_type, llvm::Function::ExternalLinkage, proto->getName(), mod);
// set names
llvm::Function::arg_iterator arg_iter = func->arg_begin();
for(int i = 0; i < proto->getParamNum(); i++){
arg_iter->setName(proto->getParamName(i).append("_arg"));
arg_iter++;
}
return func;
}
/**
* 関数定義生成メソッド
* @param FunctionAST Module
* @return 生成したFunctionのポインタ
*/
llvm::Function *CodeGen::generateFunctionDefinition(FunctionAST *func_ast, llvm::Module *mod){
llvm::Function *func = generatePrototype(func_ast->getPrototype(), mod);
if(!func){ return NULL; }
CurFunc = func;
//FuncName = func_ast->getPrototype()->getName();
llvm::BasicBlock *bblock = llvm::BasicBlock::Create(llvm::getGlobalContext(), "entry", func);
Builder->SetInsertPoint(bblock);
// Functionのボディを生成
llvm::Value *f = generateFunctionStatement(func_ast->getBody(), func);
if(!f)
return NULL;
return func;
}
/**
* 関数生成メソッド
* 変数宣言、ステートメントの順に生成
* @param FunctionStmtAST
* @return 最後に生成した
*/
llvm::Value *CodeGen::generateFunctionStatement(FunctionStmtAST *func_stmt, llvm::Function *func){
// inser variable decls
VariableDeclAST *vdecl;
llvm::Value *v = NULL;
for(int i = 0; ;i++){
// 最後まで見たら終了
if(!func_stmt->getVariableDecl(i))
break;
//create alloca
vdecl = llvm::dyn_cast<VariableDeclAST>(func_stmt->getVariableDecl(i));
v = generateVariableDeclaration(vdecl);
}
// ifに対応する変数など
BaseAST *stmt;
llvm::BasicBlock *bblock;// Blockの生成と判定式が正の時格納
llvm::BasicBlock *bend; // ifの最後
llvm::BasicBlock *bcur; // ポイント設定
llvm::BasicBlock *bbfr; // 1つ前のBlock
llvm::BasicBlock *bago; // 2つ前のBlock
std::vector<llvm::BasicBlock*> bor; // True or の次にどこに行くか
std::vector<llvm::BasicBlock*> band; // False and の次にどこに行くか
llvm::BasicBlock *bfr;
llvm::Value *fcmp;
IfStatementAST *ifs;
ComparisonAST *com;
std::string ifStr;
static llvm::IRBuilderBase::InsertPoint ip;
// 1:判定方法if, else if, else 2:brを生成するBlock
// 3:条件式を満たした際に分岐するBlock 4:比較結果
std::vector<
std::tuple<std::string, llvm::BasicBlock*, llvm::BasicBlock*, llvm::Value*, int>
> blocks;
int depth;
std::vector<
std::tuple<llvm::BasicBlock*, llvm::BasicBlock*, llvm::Value*, ForStatementAST*>
> forVals;
std::map<ForStatementAST*, std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>>> breakVals;
std::map<ForStatementAST*, std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>>> continueVals;
for(int i = 0; ;i++){
// 最後まで見たら終了
stmt = func_stmt->getStatement(i);
if(!stmt)
break;
else if(llvm::isa<IfStatementAST>(stmt)){
if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "if"){
// 条件式の生成 (まだand or出来ない)
ifs = llvm::dyn_cast<IfStatementAST>(stmt);
for(int j = 0; j < ifs->getComparisonNumber(); j++){
com = ifs->getComparison(j);
fcmp = generateComparison(com->getLHS(), com->getRHS(), com->getOp(), func_stmt);
// もしand orがあったらBlockとbrを設定する
if(j < ifs->getOpsNumber()){
if(ifs->getOp(j) == "or"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"or.lhs.false", func);
// lhs or rhs のlhsがtrueならif.thenへ
// lhs or rhs のlhsがfalseならrhsへ
blocks.emplace_back("or",
Builder->GetInsertBlock(),
bblock, fcmp,ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
else if(ifs->getOp(j) == "and"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"and.lhs.true", func);
// lhs and rhsのlhsがtrueならrhsへ
// lhs and rhsのlhsがfalseならorのrhsへ
blocks.emplace_back("and",
Builder->GetInsertBlock(),
bblock, fcmp,ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
}
}
// 条件式を満たした先のBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.then", func);
// br情報
blocks.emplace_back("to if", Builder->GetInsertBlock(), bblock, fcmp,
ifs->getDepth(ifs->getOpsNumber()));
// 条件式が正の場合のBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
}
else if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "else if"){
// br情報 if か else if の内部にいる
blocks.emplace_back("to end", Builder->GetInsertBlock(), bblock, fcmp,0);
// 条件式を評価するBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.else", func);
// if.elseにポイントを合わせる
Builder->SetInsertPoint(bblock);
// ifの条件分岐からif.elseに分岐する
blocks.emplace_back("come if else",
Builder->GetInsertBlock(), bblock, fcmp, 0);
// 条件式を生成 (まだand or出来ない)
ifs = llvm::dyn_cast<IfStatementAST>(stmt);
for(int j = 0; j < ifs->getComparisonNumber(); j++){
com = ifs->getComparison(j);
fcmp = generateComparison(com->getLHS(), com->getRHS(), com->getOp(), func_stmt);
// もしand orがあったらBlockとbrを設定する
if(j < ifs->getOpsNumber()){
if(ifs->getOp(j) == "or"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"or.lhs.false", func);
// lhs or rhs のlhsがtrueならif.thenへ
// lhs or rhs のlhsがfalseならrhsへ
blocks.emplace_back("or",
Builder->GetInsertBlock(),
bblock, fcmp,
ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
else if(ifs->getOp(j) == "and"){
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(),
"and.lhs.true", func);
// lhs and rhsのlhsがtrueならrhsへ
// lhs and rhsのlhsがfalseならorのrhsへ
blocks.emplace_back("and",
Builder->GetInsertBlock(),
bblock, fcmp,
ifs->getDepth(j));
Builder->SetInsertPoint(bblock);
}
}
}
// 条件式が正を満たした先のBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.then", func);
// br情報
blocks.emplace_back("to else if", Builder->GetInsertBlock(), bblock, fcmp, ifs->getDepth(ifs->getOpsNumber()));
// 条件が正の場合のBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
}
else if(llvm::dyn_cast<IfStatementAST>(stmt)->getIf() == "else"){
// br情報 ifかelse ifにポイントが合っている
blocks.emplace_back("to end", Builder->GetInsertBlock(), bblock, fcmp, 0);
// elseのBlockを生成
bblock = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "if.else", func);
// elseのBlockにポイントを合わせる
Builder->SetInsertPoint(bblock);
blocks.emplace_back("come else",
Builder->GetInsertBlock(), bblock, fcmp, 0);
}
}
else if(llvm::isa<IfEndAST>(stmt)){
// 現在のポイントからif.endにbrする
bend = llvm::BasicBlock::Create(llvm::getGlobalContext(), "if.end", func);
Builder->CreateBr(bend);
// brを生成
bbfr = bend;
bago = NULL;
bcur = Builder->GetInsertBlock();
bfr = bend;
//bor = Builder->GetInsertBlock();
//band = bend;
bor.clear();
bor.push_back(bend);
band.clear();
band.push_back(bend);
while(true){
ifStr = std::get<0>(blocks.at(blocks.size()-1));
bblock = std::get<2>(blocks.at(blocks.size()-1));
fcmp = std::get<3>(blocks.at(blocks.size()-1));
depth = std::get<4>(blocks.at(blocks.size()-1));
if(ifStr == "or"){
//band = bfr;
while(depth >= band.size())
band.push_back(band.at(band.size()-1));
for(int j = depth; band.size() > j; j++)
band.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(bor.size() <= depth)
bor.push_back(bor.at(bor.size()-1));
Builder->CreateCondBr(fcmp, bor.at(depth), bblock);
}
else if(ifStr == "and"){
while(depth+1 >= bor.size())
bor.push_back(bor.at(bor.size()-1));
for(int j = depth+1; bor.size() > j; j++)
bor.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(band.size() <= depth)
band.push_back(band.at(band.size()-1));
Builder->CreateCondBr(fcmp, bblock, band.at(depth));
}
else{
bago = bbfr;
bbfr = bcur;
bcur = std::get<1>(blocks.at(blocks.size()-1));
if(ifStr == "to if" || ifStr == "to else if"){
Builder->SetInsertPoint(bcur);
Builder->CreateCondBr(fcmp, bblock, bago);
//bor = bblock;
bor.clear();
bor.push_back(bblock);
}
else if(ifStr == "come if else" || ifStr == "come else"){
//band = bcur;
band.clear();
band.push_back(bcur);
}
else if(ifStr == "to end"){
Builder->SetInsertPoint(bcur);
Builder->CreateBr(bend);
}
}
bfr = std::get<1>(blocks.at(blocks.size()-1));
blocks.pop_back();
if(ifStr == "to if")
break;
}
while(blocks.size() > 0 && (std::get<0>(blocks.at(blocks.size()-1)) == "or"
|| std::get<0>(blocks.at(blocks.size()-1)) == "and")){
ifStr = std::get<0>(blocks.at(blocks.size()-1));
bblock = std::get<2>(blocks.at(blocks.size()-1));
fcmp = std::get<3>(blocks.at(blocks.size()-1));
depth = std::get<4>(blocks.at(blocks.size()-1));
if(ifStr == "or"){
//band = bfr;
while(depth >= band.size())
band.push_back(band.at(band.size()-1));
for(int j = depth; band.size() > j; j++)
band.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(bor.size() <= depth)
bor.push_back(bor.at(bor.size()-1));
Builder->CreateCondBr(fcmp, bor.at(depth), bblock);
}
else if(ifStr == "and"){
while(depth+1 >= bor.size())
bor.push_back(bor.at(bor.size()-1));
for(int j = depth+1; bor.size() > j; j++)
bor.at(j) = bfr;
Builder->SetInsertPoint(
std::get<1>(blocks.at(blocks.size()-1)));
while(band.size() <= depth)
band.push_back(band.at(band.size()-1));
Builder->CreateCondBr(fcmp, bblock, band.at(depth));
}
bfr = std::get<1>(blocks.at(blocks.size()-1));
blocks.pop_back();
}
Builder->SetInsertPoint(bend);
}
else if(llvm::isa<ForStatementAST>(stmt)){
ForStatementAST *for_expr = llvm::dyn_cast<ForStatementAST>(stmt);
llvm::BasicBlock *bcond = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for.cond", CurFunc);
llvm::BasicBlock *bbody = llvm::BasicBlock::Create(
llvm::getGlobalContext(), "for.body", CurFunc);
llvm::Value *fcmp = generateForStatement(for_expr, bcond, bbody, func_stmt);
forVals.emplace_back(bcond, bbody, fcmp, for_expr);
}
else if(llvm::isa<ForEndAST>(stmt)){
llvm::BasicBlock *bcond = std::get<0>(forVals.at(forVals.size()-1));
llvm::BasicBlock *bbody = std::get<1>(forVals.at(forVals.size()-1));
llvm::Value *fcmp = std::get<2>(forVals.at(forVals.size()-1));
ForStatementAST *for_expr = std::get<3>(forVals.at(forVals.size()-1));
llvm::BasicBlock *binc = llvm::BasicBlock::Create(llvm::getGlobalContext(), "for.inc", CurFunc);
llvm::BasicBlock *bend = llvm::BasicBlock::Create(llvm::getGlobalContext(), "for.end", CurFunc);
generateForEndStatement(bcond, bbody, binc, bend, fcmp, for_expr, func_stmt);
llvm::BasicBlock *temp = Builder->GetInsertBlock();
forVals.pop_back();
if(breakVals.find(for_expr) != breakVals.end()){
for(int i = 0; i < breakVals[for_expr].size(); i++){
Builder->SetInsertPoint(std::get<0>(breakVals[for_expr].at(i)), ++std::get<1>(breakVals[for_expr].at(i)));
Builder->CreateBr(bend);
}
breakVals[for_expr].clear();
}
if(continueVals.find(for_expr) != continueVals.end()){
for(int i = 0; i < continueVals[for_expr].size(); i++){
Builder->SetInsertPoint(std::get<0>(continueVals[for_expr].at(i)), ++std::get<1>(continueVals[for_expr].at(i)));
Builder->CreateBr(binc);
}
continueVals[for_expr].clear();
}
Builder->SetInsertPoint(temp);
}
else if(llvm::isa<BreakAST>(stmt)){
BreakAST *break_expr = llvm::dyn_cast<BreakAST>(stmt);
llvm::BasicBlock *bcur = Builder->GetInsertBlock();
ForStatementAST *for_expr;
if(break_expr->getDepth() <= 0 || forVals.size() < break_expr->getDepth()){
fprintf(stderr, "break文のカッコの中の数を確認してください\n");
return NULL;
}
else
for_expr = std::get<3>(forVals.at(forVals.size()-break_expr->getDepth()));
if(breakVals.find(for_expr) == breakVals.end()){
std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>> temp;
breakVals[for_expr] = temp;
}
if(bcur->empty())
breakVals[for_expr].emplace_back(bcur, bcur->begin());
else{
llvm::BasicBlock::iterator iter = bcur->begin();
for(int i = 0; i < bcur->size()-1; i++)
iter++;
breakVals[for_expr].emplace_back(bcur, iter);
}
}
else if(llvm::isa<ContinueAST>(stmt)){
ContinueAST *continue_expr = llvm::dyn_cast<ContinueAST>(stmt);
llvm::BasicBlock *bcur = Builder->GetInsertBlock();
ForStatementAST *for_expr;
if(continue_expr->getDepth() <= 0 || forVals.size() < continue_expr->getDepth()){
fprintf(stderr, "continue文のカッコの中の数を確認してください.\n");
return NULL;
}
else
for_expr = std::get<3>(forVals.at(forVals.size()-continue_expr->getDepth()));
if(continueVals.find(for_expr) == continueVals.end()){
std::vector<std::tuple<llvm::BasicBlock*, llvm::BasicBlock::iterator>> temp;
continueVals[for_expr] = temp;
}
if(bcur->empty())
continueVals[for_expr].emplace_back(bcur, bcur->begin());
else{
llvm::BasicBlock::iterator iter = bcur->begin();
for(int i = 0; i < bcur->size()-1; i++)
iter++;
continueVals[for_expr].emplace_back(bcur, iter);
}
}
else if(llvm::isa<GlobalVariableAST>(stmt)){
GlobalVariableAST *gVar = llvm::dyn_cast<GlobalVariableAST>(stmt);
llvm::Value *check = Mod->getNamedGlobal(gVar->getName());
if(!check){
fprintf(stderr, "%d行目 : global で宣言された変数 %s はありません.\n", gVar->getLine(), gVar->getName().c_str());
CORRECT = false;
}
}else if(!llvm::isa<NullExprAST>(stmt))
v = generateStatement(stmt, func_stmt);
}
return v;
}
/**
* 変数宣言(alloca命令)生成メソッド
* @param VariableDeclAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateVariableDeclaration(VariableDeclAST *vdecl){
if(CurFunc->getName().str() == "main"){
Mod->getOrInsertGlobal(vdecl->getName(), llvm::Type::getDoubleTy(llvm::getGlobalContext()));
llvm::GlobalVariable *gvar = Mod->getNamedGlobal(vdecl->getName());
gvar->setLinkage(llvm::GlobalValue::CommonLinkage);
gvar->setInitializer(llvm::ConstantFP::get(llvm::Type::getDoubleTy(llvm::getGlobalContext()), 0));
return gvar;
}
else{
// create alloca
llvm::AllocaInst *alloca = NULL;
if(vdecl->getIdentify() == VariableDeclAST::dint)
alloca = Builder->CreateAlloca(llvm::Type::getInt32Ty(
llvm::getGlobalContext()), 0, vdecl->getName());
if(vdecl->getIdentify() == VariableDeclAST::ddouble)
alloca = Builder->CreateAlloca(llvm::Type::getDoubleTy(
llvm::getGlobalContext()), 0, vdecl->getName());
// if args alloca
if(vdecl->getType() == VariableDeclAST::param){
// store args
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
Builder->CreateStore(vs_table.lookup(vdecl->getName().append("_arg")), alloca);
}
return alloca;
}
}
/**
* ステートメント生成メソッド
* 実際にはASTの種類を確認して各種生成メソッドを呼び出し
* @param BaseAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateStatement(BaseAST *stmt, FunctionStmtAST *func_stmt){
if(llvm::isa<BinaryExprAST>(stmt)){
return generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(stmt), func_stmt);
}else if(llvm::isa<CallExprAST>(stmt)){
return generateCallExpression(llvm::dyn_cast<CallExprAST>(stmt), func_stmt);
}else if(llvm::isa<ReturnStmtAST>(stmt)){
return generateReturnStatement(llvm::dyn_cast<ReturnStmtAST>(stmt), func_stmt);
}else{
return NULL;
}
}
/**
* 二項演算生成メソッド
* @param JumpStmtAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateBinaryExpression(BinaryExprAST *bin_expr, FunctionStmtAST *func_stmt){
BaseAST *lhs = bin_expr->getLHS();
BaseAST *rhs = bin_expr->getRHS();
llvm::Value *lhs_v;
llvm::Value *rhs_v;
// = の場合に代入先に指定するValueを格納する
llvm::Value *assigned_v;
VariableAST *lhs_var;
// assignment
if(bin_expr->getOp() == "="){
// lhs is variable
lhs_var = llvm::dyn_cast<VariableAST>(lhs);
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(lhs_var->getName()))
assigned_v = Mod->getNamedGlobal(lhs_var->getName());
else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
assigned_v = vs_table.lookup(lhs_var->getName());
}
lhs_v = generateVariable(lhs_var, func_stmt);
// other operand
}else{
// lhs = ?
// Binary?
if(llvm::isa<BinaryExprAST>(lhs)){
lhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(lhs), func_stmt);
// CallExpr?
}else if(llvm::isa<CallExprAST>(lhs)){
lhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(lhs), func_stmt);
// Variable?
}else if(llvm::isa<VariableAST>(lhs)){
lhs_v = generateVariable(llvm::dyn_cast<VariableAST>(lhs), func_stmt);
// Number?
}else if(llvm::isa<NumberAST>(lhs)){
NumberAST *num = llvm::dyn_cast<NumberAST>(lhs);
lhs_v = generateNumber(num->getNumberValue());
}
}
// create rhs value
if(llvm::isa<BinaryExprAST>(rhs)){
rhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(rhs), func_stmt);
// CallExpr?
}else if(llvm::isa<CallExprAST>(rhs)){
rhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(rhs), func_stmt);
// Variable?
}else if(llvm::isa<VariableAST>(rhs)){
rhs_v = generateVariable(llvm::dyn_cast<VariableAST>(rhs), func_stmt);
// Number?
}else if(llvm::isa<NumberAST>(rhs)){
NumberAST *num = llvm::dyn_cast<NumberAST>(rhs);
rhs_v = generateNumber(num->getNumberValue());
}
// コード生成
if(bin_expr->getOp() == "="){
// store
return Builder->CreateStore(rhs_v, assigned_v);
}
if(bin_expr->getOp() == "+"){
// add
return Builder->CreateFAdd(lhs_v, rhs_v, "add_tmp");
}else if(bin_expr->getOp() == "-"){
// sub
return Builder->CreateFSub(lhs_v, rhs_v, "sub_tmp");
}else if(bin_expr->getOp() == "*"){
// mul
return Builder->CreateFMul(lhs_v, rhs_v, "mul_tmp");
}else if(bin_expr->getOp() == "/"){
generateDenominatorCheck("割り算", rhs, bin_expr->getLine(), func_stmt);
// div
return Builder->CreateFDiv(lhs_v, rhs_v,"div_tmp");
}
else if(bin_expr->getOp() == "//"){
generateDenominatorCheck("割り切り算", rhs, bin_expr->getLine(), func_stmt);
// div
llvm::Value *div_tmp = Builder->CreateFDiv(lhs_v, rhs_v, "div_tmp");
div_tmp = Builder->CreateCast(llvm::Instruction::FPToSI, div_tmp,
llvm::Type::getInt32Ty(llvm::getGlobalContext()));
div_tmp = Builder->CreateCast(llvm::Instruction::SIToFP, div_tmp,
llvm::Type::getDoubleTy(llvm::getGlobalContext()));
return div_tmp;
}
else if(bin_expr->getOp() == "%"){
generateDenominatorCheck("余り演算", rhs, bin_expr->getLine(), func_stmt);
// rem
return Builder->CreateFRem(lhs_v, rhs_v, "rem_tmp");
}
return NULL;
}
/**
* 関数呼び出し(Call命令)生成メソッド
* @param CallExprAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateCallExpression(CallExprAST *call_expr, FunctionStmtAST *func_stmt){
std::vector<llvm::Value*> arg_vec;
BaseAST *arg;
llvm::Value *arg_v;
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
std::string Str = "";
llvm::Value *val;
if(call_expr->getCallee() == "print" || call_expr->getCallee() == "input")
arg_vec.push_back(generateString(""));
if(call_expr->getCallee() == "input"){
VariableAST *var;
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
for(int i = 0; ; i++){
if(!(arg = call_expr->getArgs(i)))
break;
if(!llvm::isa<VariableAST>(arg)){
fprintf(stderr, "inputのカッコ内の変数を確認してください.\n");
return NULL;
}
var = llvm::dyn_cast<VariableAST>(arg);
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(var->getName()))
arg_vec.push_back(Mod->getNamedGlobal(var->getName()));
else
arg_vec.push_back(vs_table.lookup(var->getName()));
}
Str = "%lf";
for(int i = 0; i < arg_vec.size()-2; i++)
Str += " %lf";
arg_vec.at(0) = generateString(Str);
return Builder->CreateCall(Mod->getFunction("__isoc99_scanf"), arg_vec, "call_temp");
}
for(int i = 0; ;i++){
if(!(arg = call_expr->getArgs(i)))
break;
// isCall
if(llvm::isa<CallExprAST>(arg)){
arg_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(arg), func_stmt);
// isBinaryExpr
}else if(llvm::isa<BinaryExprAST>(arg)){
BinaryExprAST *bin_expr = llvm::dyn_cast<BinaryExprAST>(arg);
arg_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(arg), func_stmt);
if(bin_expr->getOp() == "="){
VariableAST *var = llvm::dyn_cast<VariableAST>(bin_expr->getLHS());
arg_v = generateVariable(var, func_stmt);
}
}
// isVar
else if(llvm::isa<VariableAST>(arg)){
arg_v = generateVariable(llvm::dyn_cast<VariableAST>(arg), func_stmt);
// isNumber
}else if(llvm::isa<NumberAST>(arg)){
NumberAST *num = llvm::dyn_cast<NumberAST>(arg);
arg_v = generateNumber(num->getNumberValue());
// string
}else if(llvm::isa<StringAST>(arg)){
StringAST *str = llvm::dyn_cast<StringAST>(arg);
arg_v = generateString(str->getStringValue());
// NewLine
}else if(llvm::isa<NewLineAST>(arg)){}
if(call_expr->getCallee() == "print"){
llvm::Value *print_string;
std::vector<llvm::Value*> print_vec;
std::vector<llvm::Value*> indices;
std::vector<llvm::Value*> memset_vec;
indices.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
indices.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
llvm::AllocaInst *print_str = Builder->CreateAlloca(llvm::ArrayType::get(llvm::Type::getInt8Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(Builder->CreatePointerCast(print_str, llvm::Type::getInt8PtrTy(llvm::getGlobalContext()), "print_str_temp"));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt8Ty(llvm::getGlobalContext()), 0));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt64Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 1));
memset_vec.push_back(llvm::ConstantInt::get(llvm::Type::getInt1Ty(llvm::getGlobalContext()), false));
Builder->CreateCall(Mod->getFunction("llvm.memset.p0i8.i64"), memset_vec, "call_temp");
if(llvm::isa<StringAST>(arg)){
print_vec.push_back(generateString("%s "));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}else if(llvm::isa<NewLineAST>(arg)){
print_vec.push_back(generateString("\n"));
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}else if(arg_v->getType()->isDoubleTy()){
std::string width;
std::string digit;
if(llvm::isa<VariableAST>(arg)){
width = llvm::dyn_cast<VariableAST>(arg)->getWidth();
digit = llvm::dyn_cast<VariableAST>(arg)->getDigit();
}
else if(llvm::isa<NumberAST>(arg)){
width = llvm::dyn_cast<NumberAST>(arg)->getWidth();
digit = llvm::dyn_cast<NumberAST>(arg)->getDigit();
}
else if(llvm::isa<BinaryExprAST>(arg)){
width = llvm::dyn_cast<BinaryExprAST>(arg)->getWidth();
digit = llvm::dyn_cast<BinaryExprAST>(arg)->getDigit();
}
else if(llvm::isa<CallExprAST>(arg)){
width = llvm::dyn_cast<CallExprAST>(arg)->getWidth();
digit = llvm::dyn_cast<CallExprAST>(arg)->getDigit();
}
else{
fprintf(stderr, "printに予期しない引数の型があります\n");
return NULL;
}
if(digit == "-1"){
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.0f "));
print_vec.push_back(generateString(width));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}
else if(digit == "-2"){
llvm::Value *mod = Builder->CreateFRem(arg_v, generateNumber(1), "rem_temp");
llvm::Value *fcmp = Builder->CreateFCmpOEQ(mod, generateNumber(0), "cmp");
llvm::BasicBlock *integer = llvm::BasicBlock::Create(llvm::getGlobalContext(), "int_arg", CurFunc);
llvm::BasicBlock *decimal = llvm::BasicBlock::Create(llvm::getGlobalContext(), "dec_arg", CurFunc);
llvm::BasicBlock *end = llvm::BasicBlock::Create(llvm::getGlobalContext(), "end_arg", CurFunc);
Builder->CreateCondBr(fcmp, integer, decimal);
Builder->SetInsertPoint(integer);
// int だったら
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.0f "));
print_vec.push_back(generateString(width));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
Builder->CreateBr(end);
// print_str.clear()
print_vec.clear();
Builder->SetInsertPoint(decimal);
// decだったら
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%.5f "));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
Builder->CreateBr(end);
Builder->SetInsertPoint(end);
}else{
val = Builder->CreateInBoundsGEP(print_str,indices, "print_array");
print_vec.push_back(val);
print_vec.push_back(generateString("%%%s.%sf "));
print_vec.push_back(generateString(width));
print_vec.push_back(generateString(digit));
Builder->CreateCall(Mod->getFunction("sprintf"), print_vec, "call_temp");
print_vec.clear();
print_vec.push_back(Builder->CreateInBoundsGEP(print_str, indices, "print_array"));
print_vec.push_back(arg_v);
val = Builder->CreateCall(Mod->getFunction("printf"), print_vec, "call_temp");
}
}
}
else {
arg_vec.push_back(arg_v);
}
}
if(call_expr->getCallee() == "print"){
return val;
}
else
return Builder->CreateCall(Mod->getFunction(call_expr->getCallee()), arg_vec, "call_temp");
}
/**
* ジャンプ(今回はreturn 命令のみ)生成メソッド
* @param JumpStmtAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateReturnStatement(ReturnStmtAST *jump_stmt, FunctionStmtAST *func_stmt){
BaseAST *expr = jump_stmt->getExpr();
llvm::Value *ret_v;
if(llvm::isa<BinaryExprAST>(expr)){
ret_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(expr), func_stmt);
}if(llvm::isa<CallExprAST>(expr)){
CallExprAST *call_expr = llvm::dyn_cast<CallExprAST>(expr);
ret_v = generateCallExpression(call_expr, func_stmt);
}else if(llvm::isa<VariableAST>(expr)){
VariableAST *var = llvm::dyn_cast<VariableAST>(expr);
ret_v = generateVariable(var, func_stmt);
}else if(llvm::isa<NumberAST>(expr)){
NumberAST *num = llvm::dyn_cast<NumberAST>(expr);
ret_v = generateNumber(num->getNumberValue());
}
if(!ret_v)
return NULL;
else{
if(CurFunc->getReturnType()->isIntegerTy() && ret_v->getType()->isDoubleTy())
ret_v = Builder->CreateCast(llvm::Instruction::FPToSI, ret_v,
llvm::Type::getInt32Ty(llvm::getGlobalContext()), "int_tmp");
else if(CurFunc->getReturnType()->isDoubleTy() && ret_v->getType()->isIntegerTy())
ret_v = Builder->CreateCast(llvm::Instruction::SIToFP, ret_v,
llvm::Type::getDoubleTy(llvm::getGlobalContext()), "double_tmp");
Builder->CreateRet(ret_v);
return ret_v;
}
}
/**
* 変数参照(load命令)生成メソッド
* @param VariableAST
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateVariable(VariableAST *var, FunctionStmtAST *func_stmt){
llvm::Value *value;
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(var->getName())){
value = Mod->getNamedGlobal(var->getName());
}else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
value = vs_table.lookup(var->getName());
}
return Builder->CreateLoad(value, "var_temp");
}
/**
* 定数生成メソッド
* @param 生成する定数の値
* @return 生成したValueのポインタ
*/
llvm::Value *CodeGen::generateNumber(double value){
return llvm::ConstantFP::get(llvm::Type::getDoubleTy(llvm::getGlobalContext()), value);
}
/**
* 文字列生成メソッド
* @param 生成する文字列
* @return 生成したValueポインタ
*/
llvm::Value *CodeGen::generateString(std::string str){
return Builder->CreateGlobalStringPtr(str, ".str");
}
/**
* Module結合用メソッド
*/
bool CodeGen::linkModule(llvm::Module *dest, std::string file_name){
llvm::SMDiagnostic err;
// Moduleの読み込み
llvm::Module *link_mod = llvm::ParseIRFile(file_name, err, llvm::getGlobalContext());
if(!link_mod)
return false;
// Moduleの結合
std::string err_msg;
if(llvm::Linker::LinkModules(dest, link_mod, llvm::Linker::DestroySource, &err_msg))
return false;
SAFE_DELETE(link_mod);
return true;
}
//////////////////////////////////////////////////////
//比較を生成
//////////////////////////////////////////////////////
llvm::Value *CodeGen::generateComparison(BaseAST *lhs, BaseAST *rhs, std::string op, FunctionStmtAST *func_stmt){
llvm::Value *lhs_v;
llvm::Value *rhs_v;
// 左辺値取得
if(llvm::isa<BinaryExprAST>(lhs)){
lhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(lhs), func_stmt);
}else if(llvm::isa<CallExprAST>(lhs)){
lhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(lhs), func_stmt);
}else if(llvm::isa<VariableAST>(lhs)){
lhs_v = generateVariable(llvm::dyn_cast<VariableAST>(lhs), func_stmt);
}else if(llvm::isa<NumberAST>(lhs)){
lhs_v = generateNumber(llvm::dyn_cast<NumberAST>(lhs)->getNumberValue());
}else{
fprintf(stderr, "タイプ%dの左辺値が取得できません\n", lhs->getValueID());
return NULL;
}
// 右辺値取得
if(llvm::isa<BinaryExprAST>(rhs)){
rhs_v = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(rhs), func_stmt);
}else if(llvm::isa<CallExprAST>(rhs)){
rhs_v = generateCallExpression(llvm::dyn_cast<CallExprAST>(rhs), func_stmt);
}else if(llvm::isa<VariableAST>(rhs)){
rhs_v = generateVariable(llvm::dyn_cast<VariableAST>(rhs), func_stmt);
}else if(llvm::isa<NumberAST>(rhs)){
rhs_v = generateNumber(llvm::dyn_cast<NumberAST>(rhs)->getNumberValue());
}else{
fprintf(stderr, "右辺値が取得できません\n");
return NULL;
}
// コード生成
if(op == "==")
return Builder->CreateFCmpOEQ(lhs_v, rhs_v, "cmp");
else if(op == ">=")
return Builder->CreateFCmpOGE(lhs_v, rhs_v, "cmp");
else if(op == ">")
return Builder->CreateFCmpOGT(lhs_v, rhs_v, "cmp");
else if(op == "<=")
return Builder->CreateFCmpOLE(lhs_v, rhs_v, "cmp");
else if(op == "<")
return Builder->CreateFCmpOLT(lhs_v, rhs_v, "cmp");
else if(op == "!=")
return Builder->CreateFCmpONE(lhs_v, rhs_v, "cmp");
else
return NULL;
}
// forを表すllvmirを生成
llvm::Value *CodeGen::generateForStatement(ForStatementAST *for_expr, llvm::BasicBlock *bcond, llvm::BasicBlock *bbody, FunctionStmtAST *func_stmt){
// 繰り返し変数の設定
if(!llvm::isa<BinaryExprAST>(for_expr->getBinExpr()) && for_expr->getBinExpr()->getOp() == "="){
fprintf(stderr, "for 繰り返し数 である必要があります。\n");
SAFE_DELETE(bcond);
SAFE_DELETE(bbody);
return NULL;
}
generateBinaryExpression(for_expr->getBinExpr(), func_stmt);
// to for.condへ
Builder->CreateBr(bcond);
Builder->SetInsertPoint(bcond);
// for cond
llvm::Value *roop_variable = generateVariable(for_expr->getVal(), func_stmt);
llvm::Value *end_val;
if(llvm::isa<BinaryExprAST>(for_expr->getEndExpr()))
end_val = generateBinaryExpression(llvm::dyn_cast<BinaryExprAST>(for_expr->getEndExpr()), func_stmt);
else if(llvm::isa<VariableAST>(for_expr->getEndExpr()))
end_val = generateVariable(llvm::dyn_cast<VariableAST>(for_expr->getEndExpr()), func_stmt);
else if(llvm::isa<NumberAST>(for_expr->getEndExpr()))
end_val = generateNumber(llvm::dyn_cast<NumberAST>(for_expr->getEndExpr())->getNumberValue());
if(!end_val){
fprintf(stderr, "for 繰り返し数 である必要があります\n");
return NULL;
}
llvm::Value *fcmp = Builder->CreateFCmpOLE(roop_variable, end_val, "cmp");
// for.bodyにbr for.incに設定
Builder->SetInsertPoint(bbody);
return fcmp;
}
// forEndを表すllvmirを生成
llvm::BasicBlock *CodeGen::generateForEndStatement(llvm::BasicBlock *bcond, llvm::BasicBlock *bbody, llvm::BasicBlock *binc, llvm::BasicBlock *bend, llvm::Value *fcmp, ForStatementAST *for_expr, FunctionStmtAST *func_stmt){
// for.bodyからfor.incへ
Builder->CreateBr(binc);
Builder->SetInsertPoint(binc);
// for.incの生成
llvm::Value *roop_var = generateVariable(for_expr->getVal(), func_stmt);
llvm::Value *temp_var = Builder->CreateFAdd(roop_var, generateNumber(1.0), "add_tmp");
if(CurFunc->getName().str() == "main" || func_stmt->isGlobalVariable(for_expr->getVal()->getName())){
roop_var = Mod->getNamedGlobal(for_expr->getVal()->getName());
}else{
llvm::ValueSymbolTable &vs_table = CurFunc->getValueSymbolTable();
roop_var = vs_table.lookup(for_expr->getVal()->getName());
}
Builder->CreateStore(temp_var, roop_var);
Builder->CreateBr(bcond);
// for.condの最後にbrを生成
Builder->SetInsertPoint(bcond);
Builder->CreateCondBr(fcmp, bbody, bend);
// for.endにpointを設定
Builder->SetInsertPoint(bend);
return bend;
}
/**
* 割り算の分母確認
*/
bool CodeGen::generateDenominatorCheck(std::string op, BaseAST *rhs, int line, FunctionStmtAST *func_stmt){
llvm::Value *fcmp = generateComparison(rhs, new NumberAST(0), "==", func_stmt);
llvm::BasicBlock *zero = llvm::BasicBlock::Create(llvm::getGlobalContext(), "denominator_zero", CurFunc);
llvm::BasicBlock *not_zero = llvm::BasicBlock::Create(llvm::getGlobalContext(), "not_denominator_zero", CurFunc);
Builder->CreateCondBr(fcmp, zero, not_zero);
Builder->SetInsertPoint(zero);
std::vector<llvm::Value*> arg_vec;
std::string error_denominator_zero = std::to_string(line) + "行目 : " + op + "の分母が 0 です.\n";
arg_vec.push_back(generateString(error_denominator_zero));
Builder->CreateCall(Mod->getFunction("printf"), arg_vec, "call_temp");
Builder->CreateRet(llvm::ConstantInt::get(llvm::Type::getInt32Ty(llvm::getGlobalContext()), 0));
Builder->SetInsertPoint(not_zero);
return true;
}
| [
"shayasugu@icloud.com"
] | shayasugu@icloud.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.