text
stringlengths 8
6.88M
|
|---|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "Durante.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Durante, "Durante" );
DEFINE_LOG_CATEGORY(LogDurante)
|
#include <iostream>
#include <string>
using namespace std;
int main(int argc, const char *argv[])
{
char no_null[] = {'A','B'};
string str(no_null,10);
cout << str << endl
<< "Size:" << str.size() << endl
<< "Capacity:" << str.capacity() << endl;
string &ref = str.erase(2,8);
cout << str << endl
<< "Size:" << str.size() << endl
<< "Capacity:" << str.capacity() << endl;
cout << str << endl
<< "Size:" << str.size() << endl
<< "Capacity:" << str.capacity() << endl;
cout << str << endl
<< str.compare("AbCD") << endl;
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
int as[1000000], save[1000000];
main()
{
int n;
while(cin>>n)
{
int i, p=0, dis;
for(i=1; i<=n; i++)
{
cin>>as[i];
if(i!=1 && as[i]<as[i-1])
{
p++;
dis = i;
}
}
// cout<<p<<endl;
if(p==0)printf("0\n");
else
{
if(p==1 && as[1]>=as[n])printf("%d\n", (n-dis)+1);
else
printf("-1\n");
}
}
return 0;
}
|
// g++ -O3 -DNDEBUG benchmarkX.cpp -o benchmarkX && time ./benchmarkX
#include <Eigen/Array>
using namespace std;
using namespace Eigen;
#ifndef REPEAT
#define REPEAT 10000
#endif
#ifndef SCALAR
#define SCALAR float
#endif
int main(int argc, char *argv[])
{
typedef Matrix<SCALAR, Eigen::Dynamic, Eigen::Dynamic> Mat;
Mat m(100, 100);
m.setRandom();
for(int a = 0; a < REPEAT; a++)
{
int r, c, nr, nc;
r = Eigen::ei_random<int>(0,10);
c = Eigen::ei_random<int>(0,10);
nr = Eigen::ei_random<int>(50,80);
nc = Eigen::ei_random<int>(50,80);
m.block(r,c,nr,nc) += Mat::Ones(nr,nc);
m.block(r,c,nr,nc) *= SCALAR(10);
m.block(r,c,nr,nc) -= Mat::constant(nr,nc,10);
m.block(r,c,nr,nc) /= SCALAR(10);
}
cout << m[0] << endl;
return 0;
}
|
/**
* Copyright (c) 2013, Timothy Stack
*
* 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 Timothy Stack 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 REGENTS 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 REGENTS 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.
*
* @file state-extension-functions.cc
*/
#include <string>
#include <stdint.h>
#include "base/opt_util.hh"
#include "config.h"
#include "lnav.hh"
#include "sql_util.hh"
#include "sqlite3.h"
#include "vtab_module.hh"
static nonstd::optional<int64_t>
sql_log_top_line()
{
const auto& tc = lnav_data.ld_views[LNV_LOG];
if (tc.get_inner_height() == 0_vl) {
return nonstd::nullopt;
}
return (int64_t) tc.get_top();
}
static nonstd::optional<std::string>
sql_log_top_datetime()
{
const auto& tc = lnav_data.ld_views[LNV_LOG];
if (tc.get_inner_height() == 0_vl) {
return nonstd::nullopt;
}
auto top_time = lnav_data.ld_log_source.time_for_row(
lnav_data.ld_views[LNV_LOG].get_top());
if (!top_time) {
return nonstd::nullopt;
}
char buffer[64];
sql_strftime(buffer, sizeof(buffer), top_time.value());
return buffer;
}
static nonstd::optional<std::string>
sql_lnav_top_file()
{
auto top_view_opt = lnav_data.ld_view_stack.top();
if (!top_view_opt) {
return nonstd::nullopt;
}
auto* top_view = top_view_opt.value();
return top_view->map_top_row([](const auto& al) {
return get_string_attr(al.get_attrs(), logline::L_FILE) |
[](const auto wrapper) {
auto lf = wrapper.get();
return nonstd::make_optional(lf->get_filename());
};
});
}
static const char*
sql_lnav_version()
{
return PACKAGE_VERSION;
}
static int64_t
sql_error(const char* str, nonstd::optional<string_fragment> reason)
{
auto um = lnav::console::user_message::error(str);
if (reason) {
um.with_reason(reason->to_string());
}
throw um;
}
static nonstd::optional<std::string>
sql_echoln(nonstd::optional<std::string> arg)
{
if (arg) {
auto& ec = lnav_data.ld_exec_context;
auto outfile = ec.get_output();
if (outfile) {
fmt::print(outfile.value(), FMT_STRING("{}\n"), arg.value());
if (outfile.value() == stdout) {
lnav_data.ld_stdout_used = true;
}
}
}
return arg;
}
int
state_extension_functions(struct FuncDef** basic_funcs,
struct FuncDefAgg** agg_funcs)
{
static struct FuncDef state_funcs[] = {
sqlite_func_adapter<decltype(&sql_log_top_line), sql_log_top_line>::
builder(
help_text("log_top_line",
"Return the line number at the top of the log view.")
.sql_function()),
sqlite_func_adapter<decltype(&sql_log_top_datetime),
sql_log_top_datetime>::
builder(help_text("log_top_datetime",
"Return the timestamp of the line at the top of "
"the log view.")
.sql_function()),
sqlite_func_adapter<decltype(&sql_lnav_top_file), sql_lnav_top_file>::
builder(help_text("lnav_top_file",
"Return the name of the file that the top line "
"in the current view came from.")
.sql_function()),
sqlite_func_adapter<decltype(&sql_lnav_version), sql_lnav_version>::
builder(
help_text("lnav_version", "Return the current version of lnav")
.sql_function()),
sqlite_func_adapter<decltype(&sql_error), sql_error>::builder(
help_text("raise_error",
"Raises an error with the given message when executed")
.sql_function()
.with_parameter({"msg", "The error message"})
.with_parameter(
help_text("reason", "The reason the error occurred")
.optional())
.with_example({
"To raise an error if a variable is not set",
"SELECT ifnull($val, raise_error('please set $val', "
"'because'))",
}))
.with_flags(SQLITE_UTF8),
sqlite_func_adapter<decltype(&sql_echoln), sql_echoln>::builder(
help_text("echoln",
"Echo the argument to the current output file and return "
"it")
.sql_function()
.with_parameter(
{"value", "The value to write to the current output file"})
.with_tags({"io"}))
.with_flags(SQLITE_UTF8),
{nullptr},
};
*basic_funcs = state_funcs;
return SQLITE_OK;
}
|
/*
* application_cache_common.h
*
* Created on: Nov 16, 2009
* Author: hmolland
*/
#ifndef APPLICATION_CACHE_COMMON_H_
#define APPLICATION_CACHE_COMMON_H_
#define MANIFEST_FILENAME UNI_L("manifest.mst")
#define APPLICATION_CACHE_XML_FILE_NAME UNI_L("cache_groups.xml")
#define CACHE_FOLDER_NAME_LENGTH (32)
#define APPLICATION_CACHE_LOAD_TIMEOUT (1*60*1000) /* 1 minute */
#include "modules/url/url2.h"
/* Caches that are not fully restored from disk after a shutdown/startup
* of opera are stored as UnloadedDiskCache objects. Each cache are
* read up from the cache_group.xml file and stored in this object until
* the cache is used. When first used the read ApplicationCacheGroup and
* ApplicationCache are restored. Only the Most recent complete and non-oboslete
* cache is stored on disk for each group.
*/
class ApplicationCacheGroup;
class DOM_Environment;
struct UnloadedDiskCache
{
UnloadedDiskCache()
: m_cache_disk_size(0)
, m_cache_disk_quota(0)
{}
URL m_manifest;
OpString m_manifest_url;
OpAutoVector<OpString> m_master_urls;
OpString m_location;
UINT m_cache_disk_size; // how much the cache uses on disk in kilobytes.
int m_cache_disk_quota;
};
struct UpdateAlgorithmArguments : public Link
{
UpdateAlgorithmArguments(DOM_Environment *cache_host, const URL &manifest_url, const URL &master_url, ApplicationCacheGroup *cache_group)
: m_cache_host(cache_host)
, m_cache_group(cache_group)
, m_schedueled_for_start(FALSE)
, m_owner(NULL)
{
m_manifest_url = manifest_url;
m_master_url = master_url;
}
~UpdateAlgorithmArguments();
DOM_Environment *m_cache_host;
URL m_manifest_url;
URL m_master_url;
ApplicationCacheGroup *m_cache_group;
BOOL m_schedueled_for_start;
ApplicationCacheGroup *m_owner;
};
#endif /* APPLICATION_CACHE_COMMON_H_ */
|
//
// Created by dylan on 26-5-2020.
//
#ifndef CPSE2_GRAPHICAL_USER_INTERFACE_HPP
#define CPSE2_GRAPHICAL_USER_INTERFACE_HPP
#include <vector>
#include <SFML/Graphics.hpp>
#include "game_interface.hpp"
#include "board_builder.hpp"
#include "game_logic.hpp"
class graphical_user_interface : public game_interface {
private:
sf::RenderWindow &window;
public:
explicit graphical_user_interface(sf::RenderWindow &window);
void draw_image(bool player, float pos_x, float pos_y);
void draw_end_screen_image(std::string file_name, float x_pos, float y_pos);
void draw_moves(std::vector<game_moves> &moves) override;
void end_game(float game_state) override;
game_moves get_move(bool player) override;
};
#endif //CPSE2_GRAPHICAL_USER_INTERFACE_HPP
|
#include "Map.h" // Defines template Map<Key, Value>
#include "Employee.h" // Defines class Employee
#include "BookInfo.h"
#include <iostream>
using namespace std;
int main() {
typedef unsigned int ID; // Identification number of Employee
Map<ID, Employee> database; // Database of employees
database.add(761028073, Employee("Jan Kowalski", "salesman", 28)); // Add first employee: name: Jan Kowalski, position: salseman, age: 28,
database.add(510212881, Employee("Adam Nowak", "storekeeper", 54)); // Add second employee: name: Adam Nowak, position: storekeeper, age: 54
database.add(730505129, Employee("Anna Zaradna", "secretary", 32)); // Add third employee: name: Anna Zaradna, position: secretary, age: 32
cout << "ORIGINAL DB:" << endl << database << endl; // Print database
Map<ID, Employee> newDatabase = database; // Make a copy of database (copy constructor called)
Employee* pE;
pE = newDatabase.find(510212881); // Find employee using its ID
pE->position = "salesman"; // Modify the position of employee
pE = newDatabase.find(761028073); // Find employee using its ID
pE->age = 29; // Modify the age of employee
database = newDatabase; // Update original database (assignment operator called)
cout << "MODIFIED DB: " << endl << database << endl; // Print original database*/
typedef string BookTitle;
Map<BookTitle, BookInfo> library;
library.add("The Adventures of Tom Sawyer", BookInfo("Mark Twain", "Children's literature", 200, BookInfo::ONTHEBOOKSHELF));
library.add("Romeo and Juliet", BookInfo("William Shakespeare ", "Tragedy", 120, BookInfo::BORROWED));
library.add("Metro 2033", BookInfo("Dmitry Glukhovsky", "Post-apocalyptic", 350, BookInfo::ONTHEBOOKSHELF));
cout << endl << "=== LIBRARY ===" << endl;
cout << library;
}
|
// kumaran_14
#include <bits/stdc++.h>
using namespace std;
#define f first
#define s second
#define p push
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define foi(i, a, n) for (i = (a); i < (n); ++i)
#define foii(i, a, n) for (i = (a); i <= (n); ++i)
#define fod(i, a, n) for (i = (a); i > (n); --i)
#define fodd(i, a, n) for (i = (a); i >= (n); --i)
#define debug(x) cout << '>' << #x << ':' << x << endl;
#define all(v) v.begin(), v.end()
#define sz(x) ((int)(x).size())
#define endl " \n"
#define MAXN 100005
#define MOD 1000000007LL
#define EPS 1e-13
#define INFI 1000000000 // 10^9
#define INFLL 1000000000000000000ll //10^18
#define l long int
#define d double
#define ll long long int
#define ld long double
#define vi vector<int>
#define vll vector<long long>
#define vvi vector<vector<int>>
#define vvll vector<vll>
//vector<vector<int>> v(10, vector<int>(20,500)); 2d vector initialization. of 10 rows and 20 columns, with value 500.
#define mii map<int, int>
#define mll map<long long, long long>
#define pii pair<int, int>
#define pll pair<long long, long long>
#define fast_io() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL); \
cout.tie(NULL);
ll tc, n, m, k;
// ll ans = 0, c = 0;
ll i, j;
// ll a, b;
// ll x, y;
// polynomial rolling hash function, for lowercase letters
// collision probability is 1/M;
ll compute_hash(string const& str) {
ll P = 31;
ll M = 1e9 + 9;
ll hash_val = 0;
ll strsize = sz(str);
vll p_pow(strsize);
p_pow[0] = 1;
foi(i, 1, strsize) {
p_pow[i] = (p_pow[i-1]*P)%M;
}
foi(i, 0, sz(str)) {
hash_val += ((str[i]-'a'+1)*p_pow[i])%M;
}
return hash_val;
}
int main()
{
fast_io();
freopen("./input.txt", "r", stdin);
freopen("./output.txt", "w", stdout);
string str = "kumaran";
cout<<compute_hash(str);
return 0;
}
|
#include <cassert>
#include "Population.hpp"
Population::Population()
{
assert(Conf::MAX_POP > Conf::INITIAL_INFECTIONS);
infection_history.reserve(Conf::SIM_HOURS);
humans.reserve(Conf::MAX_POP);
Human * h;
for(uint32_t i = 0; i< Conf::MAX_POP;i++)
{
h = new Human();
humans.push_back(h);
h->setWaypoint(sf::Vector2f(gRandom((int)Conf::MAX_WIDTH),
gRandom((int)Conf::MAX_WIDTH)));
}
for(uint32_t i = 0; i< Conf::INITIAL_INFECTIONS;i++)
{
humans[i]->setStatus(Status::Infected);
}
}
Population::~Population()
{
for(auto h: humans)
{
delete h;
}
}
void Population::renderPopulation(sf::RenderWindow & mWindow)
{
for(auto it: humans)
{
it->mRenderHuman(mWindow);
}
}
void Population::movePopulation(float timeperframe)
{
for(auto it: humans)
{
it->mMove(timeperframe);
}
}
void Population::stepInfection()
{
for(auto it1: humans)
{
for(auto it2: humans)
{
if(it1->getStatus() == Status::Infected)
{
if(it1 != it2)
{
if(it2->getStatus() == Status::Vulnerable)
{
sf::Vector2f pos2target = it1->getPos() - it2->getPos();
float mag = sqrt(pow(pos2target.x, 2) + pow(pos2target.y , 2));
if(mag<=Conf::INFECTION_PROXIMITY)
{
if(gChance(Conf::INFECTION_PROBABILITY))
{
it2->setStatus(Status::Infected);
}
}
}
}
}
}
}
}
|
#include <stdio.h>
void top_up_100(int *cost, int x){
*cost += x;
}
int main(){
int a = 10;
top_up_100(&a, 100);
printf("%d\n", a);
}
|
#ifndef PORT_SYNFIRE_HELPERS_H
#define PORT_SYNFIRE_HELPERS_H
#include <stdlib.h>
#include <iostream>
#include <string>
struct SynfireParameters {
SynfireParameters();
SynfireParameters(int argc, char *argv[]);
void SetDefaults();
int network_size;
bool stats_on;
// bool LOAD = false; //1 means load data
// bool ILOAD = false;
//~ Trial parameters.
int trials; // default # of trials
double timestep; // timestep (ms)
double trial_duration; // length of trial (ms)
//~ Save strings
// string loadpath, iloadpath, synapse_path = "syn/syn", roster_path = "roster/roster", volt_e_path = "volt/volt_ensemble";
// string volt_t_path = "volt/volt_track_", conn_path = "connect/connect", r_conn_path = "read/net_struct";
// string dat_suff = ".dat", txt_suff = ".txt", sim_base = ".", sim_lab;
// int synapse_save = 100, roster_save = 1000, volt_save = 1000, conn_save = 1000; //save data intervals
//~ Tracking variables during trial
// ofstream track_volt; // stream that tracks volt and conds during trial
// int volt_post, volt_pre = 0; // contains the label of the neuron whose voltage is being tracked, it postsynaptic to volt_pre
//~ Spontaneous activity defaults
double exfreq, infreq, examp, inamp, global_i, inh_d, leak;
// Synapses defaults
int NSS, tempNSS; // max # of supersynapses allowed.
double act, sup, cap, frac, isynmax, eq_syn;
double syndec;
int conn_type;
bool plasticity;
double window; // history time window size (ms)
//~ Training defaults
int ntrain, ntrg; // number of training neurons
bool man_tt; // manual training time bool (false if training occurs at t=0)
double training_f; // training spike frequency (ms)^(-1)
double training_amp; // training spike strength
double training_t; // training duration in ms
};
#endif //PORT_SYNFIRE_HELPERS_H
|
#ifndef __BASE_PROCESS_H__
#define __BASE_PROCESS_H__
#include <string>
#include "CDLSocketHandler.h"
#include "Packet.h"
#define _NOTUSED(V) ((void) V)
class BaseProcess;
typedef struct Context {
int netfd;
unsigned int seq;
char status;
PacketHeader msgHeader;
BaseProcess *process;
CDLSocketHandler *client;
void *data;
} Context;
class BaseProcess {
public:
BaseProcess(bool encrypt = false) {
bEncrypt = encrypt;
};
virtual ~BaseProcess() {
};
virtual int doRequest(CDLSocketHandler *handler, InputPacket *inputPacket, Context *pt) { return 0; }
virtual int doResponse(CDLSocketHandler *handler, InputPacket *inputPacket, Context *pt) { return 0; }
bool isEncryptCmd() const { return bEncrypt; }
//NOTE:仅用于新版加密大厅,其余地方不应该调用该操作
void setEncryptCmd(bool encrypt) { bEncrypt = encrypt; }
public:
std::string name;
short cmd;
protected:
int sendErrorMsg(CDLSocketHandler *handler, int cmd, int uid, short errcode, unsigned short seq = 0);
int sendErrorMsg(CDLSocketHandler *handler, int cmd, int uid, short errcode, const char *errmsg,
unsigned short seq = 0);
int send(CDLSocketHandler *handler, OutputPacket *outPack, bool isEncrypt = true);
private:
bool bEncrypt;
};
#endif
|
#pragma once
namespace rasutil {
/// Thunks a member function pointer into a normal functor
/// Specifically, converts it into an empty functor with an operator() that
/// takes a T* as its first argument.
template<class F>
struct thunk_func;
/// Implementation specialization of thunk_func<F>
template<class R, class C, class...Args>
struct thunk_func<R(C::*)(Args...)> {
using func_type = R(C::*)(Args...);
thunk_func(func_type f) : f(f) {}
inline R operator()(C* c, Args...args) {
return (c->*f)(std::forward<Args>(args)...);
}
private:
func_type f;
};
template<class R, class C, class...Args>
thunk_func<R(C::*)(Args...)> thunk(R(C::*f)(Args...)) {
return thunk_func<R(C::*)(Args...)>(f);
}
}
|
/*Implementation of thread pool module.*/
#include "cc/shared/thread_pool.h"
#include "cc/shared/thread_wrapper.h"
#include <unistd.h>
namespace cc_shared {
ThreadPool::ThreadPool(int num_threads)
: threads_(new(std::nothrow) ThreadWrapper [num_threads]),
num_threads_(num_threads),
wake_count_(0),
accepting_(true) {
RT_ASSERT(num_threads_ > 0);
pthread_mutexattr_t mutexattr;
int result = pthread_mutexattr_init(&mutexattr);
RT_ASSERT_EQ(0, result);
result = pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK);
RT_ASSERT_EQ(0, result);
result = pthread_mutex_init(&mutex_, &mutexattr);
RT_ASSERT_EQ(0, result);
result = pthread_mutexattr_destroy(&mutexattr);
RT_ASSERT_EQ(0, result);
for (int i = 0; i < num_threads_; ++i) {
get_thread(i)->start_thread(thread_pool_static_func,
static_cast<void*>(this), NULL);
}
}
ThreadPool::~ThreadPool() {
lock();
accepting_ = false;
unlock();
// Signal sleeping threads to wake up and finish pending items.
event_.signal();
for (int i = 0; i < num_threads_; ++i) {
get_thread(i)->join();
}
RT_ASSERT_EQ(0, waiting_count_.get_snapshot())
<< "Waiting threads must be woken up.";
int result = pthread_mutex_destroy(&mutex_);
RT_ASSERT_EQ(0, result);
}
void ThreadPool::lock() {
int result = pthread_mutex_lock(&mutex_);
RT_ASSERT_EQ(0, result);
}
void ThreadPool::unlock() {
int result = pthread_mutex_unlock(&mutex_);
RT_ASSERT_EQ(0, result);
}
void ThreadPool::enqueue(ThreadPoolPayload payload) {
lock();
RT_ASSERT(accepting_) << "Unexpected attempt to enqueue to aborting pool.";
requests_.push(payload);
// Awaken threads if needed. waiting_count_ gets incremented under lock, so
// it won't go up now. It can go down because the event is being signaled
// here and waiting_count_ gets decremented after the threads are awakened.
if (waiting_count_.get_snapshot() > 0) {
event_.signal();
while (0 != waiting_count_.get_snapshot()) {
usleep(1000);
}
event_.reset();
++wake_count_;
}
unlock();
}
const int ThreadPool::kSleepMilliSeconds = 20;
void ThreadPool::thread_pool_func() {
static const int kMaxIdleCount = 51;
// If the idling duration is too small, threads can go to sleep in quick
// succession. This would mean the caller signaling the wait event won't get
// to know that the signal is safe to be reset. That could create an infinite
// loop in the enqueue method.
CT_ASSERT(kMaxIdleCount * kSleepMilliSeconds >= 1000);
int idle_count = 0;
while (1) {
bool do_execute = false;
bool do_quit = false;
bool do_sleep = false;
ThreadPoolPayload payload;
lock();
if (!requests_.empty()) {
idle_count = 0;
payload = requests_.front();
requests_.pop();
do_execute = true;
} else if (!accepting_) {
do_quit = true;
} else {
++idle_count;
do_sleep = (idle_count < kMaxIdleCount);
if (!do_sleep) {
// It is important to increment this before releasing the mutex.
waiting_count_.increment_and_get();
}
}
unlock();
if (do_execute) {
payload.execute();
}
else if (do_quit) {
break;
} else if (do_sleep) {
usleep(1000 * kSleepMilliSeconds);
} else {
event_.wait_for_signal();
waiting_count_.decrement_and_get();
idle_count = 0;
}
}
}
void ThreadPool::thread_pool_static_func(void* parameter) {
static_cast<ThreadPool*>(parameter)->thread_pool_func();
}
} // cc_shared
|
// Created on: 1994-02-16
// Created by: Remi LEQUETTE
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepBuilderAPI_MakeShell_HeaderFile
#define _BRepBuilderAPI_MakeShell_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BRepLib_MakeShell.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <Standard_Real.hxx>
#include <BRepBuilderAPI_ShellError.hxx>
class Geom_Surface;
class TopoDS_Shell;
//! Describes functions to build a
//! shape corresponding to the skin of a surface.
//! Note that the term shell in the class name has the same definition
//! as that of a shell in STEP, in other words the skin of a shape,
//! and not a solid model defined by surface and thickness. If you want
//! to build the second sort of shell, you must use
//! BRepOffsetAPI_MakeOffsetShape. A shell is made of a series of
//! faces connected by their common edges.
//! If the underlying surface of a face is not C2 continuous and
//! the flag Segment is True, MakeShell breaks the surface down into
//! several faces which are all C2 continuous and which are
//! connected along the non-regular curves on the surface.
//! The resulting shell contains all these faces.
//! Construction of a Shell from a non-C2 continuous Surface
//! A MakeShell object provides a framework for:
//! - defining the construction of a shell,
//! - implementing the construction algorithm, and
//! - consulting the result.
//! Warning
//! The connected C2 faces in the shell resulting from a decomposition of
//! the surface are not sewn. For a sewn result, you need to use
//! BRepOffsetAPI_Sewing. For a shell with thickness, you need to use
//! BRepOffsetAPI_MakeOffsetShape.
class BRepBuilderAPI_MakeShell : public BRepBuilderAPI_MakeShape
{
public:
DEFINE_STANDARD_ALLOC
//! Constructs an empty shell framework. The Init
//! function is used to define the construction arguments.
//! Warning
//! The function Error will return
//! BRepBuilderAPI_EmptyShell if it is called before the function Init.
Standard_EXPORT BRepBuilderAPI_MakeShell();
//! Constructs a shell from the surface S.
Standard_EXPORT BRepBuilderAPI_MakeShell(const Handle(Geom_Surface)& S, const Standard_Boolean Segment = Standard_False);
//! Constructs a shell from the surface S,
//! limited in the u parametric direction by the two
//! parameter values UMin and UMax, and limited in the v
//! parametric direction by the two parameter values VMin and VMax.
Standard_EXPORT BRepBuilderAPI_MakeShell(const Handle(Geom_Surface)& S, const Standard_Real UMin, const Standard_Real UMax, const Standard_Real VMin, const Standard_Real VMax, const Standard_Boolean Segment = Standard_False);
//! Defines or redefines the arguments
//! for the construction of a shell. The construction is initialized
//! with the surface S, limited in the u parametric direction by the
//! two parameter values UMin and UMax, and in the v parametric
//! direction by the two parameter values VMin and VMax.
//! Warning
//! The function Error returns:
//! - BRepBuilderAPI_ShellParametersOutOfRange
//! when the given parameters are outside the bounds of the
//! surface or the basis surface if S is trimmed
Standard_EXPORT void Init (const Handle(Geom_Surface)& S, const Standard_Real UMin, const Standard_Real UMax, const Standard_Real VMin, const Standard_Real VMax, const Standard_Boolean Segment = Standard_False);
//! Returns true if the shell is built.
Standard_EXPORT virtual Standard_Boolean IsDone() const Standard_OVERRIDE;
//! Returns the construction status:
//! - BRepBuilderAPI_ShellDone if the shell is built, or
//! - another value of the BRepBuilderAPI_ShellError
//! enumeration indicating why the construction failed.
//! This is frequently BRepBuilderAPI_ShellParametersOutOfRange
//! indicating that the given parameters are outside the bounds of the surface.
Standard_EXPORT BRepBuilderAPI_ShellError Error() const;
//! Returns the new Shell.
Standard_EXPORT const TopoDS_Shell& Shell() const;
Standard_EXPORT operator TopoDS_Shell() const;
protected:
private:
BRepLib_MakeShell myMakeShell;
};
#endif // _BRepBuilderAPI_MakeShell_HeaderFile
|
#ifndef INC_PARTICLE_RENDERER_H
#define INC_PARTICLE_RENDERER_H
//C++ Headers
#include<memory>
#include<vector>
//Third Party Headers
#include<gl/glew.h>
#include<glm/glm.hpp>
#include"shader.h"
#include"texture2D.h"
namespace shady_engine
{
class particles_renderer
{
private:
std::shared_ptr<shader> mShader;
GLuint VAO;
GLuint VBO;
GLuint VBOcolors;
GLuint VBOoffsets;
GLuint VBOscalers;
public:
particles_renderer();
void init();
void render(
const glm::mat4& pProjection,
const glm::mat4& pView,
int num,
const std::vector<glm::vec4>& colors,
const std::vector<glm::vec2>& translations,
const std::vector<glm::vec2>& scalers
);
~particles_renderer();
}; //End of class
} //End of Namespace
#endif
|
#ifndef BASE_DESCRIPTOR_H
#define BASE_DESCRIPTOR_H
#include <sc2api\sc2_api.h>
#include <vector>
using namespace sc2;
class BaseDescriptor
{
public:
Point3D position_center; //Position of the center of the base, ie where the command center should be placed.
std::vector<const Unit*> minerals; // Minerals in the base
std::vector<const Unit*> gas; // Gas in the base
Unit::Alliance occupation; // Who controls the base.
int iD;
public:
BaseDescriptor();
~BaseDescriptor();
};
#endif
|
#include <assert.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <libgen.h>
#include <reactor/net/Connector.h>
#include <reactor/net/EventLoop.h>
#include <reactor/net/InetAddress.h>
using namespace reactor::net;
EventLoop loop;
void on_connected(int fd) {
std::cout << fd << " connected\n";
::close(fd);
loop.quit();
}
int main(int argc, char *argv[])
{
if (argc != 3) {
std::cout << "Usage: " << basename(argv[0]) << " host port\n";
return 0;
}
int port = atoi(argv[2]);
Connector connector(&loop, InetAddress(argv[0], static_cast<uint16_t>(port)));
connector.set_connection_callback(on_connected);
connector.start();
loop.loop();
return 0;
}
|
#include <iostream>
#include <cstdio>
using namespace std;
int main()
{
int a[5][5], i, j, k, x, y, count = 0, temp;
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
if(a[i][j]==1)
{
if(i==2 && j==2)
printf("%d",count);
break;
while(i!=2)
{
if(j<2)
{
for(k=0;k<5;k++)
{
temp = a[i][k];
a[i][k] = a[i+1][k];
a[i+1][k] = a[i][k];
}
i++;
}
else
{
for(k=0;k<5;k++)
{
temp = a[i][k];
a[i][k] = a[i-1][k];
a[i-1][k] = a[i][k];
}
i--;
}
count++;
}
while(j!=2)
{
if(j<2)
{
for(k=0;k<5;k++)
{
temp = a[k][j];
a[k][j] = a[k][j+1];
a[k][j+1] = a[k][j];
}
j++;
}
else
{
for(k=0;k<5;k++)
{
temp = a[k][j];
a[k][j] = a[k][j-1];
a[k][j-1] = a[k][j];
}
j++;
}
count++;
}
}
}
}
printf("%d",count);
}
|
#include <DHT.h>
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
float h;
float t;
void setup(){
Serial.begin(9600);
dht.begin();
}
void loop(){
h=dht.readHumidity();
t=dht.readTemperature();
Serial.println(h);
Serial.println(t);
//Serial.println();
delay(1000);
}
|
/**
* @file main.cc
* @author Gerbrand De Laender
* @date 18/12/2020
* @version 1.0
*
* @brief E091103, Master thesis, software testing
*
* @section DESCRIPTION
*
* Uses IP that applies gain to an incoming AXI stream. Makes use of DMA to
* stream data from the main memory to the IP core.
*
*/
#include <stdio.h>
#include <xparameters.h>
#include <xtime_l.h>
#include "platform.h"
#include "xgain.h"
#include "xaxidma.h"
#define BUFFER_SIZE 1000
#define DMA_BASE_ADDR 0x0100000 // Make sure this is out of range of the code!
#define TX_BUF_ADDR DMA_BASE_ADDR + 0x00100000 // Outgoing AXI stream will be placed here.
#define RX_BUF_ADDR DMA_BASE_ADDR + 0x00300000 // Incoming AXI stream will be placed here.
void init_gain(XGain *ip, XGain_Config *ip_cfg) {
ip_cfg = XGain_LookupConfig(XPAR_XGAIN_0_DEVICE_ID);
if (ip_cfg) {
int status = XGain_CfgInitialize(ip, ip_cfg);
if (status != XST_SUCCESS)
printf("Error initializing 'gain'!\n");
}
}
void init_axidma(XAxiDma *ip, XAxiDma_Config *ip_cfg) {
ip_cfg = XAxiDma_LookupConfig(XPAR_AXIDMA_0_DEVICE_ID);
if (ip_cfg) {
int status = XAxiDma_CfgInitialize(ip, ip_cfg);
if (status != XST_SUCCESS)
printf("Error initializing 'axidma'!\n");
}
// Disable interrupts for now.
XAxiDma_IntrDisable(ip, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DEVICE_TO_DMA);
XAxiDma_IntrDisable(ip, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DMA_TO_DEVICE);
}
int main() {
init_platform();
// Initialize IP cores.
XGain g;
XGain_Config g_cfg;
init_gain(&g, &g_cfg);
XAxiDma dma;
XAxiDma_Config dma_cfg;
init_axidma(&dma, &dma_cfg);
XTime t1, t2;
// Initialize structures.
int *tx_buffer = reinterpret_cast<int *>(TX_BUF_ADDR);
int *rx_buffer = reinterpret_cast<int *>(RX_BUF_ADDR);
for (int i = 0; i < BUFFER_SIZE; i++)
tx_buffer[i] = i;
int gain = 5;
XGain_Set_value_r(&g, gain);
XGain_Start(&g);
// Start test.
printf("\nTimer setup:\n---\n");
XTime_GetTime(&t1);
XTime_GetTime(&t2);
printf("Empty run took %f us (%llu ticks).\n", 1000000.0 * (t2 - t1) / COUNTS_PER_SECOND, 2 * (t2 - t1));
// Flush cache of the used buffers.
Xil_DCacheFlushRange(reinterpret_cast<INTPTR>(tx_buffer),
BUFFER_SIZE * sizeof(int));
Xil_DCacheFlushRange(reinterpret_cast<INTPTR>(rx_buffer),
BUFFER_SIZE * sizeof(int));
// Send from DMA -> IP
XTime_GetTime(&t1);
XAxiDma_SimpleTransfer(&dma, reinterpret_cast<UINTPTR>(tx_buffer),
BUFFER_SIZE * sizeof(int), XAXIDMA_DMA_TO_DEVICE);
// Receive from IP -> DMA (blocking).
XAxiDma_SimpleTransfer(&dma, reinterpret_cast<UINTPTR>(rx_buffer),
BUFFER_SIZE * sizeof(int), XAXIDMA_DEVICE_TO_DMA);
while (XAxiDma_Busy(&dma, XAXIDMA_DEVICE_TO_DMA))
;
XTime_GetTime(&t2);
// Flush cache of the used buffers.
Xil_DCacheFlushRange(reinterpret_cast<INTPTR>(rx_buffer),
BUFFER_SIZE * sizeof(int));
printf("Calculation complete!\n");
for (int i = 0; i < BUFFER_SIZE; i++)
printf("gain(%d, %d) = %d\n", i, gain, rx_buffer[i]);
printf("Took %f us (%llu ticks).\n", 1000000.0 * (t2 - t1) / COUNTS_PER_SECOND, 2 * (t2 - t1));
cleanup_platform();
return 0;
}
|
//
// Created by cirkul on 27.11.2020.
//
#ifndef UNTITLED3_PLANT_H
#define UNTITLED3_PLANT_H
#include "Creature.h"
class Plant : public Creature { //ready
Plant(Playground& pg, int i, int j) : Creature(pg, i, j) {
this->lifeDuration = 3;
this->id = plant;
this->name = tree;
}
Plant *spawn(Playground& pg, int i, int j);
void aging() override;
void heal();
friend class Playground;
friend class Animal;
friend class Model;
};
#endif //UNTITLED3_PLANT_H
|
#include"head_info.h"
#include<stack>
int fibonacci(int n)
{
if(n==0 || n==1)
return 1;
else
return fibonacci(n-1) + fibonacci(n-2);
}
int fibonacci_norecursion(int n)
{
std::stack<int> st;
st.push(n);
int sum=0;
while( !st.empty() )
{
int cur = st.top();
st.pop();
if( cur==0 || cur==1 )
++sum;
else
{
st.push( cur-1 );
st.push( cur-2 );
}
}
return sum;
}
int fibonacci_no2(int n)
{
int count = 0, pre=0,cur=1;
while( count != n && n!=1 )
{
int res = pre + cur;
pre = cur;
cur = res;
++count;
}
return cur;
}
|
#include <bits/stdc++.h>
using namespace std;
struct tNode{
int data;
tNode *left;
tNode *right;
tNode(int x):data(x),left(NULL),right(NULL){}
};
class Solution{
public:
//1.递归方式
int k_level_nodes(tNode *root,int k){
if(!root || k < 1){
return 0;
}
if(k == 1){
return 1;
}
int leftNum = k_level_nodes(root->left,k-1);
int rightNum = k_level_nodes(root->right,k-1);
return leftNum+rightNum;
}
//2.非递归方式
int k_level_nodes_2(tNode *root,int k){
if(!root){
return 0;
}
int currentNodes = 1;
int nextLevelNodes = 0;
tNode *cur = root;
queue<tNode*> Q;
Q.push(cur);
int currentLevel = 1;
while(Q.empty() == false && currentLevel < k){
cur = Q.front();
Q.pop();
currentNodes--;
if(cur->left){
nextLevelNodes++;
Q.push(cur->left);
}
if(cur->right){
nextLevelNodes++;
Q.push(cur->right);
}
if(currentNodes == 0){
currentLevel++;
currentNodes = nextLevelNodes;
nextLevelNodes = 0;
}
}
return currentNodes;
}
};
int main(){
tNode *root = new tNode(1);
root->left = new tNode(2);
root->right = new tNode(3);
Solution handle;
printf("%d\n",handle.k_level_nodes_2(root,2));
return 0;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_set>
#include<unordered_map>
#include<set>
using namespace std;
class Solution {
public:
int longestSubstring(string s, int k) {
//基本思想:暴力超时
if(s.size()<k) return 0;
int len=0;
for(int i=0;i<=s.size()-k;i++)
{
for(int j=i+k-1;j<s.size()&&j-i+1>len;j++)
{
vector<int> cnt(26,0);
for(int t=i;t<=j;t++)
{
cnt[s[t]-'a']++;
}
bool flag=true;
for(auto c:cnt)
{
if(c>0&&c<k)
{
flag=false;
break;
}
}
if(flag)
len=max(len,j-i+1);
}
}
return len;
}
};
class Solution1 {
public:
int res=0;
int longestSubstring(string s, int k) {
//基本思想:分治法,对于一个字符串来说,如果要求子串最少出现k次,那么如果某些字母出现的次数小于k,
//这些字母一定不会出现在最长的子串中,并且这些字母将整个字符子串分割成小段,这些小段有可能是最长的
//但是由于被分割了,还是要检查这一小段,如果某些字母出现的次数小于k,会将小段继续分割下去
//直到该小段所有字符出现次数都不小于k,即seg.empty(),就不可再分res=max(res,int(s.size()))
Recursion(s,k);
return res;
}
void Recursion(string s,int k)
{
if(s.size()<k) return;
vector<int> cnt(26,0);
set<char> seg;
for(auto c:s)
cnt[c-'a']++;
for(int i=0;i<26;i++)
{
if(cnt[i]>0&&cnt[i]<k)
seg.insert(i+'a');
}
if(seg.empty())
{
res=max(res,int(s.size()));
return;
}
int start=0;
for(int i=0;i<=s.size();i++)
{
if(i==s.size()||seg.find(s[i])!=seg.end())
{
Recursion(s.substr(start,i-start),k);
start=i+1;
}
}
}
};
int main()
{
Solution1 solute;
string s="ababbc";
int k=2;
cout<<solute.longestSubstring(s,k)<<endl;
return 0;
}
|
#ifndef __CCrystalEditView_INL_INCLUDED
#define __CCrystalEditView_INL_INCLUDED
#include "CCrystalEditView.h"
CE_INLINE BOOL CCrystalEditView::GetOverwriteMode() const
{
return m_bOvrMode;
}
CE_INLINE void CCrystalEditView::SetOverwriteMode(BOOL bOvrMode /*= TRUE*/)
{
m_bOvrMode = bOvrMode;
}
CE_INLINE BOOL CCrystalEditView::GetDisableBSAtSOL() const
{
return m_bDisableBSAtSOL;
}
CE_INLINE BOOL CCrystalEditView::GetAutoIndent() const
{
return m_bAutoIndent;
}
CE_INLINE void CCrystalEditView::SetAutoIndent(BOOL bAutoIndent)
{
m_bAutoIndent = bAutoIndent;
}
#endif
|
#ifndef APPLICATION_DATABASECONNECTOR_H
#define APPLICATION_DATABASECONNECTOR_H
#include <cstdint>
#include <iostream>
#include <vector>
#include <utility>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/builder/stream/array.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::basic::make_document;
using bsoncxx::builder::basic::kvp;
/*
* Adapter for interaction of managers with the database
*/
class DataBaseConnector {
public:
explicit DataBaseConnector(std::string companyName = std::string("test_company"));
/*
* Checking whether the user is registered
*/
bool userIsRegistered(std::string &token);
/*
* Checking whether the user is authorized
*/
bool userIsAuthorized(std::string &token);
/*
* Adding a user to the collection of authorized users
*/
void authorizeUser(std::string &token);
/*
* Deleting a user from the collection of authorized users
*/
void logoutUser(std::string &token);
/*
* Adding a message to the chat collection
*/
void addMessage(boost::property_tree::ptree ¶ms);
/*
* Create collection for chat
*/
void createChat(boost::property_tree::ptree ¶ms);
/*
* Delete collection for chat
*/
void deleteChat(boost::property_tree::ptree ¶ms);
/*
* Delete user from users collection
*/
void deleteUser(boost::property_tree::ptree ¶ms);
/*
* Add user from users collection
*/
void createUser(boost::property_tree::ptree ¶ms);
/*
* Get user information from users collection
*/
void getUserInfo(boost::property_tree::ptree ¶ms);
/*
* Get chat information from chat collection
*/
void getChatInfo(boost::property_tree::ptree ¶ms);
/*
* Add response to logs collection
*/
void logRequest(boost::property_tree::ptree ¶ms);
/*
* Get documents from logs collection
*/
void getServerLogs(boost::property_tree::ptree ¶ms);
/*
* Get vector of user's chats from users collection
*/
std::vector<int> getUserChats(int userId);
/*
* Get team name from chat collection
*/
std::string getTeamName(int chatId);
/*
* Get messages count from chat collection
*/
int getChatMessagesCount(int chatId);
/*
* Get chats members from chat collection
*/
boost::property_tree::ptree getChatMembers(int chatId);
/*
* Get message author information from users collection
*/
void getMessageAuthorInfo(boost::property_tree::ptree ¶ms);
/*
* Get chat's last message
*/
boost::property_tree::ptree getChatLastMessage(int chatId);
/*
* Get users chats information from users collection
*/
void getUserChatsPreview(boost::property_tree::ptree ¶ms);
/*
* Get chat's messages from chat collection
*/
void getChatMessages(boost::property_tree::ptree ¶ms);
/*
* Change chat's messages status to IsChecked = true
*/
void makeMessagesInChatChecked(int chatId, int userId);
private:
mongocxx::uri uri;
mongocxx::client client;
mongocxx::database db;
};
template <typename T>
std::vector<T> ptreeVectorToStd(boost::property_tree::ptree const& pt, boost::property_tree::ptree::key_type const& key)
{
std::vector<T> r;
for (auto& item : pt.get_child(key))
r.push_back(item.second.get_value<T>());
return r;
}
#endif //APPLICATION_DATABASECONNECTOR_H
|
#include "../interface.h"
namespace exception {
obj_ptr CreateTitleBackground();
rule_ptr CreateDeathMatch(int time);
rule_ptr CreateTeamFortress(float core_life);
rule_ptr CreateHorde(int wave);
gobj_ptr CreateGameOver();
gobj_ptr CreateStageResult(int bosstime, int hit, float score);
void PutSmallExplode(const vector4& pos, int num, float strength=1.5f);
void PutSmallExplode(const box& box, const matrix44& mat, int num, float strength=1.5f);
void PutFlash(const vector4& pos, float size=100.0f);
void PutCubeExplode(const vector4& pos);
void PutSmallImpact(const vector4& pos);
void PutMediumImpact(const vector4& pos);
void PutBloom();
void PutDistortion(const vector4& pos, const vector4& dir);
gobj_ptr GetGlobals();
team_ptr CreateTeam();
player_ptr CreatePlayer(ISession& s);
fraction_ptr CreateFraction();
void ResetGlobals();
void SetGlobalScroll(const vector4& v);
void SetGlobalAccel(const vector4& v);
void SetGlobalMatrix(const matrix44& v);
void SetGlobalBoundBox(const box& v);
void SetGlobalBoundRect(const rect& v);
void SetGlobalFractionBoost(float v);
void SetGlobalPlayerBound(const box& v);
const vector4& GetGlobalScroll();
const vector4& GetGlobalAccel();
const matrix44& GetGlobalMatrix();
const matrix44& GetGlobalIMatrix();
const box& GetGlobalBoundBox();
const rect& GetGlobalBoundRect();
float GetGlobalFractionBoost();
const box& GetGlobalPlayerBound();
};
|
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <math.h>
using namespace std;
int main(int argc, char **argv) {
// int tendance = -5;
int tendance;
//int pression = 1030;
int altitude = 151.5;
int zambretti_coefficient;
int stock_pression;
// Déterminer le mois de l'année
time_t temps;
struct tm datetime;
char mois[4];
// char date[32];
time(&temps);
datetime = *localtime(&temps);
//strftime(date, "%Y-%m-%d ", &datetime);
strftime(mois, 4 , "%m", &datetime);
int nbr_mois =stoi(mois);
cout<<nbr_mois<<endl;
for (int pression=900; pression <1051; pression=pression+10){
int pression_calc = pression/ pow(1-(0.0065*altitude/288.15),5.255);
//tendance = pression_calc - stock_pression;
tendance = stock_pression - pression_calc;
cout << "tendance : "<< tendance<<endl;
cout << "pression au niveau de la mer" << pression_calc << endl;
if ((tendance <-2)){
zambretti_coefficient = 130-(10*pression_calc/81);
/* if (mois=="04") { zambretti_coefficient = zambretti_coefficient+1;}
else {zambretti_coefficient = zambretti_coefficient;}
*/
// cout<< "tendance descendante" <<endl;
} else if (tendance >2) {
zambretti_coefficient = 179-((20*pression_calc)/129);
// cout<< zambretti_coefficient << endl;
}else {
zambretti_coefficient = 147-((50*pression_calc)/376);
// cout<< zambretti_coefficient << endl;
}
switch (zambretti_coefficient){
case 1: cout << "Il fait beau"<< endl; break;
case 2: cout << "Il fait beau 2"<< endl; break;
case 3: cout << "Il fait beau 3"<< endl; break;
case 4: cout << "pluie fine" << endl; break;
case 5: cout << "incertain"<< endl; break;
case 6: cout << "incertain"<< endl; break;
case 7:cout << "pluie" << endl; break;
case 8: cout << "averses" << endl; break;
case 9: cout << "averses" << endl; break;
case 10:cout << "Il fait beau"<< endl; break;
case 11:cout << "Il fait beau 2"<< endl; break;
case 12:cout << "Il fait beau 3"<< endl; break;
case 13:cout << "soleil + nuages" << endl; break;
case 14:cout << "pluie fine" << endl; break;
case 15:cout << "incertain"<< endl; break;
case 16:cout << "incertain"<< endl; break;
case 17:cout << "pluie" << endl; break;
case 18:cout << "averses" << endl; break;
case 19:cout << "averses" << endl; break;
case 20:cout << "Il fait beau"<< endl; break;
case 21:cout << "Il fait beau 2"<< endl; break;
case 22:cout << "Il fait beau 3"<< endl; break;
case 23:cout << "soleil + nuages" << endl; break;
case 24:cout << "pluie fine" << endl; break;
case 25:cout << "incertain"<< endl; break;
case 26:cout << "incertain"<< endl; break;
case 27:cout << "pluie" << endl; break;
case 28:cout << "averses" << endl; break;
case 29:cout << "averses" << endl; break;
case 30:cout << "incertain"<< endl; break;
case 31:cout << "tempête" << endl; break;
case 32:cout << "tempete" << endl; break;
default: cout << "are you serious"<< endl; break;
}
stock_pression = pression_calc;
}
return 0;
}
|
#include "App.hpp"
#include <HTStack/Response/Response.hpp>
#include <HTStack/HTTPUtils/MIMEType.hpp>
#include <fstream>
#include <iostream>
App::App (HTStack::Server & server, std::map <std::string, std::string> & settings) : HTStack::App (server, settings) {};
void App::handleRequest (HTStack::Request & request) {
if (request.headers ["Host"] != "an0n.dev") return;
if (request.path == "/") {
std::ifstream htmlFileStream ("webroot/index.html", std::ifstream::binary);
if (!htmlFileStream) return;
HTStack::MIMEType mimeType ("index.html", true); // guess
HTStack::Response response (200, &htmlFileStream, &mimeType); // 200 = OK
response.respondTo (request);
} else if (request.path == "/logo") {
std::ifstream logoFileStream ("webroot/logo.png", std::ifstream::binary);
if (!logoFileStream) return;
HTStack::MIMEType mimeType ("logo.png", true); // guess
HTStack::Response response (200, &logoFileStream, &mimeType); // 200 = OK
response.respondTo (request);
} else {
HTStack::Response response (404);
response.respondTo (request);
}
};
extern "C" HTStack::App* factory (HTStack::Server & server, std::map <std::string, std::string> & settings) {
return new App (server, settings);
};
|
#include <downloader.h>
#include <clientversion.h>
#include <init.h>
#include <logging.h>
#include <util/system.h>
#include <util/miniunz.h>
#define CURL_STATICLIB
#include <curl/curl.h>
#include <openssl/ssl.h>
/* Downloader functions for bootstrapping and updating client software
* This xferinfo_data contains a callback function to be called
* if the value is not nullptr.
*
* void xferinfo_data(curl_off_t total, curl_off_t now);
*
* This is admittedly ugly, but it allows us to get a percentage
* callback in the GUI portion of code. by setting the xinfo_data.
*
* XXX it could use some rate limiting
*/
static void* xferinfo_data = nullptr;
static int xferinfo(void *p,
curl_off_t dltotal, curl_off_t dlnow,
curl_off_t ultotal, curl_off_t ulnow)
{
void (*ptr)(curl_off_t, curl_off_t) = (void(*)(curl_off_t, curl_off_t))xferinfo_data;
if (ptr != nullptr) ptr(dlnow, dltotal);
return 0; // continue xfer.
}
void set_xferinfo_data(void* d)
{
xferinfo_data = d;
}
void downloadFile(std::string url, const fs::path& target_file_path) {
LogPrintf("Download: Downloading from %s. \n", url);
FILE *file = fsbridge::fopen(target_file_path, "wb");
if( ! file )
throw std::runtime_error(strprintf("Download: error: Unable to open output file for writing: %s.", target_file_path.string().c_str()));
CURL *curlHandle = curl_easy_init();
CURLcode res;
char errbuf[CURL_ERROR_SIZE];
curl_easy_setopt(curlHandle, CURLOPT_ERRORBUFFER, errbuf);
errbuf[0] = 0;
curl_easy_setopt(curlHandle, CURLOPT_URL, url.c_str());
curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curlHandle, CURLOPT_NOPROGRESS, 0);
curl_easy_setopt(curlHandle, CURLOPT_XFERINFODATA, xferinfo_data);
curl_easy_setopt(curlHandle, CURLOPT_XFERINFOFUNCTION, xferinfo);
curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, file);
res = curl_easy_perform(curlHandle);
if(res != CURLE_OK) {
curl_easy_cleanup(curlHandle);
size_t len = strlen(errbuf);
if(len)
throw std::runtime_error(strprintf("Download: error: %s%s.", errbuf, ((errbuf[len - 1] != '\n') ? "\n" : "")));
else
throw std::runtime_error(strprintf("Download: error: %s.", curl_easy_strerror(res)));
}
long response_code;
curl_easy_getinfo(curlHandle, CURLINFO_RESPONSE_CODE, &response_code);
if( response_code != 200 )
throw std::runtime_error(strprintf("Download: error: Server responded with a %d .", response_code));
curl_easy_cleanup(curlHandle);
fclose(file);
LogPrintf("Download: Successful.\n");
return;
}
// bootstrap
void extractBootstrap(const fs::path& target_file_path) {
LogPrintf("bootstrap: Extracting bootstrap %s.\n", target_file_path);
if (!boost::filesystem::exists(target_file_path))
throw std::runtime_error("bootstrap: Bootstrap archive not found");
const char * zipfilename = target_file_path.string().c_str();
unzFile uf;
#ifdef USEWIN32IOAPI
zlib_filefunc64_def ffunc;
fill_win32_filefunc64A(&ffunc);
uf = unzOpen2_64(zipfilename, &ffunc);
#else
uf = unzOpen64(zipfilename);
#endif
if (uf == NULL)
throw std::runtime_error(strprintf("bootstrap: Cannot open bootstrap archive: %s\n", zipfilename));
int unzip_err = zip_extract_all(uf, GetDataDir(), "bootstrap");
if (unzip_err != UNZ_OK)
throw std::runtime_error("bootstrap: Unzip failed\n");
LogPrintf("bootstrap: Unzip successful\n");
return;
}
void validateBootstrapContent() {
LogPrintf("bootstrap: Checking Bootstrap Content\n");
if (!boost::filesystem::exists(GetDataDir() / "bootstrap" / "chainstate") ||
!boost::filesystem::exists(GetDataDir() / "bootstrap" / "blocks") ||
!boost::filesystem::exists(GetDataDir() / "bootstrap" / "indexes"))
throw std::runtime_error("bootstrap: Downloaded zip file did not contain all necessary files!\n");
}
void applyBootstrap() {
boost::filesystem::remove_all(GetDataDir() / "blocks");
boost::filesystem::remove_all(GetDataDir() / "chainstate");
boost::filesystem::remove_all(GetDataDir() / "indexes");
boost::filesystem::rename(GetDataDir() / "bootstrap" / "blocks", GetDataDir() / "blocks");
boost::filesystem::rename(GetDataDir() / "bootstrap" / "chainstate", GetDataDir() / "chainstate");
boost::filesystem::rename(GetDataDir() / "bootstrap" / "indexes", GetDataDir() / "indexes");
boost::filesystem::remove_all(GetDataDir() / "bootstrap");
boost::filesystem::path pathBootstrapTurbo(GetDataDir() / "bootstrap.zip");
boost::filesystem::path pathBootstrap(GetDataDir() / "bootstrap.dat");
if (boost::filesystem::exists(pathBootstrapTurbo)){
boost::filesystem::remove(pathBootstrapTurbo);
}
if (boost::filesystem::exists(pathBootstrap)){
boost::filesystem::remove(pathBootstrap);
}
}
void downloadBootstrap() {
LogPrintf("bootstrap: Starting bootstrap process.\n");
boost::filesystem::path pathBootstrapZip = GetDataDir() / "bootstrap.zip";
try {
downloadFile(strprintf("%s/%d.%d%s", CLIENT_URL, CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, BOOTSTRAP_PATH), pathBootstrapZip);
} catch (...) {
throw;
}
try {
extractBootstrap(pathBootstrapZip);
} catch (...) {
throw;
}
try {
validateBootstrapContent();
} catch (...) {
throw;
}
fBootstrap = true;
LogPrintf("bootstrap: bootstrap process finished.\n");
return;
}
// check for update
void downloadVersionFile() {
LogPrintf("Check for update: Getting version file.\n");
boost::filesystem::path pathVersionFile = GetDataDir() / "VERSION.json";
try {
downloadFile(strprintf("%s/%d.%d/releases/%s%s", CLIENT_URL,
CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR,
FormatVersion(CLIENT_VERSION),
VERSIONFILE_PATH), pathVersionFile
);
} catch (...) {
throw;
}
return;
}
void downloadClient(std::string fileName) {
LogPrintf("Check for update: Downloading new client.\n");
boost::filesystem::path pathClientFile = GetDataDir() / fileName;
try {
downloadFile(strprintf("%s/%d.%d/releases/%s", CLIENT_URL, CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, fileName), pathClientFile);
} catch (...) {
throw;
}
return;
}
int getArchitecture()
{
int *i;
return sizeof(i) * 8; // 8 bits/byte
}
|
/* -*- Mode: c++; tab-width: 2; indent-tabs-mode: s; c-basic-offset: 2 -*-
**
** Copyright (C) 2012 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "../includes/ipcconfig.h"
#include "../includes/ipcimpl.h"
#include <string.h>
#include <errno.h>
using namespace opera_update_checker::ipc;
using namespace opera_update_checker::status;
namespace opera_update_checker
{
namespace ipc
{
/* static */ Channel* Channel::Create(bool is_server, PidType id, ChannelMode mode, ChannelFlowDirection direction)
{
OAUCChannelImpl* this_channel = OAUC_NEW(OAUCChannelImpl, ());
if (!this_channel)
return NULL;
this_channel->is_server_ = is_server;
this_channel->mode_ = mode;
this_channel->direction_ = direction;
sprintf(this_channel->name_in_, CHANNEL_NAME_IN, id);
sprintf(this_channel->name_out_, CHANNEL_NAME_OUT, id);
if (is_server)
{
//Create fifo files
unlink(this_channel->name_in_);
if (mkfifo(this_channel->name_in_, S_IRWXU) <0) //server in
{
return NULLPTR;
}
unlink(this_channel->name_out_);
if (mkfifo(this_channel->name_out_, S_IRWXU) <0) //server out
{
return NULLPTR;
}
}
return this_channel;
}
/* static */ void Channel::Destroy(Channel* channel)
{
OAUC_DELETE(channel);
}
}
}
OAUCChannelImpl::OAUCChannelImpl()
: is_server_(false)
, is_connected_(false)
, mode_(Channel::CHANNEL_MODE_READ)
, direction_(Channel::FROM_SERVER_TO_CLIENT)
, pipe_in_(0)
, pipe_out_(0)
{
memset(name_in_, 0, MAX_CHANNEL_NAME * sizeof(char));
memset(name_out_, 0, MAX_CHANNEL_NAME * sizeof(char));
}
OAUCChannelImpl::~OAUCChannelImpl()
{
Disconnect();
CleanUpAll();
}
void OAUCChannelImpl::CleanUpAll()
{
if (pipe_in_ > 0)
close(pipe_in_);
if (pipe_out_ > 0)
close(pipe_out_);
pipe_in_ = 0;
pipe_out_ = 0;
if (is_server_ == true)
{
unlink(this->name_in_);
unlink(this->name_out_);
}
}
/* virtual */ Status OAUCChannelImpl::Connect(const OAUCTime& timeout)
{
int open_flags = O_RDONLY | O_NONBLOCK;
if (pipe_in_ == 0)
{
pipe_in_ = open(is_server_ ? name_in_ : name_out_, open_flags);
}
if (pipe_in_ <= 0)
{
return StatusCode::FAILED;
}
is_connected_ = true;
return StatusCode::OK;
}
/* virtual */ void OAUCChannelImpl::Disconnect()
{
CleanUpAll();
}
/* virtual */ Status OAUCChannelImpl::SendMessage(const opera_update_checker::ipc::Message& message, const OAUCTime& timeout)
{
int status = StatusCode::OK;
if (pipe_out_ == 0)
{
OAUCTime time_elapsed = 0;
for (;;)
{
pipe_out_ = open(is_server_ ? name_out_ : name_in_, O_WRONLY | O_NONBLOCK);
if (pipe_out_ < 0)
{
if (time_elapsed >= timeout)
{
return StatusCode::TIMEOUT;
}
time_elapsed += 10;
usleep(10000); //wait 10ms
}
else
{
break;
}
}
}
if (pipe_out_ <= 0)
{
pipe_out_ = 0;
return StatusCode::FAILED;
}
fd_set read_fds, write_fds, except_fds;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_ZERO(&except_fds);
FD_SET(pipe_out_, &write_fds);
struct timeval write_timeout;
write_timeout.tv_sec = timeout / 1000;
write_timeout.tv_usec = timeout - (write_timeout.tv_sec * 1000);
long size = sizeof(message)+message.data_len;
long data_remaining = size;
char *buf = OAUC_NEWA(char, size);
char *msg_start = buf;
memcpy(buf, &message, sizeof(message));
memcpy(buf+sizeof(message), message.data, message.data_len);
while (data_remaining > 0)
{
long data_len = data_remaining > OAUC_PIPE_SIZE ? OAUC_PIPE_SIZE : data_remaining;
if (select(pipe_out_ + 1, &read_fds, &write_fds, &except_fds, &write_timeout) == 1)
{
ssize_t bytes_written = write(pipe_out_, buf, data_len);
if (bytes_written < 0 && errno != EAGAIN)
{
status = StatusCode::FAILED;
break;
}
else if (bytes_written > 0)
{
data_remaining -= bytes_written;
buf += bytes_written;
}
}
else
{
status = StatusCode::TIMEOUT;
break;
}
}
if (msg_start != NULL)
{
OAUC_DELETEA(msg_start);
}
return status;
}
/* virtual */ const opera_update_checker::ipc::Message* OAUCChannelImpl::GetMessage(const OAUCTime& timeout)
{
int status = StatusCode::OK;
opera_update_checker::ipc::Message *msg = NULLPTR;
fd_set read_fds, write_fds, except_fds;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_ZERO(&except_fds);
FD_SET(pipe_in_, &read_fds);
struct timeval read_timeout;
read_timeout.tv_sec = timeout / 1000;
read_timeout.tv_usec = timeout - (read_timeout.tv_sec * 1000);
if (select(pipe_in_ + 1, &read_fds, &write_fds, &except_fds, &read_timeout) == 1)
{
msg = OAUC_NEW(opera_update_checker::ipc::Message, ());
memset(msg, 0, sizeof(opera_update_checker::ipc::Message));
ssize_t bytes_read = read(pipe_in_, (void*)msg, sizeof(opera_update_checker::ipc::Message));
if (bytes_read > 0)
{
//read message data
if (bytes_read == sizeof(opera_update_checker::ipc::Message))
{
if (msg->data_len < MAX_MESSAGE_PAYLOAD_SIZE)
{
msg->data = OAUC_NEWA(char, msg->data_len);
msg->owns_data = true;
FD_ZERO(&read_fds);
FD_ZERO(&write_fds);
FD_ZERO(&except_fds);
FD_SET(pipe_in_, &read_fds);
bool first = true;
long data_remaining = msg->data_len + sizeof(opera_update_checker::ipc::Message);
long offset = 0;
while (data_remaining > 0)
{
if (select(pipe_in_ + 1, &read_fds, &write_fds, &except_fds, &read_timeout) == 1)
{
if (first == true)
{
data_remaining -= sizeof(opera_update_checker::ipc::Message);
}
long data_len = data_remaining > OAUC_PIPE_SIZE ? OAUC_PIPE_SIZE : data_remaining;
bytes_read = read(pipe_in_, msg->data + offset, data_len);
if (bytes_read < 0 && errno != EAGAIN)
{
status = StatusCode::FAILED;
break;
}
else
{
first = false;
offset += bytes_read;
data_remaining -= bytes_read;
if (bytes_read == 0) //end of file
{
break;
}
}
}
else
{
status = StatusCode::TIMEOUT;
break;
}
}
}
else
{
status = StatusCode::FAILED;
}
}
else
{
status = StatusCode::FAILED;
}
}
}
else
{
status = StatusCode::TIMEOUT;
}
if (status == StatusCode::OK)
{
return msg;
}
else
{
if (msg != NULL)
{
OAUC_DELETE(msg);
msg = NULLPTR;
}
return NULLPTR;
}
}
/*static */
PidType opera_update_checker::ipc::GetCurrentProcessId() {
return getpid();
}
|
// set this to the hardware serial port you wish to use
#define HWSERIAL Serial1
int led = 13;
int en485 = 2;
#define DEBUT_TRAME '<'
#define FIN_TRAME '>'
String ReceivedString = "";
extern String Subs[];
char inByte;
String cmd="";
void setup()
{
Serial.begin(115200);
HWSERIAL.begin(115200);
pinMode(led, OUTPUT);
pinMode(en485, OUTPUT);
digitalWrite(led, LOW);
digitalWrite(en485, LOW);
delay(2000);
Serial.println();
Serial.println("***** Fish Master ****");
}
//*****************************************************
void FlushRx485()
{
while (HWSERIAL.available())
{
inByte = HWSERIAL.read();
}
}
//******************************************************
void WaitAnswer()
{
bool Flag=false;
Serial.println("Waiting for Answer ...");
while (!Flag)
{
while (!HWSERIAL.available()){};
char Chr = HWSERIAL.read();
if (Chr == DEBUT_TRAME) ReceivedString = "";
else
{
if (Chr == FIN_TRAME)
{
Serial.print("recieved: ");
Serial.println(ReceivedString);
String_Split(',', ReceivedString);
Flag=true;
}
else ReceivedString += Chr;
}
}
}
//******************************************************
void SendToFish( String Com, bool Answer)
{
Serial.println();
Serial.print("COM: ");
Serial.println(Com);
digitalWrite(led, HIGH);
digitalWrite(en485, HIGH);
delayMicroseconds(500);
HWSERIAL.println(Com);
HWSERIAL.flush();
delayMicroseconds(500);
digitalWrite(en485, LOW);
digitalWrite(led, LOW);
if(Answer) WaitAnswer();
delay(1);
}
//*****************************************************
void loop()
{
SendToFish("<LED,0,255,0,0>", false);
delay(1000);
SendToFish("<LED,0,0,0,0>", false);
delay(1000);
SendToFish("<LED,1,0,255,0>", false);
delay(1000);
SendToFish("<LED,1,0,0,0>", false);
delay(1000);
SendToFish("<LED,2,0,0,255>", false);
delay(1000);
SendToFish("<LED,2,0,0,0>", false);
delay(1000);
SendToFish("<RAINBOW,2,10>", false);
delay(3000);
SendToFish("<BLINK,2,50,50,50,10>", false);
delay(8000);
SendToFish("<BLINK,2,50,0,50,100>", false);
delay(8000);
SendToFish("<LED,2,0,0,0>", false);
delay(3000);
}
|
/*
* RF Demo Saboteur
*
* Receives switchType, reverses it, and sends it back.
* So when receiving group on, it will send a unit off back.
*
* Transmitter: digital pin 11
* Receiver: digital pin 2
*/
#include <NewRemoteReceiver.h>
#include <NewRemoteTransmitter.h>
void setup() {
Serial.begin(115200);
NewRemoteReceiver::init(0, 0, saboteur);
Serial.println("RF Saboteur gestart!");
Serial.println();
}
void loop() {
}
void saboteur(NewRemoteCode receivedCode) {
// Disable the receiver; otherwise it might pick up the retransmit as well.
NewRemoteReceiver::disable();
// Need interrupts for delay()
interrupts();
// Wait 750 milliseconds before sending.
delay(150);
// Create a new transmitter with the received address and period, use digital pin 11 as output pin
NewRemoteTransmitter transmitter(receivedCode.address, 11, receivedCode.period);
// Switch type 0 = switch off, type 1 = switch on
// Explanation:
// If original value = 1, do minus 1, makes 0, abs(0) makes 0
// If original value = 0, do minus 1, makes -1, abs(-1) makes 1.
if (receivedCode.groupBit) {
Serial.print("Received group ");
if (receivedCode.switchType == 0)
{
Serial.print("off from addr ");
} else {
Serial.print("on from address ");
}
Serial.println(receivedCode.address);
// Send to the group
transmitter.sendGroup(abs(receivedCode.switchType - 1));
Serial.print("Sent group ");
if (abs(receivedCode.switchType - 1) == 0)
{
Serial.print("off to addr ");
} else {
Serial.print("on to addr ");
}
Serial.println(receivedCode.address);
Serial.println();
}
else {
Serial.print("Received unit ");
Serial.print(receivedCode.unit);
if (receivedCode.switchType == 0)
{
Serial.print(" off from addr ");
} else {
Serial.print(" on from address ");
}
Serial.println(receivedCode.address);
// Send to a single unit
transmitter.sendUnit(receivedCode.unit, abs(receivedCode.switchType - 1 ));
Serial.print("Sent unit ");
Serial.print(receivedCode.unit);
if (abs(receivedCode.switchType - 1) == 0)
{
Serial.print(" off to addr ");
} else {
Serial.print(" on to addr ");
}
Serial.println(receivedCode.address);
Serial.println();
}
// Re-enable receiver
NewRemoteReceiver::enable();
}
|
#pragma once
#include <glad/glad.h>
#include <fstream>
#include <sstream>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
class Shader
{
public:
Shader()=default;
~Shader()=default;
unsigned int ID;
Shader(const GLchar* vertexPath, const GLchar* fragmentPath);
void use();
// uniform tools function
void setBool(const std::string& name, bool value) const;
void setInt(const std::string& name, int value) const;
void setFloat(const std::string& name, float value) const;
void setVec3(const std::string& name, float value1, float value2, float value3) const;
void setVec3(const std::string &name, const glm::vec3 &value) const;
void setMat4(const std::string& name, glm::mat4 value) const;
};
|
#pragma once
#include "ZeroAnimation.h"
#include "ZeroSprite.h"
#include "Enemy.h"
#include "PlayerCharacter.h"
class Slime :
public Enemy
{
private:
int boomDistance;
int slimeCondition;
pair<float, float> boomTimer;
pair<float, float> popTimer;
void PlayMoveSound();
public:
Slime();
enum CONDITION {
MOVE,
ATTACK
};
int speed;
bool isAlive;
bool isPop;
ZeroAnimation* slimeMove;
ZeroAnimation* slimeBoom;
void Update(float eTime) override;
void Render() override;
void SelfBoom(PlayerCharacter* target, float eTime);
bool IsCollision(PlayerCharacter* player) override;
void Damage(PlayerCharacter* player, float eTime) override;
};
|
//Space Complexity: O(1)
//Time Complexity: O(3^n), where n is the length of the array.
//Time Limit exceeded on leetcode.
class Solution {
private:
int helper(vector<vector<int>>& costs, int min, int row, int lastColor){
if(row == costs.size()){
return min;
}
int case1 = INT_MAX;
int case2 = INT_MAX;
int case3 = INT_MAX;
if(lastColor == 0){
case1 = std::min(helper(costs, min+costs.at(row).at(1), row+1, 1),helper(costs, min+costs.at(row).at(2), row+1, 2));
}
else if(lastColor == 1){
case2 = std::min(helper(costs, min+costs.at(row).at(0), row+1, 0),helper(costs, min+costs.at(row).at(2), row+1, 2));
}
else{
case3 = std::min(helper(costs, min+costs.at(row).at(0), row+1, 0),helper(costs, min+costs.at(row).at(1), row+1, 1));
}
return std::min(case1, std::min(case2,case3));
}
public:
int minCost(vector<vector<int>>& costs) {
int case1 = helper(costs, 0, 0, 0);
int case2 = helper(costs, 0, 0, 1);
int case3 = helper(costs, 0, 0, 2);
return std::min(case1,std::min(case2,case3));
}
};
|
#include <iostream>
using namespace std;
int main()
{
int n,y,mo(0),a[366]={0},day,one(0),two(0),three(0),four(0),five(0),six(0),seven(0);
cin>>n;
for(int i=1900;i<1900+n;i++)
{
if ((i%100!=0&&i%4==0)||i%400==0)
{y=366;
for(int j=0;j<y;j++){
a[j]=(j+mo)%7+1;}
for(int k : {12,43,72,103,133,164,194,225,256,286,317,347}){
switch(a[k]){
case 1:one++;break;
case 2:two++;break;
case 3:three++;break;
case 4:four++;break;
case 5:five++;break;
case 6:six++;break;
case 7:seven++;break;}
}
}
else {
y=365;
for(int j=0;j<y;j++){
a[j]=(j+mo)%7+1;}
for(int k : {12,43,71,102,132,163,193,224,255,285,316,346}){
switch(a[k]){
case 1:one++;break;
case 2:two++;break;
case 3:three++;break;
case 4:four++;break;
case 5:five++;break;
case 6:six++;break;
case 7:seven++;break;}
}
}
mo=(y-7+mo)%7;
}
cout<<one<<' '<<two<<' '<<three<<' '<<four<<' '<<five<<' '<<six<<' '<<seven;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Espen Sand
*/
#include "core/pch.h"
#include "platforms/unix/base/x11/x11_systemtrayicon.h"
#include "platforms/unix/base/x11/x11_mdebuffer.h"
#include "platforms/unix/base/x11/x11_mdescreen.h"
#include "platforms/unix/product/x11quick/iconsource.h"
#include "modules/locale/locale-enum.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/pi/ui/OpUiInfo.h" // Background color
#include "platforms/quix/environment/DesktopEnvironment.h"
#include "adjunct/desktop_util/image_utils/iconutils.h"
#include "adjunct/quick/Application.h" // For what to do on mouse clicks
#include "adjunct/quick/menus/DesktopMenuHandler.h"
using X11Types::Atom;
#define SYSTEM_TRAY_CHAT_BG 0xFF3597FC // Solid orange color
UINT32 ConvertToX11Color(UINT32 color) { return color&0xFF00FF00 | ((color&0x000000FF)<<16) | ((color&0x00FF0000)>>16); }
#define SYSTEM_TRAY_REQUEST_DOCK 0
#define SYSTEM_TRAY_WIDTH 22
#define SYSTEM_TRAY_HEIGHT 22
//static
OP_STATUS X11SystemTrayIcon::Create(X11SystemTrayIcon** icon)
{
*icon = OP_NEW(X11SystemTrayIcon, ());
if( !*icon )
{
return OpStatus::ERR_NO_MEMORY;
}
else
{
OP_STATUS rc = (*icon)->Init(0, "trayicon", X11Widget::BYPASS_WM);
if( OpStatus::IsError(rc) )
{
OP_DELETE(*icon);
return rc;
}
(*icon)->Setup();
}
return OpStatus::OK;
}
X11SystemTrayIcon::X11SystemTrayIcon()
:m_tray_window(None)
,m_tray_selection(None)
,m_unread_mail_count(0)
,m_unattended_mail_count(0)
,m_unattended_chat_count(0)
,m_unite_count(0)
,m_tray_depth(0)
,m_tray_width(0)
,m_tray_height(0)
,m_width(0)
,m_height(0)
{
m_tray_visual.visual = 0;
}
X11SystemTrayIcon::~X11SystemTrayIcon()
{
}
void X11SystemTrayIcon::OnUnattendedMailCount( UINT32 count )
{
UpdateIcon(UnattendedMail, count);
}
void X11SystemTrayIcon::OnUnreadMailCount( UINT32 count )
{
UpdateIcon(UnreadMail, count);
}
void X11SystemTrayIcon::OnUnattendedChatCount( OpWindow* op_window, UINT32 count )
{
UpdateIcon(UnattendedChat, count);
}
void X11SystemTrayIcon::OnUniteAttentionCount( UINT32 count )
{
UpdateIcon(UniteCount, count);
}
void X11SystemTrayIcon::UpdateIcon(MonitorType type, int count)
{
OpString text;
if (type == UnreadMail)
{
if (m_unread_mail_count == count)
return;
m_unread_mail_count = count;
}
else if (type == UnattendedMail)
{
if (m_unattended_mail_count == count)
return;
m_unattended_mail_count = count;
if (m_unattended_mail_count > 0)
{
text.Set("Opera");
if (m_unattended_mail_count > 1)
{
OpString tmp;
TRAPD(err, g_languageManager->GetStringL(Str::S_UNREAD_MESSAGES, tmp));
if (tmp.CStr())
{
// "%d unread messages"
text.Append("\n");
text.AppendFormat(tmp.CStr(), m_unattended_mail_count );
}
}
else if (m_unattended_mail_count == 1)
{
OpString tmp;
TRAPD(err, g_languageManager->GetStringL(Str::S_ONE_UNREAD_MESSAGE, tmp));
if (tmp.CStr())
{
// "1 unread message"
text.Append("\n");
text.Append(tmp);
}
}
}
}
else if (type == UnattendedChat)
{
if (m_unattended_chat_count == count)
return;
m_unattended_chat_count = count;
}
else if (type == UniteCount)
{
if (m_unite_count == count)
return;
m_unite_count = count;
}
else if (type == InitIcon)
{
// No test
}
else
{
return;
}
UINT8* buffer;
UINT32 size;
UINT32 unit;
if (m_height < 32)
unit = 16;
else if(m_height < 48)
unit = 32;
else
unit = 48;
if (GetMdeBuffer() && IconSource::GetSystemTrayOperaIcon(unit, buffer, size))
{
OpBitmap* bitmap = 0;
if (OpStatus::IsSuccess(OpBitmap::Create(&bitmap, unit, unit, TRUE, TRUE, 0, 0, TRUE)))
{
OpPoint p(0,0);
OpRect r(0,0,bitmap->Width(),bitmap->Height());
// Init background. Needed for 24-bit visuals
UINT32* data = (UINT32*)bitmap->GetPointer(OpBitmap::ACCESS_WRITEONLY);
if (data)
{
UINT32 c = GetBackgroundColor();
UINT32 col = (OP_GET_A_VALUE(c) << 24) | (OP_GET_R_VALUE(c) << 16) | (OP_GET_G_VALUE(c) << 8) | OP_GET_B_VALUE(c);
UINT32 size = r.width*r.height;
for (UINT32 i=0; i<size; i++ )
data[i] = col;
bitmap->ReleasePointer(TRUE);
}
OpPainter* painter = bitmap->GetPainter();
if (painter)
{
// Opera icon
OpBitmap* bm = IconUtils::GetBitmap(buffer, size, -1, -1);
if (bm)
{
painter->DrawBitmapClipped(bm, r, p);
OP_DELETE(bm);
}
// Mail overlay
if (m_unread_mail_count > 0 && IconSource::GetSystemTrayMailIcon(unit, buffer, size))
{
bm = IconUtils::GetBitmap(buffer, size, -1, -1);
if (bm)
{
painter->DrawBitmapClipped(bm, r, p);
OP_DELETE(bm);
}
}
// Chat overlay
if (m_unattended_chat_count > 0 && IconSource::GetSystemTrayChatIcon(unit, buffer, size))
{
bm = IconUtils::GetBitmap(buffer, size, -1, -1);
if (bm)
{
painter->DrawBitmapClipped(bm, r, p);
OP_DELETE(bm);
}
}
// Unite overlay.
// Note. We can not show chat and unite status at the same time (status gfx. occupy the same area)
else if (m_unite_count > 0 && IconSource::GetSystemTrayUniteIcon(unit, buffer, size))
{
bm = IconUtils::GetBitmap(buffer, size, -1, -1);
if (bm)
{
painter->DrawBitmapClipped(bm, r, p);
OP_DELETE(bm);
}
}
}
GetMdeBuffer()->SetBitmap(*bitmap);
OP_DELETE(bitmap);
}
}
UpdateAll();
}
UINT32 X11SystemTrayIcon::GetBackgroundColor()
{
UINT32 color;
if (m_tray_visual.visual && m_tray_visual.depth == 32)
color = 0x00000000;
else
color = 0xFF000000 | g_op_ui_info->GetSystemColor(OP_SYSTEM_COLOR_BUTTON);
// Special test for chat mode.
if (m_unattended_chat_count > 0)
{
const char* env = op_getenv("OPERA_CHAT_NOTIFICATION_HIGHLIGHT");
if (env)
color = SYSTEM_TRAY_CHAT_BG;
}
return color;
}
void X11SystemTrayIcon::Repaint(const OpRect& rect)
{
if (GetMdeBuffer())
{
X11Types::Display* display = GetDisplay();
GC gc = XCreateGC(display, GetWindowHandle(), 0, 0);
XSetForeground(display, gc, ConvertToX11Color(GetBackgroundColor()));
XFillRectangle(display, GetWindowHandle(), gc, rect.x, rect.y, rect.width, rect.height);
XFreeGC(display, gc);
// The buffer can be smaller than the window. Center it
int x = (int)(((float)(m_width-GetMdeBuffer()->GetWidth())/2.0)+0.5);
int y = (int)(((float)(m_height-GetMdeBuffer()->GetHeight())/2.0)+0.5);
GetMdeBuffer()->Repaint(rect, x, y);
}
}
bool X11SystemTrayIcon::HandleSystemEvent(XEvent* event)
{
// Shall only contain code that deals with events NOT sent to the widget window
switch (event->type)
{
case DestroyNotify:
{
if (event->xany.window == m_tray_window)
{
// Tray dock window has been destroyed. Try to detect a new one and
// enter it if possible, owtherwise just hide our window
EnterTray();
if (m_tray_window == None)
Hide();
return true;
}
}
break;
case ClientMessage:
{
if (m_tray_window == None)
{
X11Types::Atom manager_atom = XInternAtom(GetDisplay(), "MANAGER", False);
if (event->xclient.message_type == manager_atom && (Atom)event->xclient.data.l[1] == m_tray_selection)
{
EnterTray();
return true;
}
}
}
break;
case PropertyNotify:
{
if (event->xproperty.window == m_tray_window)
{
if (event->xproperty.atom == XInternAtom(GetDisplay(), "_NET_SYSTEM_TRAY_VISUAL", False))
{
m_tray_visual.visual = 0;
EnterTray();
return true;
}
}
}
break;
}
return false;
}
bool X11SystemTrayIcon::HandleEvent( XEvent* event )
{
switch (event->type)
{
case ButtonPress:
{
UpdateAll();
if (event->xbutton.button == 1)
{
if (!X11Widget::GetPopupWidget())
{
g_application->ShowOpera( !g_application->IsShowingOpera() );
return true;
}
}
break;
}
case ButtonRelease:
{
if (event->xbutton.button == 3) // FIXME: Should be configurable (left/right)
{
g_application->GetMenuHandler()->ShowPopupMenu("Tray Popup Menu", PopupPlacement::AnchorAtCursor());
return true;
}
break;
}
case Expose:
{
if (IsVisible())
{
// Workaround for KDE 3x. This DE fails to resize its trayicons properly
// in ConfigureNotify on startup. The size is typically way too large making
// our centering fail in Repaint(). We do this for all versions of KDE
// but I have only seen the issue in KDE 3.5.8 and later (not KDE 4). The
// first paint always spans the entire widget.
if (!m_has_painted)
{
m_has_painted = TRUE;
if (DesktopEnvironment::GetInstance().GetToolkitEnvironment() == DesktopEnvironment::ENVIRONMENT_KDE)
{
UpdateSize(event->xexpose.width, event->xexpose.height);
UpdateIcon(InitIcon, 0);
}
}
OpRect rect;
rect.x = event->xexpose.x;
rect.y = event->xexpose.y;
rect.width = event->xexpose.width;
rect.height = event->xexpose.height;
Repaint(rect);
return true;
}
break;
}
case ReparentNotify:
{
XWindowAttributes attr;
if (XGetWindowAttributes(GetDisplay(), GetWindowHandle(), &attr))
UpdateSize(attr.width, attr.height);
// Set background pixmap if tray window area does not provide a 32-bit visual
// (in case reparenting removed the attribute set in EnterTray)
if (!(m_tray_visual.visual && m_tray_visual.depth == 32))
XSetWindowBackgroundPixmap(GetDisplay(), GetWindowHandle(), ParentRelative);
Show();
return true;
}
case ConfigureNotify:
{
// Save new size. If the window is visible we update the icon as well
UpdateSize(event->xconfigure.width, event->xconfigure.height);
if (IsVisible())
UpdateIcon(InitIcon, 0);
return X11Widget::HandleEvent(event);
}
case MapNotify:
{
UpdateIcon(InitIcon, 0);
return X11Widget::HandleEvent(event);
}
case DestroyNotify:
{
bool state = X11Widget::HandleEvent(event);
RecreateWindow();
return state;
}
default:
return X11Widget::HandleEvent(event);
}
return false;
}
void X11SystemTrayIcon::UpdateSize(int width, int height)
{
// Use height only. Some systems has given "weird" values for width
m_width = m_height = height;
Resize(m_width, m_height);
SetMinSize(m_width, m_height); // Gnome (metacity) likes this
}
void X11SystemTrayIcon::Setup()
{
X11Types::Display* display = GetDisplay();
X11Types::Window root = RootWindow(display, GetScreen());
// Be informed when a tray window appears later even if we find none now.
XWindowAttributes attr;
XGetWindowAttributes(display, root, &attr);
if ((attr.your_event_mask & StructureNotifyMask) != StructureNotifyMask)
XSelectInput(display, root, attr.your_event_mask | StructureNotifyMask);
EnterTray();
}
void X11SystemTrayIcon::EnterTray()
{
DetectTrayWindow();
DetectTrayVisual();
UpdateSize(MAX(m_tray_width,SYSTEM_TRAY_WIDTH), MAX(m_tray_height, SYSTEM_TRAY_HEIGHT));
CreateMdeBuffer();
UpdateIcon(InitIcon, 0);
// Set background pixmap if tray window area does not provide a 32-bit visual
if (!(m_tray_visual.visual && m_tray_visual.depth == 32))
XSetWindowBackgroundPixmap(GetDisplay(), GetWindowHandle(), ParentRelative);
if (m_tray_window != None)
{
XSelectInput(GetDisplay(), m_tray_window, StructureNotifyMask);
XEvent event;
memset(&event, 0, sizeof(event));
event.xclient.type = ClientMessage;
event.xclient.window = m_tray_window;
event.xclient.message_type = XInternAtom(GetDisplay(), "_NET_SYSTEM_TRAY_OPCODE", False);
event.xclient.format = 32;
event.xclient.data.l[0] = CurrentTime;
event.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
event.xclient.data.l[2] = GetWindowHandle();
event.xclient.data.l[3] = 0;
event.xclient.data.l[4] = 0;
XSendEvent(GetDisplay(), m_tray_window, False, NoEventMask, &event);
SetMinSize(SYSTEM_TRAY_WIDTH, SYSTEM_TRAY_HEIGHT); // Gnome (metacity) likes this
XSync(GetDisplay(), False);
}
}
void X11SystemTrayIcon::DetectTrayWindow()
{
int screen = DefaultScreen(GetDisplay());
m_tray_window = None;
m_tray_depth = 0;
if (m_tray_selection == None)
{
OpString8 buf;
buf.AppendFormat("_NET_SYSTEM_TRAY_S%d", screen);
if (buf.HasContent())
m_tray_selection = XInternAtom(GetDisplay(), buf.CStr(), False);
}
if (m_tray_selection != None)
{
XGrabServer(GetDisplay());
m_tray_window = XGetSelectionOwner(GetDisplay(), m_tray_selection);
XUngrabServer(GetDisplay());
}
if (m_tray_window != None)
{
XWindowAttributes attr;
if (XGetWindowAttributes(GetDisplay(), m_tray_window, &attr ))
{
m_tray_depth = attr.depth;
m_tray_width = attr.width;
m_tray_height = attr.height;
}
}
}
void X11SystemTrayIcon::DetectTrayVisual()
{
if (!m_tray_visual.visual)
{
if (m_tray_window == None)
{
DetectTrayWindow();
}
if (m_tray_window != None)
{
X11Types::Atom type;
int format;
unsigned long nitems, bytes_remaining;
unsigned char *data = 0;
int rc = XGetWindowProperty(
GetDisplay(), m_tray_window, XInternAtom(GetDisplay(), "_NET_SYSTEM_TRAY_VISUAL", False), 0, 1,
False, XA_VISUALID, &type, &format, &nitems, &bytes_remaining, &data);
X11Types::VisualID visual_id = 0;
if (rc == Success && type == XA_VISUALID && format == 32 && bytes_remaining == 0 && nitems == 1 )
{
visual_id = *(X11Types::VisualID*)data;
}
if (data)
{
XFree(data);
}
if (visual_id != 0)
{
int num_match;
XVisualInfo visual_template;
visual_template.visualid = visual_id;
XVisualInfo* info = XGetVisualInfo(GetDisplay(), VisualIDMask, &visual_template, &num_match);
if (info)
{
m_tray_visual = info[0];
ChangeVisual(info);
XFree((char*)info);
}
}
}
}
}
|
#include "integral.h"
using namespace std;
int main(int argc, char **argv){
if(argc!=3){
cout<<"Usage: <Histogram filename 1> <Histogram filename 2>"<<endl;
return 1;
}
shape_distribution distribution1(argv[1]);
shape_distribution distribution2(argv[2]);
//shape_distribution distribution1("../../data/analysis_results/rubbermaid_ice_guard_pitcher_blue/1_1_17/partial.hist");
//shape_distribution distribution2("../../data/analysis_results/rubbermaid_ice_guard_pitcher_blue/1_1_17/gt.hist");
double divergence = getDivergence(distribution1, distribution2);
cout<<divergence<<endl;
}
|
// Created on: 2001-01-06
// Created by: OCC Team
// Copyright (c) 2001-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Message_PrinterOStream_HeaderFile
#define _Message_PrinterOStream_HeaderFile
#include <Message_ConsoleColor.hxx>
#include <Message_Printer.hxx>
#include <Standard_Address.hxx>
#include <Standard_OStream.hxx>
class Message_PrinterOStream;
DEFINE_STANDARD_HANDLE(Message_PrinterOStream, Message_Printer)
//! Implementation of a message printer associated with an std::ostream
//! The std::ostream may be either externally defined one (e.g. std::cout),
//! or file stream maintained internally (depending on constructor).
class Message_PrinterOStream : public Message_Printer
{
DEFINE_STANDARD_RTTIEXT(Message_PrinterOStream, Message_Printer)
public:
//! Setup console text color.
//!
//! On Windows, this would affect active terminal color output.
//! On other systems, this would put special terminal codes;
//! the terminal should support these codes or them will appear in text otherwise.
//! The same will happen when stream is redirected into text file.
//!
//! Beware that within multi-threaded environment inducing console colors
//! might lead to colored text mixture due to concurrency.
Standard_EXPORT static void SetConsoleTextColor (Standard_OStream* theOStream,
Message_ConsoleColor theTextColor,
bool theIsIntenseText = false);
public:
//! Empty constructor, defaulting to cout
Standard_EXPORT Message_PrinterOStream(const Message_Gravity theTraceLevel = Message_Info);
//! Create printer for output to a specified file.
//! The option theDoAppend specifies whether file should be
//! appended or rewritten.
//! For specific file names (cout, cerr) standard streams are used
Standard_EXPORT Message_PrinterOStream(const Standard_CString theFileName, const Standard_Boolean theDoAppend, const Message_Gravity theTraceLevel = Message_Info);
//! Flushes the output stream and destroys it if it has been
//! specified externally with option doFree (or if it is internal
//! file stream)
Standard_EXPORT void Close();
~Message_PrinterOStream()
{
Close();
}
//! Returns reference to the output stream
Standard_OStream& GetStream() const { return *(Standard_OStream*)myStream; }
//! Returns TRUE if text output into console should be colorized depending on message gravity; TRUE by default.
Standard_Boolean ToColorize() const { return myToColorize; }
//! Set if text output into console should be colorized depending on message gravity.
void SetToColorize (Standard_Boolean theToColorize) { myToColorize = theToColorize; }
protected:
//! Puts a message to the current stream
//! if its gravity is equal or greater
//! to the trace level set by SetTraceLevel()
Standard_EXPORT virtual void send (const TCollection_AsciiString& theString, const Message_Gravity theGravity) const Standard_OVERRIDE;
private:
Standard_Address myStream;
Standard_Boolean myIsFile;
Standard_Boolean myToColorize;
};
#endif // _Message_PrinterOStream_HeaderFile
|
#ifndef REDBLACKTREE_H
#define REDBLACKTREE_H
#include <iostream>
enum Color {RED,BLACK};
template <class Item>
struct TreeNode{
Item item;
Color color;
struct TreeNode* left;
struct TreeNode* right;
struct TreeNode* parent;
TreeNode():left(NULL),right(NULL),parent(NULL),color(BLACK){}
TreeNode(Item item):item(item),right(NULL),parent(NULL),color(BLACK){}
};
template <class Item>
class RedBlackTree{
private:
TreeNode<Item>* root;
public:
};
#endif //REDBLACKTREE_H
|
#if (!defined __SQLWUI_UIEXTHYPERLINKBUTTON_H)
#define __SQLWUI_UIEXTHYPERLINKBUTTON_H
#include "Prof-UIS.h"
#if (!defined __EXT_MFC_DEF_H)
#include <ExtMfcDef.h>
#endif
#if _MSC_VER > 1000
#pragma once
#endif
//////////////////////////////////////////////////////////////////////////////
// CUIExtHyperLinkButton constants
#define UIEXTHYPERLINKBUTTON_CLICK_CONTINUE 0 // continue handling the click
#define UIEXTHYPERLINKBUTTON_CLICK_CANCEL -1 // cancel handling the click
class CUIExtHyperLinkButton : public CExtHyperLinkButton
{
public:
CUIExtHyperLinkButton(HWND messageWindow, UINT message, UINT controlID);
protected:
virtual void _OnClick(bool bSelectAny, bool bSeparatedDropDownClicked);
private:
HWND m_hWndMessage; // handle of the message receiving window
UINT m_uiMessage; // number of message to be sent on click
UINT m_uiControlID; // ID of the control
};
#endif
|
//
// Persona.h
// Tarea3Ejercicio3
//
// Created by Daniel on 07/10/14.
// Copyright (c) 2014 Gotomo. All rights reserved.
//
#ifndef __Tarea3Ejercicio3__Persona__
#define __Tarea3Ejercicio3__Persona__
#include <iostream>
class Persona{
private:
std::string nombre, apellido;
int edad;
public:
Persona(){};
Persona(int i);
friend std::ostream & operator <<(std::ostream & os, Persona p);
};
#endif /* defined(__Tarea3Ejercicio3__Persona__) */
|
#include <nan.h>
#include <string>
#include "webp/encode.h"
#include "webp/decode.h"
#include "./dec/pngdec.h"
#include "./dec/jpegdec.h"
#include "./dec/imageio_util.h"
#include "./encode_worker.hpp"
#include "./errors_msg.h"
#include "./util.hpp"
NAN_METHOD(N_WebPGetFeatures)
{
if (info.Length() != 1)
{
Nan::ThrowError("Wrong number of arguments");
return;
}
v8::Local<v8::Object> imageBuffer = v8::Local<v8::Object>::Cast(info[0]);
size_t imageBufferLen = node::Buffer::Length(imageBuffer);
WebPBitstreamFeatures *webpInfo = new WebPBitstreamFeatures();
if (WebPGetFeatures((uint8_t *)node::Buffer::Data(imageBuffer), imageBufferLen, webpInfo) != VP8_STATUS_OK)
{
Nan::ThrowError("Can't get info of webp from buffer.");
return;
}
v8::Local<v8::Object> returnObject = Nan::New<v8::Object>();
Nan::Set(returnObject, Nan::New("width").ToLocalChecked(), Nan::New(webpInfo->width));
Nan::Set(returnObject, Nan::New("height").ToLocalChecked(), Nan::New(webpInfo->height));
Nan::Set(returnObject, Nan::New("has_alpha").ToLocalChecked(), Nan::New(webpInfo->has_alpha));
info.GetReturnValue().Set(returnObject);
delete webpInfo;
}
NAN_METHOD(N_WebPEncode)
{
if (info.Length() > 2 || info.Length() <= 0)
{
Nan::ThrowError("Wrong number of arguments");
return;
}
WebPConfig config;
config.quality = 75;
v8::Local<v8::Object> imageBuffer = v8::Local<v8::Object>::Cast(info[0]);
size_t imageBufferLen = node::Buffer::Length(imageBuffer);
uint8_t *imageData = (uint8_t *)node::Buffer::Data(imageBuffer);
if(info.Length() == 2) {
Util::formatWebPConfig(&config, v8::Local<v8::Object>::Cast(info[1]));
}
if (!WebPConfigPreset(&config, WEBP_PRESET_PHOTO, config.quality))
{
return;
}
// Setup the input data, allocating a picture of width x height dimension
WebPPicture *pic = new WebPPicture();
if (!WebPPictureInit(pic))
return; // version error
WebPInputFileFormat imageType = WebPGuessImageType(imageData, imageBufferLen);
if (imageType == WEBP_UNSUPPORTED_FORMAT)
{
Nan::ThrowError("Unsupported format of image.");
return;
}
WebPInputFileSize size;
if (!GetImageSize(imageType, imageData, &size))
{
Nan::ThrowError("Failed to get size of image.");
return;
}
pic->width = size.width;
pic->height = size.height;
if (!WebPPictureAlloc(pic))
{
Nan::ThrowError(std::string("Encoding image error: failed malloc memory.").c_str());
return;
}
WebPImageReader reader = WebPGetImageReader(imageType);
reader(imageData, imageBufferLen, pic, 1, NULL);
WebPMemoryWriter *writer = new WebPMemoryWriter();
pic->writer = WebPMemoryWrite;
pic->custom_ptr = writer;
WebPMemoryWriterInit(writer);
if (!WebPEncode(&config, pic))
{
WebPPictureFree(pic);
Nan::ThrowError((std::string("Encoding image error: ").append(WebPEncodingErrorMessage[pic->error_code])).c_str());
return;
}
WebPPictureFree(pic);
info.GetReturnValue().Set(Nan::CopyBuffer((char *)writer->mem, writer->size).ToLocalChecked());
delete writer->mem;
delete writer;
delete pic;
}
// Module initialization logic
NAN_MODULE_INIT(Initialize)
{
// Export the `Hello` function (equivalent to `export function Hello (...)` in JS)
NAN_EXPORT(target, N_WebPGetFeatures);
NAN_EXPORT(target, N_WebPEncode);
NAN_EXPORT(target, N_WebPEncodeAsync);
}
// Create the module called "addon" and initialize it with `Initialize` function (created with NAN_MODULE_INIT macro)
NODE_MODULE(addon, Initialize);
|
#include "precompile.h"
#include <string>
#include <cstdio>
#include "libop/op.h"
#include "parser.h"
#include "exception.h"
#include "io.h"
using namespace kwik;
int main(int argc, char** argv) {
std::vector<std::string> args {argv, argv + argc};
if (args.size() < 2) {
op::printf("Usage: {} <file>\n", args[0]);
return 1;
}
try {
Source src = args[1] == "-" ? read_stdin() : read_file(args[1]);
parse(src);
return 0;
} catch (const CompilationError& e) {
op::print(e.what());
} catch (const EncodingError& e) {
op::print(e.what());
} catch (const FilesystemError& e) {
op::printf("error: {}: {}\n", args[1], e.what());
} catch (const InternalCompilerError& e) {
op::printf("internal compiler error: {}: {}\n", args[1], e.what());
}
return 1;
}
|
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#define ui unsigned int
#define ull unsigned long long
#define us unsigned long long
#pragma GCC optimize("03")
using namespace std;
ui cur = 0;
ui a, b;
inline ui nextRand24() {
cur = cur * a + b;
return cur >> 8;
}
inline ui nextRand32() {
return (nextRand24() << 8) ^ nextRand24();
}
inline ui digit(ui num, ui i) {
return (num >> (i * 8) & 0xFF);
}
void lsd(vector<ui> &v) {
ui k = 256;
ui m = 4;
ui n = v.size();
vector<ui> nV(n);
for (ui i = 0; i < m; i++) {
vector<ui> c(k);
for (ui j = 0; j < n; j++) {
c[digit(v[j], i)]++;
}
ui count = 0;
for (ui j = 0; j < k; j++) {
ui temp = c[j];
c[j] = count;
count += temp;
}
for (ui j = 0; j < n; j++) {
ui d = digit(v[j], i);
nV[c[d]] = v[j];
c[d]++;
}
v = nV;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
ui t, n;
cin >> t >> n;
for (ui i = 0; i < t; i++) {
cin >> a >> b;
vector<ui> vec(n);
for (ui j = 0; j < n; j++) {
vec[j] = nextRand32();
}
lsd(vec);
unsigned long long summ = 0;
for (ui ij = 0; ij < n; ij++) {
summ += (unsigned long long) (ij + 1) * vec[(size_t) ij];
}
cout << summ << endl;
vec.clear();
}
return 0;
}
|
/*
* BOW.hpp
*
* Created on: 2017年4月16日
* Author: lcy
*/
#ifndef BOW_HPP_
#define BOW_HPP_
#include <opencv2/opencv.hpp>
#include <opencv2/xfeatures2d.hpp>
class BowFeature
{
public:
BowFeature() {};
~BowFeature() {};
void FormVisualWords(int clusterCount, cv::Mat &allFeatures);//allFeatrues means a single mat which consist of a number of sift descriptors,
//The function will produce a document called "dictionary.yml" which store the (vocabulary) mat
cv::Mat ExtractorFeatureByBow(cv::Mat &img, std::vector<cv::KeyPoint>& keypoints);
private:
cv::Ptr<cv::BOWKMeansTrainer> bowTrainer; //Use this to construct bags of words
cv::Ptr<cv::BOWImgDescriptorExtractor> bowImgExtractor; //Use this to extractor the descriptions
cv::Ptr<cv::xfeatures2d::SiftDescriptorExtractor> descExtractor;
cv::Ptr<cv::DescriptorMatcher> descMatcher;
cv::Mat dictionary; //Which means the BowTrainer use data to generate the result
void initBowTrainer(int clusterCount); //clusterCount is the number of cluster
void initBowImgExtractor();
};
#endif /* BOW_HPP_ */
|
#include "poligono.h"
poligono::poligono(int l , const vector<punto*>& p):lati(l){
pt = copia(p);
}
unsigned int poligono::getlati() const {
return lati;
}
vector<punto*> poligono::getpoint() const {
return copia(pt); //ritorno la copia dei puntatori a punto
}
//massimo tre controlli : visto che utilizziamo poligoni regolari fino a 4 lati
//quindi prendendo tre segmenti posso capire qual'e' il lato del poligono
double poligono::lato() const{
double lat = pt[0]->distanceTwoPoints(*pt[1]);
//il lato e' la distanza minima tra i punti inseriti
for(int i = 2 ; i < 4 ; i ++ ){
double p = pt[0]->distanceTwoPoints(*pt[i]);
if(p < lat) lat = p ;
}
return lat;
}
//se è regolare ritorna la misura del lato altrimenti ritorna 0
bool poligono::isRegular() const {
for(unsigned int i = 0 ; i < pt.size()-1 ; ++i ){
for(unsigned int j = i+1 ; j < pt.size() ; ++j ){
if(*pt[i] == *pt[j]) return false;
}
}
if(getlati() == 3){
retta r = retta::rettaFromTwoPoints(*pt[0],*pt[1]);
if((r.intersect(pt[2])).size() >= 1){
return false;
}
return true;
}
else{
double conf = lato();
unsigned int check = 0 ;
for(unsigned int i = 0 ; i < pt.size()-1 ; ++i ){
for(unsigned int j = i+1 ; j < pt.size() ; ++j ){
if(pt[i]->distanceTwoPoints(*pt[j]) == conf) {
check++; //verifico di avere n lati uguali al lato()
}
}
}
if(check == getlati()){
return true;
}
else return false;
}
}
//-----------------DISTR PROFONDO-------------------
poligono::~poligono(){
distruggi(pt);
}
void poligono::distruggi(vector<punto*>& v) {
vector<punto*>::iterator it = v.begin();
for( ; it != v.end() ; ++it ){;
delete *it;
v.erase(it);
--it;
}
}
//---------------COPIA PROFONDA-------------
vector<punto*> poligono::copia(const vector<punto*>& v){
vector<punto*> n ;
for( unsigned int i = 0 ; i < v.size() ; ++i ){
n.push_back(new punto(*v[i]));
}
return n;
}
//-------------COSTRUTTORE DI COPIA PROFONDA--------
poligono::poligono(const poligono & p){
lati = p.lati;
pt = copia(p.pt);
}
//------------------ OPERATOR ----------------
poligono& poligono::operator=( const poligono& p ) {
if(this != &p){
distruggi(pt);
pt = copia(p.pt);
lati = p.lati;
}
return *this;
}
bool poligono::operator !=(const poligono& p ){
if(p.lati == lati){
unsigned int cont = 0 ;
vector<punto*> p1 = p.getpoint();
vector<punto*> p2 = getpoint();
for(unsigned int i = 0 ; i < p1.size() -1 ; ++ i){
for(unsigned int j = i + 1 ; j < p2.size() ; ++j ){
if( *p1[i] == *p2[j] ) cont ++;
}
}
distruggi(p1);
distruggi(p2);
if(cont == lati) return true;
}
return false;
}
ostream& operator<<(ostream& os , poligono* q){
vector<punto*> p = q->pt;
vector<punto*>::const_iterator it = p.cbegin();
for(;it != p.cend() ; ++it){
os<<**it<<" ";
}
return os;
}
//parser poligono
/*-------------------------------------------------------------------*/
poligono* poligono::pars_pol(string s){
//potrebbe essere evitato, ma la rende autonoma nel caso di una chiamata esplicita
unsigned int len = s.length();
for (unsigned int var = 0; var < len; ++var) {
if(s[var] == ' '){
s.erase(s.begin()+var);
--var;
len--;
}
}
//tolto gli spazi
/* 1 trovo i punti
* 2 verifico se è regolare
* 3 se è regolare lo ritorno altrimenti eccez
*/
int pc = 0 , pa = 0 , pv = 0 ;
for (unsigned int var = 0; var < len; ++var) {
if(s[var] == ')') pc ++;
if(s[var] == '(') pa ++;
if(s[var] == ';') pv ++;
}
vector<punto*> temp;
if(pc == pa && pc == pv){
//ok parsiamo i punti
for (unsigned int var = 0; var < len; ++var) {
string single_point;
for (unsigned int i = var; s[i] != ')' ; ++i) {
single_point = single_point + s[i] ;
}
var = var + single_point.length();
single_point = single_point + s[var] ;
punto point;
//parso punto per punto e man mano che li trovo giusti li inserisco nel vector
try{point.pars_point(single_point);}
catch(input_error){
//rimando l'eccezione al chiamante
throw ;
}
catch(int){
//invoco il costruttore di copia standard
temp.push_back(new punto(point));
}
}
if( pc == 3 ){
triangolo tr(pc,temp);
if( tr.isRegular() )
return new triangolo(tr);
else
throw irregular_pol();
}
else if( pc == 4 )
{
quadrato qr(pc,temp);
if( qr.isRegular() )
return new quadrato(qr);
else
throw irregular_pol();
}
else {
throw num_lati();
}
}
else
throw input_error();
}
/*------------------------------------------------------*/
double poligono::perimetro() const {
return getlati()*lato();
}
double poligono::area() const {
double apotema = getlati() * getfisso();
return (perimetro()*apotema)/2;
}
//p1 e p2 sono diversi da nullptr nel momento in cui viene invocata all'interno di polipoli()
//questo perche' bisogna verificare che il punto trovato sia all'interno dei range dei due lati e non solo di uno
vector<punto> poligono::rettapol(retta * r , punto * p1 = nullptr ,punto * p2 = nullptr) const{
vector<punto> p;
vector<punto*> vCoord0 = getpoint();
for(unsigned int i = 0; i<vCoord0.size() - 1; i++){
for(unsigned int j = i + 1; j<vCoord0.size(); j++){
if(vCoord0[i]->distanceTwoPoints(*vCoord0[j]) == lato() || vCoord0.size() == 3){
retta prova = retta::rettaFromTwoPoints(*vCoord0[i],*vCoord0[j]);
vector<punto> intr = prova.Intersect_rette(*r);
//intersezione tra due rette è al massimo un punto
if(intr.size() > 0){
//- devo verificare che il punto trovato sia compreso tra i due vertici presi in considerazione :
//- quindi primo controllo verifico che la x dell'intersezione sia compreso tra le x di vCoord0[i] e vCoord0[j]
// poi avviene lo stesso controllo sulle y
//- se vCoord0[i] e vCoord0[j] hanno la stessa x (lato parallelo all'asse y) allora vado a verificare direttamente le y
// (vale il contrario con le y)
if( (vCoord0[i]->getX() <= intr[0].getX() && vCoord0[j]->getX() >= intr[0].getX() )
|| (vCoord0[i]->getX() >= intr[0].getX() && vCoord0[j]->getX() <= intr[0].getX() ) || (vCoord0[i]->getX() == vCoord0[j]->getX() ) ) //se ho la stessa x non la verifico
{
if( (vCoord0[i]->getY() <= intr[0].getY() && vCoord0[j]->getY() >= intr[0].getY() )
|| (vCoord0[i]->getY() >= intr[0].getY() && vCoord0[j]->getY() <= intr[0].getY() ) || (vCoord0[i]->getY() == vCoord0[j]->getY() ) )
{
if(p1 && p2){ //invocata in polipoli: p1 e p2 sono i punti che formano la retta r, quindi vado a veridfica che il punto sia tra quelle x e y.x
if( ( (p1->getX() <= intr[0].getX() && p2->getX() >= intr[0].getX() )
|| (p1->getX() >= intr[0].getX() && p2->getX() <= intr[0].getX() ) ) && ( (p1->getY() <= intr[0].getY() && p2->getY() >= intr[0].getY() )
|| (p1->getY() >= intr[0].getY() && p2->getY() <= intr[0].getY() ) ) )
{
p.push_back(punto(intr[0]));
}
}
else {
p.push_back(punto(intr[0]));//copio il punto dentro
}
}
}
}
intr.erase(intr.begin(),intr.end());
}
}
}
distruggi(vCoord0);
//verifico non ci siano ridondanze nel vector
if( p.size() > 1 ){
for( unsigned int i = 0 ; i < p.size() - 1 ; ++i ){
for( unsigned int j = i + 1 ; j < p.size() ; ++j ){
if( p[i] == p[j] ){
p.erase(p.begin()+j);
--j;
}
}
}
}
return p;
}
vector<punto> poligono::puntint(const poligono & p1) const{
vector<punto*> punti = getpoint();
vector<punto> inter;
for(unsigned int i = 0; i < punti.size(); i++){
if(p1.polipunto(punti[i])){
if(p1.polipunto(punti[i])) inter.push_back(*(punti[i]));
}
}
//se il ho n elementi nel vector e il poligono ha n vertici allora è interno e non vado a fare un ulteriore controllo
if(inter.size() != getlati()){
vector<punto*> punti2 = p1.getpoint();
for(unsigned int i = 0; i < punti2.size(); i++){
if(polipunto(punti2[i])) inter.push_back(*(punti2[i]));
}
distruggi(punti2);
}
distruggi(punti);
return inter;
}
vector<punto> poligono::polipoli(poligono * pol) const{
vector<punto> p,puntinterni;
puntinterni = puntint(*pol);
if( puntinterni.size() > 0 ){
p.vector::insert(p.end(), puntinterni.begin(), puntinterni.end());
}
vector<punto*> vCoord0 = getpoint();
for(unsigned int i = 0; i<vCoord0.size() - 1; i++){
for(unsigned int j = i + 1; j<vCoord0.size(); j++){
if(vCoord0[i]->distanceTwoPoints(*vCoord0[j]) == lato() || vCoord0.size() == 3){
retta prova = retta::rettaFromTwoPoints(*vCoord0[i],*vCoord0[j]);
vector<punto> single = pol->rettapol(&prova,vCoord0[i],vCoord0[j]);
p.vector::insert(p.end(), single.begin(), single.end());
}
}
}
distruggi(vCoord0); //distruttore dei punti
//verifico non ci siano doppioni
if(p.size() > 0){
for( unsigned int i = 0 ; i < p.size(); ++i ){
for( unsigned int j = i + 1 ; j < p.size() ; ++j ){
if( p[i] == p[j] ) {
p.erase(p.begin()+j);
--j;
}
}
}
}
return p;
}
/*metodo verifica :
1) verifico sia un vertice del poligono
2) creo una retta parallela all'asse x passante per p , se la
retta interseca per due volte il poligono , e i punti di
intersezione p1 e p2 hanno rispettivamente :
(x1 <= x <= x2 || x2 <= x <= x1 ) allora è interno .
*/
bool poligono::polipunto( punto * p ) const{
//prima verifico che sia un vertice del poligono
vector<punto> punt;
vector<punto*> lat = getpoint();
for( unsigned int i = 0 ; i < lat.size() ; ++i ){
if(*lat[i] == *p){ //punto == vertice poligono
distruggi(lat);
return p;
}
}
retta paralx(0,1,-3);
retta r = paralx.RettaParallela(*p);
//r è una retta parallela all'asse x passante per p
vector<punto> inter = rettapol(&r);
distruggi(lat);
if( inter.size() >= 2 ) {
//ok allora verifico che sia uno a dx e uno a sx del punto
if((inter[0].getX() <= p->getX() && inter[1].getX() >= p->getX())
||(inter[0].getX() >= p->getX() && inter[1].getX() <= p->getX() ) )
{
return true;
}
}
return false;
}
/*
NB: il controllo delle ridondanze dei punti sul vector avviene all'interno di più funzioni, l'obiettivo è renderle indipendenti
per un eventuale modifica futura.
*/
vector<punto> poligono::intersect(inputitem* i) const {
if( typeid(punto) == typeid(*i) ){
punto * p = dynamic_cast<punto*>(i);
vector<punto> punt ;
if(polipunto(p)) punt.push_back(*p);
return punt;
}
else{
if(typeid(retta) == typeid(*i)){
return rettapol(dynamic_cast<retta*>(i));
}
else return polipoli(dynamic_cast<poligono*>(i));
}
}
//--------distance------------------------------------------
double poligono::distance(inputitem * i) const {
//verifico che i due elementi non si intersecano, cosi eventualmente evitare calcoli inutii
if( (intersect(i)).size() > 0 ) return 0;
if( typeid(retta) == typeid(*i) ){
return distrettapol(dynamic_cast<retta*>(i));
}
else if( typeid(punto) == typeid(*i) ){
return distpuntopol(dynamic_cast<punto*>(i));
}
else return distpolipoli(dynamic_cast<poligono*>(i));
}
double poligono::distpuntopol(punto * p ) const{
vector<punto*> punti = getpoint();
vector<double> distanza;
for(unsigned int i = 0 ; i < punti.size() - 1 ; ++i ){
for(unsigned int j = i + 1 ; j < punti.size() ; ++j ){
if(punti.size() == 3 || punti[i]->distanceTwoPoints(*punti[j]) == lato() ){
retta latopol = retta::rettaFromTwoPoints(*punti[i],*punti[j]);
retta perp = latopol.RettaPerpendicolare(*p);
vector<punto> inter = perp.Intersect_rette(latopol);
if( punti[i]->getX() == punti[j]->getX() ){
if( (inter[0].getY() <= punti[i]->getY() && inter[0].getY() >= punti[j]->getY() )
|| (inter[0].getY() >= punti[i]->getY() && inter[0].getY() <= punti[j]->getY()) )
distanza.push_back(inter[0].distanceTwoPoints(*p));
}
else{
if( (inter[0].getX() <= punti[i]->getX() && inter[0].getX() >= punti[j]->getX() )
|| (inter[0].getX() >= punti[i]->getX() && inter[0].getX() <= punti[j]->getX()) )
{
distanza.push_back(inter[0].distanceTwoPoints(*p));
}
}
}
}
distanza.push_back(p->distanceTwoPoints(*punti[i]));
}
distanza.push_back(p->distanceTwoPoints(*punti[punti.size()-1]));
if(distanza.size() == 0) throw input_error("Errore.");
vector<double>::iterator result = std::min_element(std::begin(distanza), std::end(distanza));
distruggi(punti);
return *result;
}
double poligono::distrettapol(retta * r ) const{
vector<punto*> punti = getpoint();
vector<double> distanza;
for(unsigned int i = 0 ; i < punti.size() ; ++i ){
distanza.push_back(r->distancePuntoRetta(*punti[i]));
}
vector<double>::iterator result = std::min_element(std::begin(distanza), std::end(distanza));
distruggi(punti);
return *result;
}
double poligono::distpolipoli(poligono * pol1) const{
vector<punto*> punti1 = pol1->getpoint();
vector<double> distanza;
for(unsigned int i = 0 ; i< punti1.size() ; ++i ){
distanza.push_back(distpuntopol(punti1[i]));
}
vector<punto*> punti2 = getpoint();
for(unsigned int i = 0 ; i< punti2.size() ; ++i ){
distanza.push_back(pol1->distpuntopol(punti2[i]));
}
vector<double>::iterator result = std::min_element(std::begin(distanza), std::end(distanza));
distruggi(punti1);
distruggi(punti2);
return *result;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
struct Node{
int key;
Node *prev, *next;
};
Node *nil;
void Init(){
nil = (Node *)malloc(sizeof(Node));
nil -> prev = nil;
nil -> next = nil;
return;
}
void Insert(int insert_key){
// 挿入するノード宣言してキーの値を入れる
Node *x = (Node *)malloc(sizeof(Node));
x -> key = insert_key;
// 番兵の直後に要素を追加
x -> next = nil -> next;
nil -> next -> prev = x;
x -> prev = nil;
nil -> next = x;
return;
}
Node* Search(int search_key){
Node *current = nil -> next;
while(current != nil && current -> key != search_key){
current = current -> next;
}
return current;
}
void Delete(Node *x){
if(x == nil){return;}
x -> prev -> next = x -> next;
x -> next -> prev = x -> prev;
free(x);
return;
}
void DeleteFirtst(){
Delete(nil -> next);
return;
}
void DeleteLast(){
Delete(nil -> prev);
return;
}
void Output(){
Node *x = nil -> next;
while(x != nil){
printf("%d", x -> key);
if(x -> next != nil){printf(" ");}
else{printf("\n");}
x = x -> next;
}
return;
}
int main(void){
Init();
int n;
scanf("%d", &n);
char command[12];
int key;
for(int i=0; i<n; i++){
scanf("%s%d", command, &key);
if(!strcmp(command, "insert")){Insert(key);}
else if(!strcmp(command, "delete")){Delete(Search(key));}
else if(!strcmp(command, "deleteFirst")){DeleteFirtst();}
else {DeleteLast();}
}
Output();
return 0;
}
|
#include <cstdio>
#include <algorithm>
using namespace std;
int arr[805][805];
int out[805];
int final[805];
int main(void) {
int cases;
scanf("%d", &cases);
for (int c = 0; c < cases; ++c) {
int n;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
scanf("%d", &arr[i][j]);
}
out[i] = 1;
}
for (int j = 0; j < n; ++j) {
int c = -1;
for (int i = j; i < n; ++i) {
if (arr[i][j] == 1) {
c = i;
break;
}
}
if (c != -1) {
for (int i = 0; i < n; ++i) {
swap(arr[j][i], arr[c][i]);
}
swap(out[j], out[c]);
}
for (int i = j + 1; i < n; ++i) {
if (arr[i][j] == 0) continue;
for (int k = 0; k < n; ++k) {
arr[i][k] ^= arr[j][k];
}
out[i] ^= out[j];
}
}
// for (int i = 0; i < n; ++i) {
// for (int j = 0; j < n; ++j) {
// printf(" %d", arr[i][j]);
// }
// printf("\n");
// }
for (int i = n-1; i >= 0; --i) {
final[i] = out[i];
for (int k = i + 1; k < n; ++k) {
final[i] ^= arr[i][k] * final[k];
}
}
// printf("%d", out[0]);
// for (int i = 1; i < n; ++i) {
// printf(" %d", out[i]);
// }
// printf("\n");
printf("%d", final[0]);
for (int i = 1; i < n; ++i) {
printf(" %d", final[i]);
}
printf("\n");
}
return 0;
}
|
// https://oj.leetcode.com/problems/combinations/
class Solution {
void find_combine(vector<vector<int> > &ret, vector<int> &oneline, int begin, int n, int k) {
if (k == 0) {
ret.push_back(oneline);
return;
}
for (int i = begin; i <= n - k + 1; i++) {
oneline.push_back(i);
find_combine(ret, oneline, i + 1, n, k - 1);
oneline.pop_back();
}
}
public:
vector<vector<int> > combine(int n, int k) {
vector<vector<int> > ret;
vector<int> oneline;
if (n < k) {
return ret;
}
find_combine(ret, oneline, 1, n, k);
return ret;
}
};
|
#include "gizmo_painter.h"
#include <iostream>
namespace wimgui
{
void gizmo_painter::clear()
{
}
void gizmo_painter::gl_paint(view3d& view)
{
ImRect canvas = view.get_content_rectangle();
gl_program::state gl_state;
gl_state.save_current_state();
gl_state.activate_imgui_defaults();
ImVec2 viewport_position = ImVec2(
canvas.Min.x,
ImGui::GetIO().DisplaySize.y - canvas.Max.y
);
glViewport(
(GLsizei)viewport_position.x,
(GLsizei)viewport_position.y,
(GLsizei)canvas.GetWidth(),
(GLsizei)canvas.GetHeight()
);
lines_program.use();
glBindVertexArray(line_array);
transformation_matrix = view.get_view_matrix() * model_matrix;
lines_program.set_uniform("view_matrix", transformation_matrix);
glLineWidth(5.0f);
glDrawArrays(GL_LINES, 0, line_count * vertices_per_line * 3);
glBindVertexArray(0);
cones_program.use();
glBindVertexArray(x_cone_array);
transformation_matrix = view.get_view_matrix() * model_matrix;
cones_program.set_uniform("view_matrix", transformation_matrix);
cones_program.set_uniform("color", x_color);
glDrawArrays(GL_TRIANGLES, 0, imagio::meshes::x_cone::vertice_count * 3);
glBindVertexArray(y_cone_array);
cones_program.set_uniform("color", y_color);
glDrawArrays(GL_TRIANGLES, 0, imagio::meshes::y_cone::vertice_count * 3);
glBindVertexArray(z_cone_array);
cones_program.set_uniform("color", z_color);
glDrawArrays(GL_TRIANGLES, 0, imagio::meshes::z_cone::vertice_count * 3);
glBindVertexArray(0);
gl_state.restore();
}
void gizmo_painter::init_painter()
{
std::string vertex_shader_path("imagio/viewers/3d/gltool/per_vertex_color.vert");
lines_program.load_vertex_shader(vertex_shader_path);
lines_program.compile(); lines_program.use();
glGenVertexArrays(1, &line_array);
glBindVertexArray(line_array);
glGenBuffers(1, &line_buffer);
glBindBuffer(GL_ARRAY_BUFFER, line_buffer);
glBufferData(
GL_ARRAY_BUFFER,
sizeof(float) * line_count * vertices_per_line * 3,
lines,
GL_STATIC_DRAW
);
GLuint position_attribute = lines_program.get_attribute_location("position");
lines_program.set_attribute_float_pointer(position_attribute, 3);
lines_program.enable_attribute_array(position_attribute);
glGenBuffers(1, &line_normal_buffer);
glBindBuffer(GL_ARRAY_BUFFER, line_normal_buffer);
glBufferData(
GL_ARRAY_BUFFER,
sizeof(float) * line_count * vertices_per_line * 3,
line_normals,
GL_STATIC_DRAW
);
GLuint normal_attribute = lines_program.get_attribute_location("normal");
lines_program.set_attribute_float_pointer(normal_attribute, 3);
lines_program.enable_attribute_array(normal_attribute);
glGenBuffers(1, &line_color_buffer);
glBindBuffer(GL_ARRAY_BUFFER, line_color_buffer);
glBufferData(
GL_ARRAY_BUFFER,
sizeof(float) * line_count * vertices_per_line * 4,
line_colors,
GL_STATIC_DRAW
);
GLuint color_attribute = lines_program.get_attribute_location("color");
lines_program.set_attribute_float_pointer(color_attribute, 4);
lines_program.enable_attribute_array(color_attribute);
glBindVertexArray(0);
std::string cones_vertex_shader_path("imagio/viewers/3d/gltool/single_color.vert");
cones_program.load_vertex_shader(cones_vertex_shader_path);
cones_program.compile(); cones_program.use();
generate_mesh_data(
cones_program,
&x_cone_array,
imagio::meshes::x_cone::vertice_count,
&x_cone_buffer,
imagio::meshes::x_cone::vertices,
&x_cone_normal_buffer,
imagio::meshes::x_cone::normals
);
generate_mesh_data(
cones_program,
&y_cone_array,
imagio::meshes::y_cone::vertice_count,
&y_cone_buffer,
imagio::meshes::y_cone::vertices,
&y_cone_normal_buffer,
imagio::meshes::y_cone::normals
);
generate_mesh_data(
cones_program,
&z_cone_array,
imagio::meshes::z_cone::vertice_count,
&z_cone_buffer,
imagio::meshes::z_cone::vertices,
&z_cone_normal_buffer,
imagio::meshes::z_cone::normals
);
glEnable(GL_PROGRAM_POINT_SIZE);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
glCullFace(GL_BACK);
// model_matrix = glm::scale(model_matrix, glm::vec3(0.1f));
}
void gizmo_painter::generate_mesh_data(
gl_program::gl_program& program,
GLuint* vertex_array_ptr,
int vertice_count,
GLuint* vertex_buffer_ptr,
float const* vertices_ptr,
GLuint* normal_buffer_ptr,
float const* normals_ptr
)
{
glGenVertexArrays(1, vertex_array_ptr);
glBindVertexArray(*vertex_array_ptr);
glGenBuffers(1, vertex_buffer_ptr);
glBindBuffer(GL_ARRAY_BUFFER, *vertex_buffer_ptr);
glBufferData(
GL_ARRAY_BUFFER,
sizeof(float) * vertice_count * 3,
vertices_ptr,
GL_STATIC_DRAW
);
GLuint position_attribute = program.get_attribute_location("position");
program.set_attribute_float_pointer(position_attribute, 3);
program.enable_attribute_array(position_attribute);
glGenBuffers(1, normal_buffer_ptr);
glBindBuffer(GL_ARRAY_BUFFER, *normal_buffer_ptr);
glBufferData(
GL_ARRAY_BUFFER,
sizeof(float) * vertice_count * 3,
normals_ptr,
GL_STATIC_DRAW
);
GLuint normal_attribute = program.get_attribute_location("normal");
program.set_attribute_float_pointer(normal_attribute, 3);
program.enable_attribute_array(normal_attribute);
glBindVertexArray(0);
}
}
|
#include <bits/stdc++.h>
typedef long long ll;
typedef unsigned long long ull;
#define tests int t; cin >> t; while(t--)
#define vll vector<ll>
#define vi vector<int>
#define pb push_back
using namespace std;
template <typename T>
istream& operator >> (istream& i, vector<T>& v) {
for(T& j : v) i >> j;
return i;
}
vi vis, v, ans;
int n, d;
void search(int i, int lvl) {
if(!vis[i]) {
vis[i] = true;
if(v[i] == 0) {
lvl = 0;
} else {
lvl++;
}
ans[i] = lvl;
search((n+i+d)%n, lvl);
}
}
void solve() {
cin >> n >> d;
v.resize(n); cin >> v;
vis.assign(n, 0); ans.assign(n, 0);
for(int i = 0; i < n; i++) {
if(v[i] == 0) {
search(i, 0);
}
}
int ma = 0;
for(int i = 0; i < n; i++) {
if(v[i] == 1 && ans[i] == 0) {
cout << "-1\n";
return;
}
if(v[i] == 1) {
ma = max(ma, ans[i]);
}
}
cout << ma << "\n";
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
tests {
solve();
}
return 0;
}
|
#ifndef UI_ACTION_INSTANTACTIONS_REMOVESELF_H_
#define UI_ACTION_INSTANTACTIONS_REMOVESELF_H_
#pragma once
namespace ui
{
class UILIB_API RemoveSelf : public InstantAction
{
public:
static RemoveSelf* Create();
virtual void Update(float time) override;
virtual RemoveSelf* Reverse() const override;
virtual RemoveSelf* Clone() const override;
protected:
RemoveSelf() = default;
};
}
#endif
|
/**
* Copyright 2015 ViajeFacil
* pelVector.hpp
* -----------------------------------
* PEL - UEM - 2014/2015 Academic Year
* -----------------------------------
* v4.0 - May 19, 2015
*/
#ifndef PEL_Vector_HPP_INCLUDED
#define PEL_Vector_HPP_INCLUDED
#include <cstddef>
#include <string>
#include <initializer_list>
#include <stdexcept>
#include <utility>
#include <algorithm>
#include <fstream>
#include <istream>
#include <iostream>
#include <sstream>
#include "./cereal/cereal.hpp"
namespace pel {
template<typename T> // T must be a type
class Vector {
T* v_, // start of allocation
* space_, // end of sequence, start of expansion
* last_; // end of allocated memory space
void rangeCheck(std::size_t i) {
if (i >= size())
throw std::out_of_range{"Out of range index"};
}
public:
///////////////////////////////////////////////////////////////////////////
// construction/copy/destruction:
Vector() // create empty Vector
: v_{new T[0]}, space_{v_}, last_{v_} { }
Vector(std::size_t size, T const& val)
: v_{new T[size]}, space_{v_ + size}, last_{space_}
{
try {
for (std::size_t i = 0; i < size; ++i)
v_[i] = val;
}
catch (...) {
delete[] v_;
throw;
}
}
Vector(std::initializer_list<T> const& list)
: v_{new T[list.size()]}, space_{v_ + list.size()}, last_{space_}
{
try {
auto p = v_;
for (auto q = list.begin(); q != list.end(); ++p, ++q)
*p = *q;
}
catch (...) {
delete[] v_;
throw;
}
}
Vector(Vector<T> const& vec) // copy constructor
: v_{new T[vec.size()]}, space_{v_ + vec.size()}, last_{space_}
{
try {
for (std::size_t i = 0; i < vec.size(); ++i)
v_[i] = vec[i];
}
catch (...) {
delete[] v_;
throw;
}
}
Vector<T>& operator=(Vector<T> const& vec) { // copy assignment operator
// copy-and-swap idiom (strong exception safety guarantee):
Vector<T> tmp{vec};
std::swap(v_, tmp.v_);
std::swap(space_, tmp.space_);
std::swap(last_, tmp.last_);
return *this;
} // local tmp Vector is destroyed at this point
~Vector() { delete[] v_; } // destructor
////////////////////////////////////////////////////////////////////////////
// modifiers:
void push_back(T const& val) { // strong exception safety guarantee
if (space_ == last_) { // capacity exhaustion
auto const sz = size(), // original size
// new capacity
cp = (sz)? static_cast<std::size_t>(1.5*sz) : 2;
T* newBlock = new T[cp];
try {
for (std::size_t i = 0; i < sz; ++i)
newBlock[i] = v_[i];
}
catch (...) {
delete[] newBlock;
throw;
}
delete[] v_;
v_ = newBlock;
space_ = v_ + sz;
last_ = v_ + cp;
}
*space_ = val;
++space_;
}
void popBack() { // calling popBack() on an empty container is undefined
--space_;
*space_ = T{};
}
// iterator position must be valid and dereferenceable
T* erase(T* position) { // basic exception safety guarantee
for (T* p = position + 1; p != space_; ++p)
*(p - 1) = *p;
popBack();
return position;
}
T* insert(T* position, T const& val) {
if (space_ != last_ && position == space_) {
*space_ = val;
++space_;
} else if (space_ != last_) { // basic guarantee; more efficient
*space_ = *(space_ - 1);
++space_;
// copy the elements in [position,space_-2) to range ending at
// space_-1. The elements are copied in reverse order (the last
// element is copied first), but their relative order is preserved
auto it1 = space_ - 1,
it2 = space_ - 2;
while (position != it2)
*(--it1) = *(--it2);
*position = val;
} else { // strong safety guarantee trivially satisfied
std::size_t const n = position - v_;
// increase the alloc
auto const sz = size(),
cp = (sz)? static_cast<std::size_t>(1.5*size()) : 2;
T* newBlock = new T[cp];
try {
for (std::size_t i = 0; i < n; ++i)
newBlock[i] = v_[i];
newBlock[n] = val;
for (std::size_t i = n; i < sz; ++i)
newBlock[i + 1] = v_[i];
}
catch (...) {
delete[] newBlock;
throw;
}
delete[] v_;
v_ = newBlock;
space_ = v_+ sz + 1;
last_ = v_ + cp;
position = v_ + n;
}
return position;
}
void resize(std::size_t n) {
int const toDestroy = size() - n; // note: conversion to int
if (toDestroy > 0) {
for (int i = 0; i < toDestroy; ++i)
popBack();
} else if (toDestroy < 0) {
for (int i = toDestroy; i < 0; ++i)
push_back(T{});
}
}
////////////////////////////////////////////////////////////////////////////
// capacity:
std::size_t size() const { return space_ - v_; }
std::size_t capacity() const { return last_ - v_; }
bool empty() const { return v_ == space_; }
////////////////////////////////////////////////////////////////////////////
// access:
T const& operator[](std::size_t i) const { return v_[i]; }
T& operator[](std::size_t i) { return v_[i]; }
T const& at(std::size_t i) const { rangeCheck(i); return v_[i]; }
T& at(std::size_t i) { rangeCheck(i); return v_[i]; }
T const& front() const { return *v_; }
T& front() { return *v_; }
T const& back() const { return *(space_ - 1); }
T& back() { return *(space_ - 1); }
////////////////////////////////////////////////////////////////////////////
// iterators:
T const* begin() const { return v_; }
T* begin() { return v_; }
T const* end() const { return space_; }
T* end() { return space_; }
////////////////////////////////////////////////////////////////////////////
// serialization:
template<class Archive>
void save(Archive& archive) const {
archive(cereal::make_size_tag(size()));
for (std::size_t i = 0; i < size(); i++)
archive(v_[i]);
}
template<class Archive>
void load(Archive& ar) {
cereal::size_type sz;
ar(cereal::make_size_tag(sz));
resize(sz);
for (std::size_t i = 0; i < sz; i++)
ar(v_[i]);
}
void writeToFile(std::string fileName) {
std::fstream f;
f.open(fileName.c_str(), std::ios::out);
f << std::to_string(size()) << "\n";
for (std::size_t i = 0; i < size(); i++) {
v_[i].writeToFile(&f);
}
}
void readFromFile(std::string fileName) {
std::fstream f;
f.open(fileName.c_str(), std::ios::in);
std::string buffer;
int cuantos;
std::getline(f, buffer);
std::istringstream(buffer) >> cuantos;
resize(cuantos);
for (std::size_t i = 0; i < size(); i++) {
v_[i].readFromFile(&f);
}
}
};
} // namespace pel
#endif // PEL_Vector_HPP_INCLUDED
|
#include "src/Physics/CollisionModel.h"
namespace Physics {
//衝突モデル
//球
Sphere::Sphere() {}
Sphere::Sphere(const Math::Vector3& pos, float rds) :
mPos(pos), mRds(rds) {}
Sphere::Sphere(const Sphere& a) :
mPos(a.mPos), mRds(a.mRds) {}
Sphere::~Sphere() {}
Sphere& Sphere::operator=(const Sphere& a) {
mPos = a.mPos;
mRds = a.mRds;
return *this;
}
//線分
Lay::Lay(){}
Lay::Lay(const Math::Vector3& pos, const Math::Vector3& vec) :
mPos(pos), mVec(vec) {}
Lay::Lay(const Lay& a) :
mPos(a.mPos), mVec(a.mVec) {}
Lay::~Lay() {}
Lay& Lay::operator=(const Lay& a) {
mPos = a.mPos;
mVec = a.mVec;
return *this;
}
//三角平面
TriPlane::TriPlane(){}
TriPlane::TriPlane(
const Math::Vector3& p0,
const Math::Vector3& p1,
const Math::Vector3& p2) :
mP0(p0), mP1(p1), mP2(p2),
mNormal(0.f, 0.f, 0.f),
mD(0.f) {
mNormal.set_cross(p1 - p0, p2 - p1);
mNormal.set_normalize();
mD = -mNormal.dot(p0);
}
TriPlane::TriPlane(const TriPlane& a) :
mP0(a.mP0), mP1(a.mP1), mP2(a.mP2),
mNormal(a.mNormal),
mD(a.mD) {}
TriPlane::~TriPlane() {}
TriPlane& TriPlane::operator=(const TriPlane& a) {
mP0 = a.mP0;
mP1 = a.mP1;
mP2 = a.mP2;
mNormal = a.mNormal;
mD = a.mD;
return *this;
}
//AABB
AABB::AABB() {}
AABB::AABB(const Math::Vector3& min, const Math::Vector3& max) :
mMin(min),
mMax(max) {}
AABB::AABB(const Physics::OBB & obb)
: mMin()
, mMax()
{
Math::Vector3 _edges[3]{ Math::Vector3(obb.mHalfSize.x * 2.f, 0, 0), Math::Vector3(0, obb.mHalfSize.y * 2.f, 0), Math::Vector3(0, 0, obb.mHalfSize.z * 2.f) };
_edges[0] *= obb.mRot;
_edges[1] *= obb.mRot;
_edges[2] *= obb.mRot;
Math::Vector3 _origin = obb.mPos;
mMin = mMax = obb.mPos;
for (const Math::Vector3& v : obb.GetVertices())
{
mMin.x = std::min(v.x, mMin.x);
mMin.y = std::min(v.y, mMin.y);
mMin.z = std::min(v.z, mMin.z);
mMax.x = std::max(v.x, mMax.x);
mMax.y = std::max(v.y, mMax.y);
mMax.z = std::max(v.z, mMax.z);
}
}
AABB::AABB(const AABB& a):
mMin(a.mMin),
mMax(a.mMax){}
AABB::~AABB() {}
AABB& AABB::operator=(const AABB& a) {
mMin = a.mMin;
mMax = a.mMax;
return *this;
}
//OBB
OBB::OBB() {}
OBB::OBB(const Math::Vector3& pos, const Math::Vector3& half_size,
const Math::Matrix44& rot) :
mPos(pos),
mHalfSize(half_size),
mRot(rot),
mIvsRot(rot) {
mIvsRot.set_inverse();
}
OBB::OBB(const OBB& a) :
mPos(a.mPos),
mHalfSize(a.mHalfSize),
mRot(a.mRot),
mIvsRot(a.mIvsRot) {}
OBB::~OBB() {}
OBB& OBB::operator=(const OBB& a) {
mPos = a.mPos;
mHalfSize = a.mHalfSize;
mRot = a.mRot;
mIvsRot = a.mIvsRot;
return *this;
}
}//namespace Physics
|
//
// Created by Алексей Ячменьков on 04.11.2020.
//
#ifndef CALCUTE_TOKEN_H
#define CALCUTE_TOKEN_H
#include <iostream>
#include <cmath>
#include "std_lib_facilities.h"
using namespace std;
struct Token
{
char kind; // what kind of token
double value; // for numbers: a value
string name;
Token (char ch) // make a Token from a char
: kind{ ch }, value{ 0 }
{ }
Token (char ch, double val) // make a Token from a char and a double
: kind{ ch }, value{ val }
{ }
Token(char ch, string n)
: kind{ch}, name{n}
{ }
};
#endif //CALCUTE_TOKEN_H
|
// Copyright (c) 2007-2019 Hartmut Kaiser
// Copyright (c) 2011 Bryce Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <pika/config/defines.hpp>
#if defined(DOXYGEN)
/// Marks a class or function to be exported from pika or imported if it is
/// consumed.
# define PIKA_EXPORT
#else
# if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
# if !defined(PIKA_MODULE_STATIC_LINKING)
# define PIKA_SYMBOL_EXPORT __declspec(dllexport)
# define PIKA_SYMBOL_IMPORT __declspec(dllimport)
# define PIKA_SYMBOL_INTERNAL /* empty */
# endif
# elif defined(__NVCC__) || defined(__CUDACC__)
# define PIKA_SYMBOL_EXPORT /* empty */
# define PIKA_SYMBOL_IMPORT /* empty */
# define PIKA_SYMBOL_INTERNAL /* empty */
# elif defined(PIKA_HAVE_ELF_HIDDEN_VISIBILITY)
# define PIKA_SYMBOL_EXPORT __attribute__((visibility("default")))
# define PIKA_SYMBOL_IMPORT __attribute__((visibility("default")))
# define PIKA_SYMBOL_INTERNAL __attribute__((visibility("hidden")))
# endif
// make sure we have reasonable defaults
# if !defined(PIKA_SYMBOL_EXPORT)
# define PIKA_SYMBOL_EXPORT /* empty */
# endif
# if !defined(PIKA_SYMBOL_IMPORT)
# define PIKA_SYMBOL_IMPORT /* empty */
# endif
# if !defined(PIKA_SYMBOL_INTERNAL)
# define PIKA_SYMBOL_INTERNAL /* empty */
# endif
///////////////////////////////////////////////////////////////////////////////
# if defined(PIKA_EXPORTS)
# define PIKA_EXPORT PIKA_SYMBOL_EXPORT
# else
# define PIKA_EXPORT PIKA_SYMBOL_IMPORT
# endif
///////////////////////////////////////////////////////////////////////////////
// helper macro for symbols which have to be exported from the runtime and all
// components
# define PIKA_ALWAYS_EXPORT PIKA_SYMBOL_EXPORT
# define PIKA_ALWAYS_IMPORT PIKA_SYMBOL_IMPORT
#endif
|
#include "texture.h"
#include <glad/glad.h>
#include <iostream>
Texture::Texture(int width, int height, bool allocate) :
twidth(width), theight(height), allocated(allocate)
{
if (allocated)
buffer = new uint8_t[width * height * 4];
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
}
Texture::~Texture()
{
if (allocated)
delete buffer;
glDeleteTextures(1, &texture);
}
void Texture::write_pixel(int x, int y, const glm::u8vec4& color)
{
int index = (y * twidth) + x;
buffer[index * 4 + 0] = color.r;
buffer[index * 4 + 1] = color.g;
buffer[index * 4 + 2] = color.b;
buffer[index * 4 + 3] = color.a;
}
void Texture::upload_to_gpu()
{
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, twidth, theight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
}
void Texture::unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, texture);
}
|
#include "ros/ros.h"
#include <iostream>
#include "std_msgs/Float64.h"
#include <math.h>
#define GOAL 0.0
#define OFFSET 0.003
#define VEL 0.6
#define AVER_NUM 3
class camera_motor_command
{
public:
ros::NodeHandle nh;
double position_x;
double position_y;
double orientation_x;
double vel3;
double theta1;
double theta2;
double theta3;
int theta3_count;
int gostop;
camera_motor_command()
{
gostop = 1;
nh.setParam("gostop", gostop);
}
void go()
{
theta3 = 0;
theta3_count = 0;
ROS_INFO("Here");
while(ros::ok())
{
nh.getParam("gostop", gostop);
if(gostop == 0) break;
nh.getParam("position_x", position_x);
nh.getParam("position_y", position_y);
nh.getParam("orientation_x", orientation_x);
theta1 = atan(position_y / position_x);
nh.setParam("theta1", theta1);
theta2 = orientation_x * ((3.141592 * 0.5) / 0.62);
theta3 += theta2 - ((3.141592 * 0.5) - theta1);
++theta3_count;
if(theta3_count == AVER_NUM)
{
theta3 = theta3 / AVER_NUM;
//ROS_INFO("theta1 : %f, theta2 : %f, theta3 : %f",theta1, theta2, theta3);
if(theta3 > GOAL + OFFSET)
{
vel3 = VEL;
nh.setParam("vel3", vel3);
}
else if(theta3 < GOAL - OFFSET)
{
vel3 = -1 * VEL;
nh.setParam("vel3", vel3);
}
else if(theta3 >= GOAL - OFFSET && theta3 <= GOAL + OFFSET)
{
vel3 = 0.0;
nh.setParam("vel3", vel3);
}
theta3_count = 0;
theta3 = 0;
}
}
}
void stop()
{
while(ros::ok())
{
nh.getParam("gostop", gostop);
if(gostop == 1) break;
vel3 = 0;
nh.setParam("vel3", vel3);
}
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "camera_motor_command");
camera_motor_command letsgo;
while(ros::ok())
{
letsgo.go();
letsgo.stop();
}
return 0;
}
|
//
// Created by ali-masa on 3/18/20.
//
#ifndef THE_STATE_OF_THE_ART_LINKED_LIST_ULTIMATE_LINKED_LIST_H
#define THE_STATE_OF_THE_ART_LINKED_LIST_ULTIMATE_LINKED_LIST_H
#include <cstddef>
#include "../PlatformIndependentConcurrency/mutex.h"
#include "../PlatformIndependentConcurrency/concurrency_abstract_factory.h"
#include "unrolled_node.h"
namespace soa {
static ConcurrencyAbstractFactory* concurrencyFactory
= ConcurrencyAbstractFactory::getInstance();
template<class T, unsigned int SIZE> class UltimateLinkedList;
template<class T, unsigned int SIZE>
class PopperPusher {
public:
virtual bool pushBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value) = 0;
virtual T popBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList) = 0;
virtual bool pushFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value) = 0;
virtual T popFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList) = 0;
virtual ~PopperPusher() {}
};
template<class T, unsigned int SIZE> class NormalPopperPusher;
template<class T, unsigned int SIZE> class BlockingPopperPusher;
template<class T, unsigned int SIZE = 10>
class UltimateLinkedList {
friend class PopperPusher<T, SIZE>;
friend class NormalPopperPusher<T, SIZE>;
friend class BlockingPopperPusher<T, SIZE>;
friend bool operator==(const UltimateLinkedList<T, SIZE> &l1, const UltimateLinkedList<T, SIZE> &l2)
{
Iterator iterator1(l1);
Iterator iterator2(l2);
while(iterator1.hasNext() && iterator2.hasNext())
{
if(*iterator1 != *iterator2)
return false;
++iterator1;
++iterator2;
}
return !(iterator1.hasNext() || iterator2.hasNext());
}
friend bool operator!=(const UltimateLinkedList<T, SIZE> &l1, const UltimateLinkedList<T, SIZE> &l2)
{
return !(l1 == l2);
}
friend std::ostream& operator<<(std::ostream& os, UltimateLinkedList<T, SIZE>& list)
{
UnrolledNode<T, SIZE>* travser = list.m_head;
os << "[" << *travser;
std::stringstream ss;
ss << *travser;
std::string str = ss.str();
travser = &travser->getNext();
while (travser != NULL)
{
os << ", " << *travser;
str = ss.str();
travser = &travser->getNext();
}
os << "]";
return os;
}
public:
explicit UltimateLinkedList<T, SIZE>(size_t capacity);
UltimateLinkedList<T, SIZE>(const UltimateLinkedList<T, SIZE> &toCopy);
UltimateLinkedList<T, SIZE> &operator=(const UltimateLinkedList<T, SIZE> &toCopy);
virtual ~UltimateLinkedList<T, SIZE>();
class Iterator
{
friend class UltimateLinkedList<T, SIZE>;
friend bool operator==(Iterator& it1, Iterator& it2)
{
return (it1.m_pntrToTraverse == NULL && it2.m_pntrToTraverse == NULL)
|| *(it1.m_pntrToTraverse) == *(it2.m_pntrToTraverse);
}
friend bool operator!=(Iterator& it1, Iterator& it2)
{ return !(it1 == it2); }
public:
explicit Iterator(UltimateLinkedList<T, SIZE>* lstToIterate);
Iterator operator++(int);
Iterator& operator++();
Iterator& next();
bool hasNext();
protected:
UnrolledNode<T, SIZE>* operator->();
UnrolledNode<T, SIZE>& operator*();
const static Iterator s_end;
private:
Iterator(void* pntr = NULL) :m_indx(-1), m_pntrToTraverse(NULL) {}
UnrolledNode<T, SIZE>* m_pntrToTraverse;
size_t m_indx;
};
/* this doesn't work: using iterator = UltimateLinkedList<T, SIZE>::Iterator;*/
typedef UltimateLinkedList<T, SIZE>::Iterator iterator;
iterator& begin();
const iterator& cbegin() const;
iterator& end();
const iterator& cend() const;
bool empty() const;
size_t size() const;
size_t capacity() const;
bool push_back(const T &value);
T pop_back();
bool push_front(const T &value);
T pop_front();
void setWaitable(bool isWaitable);
private:
UnrolledNode<T, SIZE>* m_head;
UnrolledNode<T, SIZE>* m_tail;
// count
size_t m_size;
size_t m_nodeSize;
size_t m_capacity;
Mutex* m_threadSafetyMutex;
PopperPusher<T, SIZE>* m_popperPusher;
iterator m_iterator;
bool innerPushBack(const T &value);
T innerPopBack();
bool innerPushFront(const T &value);
T innerPopFront();
void releaseHeapAllocations();
};
template<class T, unsigned int SIZE>
class NormalPopperPusher: public PopperPusher<T, SIZE> {
public:
virtual bool pushBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value)
{ return ultimateLinkedList.innerPushBack(value); }
virtual T popBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList)
{ return ultimateLinkedList.innerPopBack(); }
virtual bool pushFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value)
{ return ultimateLinkedList.innerPushFront(value); }
virtual T popFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList)
{ return ultimateLinkedList.innerPopFront(); }
virtual ~NormalPopperPusher() {}
};
template<class T, unsigned int SIZE>
class BlockingPopperPusher: public PopperPusher<T, SIZE> {
public:
BlockingPopperPusher(UltimateLinkedList<T, SIZE> &ultimateLinkedList)
:m_addingSem(concurrencyFactory->createSemaphore(ultimateLinkedList.capacity()))
, m_removingSem(concurrencyFactory->createSemaphore(0)){}
virtual bool pushBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value)
{
m_addingSem->wait();
bool isSuccessful = ultimateLinkedList.innerPushBack(value);
m_removingSem->post();
return isSuccessful;
}
virtual T popBack(UltimateLinkedList<T, SIZE> &ultimateLinkedList)
{
m_removingSem->wait();
T backValue = ultimateLinkedList.innerPopBack();
m_addingSem->post();
return backValue;
}
virtual bool pushFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList, const T &value)
{
m_addingSem->wait();
bool isSuccessful = ultimateLinkedList.innerPushFront(value);
m_removingSem->post();
return isSuccessful;
}
virtual T popFront(UltimateLinkedList<T, SIZE> &ultimateLinkedList)
{
m_removingSem->wait();
T frontValue = ultimateLinkedList.innerPopFront();
m_addingSem->post();
return frontValue;
}
virtual ~BlockingPopperPusher()
{
delete m_addingSem;
delete m_removingSem;
}
private:
Semaphore* m_addingSem;
Semaphore* m_removingSem;
};
}
using namespace soa;
template<class T, unsigned int SIZE>
UltimateLinkedList<T, SIZE>::UltimateLinkedList(size_t capacity) :m_capacity(capacity),
m_iterator(this),m_size(0),m_nodeSize(SIZE)
,m_threadSafetyMutex(concurrencyFactory->createMutex())
,m_popperPusher(new NormalPopperPusher<T, SIZE>)
{
m_head = new UnrolledNode<T, SIZE>(m_nodeSize);
m_tail = m_head;
}
template<class T, unsigned int SIZE>
UltimateLinkedList<T, SIZE>::UltimateLinkedList(const UltimateLinkedList<T, SIZE> &toCopy)
:m_capacity(toCopy.m_capacity),m_nodeSize(SIZE),m_iterator(this),
m_size(toCopy.m_size),m_threadSafetyMutex(concurrencyFactory->createMutex())
,m_popperPusher(new NormalPopperPusher<T, SIZE>)
{
m_head = new UnrolledNode<T, SIZE>(m_nodeSize);
m_tail = m_head;
UnrolledNode<T, SIZE>* traverser = m_head;
const UnrolledNode<T, SIZE>* traverserToCopy = (toCopy.m_head);
*traverser = *traverserToCopy;
while(traverserToCopy->m_next != NULL)
{
*traverser->m_next = *traverserToCopy->m_next;
traverser = traverser->m_next;
traverserToCopy = traverserToCopy->m_next;
}
}
template<class T, unsigned int SIZE>
UltimateLinkedList<T, SIZE> &UltimateLinkedList<T, SIZE>::operator=(const UltimateLinkedList<T, SIZE> &toCopy)
{
if(*this != toCopy)
{
this->releaseHeapAllocations();
*m_popperPusher = *toCopy.m_popperPusher;
UnrolledNode<T, SIZE>* traverser = m_head;
UnrolledNode<T, SIZE>* traverserToCopy = toCopy.m_head;
*traverser = *traverserToCopy;
while(traverserToCopy->m_next != NULL)
{
*traverser->m_next = *traverserToCopy->m_next;
traverser = traverser->m_next;
traverserToCopy = traverserToCopy->m_next;
}
m_tail = traverser;
}
return *this;
}
template<class T, unsigned int SIZE>
UltimateLinkedList<T, SIZE>::~UltimateLinkedList<T, SIZE>()
{
this->releaseHeapAllocations();
}
template<class T, unsigned int SIZE>
typename UltimateLinkedList<T, SIZE>::Iterator& UltimateLinkedList<T, SIZE>::begin()
{
return m_iterator;
}
template<class T, unsigned int SIZE>
const typename UltimateLinkedList<T, SIZE>::Iterator& UltimateLinkedList<T, SIZE>::cbegin() const
{
return m_iterator;
}
template<class T, unsigned int SIZE>
typename UltimateLinkedList<T, SIZE>::iterator& UltimateLinkedList<T, SIZE>::end()
{
return UltimateLinkedList<T, SIZE>::iterator::s_end;
}
template<class T, unsigned int SIZE>
const typename UltimateLinkedList<T, SIZE>::iterator& UltimateLinkedList<T, SIZE>::cend() const
{
return UltimateLinkedList<T, SIZE>::iterator::s_end;
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::empty() const
{
return m_size == 0;
}
template<class T, unsigned int SIZE>
size_t UltimateLinkedList<T, SIZE>::size() const
{
return m_size;
}
template<class T, unsigned int SIZE>
size_t UltimateLinkedList<T, SIZE>::capacity() const
{
return m_capacity;
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::push_back(const T &value)
{
Mutex::Lock lock(m_threadSafetyMutex);
return this->m_popperPusher->pushBack(*this, value);
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::innerPushBack(const T &value) {
if(this->m_size == this->m_capacity)
return false;
if(m_tail->m_size == m_tail->m_capacity)
{
m_tail->m_next = new UnrolledNode<T, SIZE>(m_tail->m_capacity);
m_tail->m_next->m_prev = m_tail;
m_tail = m_tail->m_next;
}
m_tail->at(m_tail->m_size ++) = value;
++ this->m_size;
return true;
}
template<class T, unsigned int SIZE>
T UltimateLinkedList<T, SIZE>::pop_back()
{
Mutex::Lock lock(m_threadSafetyMutex);
return this->m_popperPusher->popBack(*this);
}
template<class T, unsigned int SIZE>
T UltimateLinkedList<T, SIZE>::innerPopBack()
{
if(m_size == 0)
return T();
if(m_tail->m_size == 0)
{
m_tail = m_tail->m_prev;
delete m_tail->m_next;
m_tail->m_next = NULL;
}
T ans = m_tail->at(m_tail->m_size--);
-- this->m_size;
return ans;
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::push_front(const T &value)
{
Mutex::Lock lock(m_threadSafetyMutex);
return this->m_popperPusher->pushFront(*this, value);
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::innerPushFront(const T &value) {
if(this->m_size == this->m_capacity)
return false;
if(!m_head->push_front(value))
{
m_head->m_prev = new UnrolledNode<T, SIZE>(m_head->m_capacity);
m_head->m_prev->m_next = m_head;
m_head = m_head->m_prev;
}
++ this->m_size;
return true;
}
template<class T, unsigned int SIZE>
T UltimateLinkedList<T, SIZE>::pop_front()
{
Mutex::Lock lock(m_threadSafetyMutex);
return this->m_popperPusher->popFront(*this);
}
template<class T, unsigned int SIZE>
T UltimateLinkedList<T, SIZE>::innerPopFront() {
UnrolledNode<T, SIZE> afterHeadCopy(*(m_head->m_next));
if(m_size == 0)
return T();
if(m_head->m_size == 0)
{
m_head = m_head->m_next;
delete m_head->m_prev;
m_head->m_prev = NULL;
}
T ans = m_head->pop_front();
-- this->m_size;
return ans;
}
template<class T, unsigned int SIZE>
void UltimateLinkedList<T, SIZE>::setWaitable(bool isWaitable)
{
delete this->m_popperPusher;
if(isWaitable)
m_popperPusher = new BlockingPopperPusher<T, SIZE>(*this);
else
m_popperPusher = new NormalPopperPusher<T, SIZE>;
}
template<class T, unsigned int SIZE>
void UltimateLinkedList<T, SIZE>::releaseHeapAllocations()
{
while(m_tail != m_head)
{
m_tail = m_tail->m_prev;
delete m_tail->m_next;
}
delete m_head;
delete m_popperPusher;
}
template<class T, unsigned int SIZE>
UltimateLinkedList<T, SIZE>::Iterator::Iterator(UltimateLinkedList<T, SIZE> *lstToIterate): m_indx(0),
m_pntrToTraverse(lstToIterate->m_head){}
template<class T, unsigned int SIZE>
typename UltimateLinkedList<T, SIZE>::Iterator UltimateLinkedList<T, SIZE>::Iterator::operator++(int)
{
if(m_pntrToTraverse->m_size == m_pntrToTraverse->m_capacity)
m_pntrToTraverse = m_pntrToTraverse->m_next;
UltimateLinkedList<T, SIZE>::Iterator ans(*this);
++m_pntrToTraverse->m_size;
return ans;
}
template<class T, unsigned int SIZE>
typename UltimateLinkedList<T, SIZE>::Iterator &UltimateLinkedList<T, SIZE>::Iterator::operator++()
{
if(m_pntrToTraverse->m_size == m_pntrToTraverse->m_capacity)
m_pntrToTraverse = m_pntrToTraverse->m_next;
++m_pntrToTraverse->m_size;
return *this;
}
template<class T, unsigned int SIZE>
UnrolledNode<T, SIZE>* UltimateLinkedList<T, SIZE>::Iterator::operator->() {
return m_pntrToTraverse;
}
template<class T, unsigned int SIZE>
UnrolledNode<T, SIZE> &UltimateLinkedList<T, SIZE>::Iterator::operator*() {
return *m_pntrToTraverse;
}
template<class T, unsigned int SIZE>
typename UltimateLinkedList<T, SIZE>::Iterator &UltimateLinkedList<T, SIZE>::Iterator::next() {
++this;
return *this;
}
template<class T, unsigned int SIZE>
bool UltimateLinkedList<T, SIZE>::Iterator::hasNext()
{
return m_pntrToTraverse->m_size < m_pntrToTraverse->m_capacity ||
m_pntrToTraverse->m_next != NULL;
}
#endif //THE_STATE_OF_THE_ART_LINKED_LIST_ULTIMATE_LINKED_LIST_H
|
#include "Map.h"
#include <QDebug>
#include <QString>
#ifdef Q_OS_ANDROID
#include <QAndroidJniObject>
#endif
#include <QDesktopServices>
#include <QUrl>
namespace wpp
{
namespace qt
{
Map *Map::singleton = 0;
Map &Map::getInstance()
{
if ( singleton == 0 )
{
static Map singletonInstance;
singleton = &singletonInstance;
}
return *singleton;
}
void Map::loadExternalMap(double longitude, double latitude, const QString& locationName, int zoom)
{
QString uriStr = QString().sprintf("geo:%lf,%lf?q=%lf,%lf&z=%d", latitude, longitude, latitude, longitude, zoom);
#if defined(Q_OS_ANDROID)
// http://androidbiancheng.blogspot.hk/2011/06/intent-android.html
// http://www.qtcentre.org/threads/58668-How-to-use-QAndroidJniObject-for-intent-setData
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(strUri));
//startActivity(intent);
QAndroidJniObject path=QAndroidJniObject::fromString(uriStr); //path is valid
QAndroidJniObject uri=QAndroidJniObject("java/net/URI","(Ljava/lang/String;)V",path.object<jstring>()); //uri is valid
// QUrl url;
// url.toEncoded();
QAndroidJniObject intent=QAndroidJniObject::callStaticObjectMethod("android/content/Intent","parseUri","(Ljava/lang/String;I)Landroid/content/Intent;",path.object<jstring>(),0x00000000);
QAndroidJniObject action=QAndroidJniObject::fromString( QString("ACTION_VIEW") ); //path is valid
intent.callObjectMethod("setAction","(Ljava/net/URI;)Landroid/content/Intent;",action.object<jobject>()); //result is invalid, intent contains type
QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); //activity is valid
//QAndroidJniObject intent("android/content/Intent","()V"); //intent is valid, but empty
//QAndroidJniObject type=QAndroidJniObject::fromString("application/vnd.android.package-archive"); //type is valid
//QAndroidJniObject result=intent.callObjectMethod("setType","(Ljava/lang/String;)Landroid/content/Intent;",type.object<jobject>()); //result is valid, intent contains type
activity.callObjectMethod("startActivity","(Landroid/content/Intent;)V",intent.object<jobject>()); //works, but shows a selection screen for the intent containing email, bluetooth etc. because intent's data member is missing
#elif defined(Q_OS_IOS)
//http://stackoverflow.com/questions/12504294/programmatically-open-maps-app-in-ios-6
/* objective-c:
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
// Create an MKMapItem to pass to the Maps app
CLLocationCoordinate2D coordinate =
CLLocationCoordinate2DMake(16.775, -3.009);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate
addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:@"My Place"];
// Pass the map item to the Maps app
[mapItem openInMapsWithLaunchOptions:nil];
}
*/
//ref - Apple URL Scheme Reference
// https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
// Qt handle URL scheme: http://stackoverflow.com/questions/6561661/url-scheme-qt-and-mac
// Intent JNI: http://blog.qt.digia.com/blog/2013/12/12/implementing-in-app-purchase-on-android/
qDebug() << "iOS open external map...";
uriStr = QString().sprintf("http://maps.apple.com/?q=%lf,%lf&z=%d", latitude, longitude, zoom);
qDebug() << "map uri:" << uriStr;
QDesktopServices::openUrl(QUrl(uriStr));
#else
qDebug() << "use desktop service...";
/*uriStr = QString().sprintf(
"http://api.map.baidu.com/staticimage?markers=%lf,%lf&zoom=%d&markerStyles=s,A,0xff0000",
longitude, latitude, zoom);*/
if ( latitude != 0 && longitude != 0 )
{
uriStr = QString().sprintf("http://maps.apple.com/?ll=%lf,%lf&z=%d", latitude, longitude, zoom);
}
else
{
uriStr = QString().sprintf("http://maps.apple.com/?q=%s&z=%d", locationName.toStdString().c_str(), zoom);
}
QDesktopServices::openUrl(QUrl(uriStr));
#endif
}
void Map::loadExternalMap(QString keyword, int zoom)
{
QString uriStr = QString().sprintf("geo:q=%s,&z=%d", keyword.toStdString().c_str(), zoom);
#if defined(Q_OS_ANDROID)
// http://androidbiancheng.blogspot.hk/2011/06/intent-android.html
// http://www.qtcentre.org/threads/58668-How-to-use-QAndroidJniObject-for-intent-setData
// Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(strUri));
//startActivity(intent);
QAndroidJniObject path=QAndroidJniObject::fromString(uriStr); //path is valid
QAndroidJniObject uri=QAndroidJniObject("java/net/URI","(Ljava/lang/String;)V",path.object<jstring>()); //uri is valid
// QUrl url;
// url.toEncoded();
QAndroidJniObject intent=QAndroidJniObject::QAndroidJniObject::callStaticObjectMethod("android/content/Intent","parseUri","(Ljava/lang/String;I)Landroid/content/Intent;",path.object<jstring>(),0x00000000);
QAndroidJniObject action=QAndroidJniObject::fromString( QString("ACTION_VIEW") ); //path is valid
intent.callObjectMethod("setAction","(Ljava/net/URI;)Landroid/content/Intent;",action.object<jobject>()); //result is invalid, intent contains type
QAndroidJniObject activity = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative", "activity", "()Landroid/app/Activity;"); //activity is valid
//QAndroidJniObject intent("android/content/Intent","()V"); //intent is valid, but empty
//QAndroidJniObject type=QAndroidJniObject::fromString("application/vnd.android.package-archive"); //type is valid
//QAndroidJniObject result=intent.callObjectMethod("setType","(Ljava/lang/String;)Landroid/content/Intent;",type.object<jobject>()); //result is valid, intent contains type
activity.callObjectMethod("startActivity","(Landroid/content/Intent;)V",intent.object<jobject>()); //works, but shows a selection screen for the intent containing email, bluetooth etc. because intent's data member is missing
#elif defined(Q_OS_IOS)
//http://stackoverflow.com/questions/12504294/programmatically-open-maps-app-in-ios-6
/* objective-c:
Class mapItemClass = [MKMapItem class];
if (mapItemClass && [mapItemClass respondsToSelector:@selector(openMapsWithItems:launchOptions:)])
{
// Create an MKMapItem to pass to the Maps app
CLLocationCoordinate2D coordinate =
CLLocationCoordinate2DMake(16.775, -3.009);
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:coordinate
addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:@"My Place"];
// Pass the map item to the Maps app
[mapItem openInMapsWithLaunchOptions:nil];
}
*/
//ref - Apple URL Scheme Reference
// https://developer.apple.com/library/ios/featuredarticles/iPhoneURLScheme_Reference/MapLinks/MapLinks.html
// Qt handle URL scheme: http://stackoverflow.com/questions/6561661/url-scheme-qt-and-mac
// Intent JNI: http://blog.qt.digia.com/blog/2013/12/12/implementing-in-app-purchase-on-android/
qDebug() << "iOS open external map...";
uriStr = QString().sprintf("http://maps.apple.com/?q=%s&z=%d", keyword.toStdString().c_str(), zoom);
QDesktopServices::openUrl(QUrl(uriStr));
#else
qDebug() << "use desktop service...";
/*uriStr = QString().sprintf(
"http://api.map.baidu.com/staticimage?markers=%lf,%lf&zoom=%d&markerStyles=s,A,0xff0000",
longitude, latitude, zoom);*/
uriStr = QString().sprintf("http://maps.apple.com/?q=%s&z=%d", keyword.toStdString().c_str(), zoom);
QDesktopServices::openUrl(QUrl(uriStr));
#endif
}
}//namespace qt
}//namespace wpp
|
#ifndef __CTRLEXECACT_H
#define __CTRLEXECACT_H
#include "ViewExecAct.h"
#include "ModelExecAct.h"
#include "CtrlBrowser.h"
#include "CtrlActBrowser.h"
#include "CtrlPropPg.h"
#include "CtrlBrowserRO.h"
namespace wh {
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
class CtrlActExecWindow final : public CtrlWindowBase<ViewExecActWindow, ModelActExecWindow>
{
sig::scoped_connection connModel_SelectPage;
sig::scoped_connection connViewCmd_Unlock;
sig::scoped_connection connViewCmd_SelectAct;
sig::scoped_connection connViewCmd_Execute;
std::shared_ptr<CtrlActBrowser> mCtrlActBrowser;
std::shared_ptr<CtrlTableObjBrowser_RO> mCtrlObjBrowser;
std::shared_ptr<CtrlPropPg> mCtrlPropPG;
public:
CtrlActExecWindow( const std::shared_ptr<ViewExecActWindow>& view
, const std::shared_ptr<ModelActExecWindow>& model );
~CtrlActExecWindow();
void SetObjects(const std::set<ObjectKey>& obj);
void SelectAct();
void Execute();
void Unlock();
};
//-----------------------------------------------------------------------------
}//namespace wh{
#endif // __****_H
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (1e15);
const int INF = (1<<27);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
bool rect[55][55][55][55];
int t[55][55][55][55];
class DonutsOnTheGridEasy {
public:
int rec(int a,int b,int c,int d) {
if (a > c || b > d) {
return 0;
}
if (t[a][b][c][d] != -1) {
return t[a][b][c][d];
}
int mx = 0;
mx = max(mx, rec(a+1, b, c, d));
mx = max(mx, rec(a, b+1, c, d));
mx = max(mx, rec(a, b, c-1, d));
mx = max(mx, rec(a, b, c, d-1));
if (rect[a][b][c][d]) {
mx = max(mx, rec(a+1, b+1, c-1, d-1) + 1);
}
return t[a][b][c][d] = mx;
}
int calc(vector <string> grid) {
int Y = (int)grid.size();
int X = (int)grid[0].size();
memset(t, -1, sizeof(t));
memset(rect, false, sizeof(rect));
for (int i=0; i<X; ++i) {
for (int j=0; j<Y; ++j) {
for (int k=i+2; k<X; ++k) {
for (int l=j+2; l<Y; ++l) {
bool flag = true;
for (int m=i; m<=k && flag; ++m) {
flag = grid[j][m] == '0' && grid[l][m] == '0';
}
if (!flag) {
continue;
}
for (int m=j; m<=l && flag; ++m) {
flag = grid[m][i] == '0' && grid[m][k] == '0';
}
if (!flag) {
continue;
}
rect[i][j][k][l] = true;
}
}
}
}
return rec(0,0,X-1,Y-1);
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"0000000"
,"0.....0"
,"0.00000"
,"0.0..00"
,"0.00000"
,"0.....0"
,"0000000"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(0, Arg1, calc(Arg0)); }
void test_case_1() { string Arr0[] = {"000"
,"0.0"
,"000"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(1, Arg1, calc(Arg0)); }
void test_case_2() { string Arr0[] = {"..."
,"..."
,"..."}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(2, Arg1, calc(Arg0)); }
void test_case_3() { string Arr0[] = {"00.000"
,"00.000"
,"0.00.0"
,"000.00"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(3, Arg1, calc(Arg0)); }
void test_case_4() { string Arr0[] =
{"000000", "000000", "0000.0", "000000"}
; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(4, Arg1, calc(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
DonutsOnTheGridEasy ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int N;
long long ans=0;
cin>>N;
for(int i=1;i<=sqrt(N);i++)
{
ans=ans+N/i-(i-1);
}
cout<<ans<<endl;
return 0;
}
|
/***************************************************************************
* Copyright (C) 2009 by Dario Freddi *
* drf@chakra-project.org *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *
***************************************************************************/
#include "Worker_p.h"
#include <QCoreApplication>
#include <QStringList>
#include <QDebug>
#include <alpm.h>
#include <signal.h>
#include <stdio.h>
static void cleanup(int signum)
{
if (signum == SIGSEGV) {
// Try at least to recover
alpm_trans_interrupt();
alpm_trans_release();
exit(signum);
} else if ((signum == SIGINT)) {
if (alpm_trans_interrupt() == 0) {
/* a transaction is being interrupted, don't exit the worker yet. */
return;
}
/* no committing transaction, we can release it now and then exit pacman */
alpm_trans_release();
/* output a newline to be sure we clear any line we may be on */
printf("\n");
}
/* free alpm library resources */
if (alpm_release() == -1) {
qCritical() << QString::fromLocal8Bit(alpm_strerrorlast());
}
exit(signum);
}
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
QCoreApplication::setOrganizationName("chakra");
QCoreApplication::setOrganizationDomain("chakra-project.org");
QCoreApplication::setApplicationName("aqpmworker");
QCoreApplication::setApplicationVersion("0.2");
QStringList arguments = app.arguments();
signal(SIGINT, cleanup);
signal(SIGTERM, cleanup);
signal(SIGSEGV, cleanup);
bool tmprz = true;
if (arguments.contains("--no-timeout")) {
tmprz = false;
}
AqpmWorker::Worker w(tmprz);
app.exec();
}
|
#ifndef _OPTIONPAY_H__
#define _OPTIONPAY_H__
/* Payoff of the option */
#include <iostream>
#include <vector>
//#include "BinomialTree.h"
class Payoff
{
protected:
double strike; //strike price
bool call; // if call, be true
//double S0; //
public:
//Payoff(double stike_, double call_):strike(strike_), call(call_){}
//void setvalue(double _strike, bool _call, double _S0); // setvalue
void setvalue(double _strike, bool _call);
virtual double operator() (double spot) = 0;
virtual Payoff* clone() = 0;
~Payoff(){}
};
// Payoff of Vanilla Option
class VanillaPay: public Payoff
{
public:
double operator() (double spot);
Payoff* clone();
};
// Payoff of digital option
class DigitalPay: public Payoff
{
public:
double operator() (double spot);
Payoff* clone();
};
#endif
|
// Copyright (c) 2017 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StdStorage_HeaderFile
#define _StdStorage_HeaderFile
#include <Standard_Macro.hxx>
#include <Storage_Error.hxx>
class StdStorage_Data;
class Storage_BaseDriver;
class TCollection_AsciiString;
//! StdStorage package is used to write and read persistent objects.
//! These objects are read and written by a retrieval or storage
//! algorithm (compatible with legacy Storage_Schema) in a container
//! (disk, memory, network ...). Drivers (FSD_File objects) assign a physical
//! container for data to be stored or retrieved.
//! The standard procedure for an application in reading a container is
//! to call one of the Read functions providing either a file path or a driver
//! opened for reading. Thes function update the instance of the StdStorage_Data
//! class which contains the data being read.
//! The standard procedure for an application in writing a container is the following:
//! - open the driver in writing mode,
//! - create an instance of the StdStorage_Data class, then
//! add the persistent data to write with the function AddRoot,
//! - call the function Write from the storage, setting the driver and the
//! Storage_Data instance as parameters,
//! - close the driver.
class StdStorage
{
public:
//! Returns the version of Storage's read/write routines
Standard_EXPORT static TCollection_AsciiString Version();
//! Returns the data read from a file located at theFileName.
//! The storage format is compartible with legacy persistent one.
//! These data are aggregated in a StdStorage_Data object which may be
//! browsed in order to extract the root objects from the container.
//! Note: - theData object will be created if it is null or cleared otherwise.
Standard_EXPORT static Storage_Error Read(const TCollection_AsciiString& theFileName,
Handle(StdStorage_Data)& theData);
//! Returns the data read from the container defined by theDriver.
//! The storage format is compartible with legacy persistent one.
//! These data are aggregated in a StdStorage_Data object which may be
//! browsed in order to extract the root objects from the container.
//! Note: - theData object will be created if it is null or cleared otherwise.
Standard_EXPORT static Storage_Error Read(const Handle(Storage_BaseDriver)& theDriver,
Handle(StdStorage_Data)& theData);
//! Writes the data aggregated in theData object into the container defined by
//! theDriver. The storage format is compartible with legacy persistent one.
//! Note: - theData may aggregate several root objects to be stored together.
//! - createion date specified in the srorage header will be overwritten.
Standard_EXPORT static Storage_Error Write(const Handle(Storage_BaseDriver)& theDriver,
const Handle(StdStorage_Data)& theData);
};
#endif // _StdStorage_HeaderFile
|
#pragma once
/*
Animation is an abstraction that defines the ways
an animation can be interacted with.
It is a collection of the points on a texture that defines each
index a sprite starts at on that texture, regardless of the size of the texture
*/
class Vector2i;
class Animation
{
public:
Animation(std::initializer_list<Vector2i> aSpriteSheetIndexes);
Animation() = default;
~Animation() = default;
Vector2i CurrentSpriteSheetRect() const;
void SetNewAnimation(const Animation& aNewAnimation);
private:
std::vector<Vector2i> m_currentAnimation;
size_t m_currentIndex = 0;
};
|
#ifndef ATTACK_H_
#define ATTACK_H_
#include <string>
#include <vector>
#include <iostream>
using namespace std;
class Attack{
private:
string object;
string status;
string print;
public:
string getObject();
void setObject(string);
string getStatus();
void setStatus(string);
string getPrint();
void setPrint(string);
Attack();
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef ICONUTILS_H
#define ICONUTILS_H
#include "adjunct/desktop_util/datastructures/StreamBuffer.h"
namespace IconUtils
{
/**
* Load a bitmap from file. All formats supported by image module
* will be read. The returned bitmap must be released by the caller
* when no longer needed.
*
* @param filename File with valid image data
* @param width Width of returned bitmap, native width is used if
* zero or negative
* @param height Height of returned bitmap, native height is used if
* zero or negative
*
* @return The bitmap or 0 on error.
*/
OpBitmap* GetBitmap(const OpStringC& filename, int width, int height);
/**
* Load a bitmap from buffer. All formats supported by image module
* will be read. The returned bitmap must be released by the caller
* when no longer needed.
*
* @param buffer Buffer with valid image data
* @param width Width of returned bitmap, native width is used if
* zero or negative
* @param height Height of returned bitmap, native height is used if
* zero or negative
*
* @return The bitmap or 0 on error.
*/
OpBitmap* GetBitmap(const StreamBuffer<UINT8>& buffer, int width, int height);
/**
* Load a bitmap from buffer. All formats supported by image module
* will be read. The returned bitmap must be released by the caller
* when no longer needed.
*
* @param buffer Buffer with valid image data
* @opara buffer_size Size og buffer in bytes
* @param width Width of returned bitmap, native width is used if
* zero or negative
* @param height Height of returned bitmap, native height is used if
* zero or negative
*
* @return The bitmap or 0 on error.
*/
OpBitmap* GetBitmap(const UINT8* buffer, UINT32 buffer_size, int width, int height);
/**
* Write bitmap content into buffer in PNG format. The buffer can
* be saved to disk as a valid PNG file.
*
* @param bitmap Bitmap to write
* @param buffer buffer with PNG data on return
*
* @return OpStatus::OK on success, otherwise ERR_NO_MEMORY on too little memory
* available or OpStatus::ERR on encoding error
*/
OP_STATUS WriteBitmapToPNGBuffer(OpBitmap* bitmap, StreamBuffer<UINT8>& buffer);
};
#endif //ICONUTILS_H
|
#include "MeMCore.h"
MeUltrasonicSensor kAndur(PORT_3);
MeDCMotor motorParem(M1);
MeDCMotor motorVasak(M2);
uint8_t motorSpeed = 100;
void setup() {
Serial.begin(9600);
}
void loop() {
float kaugus = kAndur.distanceCm();
Serial.print("Kaugus: ");
Serial.print(kaugus );
Serial.println(" cm");
delay(100);
motorParem.run(motorSpeed);
motorVasak.run(-motorSpeed);
if (kaugus < 10){
motorParem.stop();
motorVasak.stop();
//tagasi käik
motorParem.run(-motorSpeed);
motorVasak.run(motorSpeed);
delay(10);
motorParem.run(motorSpeed);
motorVasak.run(motorSpeed);
delay(500);
}
}
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "11235"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
#define MAX 100000
int table[MAX*4];
int number[MAX+5];
int Left[MAX+5];
int Right[MAX+5];
int ans;
void build_tree(int Tree[MAX*4],int Need[MAX] ,int L,int R,int seat){//0 n 1
if( L == R )
Tree[seat]=Need[L];
else{
build_tree( Tree , Need , L , (L+R)/2 , seat*2 );
build_tree( Tree , Need , (L+R)/2+1 , R , seat*2+1 );
if( Tree[seat*2] > Tree[seat*2+1] )
Tree[seat] = Tree[seat*2];
else
Tree[seat] = Tree[seat*2+1];
}
}
void find_tree(int L,int R,int target_L,int target_R,int seat){
if( R < target_L || L > target_R );
else if( L >= target_L && R <= target_R ){
ans = max(ans,table[seat]);
}
else{
find_tree( L , (L+R)/2 , target_L ,target_R , seat*2 );
find_tree( (L+R)/2+1 , R , target_L ,target_R , seat*2+1 );
}
}
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
int length,times,i;
int check,tmp,j;
int one,two;
while( ~scanf("%d",&length) && length ){
scanf("%d",×);
memset(table,0,sizeof(table));
memset(number,0,sizeof(number));
memset(Left,0,sizeof(Left));
memset(Right,0,sizeof(Right));
check = 0;
scanf("%d",&number[0]);
tmp = 1;
bool fuck = false;
for( i = 1 ; i < length ; i++ ){
scanf("%d",&number[i]);
if( number[i] == number[i-1] ){
tmp++;
fuck = false;
}
else{
for( j = check ; j < i ; j++ ){
number[j] = tmp;
Left[j] = check;
Right[j] = i-1;
}
tmp = 1;
check = i;
if( i != length-1 )
fuck = true;
else
fuck = false;
}
}
if(fuck==false)
for( j = check ; j < i ; j++ ){
number[j] = tmp;
Left[j] = check;
Right[j] = i-1;
}
build_tree(table,number,0,length-1,1);
while( times-- ){
scanf("%d %d",&one,&two);
ans = 0;
one--;
two--;
if( Left[one] == Left[two] && Right[one] == Right[two] ){
ans = two - one + 1;
}
else{
if( one > Left[one] ){
ans = Right[one] - one +1;
one = Right[one] + 1;
}
if( two < Right[two] ){
ans = max(ans, two - Left[two] + 1 );
two = Left[two] - 1;
}
if( one < two ){
find_tree(0,length-1,one,two,1);
}
}
printf("%d\n",ans );
}
}
return 0;
}
|
#include <iostream>
using namespace std;
int factorial(int x)
{
if(x==0){
cout<<"x ="<<x<<" at "<<&x<<endl;
return 1;
}else
{
cout<<"x ="<<x<<" at "<<&x<<endl;
return x*factorial(x-1);
}
}
int main()
{
factorial(5);
// Các biến x cách nhau 48 byte
// Kích thước của một stack frame cho hàm factorial là 48 byte
return 0;
}
|
#ifndef EITHER_HPP
#define EITHER_HPP
#include <functional>
#include <variant>
template <typename Left, typename Right>
class Either
{
public:
Either() = default;
Either(const Left& val) : val(val)
{
}
Either(const Right& val) : val(val)
{
}
Either(const std::variant<std::monostate, Left, Right>& val) : val(val)
{
}
operator bool() const
{
return std::holds_alternative<Left>(val);
}
Left& operator*()
{
return std::get<Left>(val);
}
Left* operator->()
{
return &std::get<Left>(val);
}
const Left& operator*() const
{
return std::get<Left>(val);
}
const Left* operator->() const
{
return &std::get<Left>(val);
}
Right& error()
{
return std::get<Right>(val);
}
const Right& error() const
{
return std::get<Right>(val);
}
Either& left_map(const std::function<Left(Left)>& func)
{
if (std::holds_alternative<Left>(val)) {
val = func(std::get<Left>(val));
}
return *this;
}
Either& right_map(const std::function<Right(Right)>& func)
{
if (std::holds_alternative<Left>(val)) {
val = func(std::get<Right>(val));
}
return *this;
}
std::variant<Left, Right> get() const
{
return val;
}
private:
std::variant<Left, Right> val;
};
#endif // EITHER_HPP
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
// Url_cm.cpp
// URL Cookie Management
#include "core/pch.h"
#include "modules/pi/OpSystemInfo.h"
#include "modules/url/url_man.h"
#include "modules/formats/url_dfr.h"
#include "modules/cookies/url_cm.h"
#include "modules/cookies/cookie_common.h"
#include "modules/datastream/opdatastreamsafefile.h"
#include "modules/util/opfile/opmemfile.h"
#ifdef WIC_COOKIE_MANAGER_LISTENER
#include "modules/windowcommander/OpCookieManager.h"
#endif
#ifdef DISK_COOKIES_SUPPORT
void Cookie_Manager::AutoSaveCookies()
{
if(updated_cookies)
{
TRAPD(op_err, WriteCookiesL());
if(OpStatus::IsMemoryError(op_err)) // Only leave if it was a memory error
g_memory_manager->RaiseCondition(op_err);
updated_cookies = FALSE;
}
}
#ifdef WIC_COOKIE_MANAGER_LISTENER
/** Convenience class to call listener when WriteCookiesL exits (it may leave) */
class CookieWriteAutoNotify
{
public:
CookieWriteAutoNotify(BOOL requested_by_platform) : m_success(TRUE), m_requested_by_platform(requested_by_platform) {}
~CookieWriteAutoNotify()
{
if (g_cookie_API)
g_cookie_API->GetCookieManagerListener()->OnCookieFileSaveFinished(m_success, m_requested_by_platform);
}
void SetSuccess() { m_success = TRUE; }
private:
BOOL m_success;
BOOL m_requested_by_platform;
};
#endif // WIC_COOKIE_MANAGER_LISTENER
void Cookie_Manager::WriteCookiesL(BOOL requested_by_platform)
{
CookieContextItem * OP_MEMORY_VAR item = (CookieContextItem *) ContextManagers.First();
#ifdef WIC_COOKIE_MANAGER_LISTENER
CookieWriteAutoNotify notifier(requested_by_platform);
ANCHOR(CookieWriteAutoNotify, notifier);
#endif // WIC_COOKIE_MANAGER_LISTENER
while(item)
{
TRAPD(op_err, item->context->WriteCookiesL());
OpStatus::Ignore(op_err);
item = (CookieContextItem *) item->Suc();
}
if(!cookie_file_read)
{
#ifdef WIC_COOKIE_MANAGER_LISTENER
notifier.SetSuccess();
#endif
return;
}
#if !(defined EXTERNAL_COOKIE_STORAGE)
if(cookie_file_location == OPFILE_ABSOLUTE_FOLDER)
return;
#endif // !EXTERNAL_COOKIE_STORAGE
DataStream_NonSensitive_ByteArrayL(write_cookies);
#ifdef _DEBUG_COOKIES_
FILE* fp = fopen("c:\\klient\\dcookie.txt", "a");
if (fp)
{
cookie_root->DebugWriteCookies(fp);
fclose(fp);
}
#endif
time_t this_time;
this_time = (time_t) (g_op_time_info->GetTimeUTC()/1000.0);
OP_STATUS op_err = OpStatus::OK;
#if defined EXTERNAL_COOKIE_STORAGE
OpMemFile* cfp = OP_NEW_L(OpMemFile, ());
cfp->Open(OPFILE_WRITE);
#else
OpSafeFile* cfp = OP_NEW(OpDataStreamSafeFile, ());
ANCHOR_PTR(OpSafeFile, cfp);
if (cfp)
{
op_err = cfp->Construct(CookiesFile, cookie_file_location);
}
if (!cfp || OpStatus::IsError(op_err) || OpStatus::IsError(op_err = cfp->Open(OPFILE_WRITE)))
{
if(!cfp || OpStatus::IsMemoryError(op_err))
g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY);
ANCHOR_PTR_RELEASE(cfp);
OP_DELETE(cfp);
return;
}
#endif
DataFile c4fp(cfp, COOKIES_FILE_VERSION, 1, 2);
c4fp.InitL();
#if (COOKIES_MAX_FILE_SIZE > 0) || (CONTEXT_COOKIES_MAX_FILE_SIZE > 0)
unsigned int cookie_file_max_size = 0;
if (context_id != 0)
cookie_file_max_size = CONTEXT_COOKIES_MAX_FILE_SIZE;
else
cookie_file_max_size = COOKIES_MAX_FILE_SIZE;
if (cookie_file_max_size > 0)
{
// size of data file header :
// (uint32 file_version_number; uint32 app_version_number; uint16 idtag_length; uint16 length_length;)
const int file_header_size = 4+4+2+2;
// dry run for estimation of file size
int file_size = cookie_root->WriteCookiesL(c4fp, this_time, TRUE);
// removing least recently used cookies until size of file exceeds defined maximum
while (file_size + file_header_size > cookie_file_max_size)
{
Cookie* ck = cookie_root->GetLeastRecentlyUsed(this_time, this_time);
if (ck)
{
if(ck->Persistent(this_time))
{
DataFile_Record rec(TAG_COOKIE_ENTRY);
ANCHOR(DataFile_Record,rec);
rec.SetRecordSpec(c4fp.GetRecordSpec());
ck->FillDataFileRecordL(rec);
size_t cookie_size = rec.CalculateLength();
file_size -= cookie_size;
}
ck->Out();
delete ck;
}
else
{
// there aren't any meaning all is protected
break;
}
}
}
#endif //(COOKIES_MAX_FILE_SIZE > 0) || (CONTEXT_COOKIES_MAX_FILE_SIZE > 0)
cookie_root->WriteCookiesL(c4fp, this_time);
#if defined EXTERNAL_COOKIE_STORAGE
if(c4fp.Opened()) // file is closed and deleted on error
{
OpFileLength len = cfp->GetFileLength();
unsigned char* buf = OP_NEWA_L(unsigned char, len);
ANCHOR_ARRAY(unsigned char, buf);
cfp->SetFilePos(0);
OpFileLength read;
LEAVE_IF_ERROR(cfp->Read(buf, len, &read));
if (read != len)
LEAVE(OpStatus::ERR); // Unable to read everything at once?
extern void WriteExternalCookies(URL_CONTEXT_ID, const unsigned char*, int);
WriteExternalCookies(context_id, buf, len);
}
#endif
ANCHOR_PTR_RELEASE(cfp);
c4fp.Close();
#ifdef WIC_COOKIE_MANAGER_LISTENER
notifier.SetSuccess();
#endif
}
#endif // DISK_COOKIES_SUPPORT
|
#pragma once
template <typename T>
void swap(T *a, T *b);
template <typename T>
void bubble_sort(T *list, int size);
template <typename T>
void selection_sort(T *list, int size);
template <typename T>
void insertion_sort(T *list, int size);
template <typename>
void merge_sort(T *list, int size);
#include "functions.cpp"
|
#include "Shader.h"
#include <cassert>
#include <fstream>
#include <glad/glad.h>
static void checkShaderError(int shader, int flag, bool isProgram, const std::string& errorMessage);
static std::string loadShader(const std::string& fileName);
Shader::Shader()
{
m_programID = glCreateProgram();
if (m_programID == 0) {
std::cout << "[ERROR] :: Unable to create Shader Program" << std::endl;
//exit(1);
}
}
Shader::~Shader()
{
for (auto const& value : m_shaders) {
glDetachShader(m_programID, value);
glDeleteShader(value);
}
glDeleteProgram(m_programID);
}
void Shader::bind()
{
glUseProgram(m_programID);
}
void Shader::unbind()
{
glUseProgram(0);
}
// CLASS METHODS ---------------------------------------------------------------------------------------------------------
void Shader::addUniform(const std::string& uniformName)
{
unsigned int location = glGetUniformLocation(m_programID, uniformName.c_str());
//assert(location != 0);
m_uniforms.insert(std::pair<std::string, int>(uniformName, location));
}
void Shader::addVertexShaderFromFile(const std::string& fileName)
{
addVertexShader(loadShader(fileName));
}
void Shader::addFragmentShaderFromFile(const std::string& fileName)
{
addFragmentShader(loadShader(fileName));
}
void Shader::addGeometryShaderFromFile(const std::string& fileName)
{
addGeometryShader(loadShader(fileName));
}
void Shader::addVertexShader(const std::string& text)
{
addProgram(text, GL_VERTEX_SHADER);
}
void Shader::addFragmentShader(const std::string& text)
{
addProgram(text, GL_FRAGMENT_SHADER);
}
void Shader::addGeometryShader(const std::string& text)
{
addProgram(text, GL_GEOMETRY_SHADER);
}
void Shader::addProgram(const std::string& text, int type)
{
int shader = glCreateShader(type);
if (shader == 0)
{
std::cout << "[ERROR] :: Error creating shader // type = " << type << std::endl;
}
const GLchar* p[1];
p[0] = text.c_str();
GLint lengths[1];
lengths[0] = text.length();
glShaderSource(shader, 1, p, lengths);
glCompileShader(shader);
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success)
{
GLchar infoLog[1024];
glGetShaderInfoLog(shader, 1024, NULL, infoLog);
fprintf(stderr, "[ERROR] :: Error compiling shader type %d: '%s'\n", shader, infoLog);
//exit(1);
}
glAttachShader(m_programID, shader);
m_shaders.push_back(shader);
}
void Shader::compileShader()
{
glLinkProgram(m_programID);
checkShaderError(m_programID, GL_LINK_STATUS, true, "Error linking shader program");
glValidateProgram(m_programID);
checkShaderError(m_programID, GL_VALIDATE_STATUS, true, "Invalid shader program");
}
void Shader::setAttributeLocation(const std::string& attributeName, int location)
{
glBindAttribLocation(m_programID, location, attributeName.c_str());
}
void Shader::setUniformi(const std::string& name, int value)
{
glUniform1i(m_uniforms.at(name), value);
}
void Shader::setUniformf(const std::string& name, float value)
{
glUniform1f(m_uniforms.at(name), value);
}
void Shader::setUniform(const std::string& name, const glm::vec3& value)
{
glUniform3f(m_uniforms.at(name), value.x, value.y, value.z);
}
void Shader::setUniform(const std::string& name, const glm::mat4& value)
{
glUniformMatrix4fv(m_uniforms.at(name), 1, GL_FALSE, &(value[0][0]));
}
void Shader::updateUniforms(Texture* texture)
{
}
void Shader::updateUniforms(Transform& transform, Model& model)
{
}
void Shader::updateUniforms(Transform& transform, Model& model, RenderingEngine* renderingEngine)
{
}
void Shader::updateX()
{
}
// --------------------------------------------------------------------------------------------------------------------
static void checkShaderError(int shader, int flag, bool isProgram, const std::string& errorMessage)
{
GLint success = 0;
GLchar error[1024] = { 0 };
if (isProgram)
glGetProgramiv(shader, flag, &success);
else
glGetShaderiv(shader, flag, &success);
if (!success)
{
if (isProgram)
glGetProgramInfoLog(shader, sizeof(error), NULL, error);
else
glGetShaderInfoLog(shader, sizeof(error), NULL, error);
std::cout << errorMessage << std::endl;
}
}
static std::string loadShader(const std::string& fileName)
{
std::ifstream file;
file.open(("res/shaders/" + fileName).c_str());
std::string output;
std::string line;
if (file.is_open())
{
while (file.good())
{
getline(file, line);
output.append(line + "\n");
}
}
else
{
std::cerr << "[ERROR] :: Unable to load Shader: " << fileName << std::endl;
}
return output;
}
|
#include "screen.h"
#include <stdio.h>
#include <cstring>
namespace pawstef {
Screen::Screen() : window(NULL), renderer(NULL), texture(NULL), buffer1(NULL), buffer2(NULL)
{
}
bool Screen::init()
{
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
return false;
}
window = SDL_CreateWindow("Training project", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, screenWidth, screenHeight, SDL_WINDOW_SHOWN);
if (window == NULL) {
SDL_Quit();
return false;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_PRESENTVSYNC);
texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA8888, SDL_TEXTUREACCESS_STATIC, screenWidth, screenHeight);
if (renderer == NULL) {
SDL_DestroyWindow(window);
SDL_Quit();
return false;
}
if (texture == NULL) {
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return false;
}
buffer1 = new Uint32[screenWidth*screenHeight];
buffer2 = new Uint32[screenWidth*screenHeight];
memset(buffer1, 0, screenWidth*screenHeight*sizeof(Uint32));
memset(buffer2, 0, screenWidth*screenHeight*sizeof(Uint32));
return true;
}
void Screen::setPixel(int x, int y, Uint8 red, Uint8 green, Uint8 blue)
{
if (x < 0 || x >= screenWidth || y < 0 || y >= screenHeight) {
return;
}
Uint32 color = 0;
color += red;
color <<= 8;
color += green;
color <<= 8;
color += blue;
color <<= 8;
color += 0xFF;
buffer1[(y * screenWidth) + x] = color;
}
void Screen::update()
{
// drawing code
SDL_UpdateTexture(texture, NULL, buffer1, screenWidth*sizeof(Uint32));
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, NULL, NULL);
SDL_RenderPresent(renderer);
}
bool Screen::processEvents()
{
SDL_Event event;
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT){
return false;
}
}
return true;
}
void Screen::close()
{
delete [] buffer1;
delete [] buffer2;
SDL_DestroyRenderer(renderer);
SDL_DestroyTexture(texture);
SDL_DestroyWindow(window);
SDL_Quit();
}
void Screen::boxBlur()
{
Uint32 *temp = buffer1;
buffer1 = buffer2;
buffer2 = temp;
for(int y=0; y<screenHeight; y++) {
for(int x=0; x<screenWidth; x++) {
int redTotal=0;
int greenTotal=0;
int blueTotal=0;
for(int row=-1; row<=1; row++){
for(int col=-1; col<=1; col++){
int currentX = x + col;
int currentY = y + row;
if(currentX >= 0 && currentX < screenWidth && currentY >= 0 && currentY < screenHeight) {
Uint32 color = buffer2[currentY*screenWidth + currentX];
Uint8 red = color >> 24;
Uint8 green = color >> 16;
Uint8 blue = color >> 8;
redTotal += red;
greenTotal += green;
blueTotal += blue;
}
}
}
Uint8 red = redTotal/9;
Uint8 green = greenTotal/9;
Uint8 blue = blueTotal/9;
setPixel(x, y, red, green, blue);
}
}
}
}
|
// Q. Variable sized array
// https://www.hackerrank.com/challenges/variable-sized-arrays/problem
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector< vector<unsigned int> > arr;
unsigned int n, q, i, j, k, num;
cin>>n>>q;
for(i=0; i<n; i++) {
vector<unsigned int> temp;
cin>>k;
for(j=0; j<k; j++) {
cin>>num;
temp.push_back(num);
}
arr.push_back(temp);
}
while(q--) {
cin>>i>>j;
cout<<arr[i][j]<<endl;
}
return 0;
}
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_MINER_H
#define XMRIG_MINER_H
#include <vector>
#include "backend/common/interfaces/IRxListener.h"
#include "base/api/interfaces/IApiListener.h"
#include "base/crypto/Algorithm.h"
#include "base/kernel/interfaces/IBaseListener.h"
#include "base/kernel/interfaces/ITimerListener.h"
#include "base/tools/Object.h"
namespace xmrig {
class Controller;
class Job;
class MinerPrivate;
class IBackend;
class Miner : public ITimerListener, public IBaseListener, public IApiListener, public IRxListener
{
public:
XMRIG_DISABLE_COPY_MOVE_DEFAULT(Miner)
Miner(Controller *controller);
~Miner() override;
bool isEnabled() const;
bool isEnabled(const Algorithm &algorithm) const;
const Algorithms &algorithms() const;
const std::vector<IBackend *> &backends() const;
Job job() const;
void execCommand(char command);
void pause();
void setEnabled(bool enabled);
void setJob(const Job &job, bool donate);
void stop();
protected:
void onConfigChanged(Config *config, Config *previousConfig) override;
void onTimer(const Timer *timer) override;
# ifdef XMRIG_FEATURE_API
void onRequest(IApiRequest &request) override;
# endif
# ifdef XMRIG_ALGO_RANDOMX
void onDatasetReady() override;
# endif
private:
MinerPrivate *d_ptr;
};
} // namespace xmrig
#endif /* XMRIG_MINER_H */
|
/**********************************************************
//
// Wih (Wireless Interface Hockey)
//
// airhockey.cpp (ゲームのメインクラス)
//
// Copyright (C) 2007,
// Masayuki Morita, Kazuki Hamada, Tatsuya Mori,
// All Rights Reserved.
**********************************************************/
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include "airhockey.h"
#include "msgqueue.h"
//前方宣言
void WaitUpdate(int msec);
HFONT SetMyFont(HDC hdc, LPCTSTR face, int h);
extern CMsgQueue* g_pMsgQueue;
extern SGameSetting g_game_setting;
//初期化
bool CAirHockey::init(){
if(state_!=EState::init_ng) return true;
state_=EState::init_ng;
//入力デバイスの初期化
if(!init_input_device(1,g_game_setting.input_mode1_)) return false;
if(!init_input_device(2,g_game_setting.input_mode2_)){
delete p_inputdevice1_;//1は成功しているので初期化を開放
return false;
}
//プレイヤーの初期化
p_player1_=new CPlayer(CPoint2(PLAYER_X1,PLAYER_Y1),
PLAYER_WIDTH,PLAYER_HEIGHT,p_inputdevice1_);
p_player2_=new CPlayer(CPoint2(PLAYER_X2,PLAYER_Y2),
PLAYER_WIDTH,PLAYER_HEIGHT,p_inputdevice2_);
if(p_player1_ == NULL || p_player2_ == NULL) return false;
//テーブルの初期化
p_table_=new CTableBMP(TABLE_WIDTH,TABLE_HEIGHT,TABLE_WALL,TABLE_GOAL);
if(p_table_==NULL) return false;
//乱数の初期化
srand((unsigned int)time(NULL));
score1_=0;
score2_=0;
state_=EState::init_ok;
return true;
}
//入力デバイスの初期化
bool CAirHockey::init_input_device(int player_id, int type){
//RS232Cの初期化
if( (type==INPUT_RS232C) && (p_rs232c_==NULL) ){
p_rs232c_=new CRs232c(g_game_setting.input_com_);
if(p_rs232c_==NULL) return false;
if(!p_rs232c_->init()){//初期化に失敗
delete p_rs232c_;
p_rs232c_=NULL;
return false;
}
}
//初期化対象の設定
typedef CInputDevice* PCInputDevice;
PCInputDevice& p_in= ((player_id==1)? p_inputdevice1_ : p_inputdevice2_);
CPoint2 pos=((player_id==1)? CPoint2(PLAYER_X1,PLAYER_Y1) : CPoint2(PLAYER_X2,PLAYER_Y2));
//入力デバイスの生成
switch(type){
case INPUT_RS232C:
p_in=new CInputDeviceRs232c(pos,p_rs232c_,player_id);
break;
case INPUT_CPU_MASTER:
p_in=new CInputDeviceMaster(pos,this);
break;
case INPUT_CPU_RANDOM:
p_in=new CInputDeviceRandom(pos,this);
break;
default:
return false;
}
if(p_in==NULL) return false;
else return true;
}
//ゲーム開始
bool CAirHockey::start(){
if(state_!=EState::init_ok) return false;
//SPACE入力待ち
WaitUpdate(-1);
return true;
}
//外部から強制終了または点数で終了(game_win)後
bool CAirHockey::end(){
if(!(state_==EState::game_play || state_==EState::game_win)) return false;
state_=EState::game_end;
//リセットor終了確認
g_pMsgQueue->push("続ける?",1000);
WaitUpdate(-1);
return true;
}
//リセット
bool CAirHockey::reset(){
if(state_!=EState::game_end) return false;
score1_=0;
score2_=0;
state_=EState::game_countdown_start;
return true;
}
//メモリ開放
bool CAirHockey::cleanup(){
//delete
delete p_puck_;
delete p_table_;
delete p_player2_;
delete p_player1_;
delete p_inputdevice2_;
delete p_inputdevice1_;
delete p_rs232c_;
state_=EState::init_ng;
return true;
}
///////////////////////////////////////////////////////////
// UPDATE_TIMER_INTERVAL間隔で呼ばれるゲームメインループ
void CAirHockey::update(){
if(!wait_flg_){
switch(state_){
case EState::game_play:
update_play();
break;
case EState::game_win:
update_win();
break;
case EState::game_countdown_start:
update_countdown_start();
break;
default:
break;
}
}
}
//カウントダウン
void CAirHockey::update_countdown_start(){
//パック生成
p_puck_=new CPuck(p_table_->center(),g_game_setting.puck_step_,PUCK_RADIUS,(rand()%4)+1);
//初期位置にリセット
p_player1_->reset();
p_player2_->reset();
//カウントダウン表示
g_pMsgQueue->push("さん",1000);
g_pMsgQueue->push("にぃー",1000);
g_pMsgQueue->push("いち",1000);
g_pMsgQueue->push("すたーと!",300);
WaitUpdate(3300);
}
//状態別のupdate()内部処理
// ゲーム中
void CAirHockey::update_play(){
int goal;
//パックを移動
p_puck_->move();
//ゴールの判定
if(goal=p_table_->is_goal(p_puck_)){
//ゴールした
goal_sub(goal);
}else{
//ゴールしてない
//プレイヤーの移動
p_player1_->move();
p_player2_->move();
//当たり判定
int direction;//ヒットした場合は反射方向、ヒットしなければ0
if(direction=p_table_->is_hit(p_puck_)){
p_puck_->set_direction(direction);
}else if(direction=p_player1_->is_hit(p_puck_)){
p_puck_->set_direction(direction);
}else if(direction=p_player2_->is_hit(p_puck_)){
p_puck_->set_direction(direction);
}
}
}
//得点の更新
void CAirHockey::goal_sub(int goal){
//パックの消去
delete p_puck_;
p_puck_=NULL;
//スコアの更新
if(goal==1){
score1_++;//Player1が得点
}else{
score2_++;//Player2が得点
}
//得点表示
char str[MSG_LEN_MAX];
sprintf(str,"%d : %d",score1_,score2_);
g_pMsgQueue->push("GOOOOOA L ! !",1000);
g_pMsgQueue->push(str,1500);
//終了判定へ
state_=EState::game_win;
}
//終了判定
void CAirHockey::update_win(){
//ゲーム終了判定
if( (score1_ >= g_game_setting.game_score_) || (score2_ >= g_game_setting.game_score_) ){
//ゲーム終了
char str[MSG_LEN_MAX];
sprintf(str,"Player %d WIN",( (score1_>score2_) ? 1 : 2));
g_pMsgQueue->push(str,1000);
end();
}else{
//ゲーム継続、次のパック待ちカウントダウンへ
WaitUpdate(-1);
state_=EState::init_ok;
}
}
///////////////////////////////////////////////////////
// 描画処理
void CAirHockey::draw(HDC hdc) const{
if(state_!=EState::init_ng){
//初期化されていればテーブルとプレイヤーは存在
p_table_->draw(hdc);
p_player1_->draw(hdc);
p_player2_->draw(hdc);
if(p_puck_!=NULL){//ゲーム遷移中はパックがない場合がある
p_puck_->draw(hdc);
}
//スコア部分の描画
draw_score(hdc);
}
}
//スコア部分の描画
void CAirHockey::draw_score(HDC hdc) const{
char str[SCORE_LEN_MAX];
strcpy(str,"Player1 Player2");
int bkOld = SetBkMode(hdc, TRANSPARENT);
//メッセージのフォント設定
HFONT hFont = SetMyFont(hdc, (LPCTSTR)"HGS創英角ポップ体", 30);
HFONT hFontOld = (HFONT)SelectObject(hdc, hFont);
SetTextColor(hdc, RGB(0, 64, 128));
SIZE text_metric;
GetTextExtentPoint32(hdc , str , (int)strlen(str) , &text_metric);
//メッセージボックス描画
HPEN hPenOld=(HPEN)SelectObject(hdc,GetStockObject(NULL_PEN));
HBRUSH hBrush=CreateSolidBrush(RGB(189,189,223));
HBRUSH hBrushOld=(HBRUSH)SelectObject(hdc,hBrush);
Rectangle(hdc,0,TABLE_HEIGHT+1,TABLE_WIDTH,PARENT_HEIGHT);
HBRUSH hBrush2=CreateSolidBrush(RGB(215,255,255));
SelectObject(hdc,hBrush2);
RoundRect(hdc,(TABLE_WIDTH-SCORE_WIDTH)/2,
TABLE_HEIGHT+10,
(TABLE_WIDTH+SCORE_WIDTH)/2,
PARENT_HEIGHT-10,
30,30);
SelectObject(hdc,hPenOld);
SelectObject(hdc,hBrushOld);
DeleteObject(hBrush);
DeleteObject(hBrush2);
//メッセージ描画
//Player1枠
TextOut(hdc, (TABLE_WIDTH-text_metric.cx)/2, TABLE_HEIGHT+(SCORE_HEIGHT-text_metric.cy)/2+10,
str , (int)strlen(str));
//スコア部分
HFONT hFont2 = SetMyFont(hdc, (LPCTSTR)"HGS創英角ポップ体", 50);
SelectObject(hdc,hFont2);
SetTextColor(hdc, RGB(255, 128, 0));
sprintf(str,"%2d : %2d",score1_,score2_);
GetTextExtentPoint32(hdc , str , (int)strlen(str) , &text_metric);
TextOut(hdc, (TABLE_WIDTH-text_metric.cx)/2, TABLE_HEIGHT+(SCORE_HEIGHT-text_metric.cy)/2+10,
str , (int)strlen(str));
//座標の表示
int y1=(int)(100.0*(p_player1_->pos().y_-TABLE_WALL)/(TABLE_HEIGHT-TABLE_WALL*2-PLAYER_HEIGHT));
int y2=(int)(100.0*(p_player2_->pos().y_-TABLE_WALL)/(TABLE_HEIGHT-TABLE_WALL*2-PLAYER_HEIGHT));
sprintf(str,"%3d %3d",y1,y2);
GetTextExtentPoint32(hdc , str , (int)strlen(str) , &text_metric);
TextOut(hdc, (TABLE_WIDTH-text_metric.cx)/2, TABLE_HEIGHT+(SCORE_HEIGHT-text_metric.cy)/2+10,
str , (int)strlen(str));
//後始末
SelectObject(hdc, hFontOld);
DeleteObject(hFont2);
DeleteObject(hFont);
SetBkMode(hdc, bkOld);
}
|
// Print the prime factorisation of number
#include <iostream>
using namespace std;
int main()
{
int n,c;
cin>>n;
for(int i=2;i<n;i++)
{
if(n%i==0)
{
c=1;
for(int j=2;j<i/2;j++)
{
if(i%j==0) c=0;
}
if(c==1) cout<<i<<' ';
}
}
return 0;
}
|
#include "Light.h"
Light::Light()
{
_iRed = 0;
_iGreen = 0;
_iBlue = 0;
}
Light::Light(float r, float g, float b)
{
_iRed = r;
_iGreen = g;
_iBlue = b;
}
Light::Light(float x)
{
_iRed = _iBlue = _iGreen = x;
}
float Light::GetRedIntensity()
{
return _iRed;
}
void Light::SetRedIntensity(const float r)
{
_iRed = r;
}
float Light::GetGreenIntensity()
{
return _iGreen;
}
void Light::SetGreenIntensity(const float g)
{
_iGreen = g;
}
float Light::GetBlueIntensity()
{
return _iBlue;
}
void Light::SetBlueIntensity(const float b)
{
_iBlue = b;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#include "core/pch.h"
#ifdef SKIN_SUPPORT
#include "modules/skin/skin_module.h"
#include "modules/skin/OpSkinManager.h"
#include "modules/skin/IndpWidgetPainter.h"
#include "modules/widgets/OpWidgetPainterManager.h"
#include "modules/widgets/OpWidget.h"
void SkinModule::InitL(const OperaInitInfo& info)
{
m_skintype_names[0] = "";
m_skintype_names[1] = ".left";
m_skintype_names[2] = ".top";
m_skintype_names[3] = ".right";
m_skintype_names[4] = ".bottom";
m_skintype_sizes[0] = 0;
m_skintype_sizes[1] = 5;
m_skintype_sizes[2] = 4;
m_skintype_sizes[3] = 6;
m_skintype_sizes[4] = 7;
m_skinsize_names[0] = "";
m_skinsize_names[1] = ".large";
m_skinsize_sizes[0] = 0;
m_skinsize_sizes[1] = 6;
m_skinpart_names[0] = "Tile Center";
m_skinpart_names[1] = "Tile Left";
m_skinpart_names[2] = "Tile Top";
m_skinpart_names[3] = "Tile Right";
m_skinpart_names[4] = "Tile Bottom";
m_skinpart_names[5] = "Corner Topleft";
m_skinpart_names[6] = "Corner Topright";
m_skinpart_names[7] = "Corner Bottomright";
m_skinpart_names[8] = "Corner Bottomleft";
#ifdef ANIMATED_SKIN_SUPPORT
m_image_animation_handlers = OP_NEW_L(Head, ());
#endif // ANIMATED_SKIN_SUPPORT
skin_manager = OP_NEW_L(OpSkinManager, ());
if (OpStatus::IsError(skin_manager->InitL()) && g_widgetpaintermanager)
{
g_widgetpaintermanager->SetPrimaryWidgetPainter(NULL);
}
#ifdef SKIN_PRELOAD_COMMON_BITMAPS
g_skin_manager->GetSkinElement("Scrollbar Horizontal Skin");
g_skin_manager->GetSkinElement("Scrollbar Horizontal Knob Skin");
g_skin_manager->GetSkinElement("Scrollbar Horizontal Left Skin");
g_skin_manager->GetSkinElement("Scrollbar Horizontal Right Skin");
g_skin_manager->GetSkinElement("Scrollbar Vertical Skin");
g_skin_manager->GetSkinElement("Scrollbar Vertical Knob Skin");
g_skin_manager->GetSkinElement("Scrollbar Vertical Down Skin");
g_skin_manager->GetSkinElement("Scrollbar Vertical Up Skin");
g_skin_manager->GetSkinElement("Push Button Skin");
g_skin_manager->GetSkinElement("Push Default Button Skin");
g_skin_manager->GetSkinElement("Radio Button Skin");
g_skin_manager->GetSkinElement("Checkbox Skin");
g_skin_manager->GetSkinElement("Edit Skin");
g_skin_manager->GetSkinElement("MultilineEdit Skin");
g_skin_manager->GetSkinElement("Dropdown Skin");
g_skin_manager->GetSkinElement("Dropdown Button Skin");
g_skin_manager->GetSkinElement("Listbox Skin");
#endif // SKIN_PRELOAD_COMMON_BITMAPS
}
void SkinModule::Destroy()
{
OP_DELETE(g_IndpWidgetInfo);
g_IndpWidgetInfo = NULL;
OP_DELETE(skin_manager);
skin_manager = NULL;
#ifdef ANIMATED_SKIN_SUPPORT
#ifdef _DEBUG
OP_ASSERT(m_image_animation_handlers->Cardinal() == 0);
#endif // _DEBUG
OP_DELETE(m_image_animation_handlers);
m_image_animation_handlers = NULL;
#endif // ANIMATED_SKIN_SUPPORT
}
#endif // SKIN_SUPPORT
|
#include "aes256.h"
#include "encrypt_commons.h"
#include <iostream>
int main (int argc, char * argv[]) {
if (argc != 4) {
printf("Usage: %s <filepath to object to cipher> <password path> <out_path>\n", argv[0]);
exit(1);
}
using namespace Cipher;
std::string pass;
loadfile_into_str(argv[2], Mode::binary, pass);
std::vector<CryptoPP::byte> obj;
loadfile_into_vector(argv[1], Mode::binary, obj);
AES256_encryptor enc(pass);
enc.encrypt(obj.data(), obj.size());
std::ofstream out(argv[3], Mode::binary & Mode::out);
for (auto i: obj) {
out << i;
}
return 0;
}
|
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <stdio.h>
using namespace std;
#include "soft.h"
soft* my_obj = nullptr;
int main() {
int command_1;
int memory;
string str;
char name[20];
char extension[20];
int size;
char date[20];
char time[20];
soft* copy_obj = nullptr;
while(1) {
system("cls");
cout << "1.Crete object using default constructor\n";
cout << "2.Create object using changing type constructor\n";
cout << "3.Check copy constructor\n";
cout << "4.Print object\n";
cout << "5.Modify name\n";
cout << "6.Modify extension\n";
cout << "7.Delete object\n";
cout << "8.Exit\n";
cout << "\nEnter command\n>";
cin >> command_1;
switch(command_1) {
case 1:
system("cls");
if(my_obj) {
cout << "Memory exist\n";
system("pause");
break;
}
cout << "Give the name of the file:" << endl;
cin >> name;
cout << "Give the extension of the file:" << endl;
cin >> extension;
cout << "Give the size of the file(in MB):" << endl;
cin >> size;
cout << "Give the date of the file:" << endl;
cin >> date;
cout << "Give the time of the file:" << endl;
cin >> time;
my_obj = new soft(name,extension,size,date,time);
if(my_obj) {
system("cls");
cout << "Object succesfully created!\a\n";
system("pause");
break;
}
case 2:
system("cls");
if(my_obj) {
cout << "Memory exist\n";
system("pause");
memory=1;
break;
}
cout << "Enter name/extension/size/date/time delimeter by space:" << endl << ">";
fflush(stdin);
getline(cin,str);
my_obj = new soft(str);
if(my_obj) {
system("cls");
cout << "Object succesfully created!\a\n";
system("pause");
memory=1;
break;
}
case 3:
system("cls");
if(!my_obj) {
cout << "No object in dirrectory!\a\n";
memory=1;
system("pause");
break;
}
copy_obj = my_obj;
cout << "First object:\n";
my_obj -> print();
cout << "\nSecond object:\n";
copy_obj -> print();
system("pause");
memory=1;
break;
case 4:
system("cls");
if(!my_obj) {
cout << "No object in dirrectory!\a\n";
memory=1;
system("pause");
break;
}
my_obj -> print();
system("pause");
memory=1;
break;
case 5:
system("cls");
if(!my_obj) {
cout << "No object in dirrectory!\a\n";
memory=1;
system("pause");
break;
}
my_obj -> modify_name();
system("pause");
break;
case 6:
system("cls");
if(!my_obj) {
cout << "No object in dirrectory!\a\n";
memory=1;
system("pause");
break;
}
my_obj -> modify_extension();
memory=1;
system("pause");
break;
case 7:
system("cls");
if(my_obj) delete my_obj;
my_obj = nullptr;
cout << "\aObject succesfully deleted!\n";
system("pause");
break;
case 8:
system("cls");
if(my_obj) delete my_obj;
my_obj = nullptr;
cout << "GOOD BYE\n";
system("pause");
exit(1);
default:
system("cls");
cout << "Incorrect taste!\a\n";
memory=1;
system("pause");
break;
}
}
}
return 0;
}
|
/*Assume that the value of a = 1, b = 2, c = 3, ... , z = 26. You are given a numeric string S. Write a program to return the list of all possible codes that can be generated from the given string.
Note : The order of codes are not important. And input string does not contain 0s.
Input format :
A numeric string
Constraints :
1 <= Length of String S <= 10
Sample Input:
1123
Sample Output:
aabc
kbc
alc
aaw
kw
*/
#include<bits/stdc++.h>
using namespace std;
int getCodes(string input,string output[]){
if(input.empty()){
output[0] = "";
return 1;
}
string o1[10000];
string o2[10000];
int i1 = input[0] - '0';
char c1 = 'a' + i1 - 1;
char c2 = '\0';
int s1 = getCodes(input.substr(1),o1);
int s2 = 0;
if(input[1] != '\0'){
int i2 = i1 * 10 + (input[1] - '0');
if(i2 >= 0 && i2 <= 26){
c2 = 'a' + i2 - 1;
s2 = getCodes(input.substr(2),o2);
}
}
for(int i=0;i<s1;i++){
output[i] = c1 + o1[i];
}
for(int i=0;i<s2;i++){
output[s1 + i] = c2 + o2[i];
}
return s1 + s2;
}
int main(){
string input;
cin >> input;
string output[10000];
int count = getCodes(input,output);
for(int i=0;i<count && i<10000;i++){
cout << output[i] << endl;
}
return 0;
}
|
#ifndef TREEFACE_VISUAL_OBJECT_GUTS_H
#define TREEFACE_VISUAL_OBJECT_GUTS_H
#include "treeface/scene/VisualObject.h"
#include "treeface/scene/SceneGraphMaterial.h"
#include "treeface/scene/guts/Utils.h"
#include "treeface/gl/VertexArray.h"
namespace treeface
{
struct VisualObject::Impl
{
Impl(Geometry* geom, SceneGraphMaterial* mat);
~Impl();
void update_uniform_cache();
VisualObject::Impl* same_geom_prev = nullptr;
VisualObject::Impl* same_geom_next = nullptr;
treecore::RefCountHolder<SceneGraphMaterial> material = nullptr;
treecore::RefCountHolder<Geometry> geometry = nullptr;
treecore::RefCountHolder<VertexArray> vertex_array = nullptr;
bool uniform_cache_dirty = true;
treecore::Array<UniformKV> cached_uniforms;
UniformMap uniforms;
};
} // namespace treeface
#endif // TREEFACE_VISUAL_OBJECT_GUTS_H
|
#include "trackingvideo.h"
#include "ui_trackingvideo.h"
#include "MatToQImage.h"
#include "facetracking.h"
#include "QProgressBar"
#include <QGraphicsDropShadowEffect>
void Worker::doWork(){
//referencia https://stackoverflow.com/questions/35673201/qt-5-update-qprogressbar-during-qthread-work-via-signal/35673612
cv::Mat frame, prev_frame;
prev_frame = GetFittedImage(kf_image,OUTPUT_VIDEO_H,OUTPUT_VIDEO_W);
tracker.candide->pose_tracking_indxs = new std::vector<int>{ 37,94,38,111,112,29,62,23,56, 5 }; // Quite el vertice 10 pq sino al mover la boca la mascara se mueve
//Guardo resultado en un video para luego mostrarlo
std::string out = logfile.filename.substr(0, logfile.filename.find(".")) + std::string("_tracking.avi");
cv::VideoWriter video(out, cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), cap.get(cv::CAP_PROP_FPS), cv::Size(OUTPUT_VIDEO_W, OUTPUT_VIDEO_H));
// Init Log File
logfile.start_log(tracker);
logfile.write_log(tracker,cap.get(cv::CAP_PROP_POS_FRAMES));
//Init Tracking
bool detected = false;
cv::Rect face = tracker.detectFace(prev_frame, detected);
if (detected) {
detected = false;
tracker.facelandmarks(prev_frame, face, detected);
if (detected){
for (cv::Point2f lp : tracker.landmarks)
{
tracker.stabilized_landmarks.emplace_back(lp);
}
}
}
while(cap.read(frame)){
frame = GetFittedImage(frame,OUTPUT_VIDEO_H,OUTPUT_VIDEO_W);
cv::Mat frame_orig = frame.clone();
// ======> Tracking
tracker.step(prev_frame, frame);
prev_frame = frame.clone();
// Write Log
logfile.write_log(tracker,cap.get(cv::CAP_PROP_POS_FRAMES));
// Guardo video procesado
video.write(tracker.candide->graficar_mesh(frame));
// Actualizo Loading Bar
emit updateLoadingBar(cap.get(cv::CAP_PROP_POS_FRAMES));
}
//End Log
logfile.end_log();
emit resultReady();
}
TrackingVideo::TrackingVideo(QWidget *parent) :
QWidget(parent),
ui(new Ui::TrackingVideo)
{
std::cout << "Inicializando TrackingVideo..." << std::endl;
ui->setupUi(this);
ui->boton_reproducir->setDisabled(true);
ui->boton_resultados->setDisabled(true);
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
ui->fecha->setText(QString::number(now->tm_mday) + "/" + QString::number(now->tm_mon + 1) + "/" + QString::number(now->tm_year + 1900));
// Sombras
QGraphicsDropShadowEffect *shadow = new QGraphicsDropShadowEffect();
shadow->setBlurRadius(20);
shadow->setXOffset(4);
shadow->setYOffset(4);
shadow->setColor(QColor(0, 0, 0, 100));
ui->progressBar->setGraphicsEffect(shadow);
QGraphicsDropShadowEffect *shadow_img = new QGraphicsDropShadowEffect();
shadow_img->setBlurRadius(40);
shadow_img->setXOffset(10);
shadow_img->setYOffset(10);
shadow_img->setColor(QColor(0, 0, 0, 130));
ui->img_label->setGraphicsEffect(shadow_img);
QGraphicsDropShadowEffect *shadow_button = new QGraphicsDropShadowEffect();
shadow_button->setBlurRadius(20);
shadow_button->setXOffset(0);
shadow_button->setYOffset(0);
shadow_button->setColor(QColor(0, 0, 0, 200));
ui->boton_resultados->setGraphicsEffect(shadow_button);
// Size
QSizePolicy img_size;
img_size.setHorizontalPolicy(QSizePolicy::Minimum);
img_size.setVerticalPolicy(QSizePolicy::Minimum);
ui->img_label->setSizePolicy(img_size);
// Bug cuando el video es largo si escribo en las LineEdit la barra de progreso
// deja de actualizarse, por lo que pongo visible los campos luego de que se procese
// el video.
ui->nombre->setVisible(false);
ui->apellido->setVisible(false);
ui->edad->setVisible(false);
ui->dni->setVisible(false);
ui->fecha->setVisible(false);
ui->label_nombre->setVisible(false);
ui->label_apellido->setVisible(false);
ui->label_edad->setVisible(false);
ui->label_dni->setVisible(false);
ui->label_fecha->setVisible(false);
ui->label_datos->setVisible(false);
std::cout << "TrackingVideo inicializado." << std::endl;
}
TrackingVideo::~TrackingVideo()
{
delete ui;
}
void TrackingVideo::resizeEvent(QResizeEvent *event){
ui->img_label->setMinimumHeight(int(ui->img_label->width()*0.5625) );
if(ui->boton_reproducir->isEnabled()){
qDebug() << "Entro a resizeEvent TrackingVideo";
ui->img_label->setPixmap(ui->img_label->pixmap()->scaled(ui->img_label->width(),ui->img_label->width()*0.5625));
}
}
void TrackingVideo::procesarvideo(){
tracker.candide->pose_tracking_indxs = new std::vector<int>{ 37,94,38,111,112,29,62,23,56, 5 }; // Quite el vertice 10 pq sino al mover la boca la mascara se mueve
ui->progressBar->setRange(cap.get(cv::CAP_PROP_POS_FRAMES), cap.get(cv::CAP_PROP_FRAME_COUNT));
ui->progressBar->setValue(cap.get(cv::CAP_PROP_POS_FRAMES));
ui->progressBar->setTextVisible(true);
ui->progressBar->setAlignment(Qt::AlignCenter);
ui->progressBar->setHidden(false);
QThread* thread = new QThread;
Worker* worker = new Worker; // Do not set a parent. The object cannot be moved if it has a parent.
worker->tracker = tracker;
worker->kf_image = kf_image;
worker->cap = cap;
worker->logfile.set_log_filename(logfile.filename, TEMPORARY_LOG);
worker->logfile.set_total_frames(cap.get(cv::CAP_PROP_FRAME_COUNT) - cap.get(cv::CAP_PROP_POS_FRAMES));
worker->moveToThread(thread);
connect(worker, SIGNAL(updateLoadingBar(int)), ui->progressBar, SLOT(setValue(int)));
connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(started()), worker, SLOT(doWork()));
connect(worker, SIGNAL(resultReady()), this, SLOT(videoprocesado()));
thread->start();
}
void TrackingVideo::videoprocesado()
{
ui->progressBar->setFormat("PROCESADO ✔");
ui->progressBar->setAlignment(Qt::AlignCenter);
ui->boton_reproducir->setDisabled(false);
ui->boton_resultados->setDisabled(false);
// Bug cuando el video es largo si escribo en las LineEdit la barra de progreso
// deja de actualizarse, por lo que pongo visible los campos luego de que se procese
// el video.
ui->nombre->setVisible(true);
ui->apellido->setVisible(true);
ui->edad->setVisible(true);
ui->dni->setVisible(true);
ui->fecha->setVisible(true);
ui->label_nombre->setVisible(true);
ui->label_apellido->setVisible(true);
ui->label_edad->setVisible(true);
ui->label_dni->setVisible(true);
ui->label_fecha->setVisible(true);
ui->label_datos->setVisible(true);
cv::VideoCapture processed;
processed.open(logfile.filename.substr(0, logfile.filename.find(".")) + std::string("_tracking.avi"));
processed.read(frame);
QImage imgQ = MatToQImage(frame);
ui->img_label->setPixmap(QPixmap::fromImage(imgQ).scaled(ui->img_label->width(),ui->img_label->width()*0.5625));
processed.release();
}
void TrackingVideo::on_boton_resultados_clicked()
{
nombre= ui->nombre->text();
apellido= ui->apellido->text();
edad= ui->edad->text();
dni= ui->dni->text();
fecha= ui->fecha->text();
emit show_results();
}
void TrackingVideo::on_boton_reproducir_clicked()
{
cv::VideoCapture processed;
processed.open(logfile.filename.substr(0, logfile.filename.find(".")) + std::string("_tracking.avi"));
while(processed.read(frame)){
QImage imgQ = MatToQImage(frame);
ui->img_label->setPixmap(QPixmap::fromImage(imgQ).scaled(ui->img_label->width(),ui->img_label->width()*0.5625));
cv::waitKey(1000/processed.get(cv::CAP_PROP_FPS));
}
}
|
#include "Producer.h"
#include "Utils.h"
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
// Producer class which encapsulates the functionalities
// of a producer, such as produce random numbers and write
// to the pipe.
// The constructor receives an array of references to the
// pipe file descriptor.
Producer::Producer(int (&pipe_fd)[2], int number_of_numbers)
{
pipe_fd_ = pipe_fd;
number_of_numbers_ = number_of_numbers;
}
int Producer::produceRandomNumbers()
{
// Closes the reading edge of the pipe.
close(*pipe_fd_);
// Starts with N0 = 1.
int number_to_be_sent = 1;
for (int i = 0; i < number_of_numbers_; i++) {
number_to_be_sent = number_to_be_sent + Utils::generateRandomNumber();
string value_to_be_sent = to_string(number_to_be_sent);
cout << "*** Producer ***\n";
cout << "Value to be written in pipe: " << value_to_be_sent << "\n\n";
writeToPipe(value_to_be_sent);
sleep(1);
}
return terminateProduction();
}
void Producer::writeToPipe(string value)
{
// Writes writing edge, which requires the C++ string
// to be converted to a C string.
write(*(pipe_fd_ + 1), value.c_str(), 21);
}
int Producer::terminateProduction()
{
cout << "*** Producer ***\n";
cout << "End of numbers generation.\n" << endl;
string value_to_be_sent = "0";
writeToPipe(value_to_be_sent);
close(*(pipe_fd_ + 1));
return EXIT_SUCCESS;
}
|
// 2 The Edge - Team 8: Liam Hall, Dan Powell, Louis Mills, Mo Patel, Ethan Gangotra, Hencraft, keasibanda
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Pickup.generated.h"
class ATwoTheEdgeCharacter;
UCLASS()
class TWOTHEEDGE_API APickup : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
APickup();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void Pickup(ATwoTheEdgeCharacter* Character);
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintCallable)
void OnOverlap(AActor* Actor);
/** Called when the item has been picked up */
UFUNCTION(BlueprintImplementableEvent)
void OnPickup(ATwoTheEdgeCharacter* Character);
private:
bool bDestroyPending;
};
|
#pragma once
#include <unordered_map>
#include <memory>
template <typename Resource>
class ResourceManager
{
std::unordered_map<std::string, std::shared_ptr<Resource>> resources;
public:
inline void add(std::string&& key, std::shared_ptr<Resource>&& res) { resources[key] = res; }
inline void remove(std::string&& key) { resources.erase(key); }
inline Resource& operator[](const std::string& key) { return *resources[key]; }
inline std::unordered_map<std::string, std::shared_ptr<Resource>>& getResources() { return resources; }
};
|
#include "menu-1.h"
#include "jeu.h"
void menu1(SDL_Surface *ecran)
{
/// On cree l'ensemble des surfaces n�cessaires
SDL_Surface* menu;
SDL_Surface* buttonPlay;
SDL_Surface* buttonHelp;
SDL_Surface* buttonClose;
menu = IMG_Load("images/menu-1.jpg") ;
buttonPlay = IMG_Load("images/options/play.png") ;
buttonHelp = IMG_Load("images/options/help.png");
buttonClose = IMG_Load("images/options/close.png");
/// On positionne les surfaces
SDL_Rect positionMenu;
SDL_Rect positionPlay;
SDL_Rect positionHelp;
SDL_Rect positionClose;
positionMenu.x = 0 ;
positionMenu.y = 0 ;
positionPlay.x = 2 * CELLULE ;
positionPlay.y = 6 * CELLULE ;
positionHelp.x = 0.5 * CELLULE ;
positionHelp.y = 0.5 * CELLULE ;
positionClose.x = 5.5 * CELLULE;
positionClose.y = 0.5 * CELLULE;
///On colle les surfaces dans l'ecran
SDL_BlitSurface(menu, NULL, ecran, &positionMenu) ;
SDL_BlitSurface(buttonPlay, NULL, ecran, &positionPlay) ;
SDL_BlitSurface(buttonHelp, NULL, ecran, &positionHelp) ;
SDL_BlitSurface(buttonClose, NULL, ecran, &positionClose) ;
///On met � jour l'ecran
SDL_Flip(ecran) ;
///On passe aux �v�nements
float m, n;
int continuer = 0;
while (!continuer)
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
{
continuer = 1;
break;
}
case SDL_KEYDOWN:
{
if (event.key.keysym.sym == SDLK_ESCAPE)
continuer = 1;
}
break;
case SDL_MOUSEMOTION :
{
m = event.motion.x / CELLULE;
n = event.motion.y / CELLULE;
if ((m >= 2) && (m <= 5) && (n >= 6) && (n <= 7))
{
buttonPlay = IMG_Load("images/play-hover.png") ;
}
else if ((m >= 0.5) && (m <= 1.5) && (n >= 0.5) && (n <= 1.5))
{
buttonHelp = IMG_Load("images/options/help-hover.png");
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
buttonClose = IMG_Load("images/options/close-hover.png");
}
else
{
buttonPlay = IMG_Load("images/play.png") ;
buttonHelp = IMG_Load("images/options/help.png");
buttonClose = IMG_Load("images/options/close.png");
}
SDL_BlitSurface(buttonPlay, NULL, ecran, &positionPlay) ;
SDL_BlitSurface(buttonHelp, NULL, ecran, &positionHelp) ;
SDL_BlitSurface(buttonClose, NULL, ecran, &positionClose) ;
}
break ;
case SDL_MOUSEBUTTONUP :
{
if (event.button.button == SDL_BUTTON_LEFT)
{
m = event.button.x / CELLULE;
n = event.button.y / CELLULE;
if ((m >= 2) && (m <= 5) && (n >= 6) && (n <= 7))
{
menu2(ecran) ;
continuer = 1;
}
else if ((m >= 5.5) && (m <= 6.5) && (n >= 0.5) && (n <= 1.5))
{
continuer = 1;
}
}
}
break;
}
}
SDL_Flip(ecran);
}
///On lib�re les surfaces
SDL_FreeSurface(menu);
SDL_FreeSurface(buttonPlay);
SDL_FreeSurface(buttonHelp);
SDL_FreeSurface(buttonClose);
}
|
#include "CQEnum_Pch.hpp"
#include "CQEnum.hpp"
namespace CQSL { namespace CQEnum {
void CQEnumInfo::ParseFrom(InputSrc& srcFile)
{
// Check the main file info stuff, so File= first
srcFile.bCheckNextId("File", "Expected the File= block to be first in the file", true, true);
// We have to see the version first
m_iVersion = srcFile.iCheckSignedValue("Version", "Expected the Version attribute");
if (m_iVersion != 1)
{
srcFile.ThrowParseErr("The version number must be equal to 1");
}
// We expect to see a namespaces value next
srcFile.bCheckNextId("Namespaces", "Expected to see Namespaces= here", true, true);
srcFile.GetSpacedValues(m_vNamespaces);
// We can have an export macro
if (srcFile.bCheckNextId("ExportMacro", "Expected to see ExportMacro= here", true, false))
{
srcFile.GetIdToken("Expected to see export macro name here", m_strExportMacro);
// Add a space after it so that we don't ahve to do that every time we output it
m_strExportMacro.push_back(' ');
}
// We have to see the end of the file block
srcFile.CheckBlockEnd("File");
// If we have a constants block, parse it
if (srcFile.bCheckNextId("Constants", "Expected Constants=, Enums=", true, false))
{
m_listConsts.ParseFrom(srcFile);
}
// If we have an enums block, parse it
if (srcFile.bCheckNextId("Enums", "Expected Constants=, Enums=", true, false))
{
m_listEnums.ParseFrom(srcFile);
}
//
// Pre-build up the namespace prefix for the user's defined namespaces. This is used
// a lot so it saves a lot of grunt work.
//
m_strNSPrefix.clear();
for (const std::string& strNS : m_vNamespaces)
{
m_strNSPrefix.append(strNS);
m_strNSPrefix.append("::");
}
}
}};
|
#include "Races.h"
class cArmyManager
{
private:
typedef MapPair std::pair<int,cArmy>
std::map<MapPair> mArmies;
int mLastID;
public:
cArmyManager()
: mLastID(0)
{}
cArmy& GetNewArmy(eRace aOwner, int aWeak, int aStrong){}
void DisbandArmy(int aArmyID){}
cArmy& GetArmyByID(int aArmyID){mArmies.}
};
class cArmy
{
private:
eRace mOwner;
int mArmyID;
int mWeakUnitNumber;
int mStrongUnitNumber;
public:
cArmy(eRace aOwner, int aArmyID, int aWeak, int aStrong)
: mOwner(aOwner)
, mWeakUnitNumber(aWeak)
, mStrongUnitNumber(aStrong)
{
}
eRace GetOwner() {return mOwner;}
int GetArmyID() {return mArmyID;}
int GetWeakUnitNumber() {return mWeakUnitNumber;}
int GetStrongUnitNumber() {return mStrongUnitNumber;}
};
|
#include<stdio.h>
#include<conio.h>
#include<string.h>
using namespace std;
int main()
{
FILE *fp1,*fp2;
fp1 = fopen("trial.txt","r");
fp2 = fopen("trial1.txt","w");
char str[80];
char str1[80];
while(fgets(str,80,fp1)!=NULL)
{
fputs(str,stdout);
strcpy(str1,str);
fprintf(fp2,str1);
}
fclose(fp1);
fclose(fp2);
getch();
}
|
/*
ID: stevenh6
TASK: milk2
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
struct Time {
int start, end;
};
bool comp(Time l, Time r) {
return l.start < r.start;
}
int main() {
ofstream fout ("milk2.out");
ifstream fin ("milk2.in");
int n;
fin >> n;
Time cows[n];
int milking = 0;
int notmilking = 0;
for (int i = 0; i < n; i++) {
fin >> cows[i].start >> cows[i].end;
//cout << cows[i].start << endl;
}
sort(cows, cows + n, comp);
for (int i = 0; i < n; i++) {
cout << cows[i].start << endl;
}
int last = 0;
for (int i = 1; i < n; i++) {
if (cows[i].start <= cows[last].end) {
cows[last].end = cows[last].end > cows[i].end ? cows[last].end : cows[i].end;
} else {
if (cows[i].start - cows[last].end > notmilking) {
notmilking = cows[i].start - cows[last].end;
}
if (cows[last].end - cows[last].start > milking) {
milking = cows[last].end - cows[last].start;
}
last = i;
}
}
if (cows[last].end - cows[last].start > milking) {
milking = cows[last].end - cows[last].start;
}
fout << to_string(milking) + " " + to_string(notmilking) << endl;
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.