text
stringlengths 8
6.88M
|
|---|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2010-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
*/
#include "core/pch.h"
#ifdef SVG_SUPPORT
#include "modules/svg/src/svgpch.h"
#include "modules/svg/src/SVGDynamicChangeHandler.h"
#include "modules/svg/src/animation/svganimationsandwich.h"
#include "modules/svg/src/SVGAnimationContext.h"
#include "modules/svg/src/AttrValueStore.h"
SVGAnimationSandwich::~SVGAnimationSandwich()
{
animations.Clear();
}
BOOL
SVGAnimationSandwich::MatchesTarget(SVGAnimationTarget *match_target, SVGAnimationAttributeLocation match_attribute_location)
{
return (match_target == target && match_attribute_location == attribute_location);
}
SVG_ANIMATION_TIME
SVGAnimationSandwich::NextIntervalTime(SVG_ANIMATION_TIME document_time, BOOL at_prezero) const
{
SVG_ANIMATION_TIME next_interval_time = SVGAnimationTime::Indefinite();
SVGAnimationSlice *iter;
for (iter = animations.First(); iter; iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
next_interval_time = MIN(next_interval_time, schedule.NextIntervalTime(iter->timing_arguments, document_time, at_prezero));
}
return next_interval_time;
}
SVG_ANIMATION_TIME
SVGAnimationSandwich::NextAnimationTime(SVG_ANIMATION_TIME document_time) const
{
SVG_ANIMATION_TIME next_animation_time = SVGAnimationTime::Indefinite();
SVGAnimationSlice *iter;
for (iter = animations.First(); iter && next_animation_time > document_time; iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
next_animation_time = MIN(next_animation_time, schedule.NextAnimationTime(iter->timing_arguments, document_time));
}
return next_animation_time;
}
void
SVGAnimationSandwich::InsertSlice(SVGAnimationSlice* animation_slice,
SVG_ANIMATION_TIME document_time)
{
animation_slice->Out();
// Find correct position to insert the animation into
SVGAnimationSchedule &new_schedule = animation_slice->animation->AnimationSchedule();
SVG_ANIMATION_TIME new_begin_time = new_schedule.GetNextBeginTime(document_time, animation_slice->animation_arguments);
HTML_Element *new_elm = animation_slice->animation->GetElement();
if (new_begin_time <= SVGAnimationTime::Latest())
{
SVGAnimationSlice *iter;
for (iter = animations.Last(); iter; iter = iter->Pred())
{
if (HasHigherPriority(document_time, *iter, new_schedule, new_begin_time, new_elm))
{
animation_slice->Follow(iter);
return;
}
}
animation_slice->IntoStart(&animations);
}
else
animation_slice->Into(&animations);
}
void
SVGAnimationSandwich::Reset(SVG_ANIMATION_TIME document_time)
{
SVGAnimationSlice *iter;
for (iter = animations.First(); iter; iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
schedule.Reset(iter->timing_arguments);
}
}
OP_STATUS
SVGAnimationSandwich::UpdateIntervals(SVGAnimationWorkplace *animation_workplace)
{
SVGAnimationSlice *iter;
OP_STATUS status = OpStatus::OK;
for (iter = animations.First();
iter && OpStatus::IsSuccess(status);)
{
SVGAnimationSlice *tmp = iter;
iter = iter->Suc();
SVGAnimationSchedule &schedule = tmp->animation->AnimationSchedule();
status = schedule.UpdateIntervals(animation_workplace, tmp->animation, tmp->timing_arguments);
}
return status;
}
OP_STATUS
SVGAnimationSandwich::CommitIntervals(SVGAnimationWorkplace *animation_workplace,
BOOL send_events,
SVG_ANIMATION_TIME document_time,
SVG_ANIMATION_TIME elapsed_time,
BOOL at_prezero)
{
SVGAnimationSlice *iter;
List<SVGAnimationSlice> reposition_list;
OP_BOOLEAN has_new_interval = OpBoolean::IS_FALSE;
for (iter = animations.First();
iter && OpStatus::IsSuccess(has_new_interval);)
{
SVGAnimationSlice *tmp = iter;
iter = iter->Suc();
SVGAnimationSchedule &schedule = tmp->animation->AnimationSchedule();
has_new_interval = schedule.CommitIntervals(animation_workplace, document_time, send_events,
elapsed_time, at_prezero, tmp->animation, tmp->timing_arguments);
if (has_new_interval == OpBoolean::IS_TRUE)
{
tmp->Out();
tmp->Into(&reposition_list);
}
}
while ((iter = reposition_list.First()) != NULL)
InsertSlice(iter, document_time);
#ifdef _DEBUG
SVG_ANIMATION_TIME begin = SVGAnimationTime::Earliest();
/* Check that the sandwich is properly sorted */
for (iter = animations.First();
iter; iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
SVG_ANIMATION_TIME this_begin = schedule.GetNextBeginTime(document_time, iter->animation_arguments);
OP_ASSERT(begin <= this_begin);
begin = this_begin;
}
#endif // _DEBUG
return OpStatus::IsError(has_new_interval) ? has_new_interval :OpStatus::OK;
}
OP_STATUS
SVGAnimationSandwich::UpdateValue(SVGAnimationWorkplace *animation_workplace, SVG_ANIMATION_TIME document_time)
{
BOOL is_active = FALSE;
HTML_Element *animated_element = target->TargetElement();
SVGAttributeField computed_field = SVG_ATTRFIELD_BASE;
SVGAttribute *attribute = AttrValueStore::GetSVGAttr(animated_element,
attribute_location.animated_name,
attribute_location.GetNsIdxOrSpecialNs(),
attribute_location.is_special);
SVGAnimationValueContext context;
context.Bind(animated_element);
context.UpdateToAttribute(&attribute_location);
SVGObject *base_svg_object = GetBaseObject(attribute_location);
SVGObject *animation_svg_object;
OP_STATUS status = GetAnimationObject(animated_element,
attribute,
animation_svg_object,
attribute_location,
computed_field);
RETURN_IF_ERROR(status);
OP_ASSERT(attribute && animation_svg_object);
OpAutoPtr<SVGObject> old_svg_object(animation_svg_object->Clone());
if (!old_svg_object.get())
return OpStatus::ERR_NO_MEMORY;
SVGAnimationValue animation_value;
if (!SVGAnimationValue::Initialize(animation_value, animation_svg_object, context))
return OpStatus::ERR;
for (SVGAnimationSlice *iter = animations.First(); iter && !OpStatus::IsMemoryError(status); iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
if (schedule.IsActive(document_time, iter->animation_arguments))
{
SVGObject *cloned_base_svg_object = base_svg_object ? base_svg_object->Clone() : NULL;
SVGObject::IncRef(cloned_base_svg_object);
SVGAnimationValue base_animation_value = SVGAnimationValue::Empty();
SVGAnimationValue::Initialize(base_animation_value, cloned_base_svg_object, context);
if (!attribute_location.is_special)
{
NS_Type ns = g_ns_manager->GetNsTypeAt(animated_element->ResolveNsIdx(attribute_location.GetNsIdxOrSpecialNs()));
BOOL is_presentation_attribute = ns == NS_SVG && SVGUtils::IsPresentationAttribute(attribute_location.animated_name);
if (base_animation_value.value_type == SVGAnimationValue::VALUE_EMPTY && is_presentation_attribute)
SVGAnimationValue::SetCSSProperty(attribute_location, base_animation_value, context);
}
SVGAnimationInterval *active_interval = schedule.GetActiveInterval(document_time);
SVG_ANIMATION_INTERVAL_POSITION interval_position;
SVG_ANIMATION_INTERVAL_REPETITION interval_repetition;
active_interval->CalculateIntervalPosition(document_time, interval_position,
interval_repetition);
SVGAnimationCalculator calculator(animation_workplace, iter->animation,
target, iter->timing_arguments,
iter->animation_arguments, iter->from_value_cache, iter->to_value_cache);
status = calculator.ApplyAnimationAtPosition(interval_position,
interval_repetition,
animation_value,
base_animation_value,
context);
is_active = TRUE;
SVGObject::DecRef(cloned_base_svg_object);
base_svg_object = animation_svg_object;
}
}
BOOL was_active = FALSE;
if (is_active)
was_active = attribute->ActivateAnimationObject(computed_field);
else
{
was_active = attribute->DeactivateAnimation();
if (animated_element->HasSpecialAttr(Markup::SVGA_ANIMATE_TRANSFORM_ADDITIVE, SpecialNs::NS_SVG))
{
animated_element->SetSpecialAttr(Markup::SVGA_ANIMATE_TRANSFORM_ADDITIVE,
ITEM_TYPE_NUM, NUM_AS_ATTR_VAL(1),
FALSE, SpecialNs::NS_SVG);
}
}
if (SVGDocumentContext *element_doc_ctx = AttrValueStore::GetSVGDocumentContext(animated_element))
{
BOOL has_changed = is_active != was_active || !old_svg_object->IsEqual(*animation_svg_object);
if (has_changed)
{
NS_Type ns = g_ns_manager->GetNsTypeAt(animated_element->ResolveNsIdx(attribute_location.ns_idx));
SVGDynamicChangeHandler::HandleAttributeChange(element_doc_ctx,
animated_element,
attribute_location.animated_name, ns, FALSE);
}
}
return status;
}
/* static */ BOOL
SVGAnimationSandwich::HasHigherPriority(SVG_ANIMATION_TIME document_time,
SVGAnimationSlice &item,
SVGAnimationSchedule &new_schedule,
SVG_ANIMATION_TIME new_begin_time,
HTML_Element *new_elm)
{
/* Lists are sorted by begin time. If the begin times are equal,
we evaluate if one is time dependant of the other. Time
dependants has higher priority. The specification doesn't tell
what to do if there are time dependencies both ways, so that
case is undefined.
In the case where there are no time dependency between the two,
the logical order is used. */
SVGAnimationSchedule &schedule = item.animation->AnimationSchedule();
SVG_ANIMATION_TIME begin_time = schedule.GetNextBeginTime(document_time, item.animation_arguments);
if (new_begin_time > begin_time)
return TRUE;
else if (begin_time == new_begin_time)
{
if (schedule.HasDependant(&new_schedule))
return TRUE;
else if (!new_schedule.HasDependant(&schedule))
{
HTML_Element *elm = item.animation->GetElement();
if (elm->Precedes(new_elm))
return TRUE;
}
}
return FALSE;
}
SVGObject*
SVGAnimationSandwich::GetBaseObject(SVGAnimationAttributeLocation &location)
{
if (location.base_name == Markup::HA_XML)
return NULL;
SVGAttribute *attribute = AttrValueStore::GetSVGAttr(target->TargetElement(),
attribute_location.base_name,
attribute_location.ns_idx,
FALSE);
SVGObject* presentation_object = attribute ? attribute->GetSVGObject(SVG_ATTRFIELD_BASE, SVGATTRIBUTE_AUTO) : NULL;
if (presentation_object && !presentation_object->Flag(SVGOBJECTFLAG_UNINITIALIZED))
return presentation_object;
else
return NULL;
}
OP_STATUS
SVGAnimationSandwich::GetAnimationObject(HTML_Element* target_elm,
SVGAttribute*& attribute,
SVGObject*& obj,
SVGAnimationAttributeLocation &location,
SVGAttributeField &computed_field)
{
HTML_Element *animated_element = target->TargetElement();
Markup::AttrType attribute_name = location.animated_name;
int ns_idx = location.GetNsIdxOrSpecialNs();
BOOL is_special = location.is_special;
obj = NULL;
if (attribute == NULL)
{
attribute = OP_NEW(SVGAttribute, (NULL));
if (!attribute)
return OpStatus::ERR_NO_MEMORY;
if (is_special)
{
OP_ASSERT(Markup::IsSpecialAttribute(attribute_name));
if (target_elm->SetSpecialAttr(attribute_name, ITEM_TYPE_COMPLEX,
attribute, TRUE, static_cast<SpecialNs::Ns>(ns_idx)) < 0)
return OpStatus::ERR_NO_MEMORY;
}
else
{
OP_ASSERT(!Markup::IsSpecialAttribute(attribute_name));
if (target_elm->SetAttr(attribute_name, ITEM_TYPE_COMPLEX,
attribute, TRUE, ns_idx) < 0)
return OpStatus::ERR_NO_MEMORY;
}
}
NS_Type attr_ns = is_special ? NS_SPECIAL : g_ns_manager->GetNsTypeAt(target_elm->ResolveNsIdx(ns_idx));
BOOL matches_css_value = ((location.type == SVGATTRIBUTE_CSS || location.type == SVGATTRIBUTE_AUTO) &&
attr_ns == NS_SVG && SVGUtils::IsPresentationAttribute(attribute_name));
computed_field = matches_css_value ? SVG_ATTRFIELD_CSS : SVG_ATTRFIELD_ANIM;
obj = attribute->GetAnimationSVGObject(location.type);
if (obj == NULL)
{
RETURN_IF_ERROR(AttrValueStore::CreateDefaultAttributeObject(animated_element, attribute_name, ns_idx, is_special, obj));
if (matches_css_value)
obj->SetFlag(SVGOBJECTFLAG_IS_CSSPROP);
if (OpStatus::IsMemoryError(attribute->SetAnimationObject(computed_field, obj)))
{
OP_DELETE(obj);
return OpStatus::ERR_NO_MEMORY;
}
else
return OpStatus::OK;
}
return attribute->SetAnimationObject(computed_field, obj);
}
/* virtual */ OP_STATUS
SVGAnimationSandwich::HandleAccessKey(uni_char access_key, SVG_ANIMATION_TIME document_time)
{
SVGAnimationSlice *iter;
for (iter = animations.First(); iter; iter = iter->Suc())
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
RETURN_IF_MEMORY_ERROR(schedule.HandleAccessKey(access_key, document_time, iter->animation->GetElement()));
}
return OpStatus::OK;
}
/* virtual */ OP_STATUS
SVGAnimationSandwich::Prepare(SVGAnimationWorkplace* animation_workplace)
{
SVGAnimationSlice* iter;
for (iter = animations.First(); iter; iter = iter->Suc())
{
SVGAnimationSchedule& schedule = iter->animation->AnimationSchedule();
RETURN_IF_MEMORY_ERROR(schedule.Prepare(animation_workplace, iter->animation,
iter->timing_arguments, target->TargetElement()));
}
return OpStatus::OK;
}
/* virtual */ void
SVGAnimationSandwich::RemoveElement(SVGAnimationWorkplace* animation_workplace,
HTML_Element *element,
BOOL &remove_item)
{
SVGAnimationSlice* iter;
for (iter = animations.First(); iter;)
{
SVGAnimationSlice* tmp = iter;
iter = iter->Suc();
if (tmp->animation->GetElement() == element)
{
SVGAnimationSchedule &schedule = tmp->animation->AnimationSchedule();
schedule.Destroy(animation_workplace, tmp->animation, tmp->timing_arguments, target->TargetElement());
tmp->Out();
OP_DELETE(tmp);
}
}
remove_item = animations.Empty();
}
/* virtual */ void
SVGAnimationSandwich::UpdateTimingParameters(HTML_Element* element)
{
SVGAnimationSlice* iter;
for (iter = animations.First(); iter; iter = iter->Suc())
if (iter->animation->GetElement() == element)
{
iter->animation->SetTimingArguments(iter->timing_arguments);
SVGAnimationSchedule &schedule =
iter->animation->AnimationSchedule();
schedule.MarkInstanceListsAsDirty();
break;
}
}
/* virtual */ void
SVGAnimationSandwich::Deactivate()
{
HTML_Element* animated_element = target->TargetElement();
SVGAttribute *attribute = AttrValueStore::GetSVGAttr(animated_element,
attribute_location.animated_name,
attribute_location.GetNsIdxOrSpecialNs(),
attribute_location.is_special);
if (attribute)
attribute->DeactivateAnimation();
#ifdef SVG_APPLY_ANIMATE_MOTION_IN_BETWEEN
// Remove/reset the additive flag if we set one.
animated_element->RemoveSpecialAttribute(Markup::SVGA_ANIMATE_TRANSFORM_ADDITIVE, SpecialNs::NS_SVG);
#endif // SVG_APPLY_ANIMATE_MOTION_IN_BETWEEN
}
/* virtual */ OP_STATUS
SVGAnimationSandwich::RecoverFromError(SVGAnimationWorkplace *animation_workplace, HTML_Element *element)
{
SVGAnimationSlice *iter;
for (iter = animations.First(); iter; iter = iter->Suc())
{
if (iter->animation->GetElement() == element)
{
SVGAnimationSchedule &schedule = iter->animation->AnimationSchedule();
RETURN_IF_MEMORY_ERROR(schedule.TryRecoverFromError(animation_workplace, iter->animation, iter->timing_arguments, NULL));
}
}
return OpStatus::OK;
}
#endif // SVG_SUPPORT
|
#include "BlackScholesMertonPut.hpp"
BlackScholesMertonPut::BlackScholesMertonPut(double _S0, double _E, double _r, double _sigma, double _T)
: BlackScholesMerton(_S0, _E, _r, _sigma, _T) {}
double BlackScholesMertonPut::calculate(const double t) {
double time_diff = this->T - t;
double d1 = this->calculate_d1(time_diff);
double d2 = this->calculate_d2(time_diff, d1);
double NNegd1 = cumulative_dist_of_stan_norm(-d1);
double NNegd2 = cumulative_dist_of_stan_norm(-d2);
return this->E * exp(-this->r * time_diff) * NNegd2 - this->S0 * exp(-this->q * time_diff) * NNegd1;
}
BlackScholesMertonPut::BlackScholesMertonPut(double _S0, double _E, double _r, double _sigma, double _T, double _q)
: BlackScholesMerton(_S0, _E, _r, _sigma, _T, _q) {
}
double BlackScholesMertonPut::delta(double t) {
double tau = this->T - t;
return -exp(-this->q * tau) * cumulative_dist_of_stan_norm(-this->calculate_d1(tau));
}
double BlackScholesMertonPut::theta(double t) {
double tau = this->T - t;
double tau_sqrt = sqrt(tau);
double d1 = this->calculate_d1(tau);
double d2 = this->calculate_d2(tau, d1);
double first = exp(-this->q * tau) * ((this->S0 * stand_normal_dist(d1) * this->sigma) / (2 * tau_sqrt));
double second = this->r * this->E * exp(-this->r * tau) * cumulative_dist_of_stan_norm(-d2);
double third = this->q * this->S0 * exp(-this->q * tau) * cumulative_dist_of_stan_norm(-d1);
return -first + second - third;
}
double BlackScholesMertonPut::rho(double t) {
double tau = this->T - t;
return -this->E * tau * exp(-r * tau) * cumulative_dist_of_stan_norm(-this->calculate_d2(tau));
}
double BlackScholesMertonPut::charm(double t) {
double tau = this->T - t;
double tau_sqrt = sqrt(tau);
double d1 = this->calculate_d1(tau);
double d2 = this->calculate_d2(tau, d1);
double eqt = exp(-this->q * tau);
return -this->q * eqt * cumulative_dist_of_stan_norm(-d1) - eqt * stand_normal_dist(d1) *
((2 * (r - this->q) * tau -
d2 * this->sigma * tau_sqrt) /
(2 * tau * this->sigma * tau_sqrt));
}
|
/*
https://www.acmicpc.net/problem/1193
*/
#include <iostream>
using namespace std;
int main(void)
{
int num;
scanf("%d", &num);
int i;
for (i = 1; num > 0; i++)
num -= i;
i -= 1;
// i가 홀수인 줄은 내림차(높->낮)
// i가 짝수인 줄은 오름차(낮->높)
if (i % 2 == 1)
printf("%d/%d", 1 - num, i + num);
else
printf("%d/%d", i + num, 1 - num);
return 0;
}
|
#include "cnn_multi_tracker.h"
#include "../game/object_info.h"
#include "detector/detector.h"
namespace ice
{
CNNMultiTracker::CNNMultiTracker() :
key_max_(0)
{
OnInit();
}
CNNMultiTracker::~CNNMultiTracker()
{
OnDestroy();
}
void CNNMultiTracker::OnInit()
{
}
void CNNMultiTracker::OnDestroy()
{
//delete object
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
if (obj_itr->second)
delete obj_itr->second;
obj_itr->second = NULL;
}
}
bool CNNMultiTracker::IsOutboard(cv::Rect & positionBox)
{
int cent_x = positionBox.x + (positionBox.width >> 1);
int cent_y = positionBox.y + (positionBox.height >> 1);
//check if out of board
if (
cent_x < 0 || // outboard
cent_y < 0 ||
cent_x >= bound_mask_.cols ||
cent_y >= bound_mask_.rows ||
bound_mask_.at<uchar>(cent_y, cent_x) == 0
)
{
return true;
}
else
{
return false;
}
}
void CNNMultiTracker::AddTracker(cv::Mat & frame, cv::Rect & positionBox)
{
positionBox &= cv::Rect(0, 0, frame.cols, frame.rows);
int cent_x = positionBox.x + (positionBox.width >> 1);
int cent_y = positionBox.y + (positionBox.height >> 1);
//check if out of board
if (IsOutboard(positionBox)) return;
//else
int index = GetIndex_();
LOG(INFO) << "add tracker GetIndex_=" << index <<", loc: " << positionBox;
object_info_map_[index] = new ObjectInfo(index, cv::Point(cent_x, cent_y), positionBox);
}
void CNNMultiTracker::OnUpdate(cv::Mat & frame)
{
cv::Mat highest_mat = frame.clone();
static Stopwatch T_detect("detect");
LOG(INFO) << "Trackers number: " << object_info_map_.size();
//net forward to get every object newest loc.
static std::vector<std::vector<cv::Rect> > obj_boxes;
static std::vector<cv::Rect> scale_rect_bais;
static std::vector<std::vector<float> > score;
static std::vector<cv::Mat> mat_vec;
mat_vec.clear(), obj_boxes.clear(), score.clear(), scale_rect_bais.clear();
//////////////////////////////////////////////////////////////////
//For 1: clear objects when Iou > thresh over objs themselves;
//For 2: check the probility of collision between objects;
//
//Reset SearchRatio
for(auto& iter : object_info_map_) iter.second->SearchRatio() = 2.0;
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
if(obj_itr->second->IsShit() == true) continue;
std::map<size_t, ObjectInfo*>::iterator obj_j = obj_itr;
++obj_j;
for (; obj_j != obj_end_itr; ++obj_j)
{
//For 1
cv::Rect in = (obj_itr->second->Box() & obj_j->second->Box());
float t = max((float)in.area() / obj_itr->second->Box().area(), (float)in.area() / obj_j->second->Box().area());
if (t > 0.8)
{
//the later one of them should be shit
//obj_itr->second->IsShit() = true;
obj_j->second->IsShit() = true;
}
//For 2
static double factor = 1.5;
int dist = L1distanceOfCentroid(obj_itr->second->Box(), obj_j->second->Box());
double ratio_w_u = (float)dist / obj_itr->second->Box().width * factor;
double ratio_h_u = (float)dist / obj_itr->second->Box().height * factor;
double ratio_u = min(ratio_w_u, ratio_h_u);
obj_itr->second->SearchRatio() = min(obj_itr->second->SearchRatio(), ratio_u);
double ratio_w_v = (float)dist / obj_j->second->Box().width * factor;
double ratio_h_v = (float)dist / obj_j->second->Box().height * factor;
double ratio_v = min(ratio_w_v, ratio_h_v);
obj_j->second->SearchRatio() = min(obj_j->second->SearchRatio(), ratio_v);
//LOG(INFO) << "[dist, obj_itr->second->Box().width, height]: " << dist << ", " << obj_itr->second->Box().width << "," << obj_itr->second->Box().height;
//LOG(INFO) << "[ratio_w, ratio_h, obj_itr->second->SearchRatio()]: " << ratio_w << ", " << ratio_h << "," <<obj_itr->second->SearchRatio();
}
//For 2 , at least expand to 1.2, and at most expand to 2.0
obj_itr->second->SearchRatio() = max(obj_itr->second->SearchRatio(), 1.4);
obj_itr->second->SearchRatio() = min(obj_itr->second->SearchRatio(), 2.0);
}
//////////////////////////////////////////////////////////////////
//update cnn tracker
obj_itr = object_info_map_.begin();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
cv::Rect& loc = obj_itr->second->Box();
cv::Rect scale_rect = scaleRect(loc, 2.0);
cv::Rect actual_rect = scaleRect(loc, obj_itr->second->SearchRatio());
scale_rect &= cv::Rect(0, 0, frame.cols, frame.rows);
actual_rect &= cv::Rect(0, 0, frame.cols, frame.rows);
scale_rect_bais.push_back(scale_rect);
cv::Mat actual_roi = frame(actual_rect);
cv::Mat merged(cv::Size(scale_rect.width, scale_rect.height), actual_roi.type());
merged = cv::Scalar::all(127.5);
//cv::imshow("a-merged", merged);
cv::Rect actual_loc((scale_rect.width - actual_rect.width) / 2.0, (scale_rect.height - actual_rect.height) / 2.0, actual_rect.width, actual_rect.height);
actual_roi.copyTo(merged(actual_loc));
mat_vec.push_back(merged);
cv::imshow("b-merged", merged);
//cv::Mat scale_roi = frame(scale_rect);
//cv::imshow("roix2", scale_roi);
//cv::waitKey(0);
//cv::waitKey(0);
}
T_detect.Reset(); T_detect.Start();
Detector::Instance()->Detect(mat_vec, obj_boxes, score, Detector::DETECTOR_SCALE_LOCAL);
T_detect.Stop();
LOG(INFO) << "local model detection cost: " << T_detect.GetTime();
obj_itr = object_info_map_.begin();
for (int i = 0; obj_itr != obj_end_itr; ++obj_itr, ++i)
{
//LOG(INFO) << "scale_roi detect number: " << obj_boxes.size();
if(!obj_boxes[i].empty())
{
//std::cout << "score:" <<std::endl;
//for(auto& s:score[i]) std::cout << s << ",";
//std::cout << "box:" <<std::endl;
//for(auto& r:obj_boxes[i]) std::cout << r << ",";
//std::cout << std::endl;
//find top 1 score and box, update object loc.
std::vector<float>::iterator biggest = std::max_element(std::begin(score[i]), std::end(score[i]));
cv::Rect& highest_rect = obj_boxes[i].at(std::distance(std::begin(score[i]), biggest));
//LOG(INFO) << "-scale_rect box: " << scale_rect_bais[i];
//LOG(INFO) << "-highest rect: " << highest_rect;
//highest_rect &= cv::Rect(0, 0, scale_rect.width, scale_rect.height);
//if(highest_rect.width == 0 || highest_rect.height == 0) continue;
//cv::rectangle(mat_vec[i], highest_rect, cv::Scalar(255, 0, 0), 2);
//cv::imshow("scale", mat_vec[i]);
highest_rect.x += scale_rect_bais[i].x;
highest_rect.y += scale_rect_bais[i].y;
int cent_x = highest_rect.x + (highest_rect.width >> 1);
int cent_y = highest_rect.y + (highest_rect.height >> 1);
obj_itr->second->GetTrace().push_back(cv::Point(cent_x, cent_y));
obj_itr->second->Box() = highest_rect;
obj_itr->second->ClearMiss();
//cv::Mat img = frame.clone();
cv::rectangle(highest_mat, highest_rect, cv::Scalar(255, 250, 250), 2);
//cv::imshow("highest", img);
//cv::waitKey(0);
}
else
{
//could not find any detection around it, maybe the obj is background.
//Here should be marked.
obj_itr->second->AddToMiss();
}
//cv::waitKey(0);
obj_itr->second->OnUpdate(bound_mask_, frame);
}
cv::imshow("highest", highest_mat);
}
void CNNMultiTracker::Mark(size_t index)
{
}
void CNNMultiTracker::RemoveInvalid()
{
//search invalid object's index
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
if (obj_itr->second->IsShit())
invalid_index_list_.push_back(obj_itr->first);
}
//move invalid object to recycle by index
std::list<size_t>::iterator iil_it = invalid_index_list_.begin();
std::list<size_t>::iterator iil_end_it = invalid_index_list_.end();
for (; iil_it != iil_end_it; ++iil_it)
{
size_t idx = *iil_it;
//LOG(INFO) << "remove tracker index : " << idx;
RemoveTrackerByIndex_(idx);
//index_pool_set_.insert(idx);
}
invalid_index_list_.clear();
}
void CNNMultiTracker::RemoveTrackerByIndex_(size_t index)
{
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.find(index);
if (obj_itr != object_info_map_.end())
{
//obj_itr->second->SetEndTime(getSystemTime());
delete obj_itr->second;
object_info_map_.erase(obj_itr);
}
}
void CNNMultiTracker::Replace(cv::Mat & frame, cv::Rect & positionBox, size_t index)
{
}
std::vector<cv::Scalar> color_pool =
{
CV_RGB(255, 0, 0),
CV_RGB(255, 128, 0),
CV_RGB(0, 255, 0),
CV_RGB(0, 255, 255),
CV_RGB(128, 0, 255),
};
void CNNMultiTracker::DrawTrace(cv::Mat& frame)
{
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
//if (obj_itr->second->CanBeRecycle() == true)
{
std::list<cv::Point>::iterator point_it = obj_itr->second->GetTrace().begin();
if (obj_itr->second->GetTrace().size() > 20)
{
std::advance(point_it, obj_itr->second->GetTrace().size() - 20);
}
std::list<cv::Point>::iterator point_end_it = obj_itr->second->GetTrace().end();
for (; point_it != point_end_it; ++point_it)
{
cv::circle(frame, *point_it, 0, color_pool[obj_itr->first % color_pool.size()], 2, 1);
}
cv::Rect banner(obj_itr->second->Box().x - 1, obj_itr->second->Box().y - 20, obj_itr->second->Box().width + 2, 20);
banner &= cv::Rect(0, 0, frame.cols, frame.rows);
frame(banner) = color_pool[obj_itr->first % color_pool.size()];
cv::rectangle(frame, obj_itr->second->Box(), color_pool[obj_itr->first % color_pool.size()], 2, 1, 0);
//cv::putText(frame, std::to_string(obj_itr->first).c_str(), cv::Point(obj_itr->second->Box().x, obj_itr->second->Box().y - 4), 1, 0.9, CV_RGB(0, 0, 0), 1);
//cv::putText(frame, std::to_string(obj_itr->second->SynceOver()).c_str(), cv::Point(obj_itr->second->Box().x + 10, obj_itr->second->Box().y + 20), 2, 0.5, color_pool[obj_itr->first % color_pool.size()], 1);
cv::putText(frame, std::to_string(obj_itr->second->Life()).c_str(), cv::Point(obj_itr->second->Box().x + 10, obj_itr->second->Box().y + 30), 2, 0.4, color_pool[obj_itr->first % color_pool.size()], 1);
}
}
}
////////////////////////////////////////////////////////////
//Draw UI in a high-quality image
////////////////////////////////////////////////////////////
void CNNMultiTracker::DrawUI(cv::Mat& frame)
{
int mg_x = g_margin * ((float)frame.cols / g_detect_win.width);
int mg_y = g_margin * ((float)frame.rows / g_detect_win.height) * 0.7;
cv::Rect bound(mg_x, mg_y,
frame.cols - 2 * mg_x, frame.rows - 2 * mg_y);
cv::rectangle(frame, bound, CV_RGB(125,255, 190), 3, 1, 0);
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
if (obj_itr->second->IsShit() == false)
{
std::list<cv::Point>::iterator point_it = obj_itr->second->GetTrace().begin();
if (obj_itr->second->GetTrace().size() > 20)
{
std::advance(point_it, obj_itr->second->GetTrace().size() - 20);
}
std::list<cv::Point>::iterator point_end_it = obj_itr->second->GetTrace().end();
static float fractor_x = (float)frame.cols / g_detect_win.width;
static float fractor_y = (float)frame.rows / g_detect_win.height;
for (; point_it != point_end_it; ++point_it)
{
cv::Point dot(int(point_it->x * fractor_x), int(point_it->y * fractor_y));
cv::circle(frame, dot, 0, color_pool[obj_itr->first % color_pool.size()], 2, 1);
}
cv::Rect head_box;
head_box.x = int(obj_itr->second->Box().x * fractor_x);
head_box.y = int(obj_itr->second->Box().y * fractor_y);
head_box.width = int(obj_itr->second->Box().width * fractor_x);
head_box.height = int(obj_itr->second->Box().height * fractor_y);
cv::Rect banner(head_box.x - 1, head_box.y - 20, head_box.width + 2, 20);
banner &= cv::Rect(0, 0, frame.cols, frame.rows);
frame(banner) = color_pool[obj_itr->first % color_pool.size()];
cv::rectangle(frame, head_box, color_pool[obj_itr->first % color_pool.size()], 2, 1, 0);
cv::putText(frame, std::string("ID ") + std::to_string(obj_itr->first).c_str(), cv::Point(head_box.x, head_box.y - 4), 1, 0.9, CV_RGB(0, 0, 0), 1);
cv::putText(frame, std::string("Ratio ") + std::to_string(obj_itr->second->SearchRatio()).substr(0, 4).c_str(), cv::Point(head_box.x, head_box.y + 15), 2, 0.4, CV_RGB(255, 2, 215), 1);
cv::putText(frame, std::string("MissTime ") + std::to_string(obj_itr->second->MissTime()).c_str(), cv::Point(head_box.x, head_box.y + 35), 2, 0.4, color_pool[obj_itr->first % color_pool.size()], 1);
}
}
}
void CNNMultiTracker::SetAllMatchFalse()
{
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.begin();
std::map<size_t, ObjectInfo*>::iterator obj_end_itr = object_info_map_.end();
for (; obj_itr != obj_end_itr; ++obj_itr)
{
obj_itr->second->SetMatchFalse();
}
}
void CNNMultiTracker::SetMatchTrue(size_t index)
{
std::map<size_t, ObjectInfo*>::iterator obj_itr = object_info_map_.find(index);
//if(obj_itr != object_info_map_.end())
obj_itr->second->SetMatchTrue();
}
void CNNMultiTracker::SetBound(cv::Size size, cv::Rect bound)
{
bound_mask_ = cv::Mat(size, CV_8UC1);
bound_mask_ = cv::Scalar::all(0);
bound_mask_(bound) = cv::Scalar::all(255);
//cv::imshow("bound", bound_mask_);
//cv::waitKey(0);
}
int CNNMultiTracker::GetIndex_()
{
if (index_pool_set_.empty())
{
return ++key_max_;
}
else
{
int index = *(index_pool_set_.begin());
index_pool_set_.erase(index_pool_set_.begin());
return index;
}
}
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "kinect2ArrayProject.h"
#include "k2Array.h"
#include <math.h>
//General Log
DEFINE_LOG_CATEGORY(logK2Array);
// Sets default values
Ak2Array::Ak2Array()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Texture = nullptr;
UE_LOG(logK2Array, Warning, TEXT("Constructor >> Hello World!")); //temp msg
}
// Called when the game starts or when spawned
void Ak2Array::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void Ak2Array::Tick( float DeltaTime )
{
Super::Tick( DeltaTime );
// schedule a task on the render thread
ENQUEUE_UNIQUE_RENDER_COMMAND_TWOPARAMETER(
UpdateTextureData,
UTexture2D*, Texture, Texture,
TArray<FColor>&, Array, TextureData,
{
UpdateTextureData(Texture, Array);
}
);
}
// save the texture in a var (must be a BlueprintCallable UFUNCTION)
void Ak2Array::SetTexture(UTexture2D* Texture)
{
this->Texture = Texture;
}
// update the array reading the texture pixels on render thread
void Ak2Array::UpdateTextureData(UTexture2D* Texture, TArray<FColor>& TextureData)
{
if (!Texture || !Texture->IsValidLowLevel()) return;
// the amount of pixels in the texture
const int32 NumPixels = Texture->GetSizeX() * Texture->GetSizeY();
// lock the texture memory
FColor* TextureBuffer = static_cast<FColor*>(Texture->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_ONLY));
// fastest way (I think) of copying it to the array
TextureData.SetNum(NumPixels); // make sure there's the right amount of memory reserved on this array
FMemory::Memcpy(TextureData.GetData(), TextureBuffer, sizeof(FColor) * NumPixels);
/* ^^^ It may be that the data from the Kinect camera (via the texture buffer) has been configured or optimized in some unexpected way.
This function gets good results with basic texture settings (no mipMaps, and basic compression - for eg. try 'T_radialGradient1_D').
Using any of the Kinect camera's as an input texture returns a constant gray value.
This is the same gray value you'd get running the function without a Kinect even connected.
It may be possible to copy the texture buffer data into a temporary texture, and then reconfigure the texture to make it readable.
The settings might take some experimentation; but, 'no mipMap' and 'VectorDisplacementmap (RGBA8)' seem like a good place to start.
What do you think? */
// unlock the texture (very important!!)
Texture->PlatformData->Mips[0].BulkData.Unlock();
}
// the pixels are in a linear sequence. This function just makes it easier to get them from x and y coordinates
FColor Ak2Array::SampleTextureAt(int32 X, int32 Y)
{
if (!Texture || !Texture->IsValidLowLevel()) return FColor();
const int32 SizeX = Texture->GetSizeX(),
SizeY = Texture->GetSizeY();
// check for valid coordinates
if (X >= 0 && X < SizeX && Y >= 0 && Y < SizeY)
{
return TextureData[Y * SizeX + X];
}
// coordinates were invalid!
return FColor();
}
/* moves objects in array according to pixel values - must be a fast as possible.
I guess speed will come, and in the meantime if it woks... ;) */
void Ak2Array::transform_Array(TArray<FColor> txtrData, TArray<UStaticMeshComponent*> objectArray, bool bVerbose, int32 pxPerUnit=8, int32 depthScalar=100)
{
// Local Variables
UStaticMeshComponent* object; //object to be moved - as a pointer
FVector location; //object's current location - xyz
int32 txtrSize; //texture's x&y dimension - assumes square texture
int32 pxIndx = 0; //pixel array index
FVector pxVctr; //pixel colour as vector - xyz
//const int32 depthScalar = 125; //scale vector y axis ### depthScalar will become a blueprint property
if (txtrData.Num()) { // warning, pixel array may still be empty shortly after initialization
txtrSize = sqrt(txtrData.Num()); // texture's x&y dimension - assumes square texture
for (int32 i = 0; i < objectArray.Num(); i++) //iterate over all objects in objectArray
{
object = objectArray[i]; //get object
location = object->GetComponentLocation(); //get object location
pxIndx = (i * pxPerUnit % txtrSize) + (i * pxPerUnit / txtrSize * txtrSize * pxPerUnit); //calculate corresponding pixel index
pxVctr = FVector(txtrData[pxIndx]); //get pixel colour as a vector - xyz
object->SetWorldLocation(FVector(location[0], pxVctr[1] * depthScalar, location[2])); //use vector (*depthScalar) to update object's y-location (one RGBA channel)
if (bVerbose == 1) { UE_LOG(logK2Array, Warning, TEXT("#### >> transform_Array >> %f, %f, %f"), pxVctr[0], pxVctr[1], pxVctr[2]); } //log message
}
}
}
|
/* LIBRARIES */
#include <LiquidCrystal_I2C.h>
#include <PID_v1.h>
#include "constants.h"
#include "SD_management.h"
#include "voltage_management.h"
#define DEBUG
/*
#ifdef DEBUG
...
#endif
*/
/* VARIABLES AND CONSTANTS */
/***************Voltage output**********************/
// Readeable values from ADC
// Global values
unsigned char Vs = Vs_DF; // Voltage Source Output (PID Setpoint)
unsigned char Is = Is_DF; // Current Source Output
// PWM for High Voltage output variables
unsigned int TP = T_DF; // (Signal Period[ms])
unsigned int PW = PW_DF; // (Signal Pulse Width[ms])
unsigned int R = R_DF; // Default resistance value in ohms
unsigned int Tt = 0;
unsigned int NP = NP_DF; // Signal Number of pulses normalized
unsigned long TP_start = 0; // Restarting Period counter
unsigned long TT_stop = 0; // Auxiliary period time counter
bool VSAFE = false; // Voltage Safe Verifier
bool goWAVE = false; // Wave DEFAULT enabler
bool goWAVESD = false; // Wave FROM SD enabler
bool goSETV = false;
bool goVS = false;
bool goIS = false;
bool goRMEA = false;
bool goR = false;
/**********************PID**************************/
/************************LCD************************/
LiquidCrystal_I2C lcd(I2C_ADDR, EN_PIN, RW_PIN, RS_PIN, D4_PIN,
D5_PIN, D6_PIN, D7_PIN, BACKLIGHT_PIN, POSITIVE);
unsigned char screen = 1; // Screen selector, default 1 -> Voltage Range Test
unsigned char posX = 0;
unsigned char posY = 0;
byte slct[8] = { // Cursor
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111,
B11111
};
const byte KPinterruptPin = 2; // Interrupt Pin association
/***********************Keypad**********************/
unsigned char button = NO_BUTTON; // Last button pressed
unsigned short v_A2 = 0; // Readeable values for keyboard
/***********************Interrupts******************/
/***********************SD**************************/
unsigned short NofFiles = 0;
unsigned short posDIR = 0;
String info_file;
String root_path = "/";
String act_dir_path = "/";
String PSETname = "P_";
String DATAname = "D_";
String PSET = "";
void setup() {
// GENERAL AND DEBUG CONFIG
#ifdef DEBUG
// Initializing serial:
Serial.begin(9600);
#endif
// KEYPAD CONFIG
pinMode(KPinterruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(KPinterruptPin), keypad_management, RISING);
// LCD CONFIG
lcd.begin(20, 4);
lcd.createChar(0, slct);
// PID
// VOLTAGE OUTPUT
// Making the pins PWM and SW outputs:
pinMode(PWMR, OUTPUT);
pinMode(SW, OUTPUT);
// Making the pins ADC inputs:
pinMode(A0, INPUT); // Voltage before switch
pinMode(A1, INPUT); // Voltage on leads
pinMode(A2, INPUT); // Keypad output
// Default pins values:
digitalWrite(SW, LOW);
analogWrite(PWMR, 0);
// Voltage Test Range
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Voltage Test Range"));
while (!VTR()) {
VSAFE = false;
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F("TEST FAILURE!"));
lcd.setCursor(0, 2);
lcd.print(F("To try again"));
lcd.setCursor(0, 3);
lcd.print(F("press RUN."));
button = NO_BUTTON;
while (button != 1) {
keypad_management();
delay(SB_T);
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Voltage Test Range"));
}
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F("VTR Successful!"));
delay(SB_T);
lcd.clear();
// microSD
SD_check();
button = NO_BUTTON;
}
bool VTR() {
for (Vs = Vs_MAX; Vs > Vs_MIN; Vs -= 10) {
VSAFE = voltage_setup(VSAFE, Vs);
if (!VSAFE) {
delay(SB_T);
return VSAFE;
}
lcd_management(1);
}
Vs = Vs_MIN;
VSAFE = voltage_setup(VSAFE, Vs);
lcd_management(1);
delay(SB_T);
return VSAFE;
}
// SCREEN MANAGEMENT
void SD_check() {
lcd.setCursor(0, 0);
lcd.print(F("Checking SD card"));
goWAVESD = SD.begin(CHIP_SELECT);
button = NO_BUTTON;
while (!goWAVESD && button != 3) {
lcd.setCursor(0, 1);
lcd.print(F("Couldn't read card."));
lcd.setCursor(0, 2);
lcd.print(F("Try again?"));
lcd.setCursor(0, 3);
lcd.print(F(" RUN CANCEL "));
button = NO_BUTTON;
while (button != 3 && button != 1) {
delay(SB_T / 1000);
}
if (button == 1) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Checking SD card"));
goWAVESD = SD.begin(CHIP_SELECT);
}
lcd.clear();
}
lcd.clear();
if (goWAVESD) {
screen = 2;
} else {
lcd.setCursor(0, 0);
lcd.print(F("WARNING!"));
lcd.setCursor(0, 1);
lcd.print(F("DATA CANNOT BE"));
lcd.setCursor(0, 2);
lcd.print(F("SAVED/LOADED"));
delay(SB_T / 100);
screen = 3;
}
lcd.clear();
}
void VTR_screen() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Voltage Test Range"));
lcd.setCursor(0, 1);
lcd.print(F("VS="));
lcd.setCursor(3, 1);
lcd.print(int(Vs));
lcd.setCursor(6, 1);
if (VSAFE) {
lcd.print(F("PASSED"));
} else {
lcd.print(F("FAILED"));
}
}
void SD_screen() {
NofFiles = num_of_files(act_dir_path);
posDIR = constrain(posDIR, 0, NofFiles - 1);
posY = constrain(posDIR % 4, 0, NofFiles - 1);
lcd.setCursor(0, posY);
lcd.write(byte(0));
for (unsigned short i = (posDIR - (posDIR % 4)); (i - (posDIR - (posDIR % 4))) < 4 && i < NofFiles; i++) {
lcd.setCursor(1, i - (posDIR - (posDIR % 4)));
lcd.print(givemeNpreset_SD(i, act_dir_path));
}
delay(SB_T / 2);
lcd.clear();
switch (button) {
case 3:
//CANCEL
posDIR = 0;
act_dir_path.remove(0);
act_dir_path.trim();
act_dir_path = root_path;
break;
case 4:
//NEW
lcd.setCursor(0, 0);
lcd.print(F(" Please enter a name"));
name_screen();
if (!(PSETname == String("P_"))) {
DATAname = String("D_" + PSETname.substring(2, PSETname.lastIndexOf(".")) + ".csv");
screen = 3;
goSETV = true;
lcd.clear();
}
break;
case 1:
case 6:
button = NO_BUTTON;
if (ask_preset(posDIR, act_dir_path)) {
PSETname.remove(0);
PSETname.trim();
PSETname = (givemeNpreset_SD(posDIR, act_dir_path));
DATAname = String("D_" + PSETname.substring(2, PSETname.lastIndexOf(".")) + ".csv");
info2parameters(load_SD(posDIR, act_dir_path));
goSETV = true;
screen = 3;
posY = 0;
posX = 0;
}
break;
case 8:
//UP
posDIR--;
break;
case 10:
//LEFT (close directory)
if ((act_dir_path != root_path)) {
act_dir_path.remove(act_dir_path.lastIndexOf("/"));
act_dir_path.remove(act_dir_path.lastIndexOf("/") + 1);
act_dir_path.trim();
posDIR = 0;
}
break;
case 11:
//DOWN
posDIR ++;
break;
case 12:
//RIGHT (open directory)
if (ask_directory(posDIR, act_dir_path)) {
act_dir_path.concat(givemeNpreset_SD(posDIR, act_dir_path));
}
break;
default:
//NO BUTTON
break;
}
button = NO_BUTTON;
}
void name_screen() {
unsigned char n = 2;
bool cnfirm = false;
unsigned char input = 'a';
button = NO_BUTTON;
PSETname = String("P_ ");
while (!cnfirm && button != 3) {
lcd.setCursor(0, 2);
lcd.print(F(" CONFIRM "));
lcd.setCursor(0, 3);
lcd.print(F(" RUN CANCEL "));
lcd.setCursor(0, 1);
lcd.print(F(" "));
lcd.setCursor(0, 1);
lcd.print(PSETname);
input = constrain(input, 0, 255);
lcd.setCursor(n, 1);
lcd.print(char(input));
switch (button) {
case 1: //RUN
if (exists_SD(PSETname, act_dir_path)) {
cnfirm = false;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("This file already"));
lcd.setCursor(0, 1);
lcd.print(F("exists"));
lcd.setCursor(0, 2);
lcd.print(F(" OVERWRITE? "));
lcd.setCursor(0, 3);
lcd.print(F(" RUN CANCEL "));
button = NO_BUTTON;
while (button != 1 && button != 3) {
delay(SB_T);
}
if (button == 1) {
cnfirm = true;
} else {
cnfirm = false;
}
} else {
cnfirm = true;
}
break;
case 8: //up
input++;
break;
case 10: //left
PSETname.setCharAt(n, char(input));
n--;
n = constrain(n, 2, 19);
break;
case 11: //down
input--;
break;
case 12: //right
PSETname.setCharAt(n, char(input));
n++;
n = constrain(n, 2, 19);
break;
default:
break;
}
keypad_management();
delay(SB_T / 3);
}
if (button == 3) {
PSETname = String("P_");
}
button = NO_BUTTON;
PSETname.trim();
lcd.clear();
}
void parameters2info() {
PSET = String("VS=" + String(int(Vs)) + ";" + "IS=" + String(int(Is)) + ";" + "PW=" + String(PW) + ";"
+ "TP=" + String(TP) + ";" + "NP=" + String(NP) + ";" + "TT=" + String(Tt));
}
void info2parameters(String PSET) {
bool goTP = false;
bool goPW = false;
bool goTT = false;
bool goNP = false;
bool goALL = false;
bool goEND = false;
unsigned short p_posSTRING = 0;
unsigned short n_posSTRING = 0;
String token;
n_posSTRING = PSET.indexOf(";", p_posSTRING);
if (PSET.indexOf(";", p_posSTRING) < 0) {
goEND = true;
}
token = PSET.substring(p_posSTRING, n_posSTRING);
token.trim();
while (!goEND && !goALL) {
if ((token.startsWith("VS=")) && !goVS && !goIS) {
Vs = (token.substring(3)).toInt();
Vs = constrain(Vs, Vs_MIN, Vs_MAX);
goVS = true;
}
if ((token.startsWith("IS=")) && !goVS && !goIS) {
Is = (token.substring(3)).toInt();
Is = constrain(Is, Is_MIN, Is_MAX);
goIS = true;
}
if ((token.startsWith("TP=")) && !goTP) {
TP = (token.substring(3)).toInt();
TP = constrain(TP, TP_MIN, TP_MAX);
goTP = true;
}
if ((token.startsWith("PW=")) && !goPW) {
PW = (token.substring(3)).toInt();
PW = constrain(PW, PW_MIN, PW_MAX);
goPW = true;
}
if ((token.startsWith("NP=")) && !goNP) {
NP = (token.substring(3)).toInt();
NP = constrain(NP, NP_MIN, NP_MAX);
goNP = true;
}
if ((token.startsWith("TT=")) && !goTT) {
Tt = (token.substring(3)).toInt();
Tt = constrain(Tt, TT_MIN, TT_MAX);
goTT = true;
}
p_posSTRING = n_posSTRING + 1;
n_posSTRING = PSET.indexOf(";", p_posSTRING);
if (PSET.indexOf(";", p_posSTRING) < 0) {
goEND = true;
}
token = PSET.substring(p_posSTRING, n_posSTRING);
token.trim();
goALL = (goVS || goIS) && ((goTP && goPW && goTT) || (goTP && goPW && goNP) || (goPW && goNP && goTT));
}
if (!goVS) {
Vs = Vs_DF;
}
if (!goIS) {
Is = Is_DF;
}
if (!goTP) {
TP = T_DF;
}
if (!goPW) {
PW = PW_DF;
}
if (!goTT) {
Tt = Tt_DF;
}
if (!goNP) {
NP = NP_DF;
}
if (goVS) {
Is = Vs / R;
}
if (goIS) {
Vs = Is * R;
}
if (goTP && goPW && goTT) {
NP = Tt / TP;
}
if (goTP && goPW && goNP) {
Tt = (NP) * TP;
}
if (goPW && goNP && goTT) {
TP = (Tt) / NP;
}
goSETV = true;
posX = 0;
posY = 0;
}
void PRESET_screen() {
if (goSETV) {
lcd.setCursor(0, 1);
lcd.print (F(" SETTING VOLTAGE "));
VSAFE = voltage_setup(VSAFE, Vs);
if (VSAFE) {
lcd.setCursor(0, 2);
lcd.print(F(" SUCCESS "));
delay(SB_T);
} else {
lcd.setCursor(0, 2);
lcd.print(F(" FAILURE "));
delay(SB_T);
}
lcd.clear();
goSETV = false;
}
lcd.setCursor(0, 0);
lcd.print(F(" VS IS TP PW "));
lcd.setCursor(0, 1);
lcd.print(F(" V m"));
lcd.setCursor(0, 2);
lcd.print(F(" TT R NP RMEA"));
lcd.setCursor(1, 1);
lcd.print(short(CAL_A0 * analogRead(A0)));
Is = (CAL_A0 * analogRead(A0)) * 1000 / R;
Is = constrain(Is, Is_MIN, Is_MAX);
if (Is < 10) {
lcd.setCursor(7, 1);
} else {
lcd.setCursor(6, 1);
}
lcd.print(int(Is));
print_times(11, 1, TP);
PW = constrain(PW, PW_MIN, TP);
print_times(16, 1, PW);
Tt = (NP) * TP;
print_times( 1, 3, Tt);
print_R(6, 3, R);
lcd.setCursor(11, 3);
lcd.print(NP);
lcd.setCursor(17, 3);
if (goR) {
lcd.print(F("YES"));
} else {
lcd.print(F("NO"));
}
lcd.setCursor(posX, posY);
lcd.write(byte(0));
delay(SB_T);
if (button != NO_BUTTON) {
// 1 = RUN 2 = RM 3 = CANCEL
// 4 = NEW 5 = SAVE 6 = LOAD
// 7 = EDIT 8 = UP 9 = DEL
// 10 = LEFT 11 = DOWN 12 = RIGHT
switch (button) {
case 1:
button = NO_BUTTON;
if (confirm()) {
lcd.clear();
if (goWAVESD) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Settings will be"));
lcd.setCursor(0, 1);
lcd.print(F("save on:"));
lcd.setCursor(0, 2);
lcd.print(PSETname);
parameters2info();
delay(SB_T);
if (!savePSET_SD(PSETname, PSET, act_dir_path)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("SAVING FAILED"));
delay(SB_T * 1000);
button = NO_BUTTON;
break;
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Data will be"));
lcd.setCursor(0, 1);
lcd.print(F("save on:"));
DATAname = String("D_" + PSETname.substring(2, PSETname.lastIndexOf(".")) + ".csv");
for (unsigned char j = 0; exists_SD(DATAname, act_dir_path); j++) {
DATAname = String("D_" + PSETname.substring(2, PSETname.lastIndexOf(".")) + String(j) + ".csv" );
}
lcd.setCursor(0, 2);
lcd.print(DATAname);
delay(SB_T * 5);
if (!saveDATA_SD(DATAname, String(String(0) + "," + String(millis())), act_dir_path)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("SAVING FAILED"));
delay(SB_T * 1000);
button = NO_BUTTON;
break;
}
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(PSETname);
lcd.setCursor(0, 2);
lcd.print(F("Saving data on:"));
lcd.setCursor(0, 3);
lcd.print(DATAname);
}
lcd.setCursor(0, 0);
lcd.print(F(" RUNNING "));
goWAVE = true;
}
break;
case 5:
button = NO_BUTTON;
if (goWAVESD) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Settings will be"));
lcd.setCursor(0, 1);
lcd.print(F("save on:"));
lcd.setCursor(0, 2);
lcd.print(PSETname);
if (!savePSET_SD(PSETname, PSET, act_dir_path)) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("SAVING FAILED"));
delay(SB_T);
break;
}
}
case 3:
if (!goWAVESD) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("Insert SD and"));
lcd.setCursor(0, 1);
lcd.print(F("then press LOAD"));
delay(SB_T);
} else {
lcd.clear();
screen = 2;
}
break;
case 6:
button = NO_BUTTON;
if (!goWAVESD) {
lcd.clear();
SD_check();
} else {
screen = 3;
posDIR = 0;
}
break;
case 7:
screen = 5;
break;
case 8:
posY -= 2;
posY = constrain(posY, 0, 2);
break;
case 10:
posX -= 5;
posX = constrain(posX, 0, 15);
break;
case 11:
posY += 2;
posY = constrain(posY, 0, 2);
break;
case 12:
posX += 5;
posX = constrain(posX, 0, 15);
break;
default:
break;
}
button = NO_BUTTON;
}
}
void EDIT_screen() {
int hold_value;
lcd.clear();
button = NO_BUTTON;
if (posY == 0) {
switch (posX) {
case 0: //VS
lcd.print(F("VS [V]"));
hold_value = value_read();
if ((hold_value) > -1) {
Vs = constrain(hold_value, Vs_MIN, Vs_MAX);
goSETV = true;
}
break;
case 5: //IS
lcd.print(F("IS [mA]"));
hold_value = value_read();
if ((hold_value) > -1) {
Is = constrain(hold_value, Is_MIN, Is_MAX);
Vs = Is * R / 1000;
Vs = constrain(Vs, Vs_MIN, Vs_MAX);
goSETV = true;
}
break;
case 10: //TP
lcd.print(F("TP [ms]"));
hold_value = value_read();
if ((hold_value) > -1) {
TP = constrain(hold_value, TP_MIN, TP_MAX);
}
break;
case 15: //PW
lcd.print(F("PW [ms]"));
hold_value = value_read();
if ((hold_value) > -1) {
PW = constrain(hold_value, PW_MIN, TP);
}
break;
default:
break;
}
} else {
switch (posX) {
case 0: //TT
lcd.print(F("TT [ms]"));
hold_value = value_read();
if ((hold_value) > -1) {
Tt = constrain(hold_value, TT_MIN, TT_MAX);
NP = (Tt - PW) / TP;
}
break;
case 5: //R
lcd.print(F("R [Ohm]"));
hold_value = value_read();
if ((hold_value) > -1) {
R = constrain(hold_value, R_MIN, R_MAX);
Vs = Is * R / 1000;
Vs = constrain(Vs, Vs_MIN, Vs_MAX);
goSETV = true;
}
break;
case 10: //NP
lcd.print(F(" NP"));
hold_value = value_read();
if ((hold_value) > -1) {
NP = constrain(hold_value, NP_MIN, NP_MAX);
}
case 15: //RMEA
break;
default:
break;
}
}
lcd.clear();
screen = 3;
}
int value_read() {
int input = 0;
button = NO_BUTTON;
while (button != 1 && button != 3) {
lcd.setCursor(0, 2);
lcd.print(F(" CONFIRM "));
lcd.setCursor(0, 3);
lcd.print(F(" RUN CANCEL "));
lcd.setCursor(0, 1);
lcd.print(F(" "));
lcd.setCursor(0, 1);
lcd.print(input);
switch (button) {
case 8: //up
input++;
break;
case 10: //left
input -= 10;
break;
case 11: //down
input--;
break;
case 12: //right
input += 10;
break;
default:
break;
}
input = constrain(input, 0, R_MAX);
keypad_management();
delay(SB_T / 5);
}
if (button == 3) {
input = -1;
}
button = NO_BUTTON;
return input;
}
void print_times(unsigned char pos_scrX, unsigned char pos_scrY, unsigned short t) {
if (t < 1000) {
lcd.setCursor(pos_scrX, pos_scrY);
lcd.print(int(t));
if (t < 10) {
lcd.setCursor(pos_scrX + 1, pos_scrY);
}
if (t < 100) {
lcd.setCursor(pos_scrX + 2, pos_scrY);
} else {
lcd.setCursor(pos_scrX + 3, pos_scrY);
}
lcd.print(F("m"));
} else {
lcd.setCursor(pos_scrX, pos_scrY);
lcd.print(int(t / 1000));
if ((t / 1000) < 10) {
lcd.setCursor(pos_scrX + 1, pos_scrY);
}
if ((t / 1000) < 100) {
lcd.setCursor(pos_scrX + 2, pos_scrY);
} else {
lcd.setCursor(pos_scrX + 3, pos_scrY);
}
lcd.print(F("s"));
}
}
void print_R(unsigned char pos_scrX, unsigned char pos_scrY, unsigned int res) {
if (res < 1000) {
lcd.setCursor(pos_scrX, pos_scrY);
lcd.print(int(res));
} else {
lcd.setCursor(pos_scrX, pos_scrY);
lcd.print(int(res / 1000));
if ((res / 1000) < 10) {
lcd.setCursor(pos_scrX + 1, pos_scrY);
}
if ((res / 1000) < 100) {
lcd.setCursor(pos_scrX + 2, pos_scrY);
} else {
lcd.setCursor(pos_scrX + 3, pos_scrY);
}
lcd.print(F("k"));
}
}
bool confirm() {
lcd.clear();
lcd.setCursor(0, 1);
lcd.print(F(" CONFIRM "));
lcd.setCursor(0, 2);
lcd.print(F(" RUN CANCEL "));
button = NO_BUTTON;
keypad_management();
while ((button != 1) && (button != 3)) {
delay(SB_T);
}
if (button == 1) {
button = NO_BUTTON;
return true;
}
button = NO_BUTTON;
return false;
}
void lcd_management(unsigned char screen) {
switch (screen) {
case 1:
VTR_screen();
break;
case 2:
SD_screen();
break;
case 3:
PRESET_screen();
break;
case 5:
EDIT_screen();
break;
}
}
// KEYPAD MANAGEMENT
void keypad_management() {
v_A2 = analogRead(A2);
if (v_A2 > 1023 - (2 * KPR)) {
button = 1; //RUN
}
if ((930 + (2 * KPR) > v_A2) && (v_A2 > 930 - (2 * KPR))) {
button = 2; //RM
}
if ((860 + (2 * KPR) > v_A2) && (v_A2 > 860 - (2 * KPR))) {
button = 3; //CANCEL
}
if ((800 + (2 * KPR) > v_A2) && (v_A2 > 800 - (2 * KPR))) {
button = 4; //NEW
}
if ((750 + (2 * KPR) > v_A2) && (v_A2 > 750 - (2 * KPR))) {
button = 5; //SAVE
}
if ((710 + (2 * KPR) > v_A2) && (v_A2 > 710 - (2 * KPR))) {
button = 6; //LOAD
}
if ((680 + (2 * KPR) > v_A2) && (v_A2 > 680 - (2 * KPR))) {
button = 7; //EDIT
}
if ((650 + (2 * KPR) > v_A2) && (v_A2 > 650 - KPR)) {
button = 8; //UP
}
if ((620 + KPR > v_A2) && (v_A2 > 620 - KPR)) {
button = 9; //DELETE
}
if ((600 + KPR > v_A2) && (v_A2 > 600 - KPR)) {
button = 10; //LEFT
}
if ((570 + KPR > v_A2) && (v_A2 > 570 - KPR)) {
button = 11; //DOWN
}
if ((550 + KPR > v_A2) && (v_A2 > 550 - KPR)) {
button = 12; //RIGHT
}
if (550 - KPR > v_A2 ) {
button = NO_BUTTON;
}
}
// SD MANAGEMENT
void loop() {
File DATAFILE;
while (!goWAVE) {
lcd_management(screen);
}
if (goWAVESD) {
DATAFILE = SD.open(String(act_dir_path + DATAname), FILE_WRITE);
DATAFILE.flush();
}
while (goWAVE) {
TT_stop = millis() + Tt;
TP_start = millis() + TP;
while (millis() < TT_stop) {
if (goWAVESD) { // This needs to not be executed every time
// Record DATA
DATAFILE.print(analogRead(A1)*CAL_A1);
DATAFILE.print(",");
DATAFILE.println(millis() - (TT_stop - Tt));
DATAFILE.flush();
}
if (millis() >= (TP_start - PW) ) { // When the counter reaches the period
digitalWrite(SW, HIGH); // switches the Voltage output ON
}
if (millis() >= TP_start) { // When the counter reaches the Pulse Width
digitalWrite(SW, LOW); // switches the Voltage output OFF
TP_start = millis() + TP;
}
}
goWAVE = false; // Turning the wave off
}
digitalWrite(SW, LOW); // Turning switch off
TP_start = 0; // Restarting Period counter
TT_stop = 0; // Restarting Total time counter
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(F("COMPLETED"));
if (goWAVESD) {
lcd.setCursor(0, 1);
lcd.print(F(" DATA SAVED IN FILE"));
lcd.setCursor(0, 2);
lcd.print(DATAname);
DATAFILE.close();
}
delay(SB_T * 2);
lcd.clear();
button = NO_BUTTON;
}
|
/**
* Copyright 2008 Matthew Graham
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "stdopt/usage.h"
#include <iostream>
#include <sstream>
#include <cstring>
using namespace stdopt;
/*
void usage_option_c::write_usage_doc( std::ostream &doc ) const
{
if ( m_short_opt ) {
doc << "\t-" << m_short_opt;
}
if ( ! m_long_opt.empty() ) {
doc << "\t--" << m_long_opt;
}
if ( ! m_description.empty() ) {
doc << "\t" << m_description;
}
doc << std::endl;
}
*/
void usage_c::add( usage_option_i &option )
{
m_option.push_back( &option );
}
bool usage_c::parse_args( int argc, const char **argv )
{
positional_list::iterator pos_it( m_positional.begin() );
// skip the first arg which is the command
for ( int i(1); i<argc; ++i ) {
// usage_error = usage_error ||
// std::cerr << "argv[" << i << "] = " << argv[i] << std::endl;
bool consumed_param( false );
if ( long_style_arg( argv[i] ) ) {
parse_long_arg( argv[i] + 2 );
} else if ( short_style_arg( argv[i] ) ) {
std::string short_param;
if ( i + 1 < argc ) {
short_param = argv[i+1];
}
parse_short_args( argv[i] + 1, short_param
, consumed_param );
} else {
// positional arg
if ( pos_it == m_positional.end() ) {
m_error = true;
continue;
}
(*pos_it)->parse_value( argv[i] );
++pos_it;
}
if ( consumed_param ) {
++i;
}
}
return ! m_error;
}
bool usage_c::short_style_arg( const char *arg )
{
return arg[0] == '-' && arg[1] != '-';
}
bool usage_c::long_style_arg( const char *arg )
{
return arg[0] == '-' && arg[1] == '-';
}
void usage_c::parse_short_args( const std::string &args
, const std::string ¶m, bool &consumed_param )
{
std::string::const_iterator it( args.begin() );
for ( ; it!=args.end(); ++it ) {
// short option
usage_option_i *option = find_short_option( *it );
if ( ! option ) {
// this option is not found
// flag as error
m_error = true;
}
if ( option->requires_param() ) {
if ( ! param.empty() ) {
consumed_param = true;
option->parse_value( param );
} else {
m_error = true;
}
} else {
std::string no_param;
option->parse_value( no_param );
}
}
}
void usage_c::parse_long_arg( const std::string &arg )
{
std::string option_name;
std::string option_value;
bool has_value;
std::size_t equal_pos( arg.find( "=" ) );
if ( equal_pos == std::string::npos ) {
option_name = arg;
} else {
option_name = arg.substr( 0, equal_pos );
option_value = arg.substr( equal_pos + 1 );
has_value = true;
}
usage_option_i *option = find_long_option( option_name );
if ( ! option ) {
m_error = true;
return;
}
if ( option->requires_param() && ! has_value ) {
m_error = true;
return;
}
option->parse_value( option_value );
}
usage_option_i * usage_c::find_short_option( char short_opt )
{
option_list::iterator it;
for ( it=m_option.begin(); it!=m_option.end(); ++it ) {
usage_option_i &opt( **it );
if ( opt.usage_character() == short_opt ) {
return &opt;
}
}
return NULL;
}
usage_option_i * usage_c::find_long_option( const std::string &long_opt )
{
option_list::iterator it;
for ( it=m_option.begin(); it!=m_option.end(); ++it ) {
usage_option_i &opt( **it );
if ( opt.option_name() == long_opt ) {
return &opt;
}
}
return NULL;
}
/*
void usage_doc_c::write( const usage_c &usage, std::ostream &doc ) const
{
doc << "Usage: shessiond [OPTIONS]\n\n";
doc << "Options:\n";
usage_option_c::list::const_iterator it;
for ( it=usage.m_option.begin(); it!=usage.m_option.end(); ++it ) {
(*it)->write_usage_doc( doc );
}
doc << "\n";
}
*/
|
#include "GnMeshPCH.h"
#include "GnGamePCH.h"
#include "GInfoBasic.h"
#include "GActorInfoDatabase.h"
void GInfoBasic::LoadDataFromQuery(GnSQLiteQuery* pQuery)
{
mHP = (gint32)pQuery->GetIntField( COL_HP );
mStrength = (guint32)pQuery->GetIntField( COL_STRENGTH );
mMoveSpeed = (float)pQuery->GetFloatField( COL_MOVESPEED );
mAttackSpeed = (float)pQuery->GetFloatField( COL_ATTACKSPEED );
mAttackType = (gint32)pQuery->GetIntField( COL_ATTACKTYPE );
mAttackCount = (guint32)pQuery->GetIntField( COL_ATTACKCOUNT );
mPush = (guint32)pQuery->GetIntField( COL_PUSH );
guint32 uilise = (gint32)pQuery->GetIntField( COL_LISEHP );
mHP += GetLevel() * uilise;
uilise = (guint32)pQuery->GetIntField( COL_LISEPOWER );
mStrength += GetLevel() * uilise;
float flise = (float)pQuery->GetFloatField( COL_LISEATTACKSPEED );
mAttackSpeed += GetLevel() * flise;
}
|
#include "MeshComponent.h"
#include "../core/resources/RenderObject.h"
#include "../core/GameCore.h"
#include "TransformComponent.h"
namespace Game
{
MeshComponent::MeshComponent() : mRenderObject()
{
}
void MeshComponent::loadMesh(const char *path)
{
mRenderObject.load(path);
}
void MeshComponent::update()
{
}
void MeshComponent::draw()
{
Transform transform = entity->getComponent<TransformComponent>().getTransform();
GameCore::get().getModule<DrawModule>()->drawMesh(mMeshId, transform);
}
void MeshComponent::start()
{
mMeshId = GameCore::get().getModule<DrawModule>()->addMesh(mRenderObject.getMesh());
}
void MeshComponent::stop()
{
}
void MeshComponent::configure()
{
}
void MeshComponent::cleanup()
{
}
MeshTransform& MeshComponent::getMeshData()
{
mRenderObject.getMesh();
}
void MeshComponent::onCreate()
{
}
}
|
#include "abstractphysicpoint.h"
namespace sbg {
AbstractPhysicPoint::~AbstractPhysicPoint() = default;
double AbstractPhysicPoint::getMass() const
{
return _mass;
}
void AbstractPhysicPoint::setMass(const double mass)
{
_mass = mass;
}
}
|
#include <Keyboard.h>
// exemplo: quero a tecla "F5", será KEY_F5
// para ter acesso a todas as teclas especias visite: https://www.arduino.cc/reference/en/language/functions/usb/keyboard/keyboardmodifiers/
// altere a tecla abaixo conforme a necessidade, basta alterar a parte do "F"
char tecla = KEY_F8;
void setup() {
pinMode(7, INPUT_PULLUP);
Keyboard.begin();
}
void loop() {
if(digitalRead(7) == LOW) {
delay(250);
if(digitalRead(7) == LOW) {
Keyboard.press(tecla);
delay(100);
Keyboard.release(tecla);
delay(800);
}
}
}
|
#include "StatusTextManager.h"
#include "StatusText.h"
#include <SFML/Graphics/RenderWindow.hpp>
namespace Platy
{
namespace Game
{
std::vector<StatusText> StatusTextManager::myStatusTexts;
void StatusTextManager::Update(float& someDeltaTime)
{
for (auto i = myStatusTexts.size(); i > 0; i--)
{
myStatusTexts.at(i - 1).Update(someDeltaTime);
if (!myStatusTexts.at(i - 1).GetAlive())
{
myStatusTexts.erase(myStatusTexts.begin() + i - 1);
}
}
}
void StatusTextManager::Draw(sf::RenderWindow& aWindow)
{
for (const auto& it : myStatusTexts)
{
aWindow.draw(it);
}
}
void StatusTextManager::AddStatusText(const StatusText& aStatusText)
{
myStatusTexts.push_back(aStatusText);
}
}
}
|
#ifndef AM_PM_CLOCK_H_
#define AM_PM_CLOCK_H_
#include <ostream>
class am_pm_clock {
int hours;
int minutes;
int seconds;
bool am;
public:
am_pm_clock():
hours(12),
minutes(0),
seconds(0),
am(true)
{
}
/*
* Default constructor - initial time should be midnight
*/
am_pm_clock(int hrs, int mins, int secs, bool am_val):
hours(hrs),
minutes(mins),
seconds(secs),
am(am_val)
{
}
/*
* Constructor - sets fields to the given argument values
*/
/*
* Copy constructor
*/
am_pm_clock(const am_pm_clock &clock);
/*
* Assignment operator
*/
am_pm_clock& operator=(const am_pm_clock& clock);
/*
* Toggles the am/pm value for the clock
*/
void toggle_am_pm(){
hours=12;
minutes=0;
seconds=0;
am=true;
}
/*
* Resets the time to midnight
*/
void reset();
/*
* Advances the time of the clock by one second
*/
void advance_one_sec(){
seconds=seconds+1;
if (seconds==60){
minutes=minutes+1;
seconds=0;}
if (minutes==60){
hours=hours+1;
minutes=0;
}
if (hours==13){
hours=1;
if(am)
am=false;
else
am=true;
}
}
/*
* Advances the time of the clock by n seconds
*/
void advance_n_secs( int n){
for (int i=0; i<n; i++)
advance_one_sec();
}
/*
* Getter for hours field
*/
unsigned int get_hours() const{
return hours;
}
/*
* Setter for hours field; throws an invalid_argument exception
* if hrs is not a legal hours value
*/
void set_hours( int hrs){
hours=hrs;
}
/*
* Getter for minutes field
*/
unsigned int get_minutes() const{
return minutes;
}
/*
* Setter for minutes field; throws an invalid_argument exception
* if mins is not a legal minutes value
*/
void set_minutes( int mins){
minutes=mins;
}
/*
* Getter for seconds field
*/
int get_seconds() const{
return seconds;
}
/*
* Setter for seconds field; throws an invalid_argument exception
* if secs is not a legal seconds value
*/
void set_seconds( int secs){
seconds=secs;
}
/*
* Getter for am field
*/
bool is_am() const{
return am;
}
/*
* Setter for am field
*/
void set_am(bool am_val){
am=am_val;
}
/*
* Print function - helper for output operator
*/
void print(std::ostream& out) const {
char buff[11];
std::sprintf(buff, "%02d:%02d:%02d%cm", hours, minutes, seconds,
( am ? 'a' : 'p' ));
out << buff;
}
/*
* Destructor
*/
~am_pm_clock();
};
inline std::ostream& operator << (std::ostream& out, const am_pm_clock& clock) {
clock.print(out);
return out;
}
#endif /* AM_PM_CLOCK_H_ */
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2002-2006 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* Owner: julienp
*/
#ifdef FEATURE_SCROLL_MARKER
//The following define how the scroll marker should appear
//Currently, sortof bullets defined by the skin are used to mark it.
//The other solution (cover the part of the screen scrolled from with a transparent layer) is too slow on Unix
//but I keep it as an option for the future.
#define OP_SCROLL_MARKER_SCROLL_TIME 750
#define OP_SCROLL_MARKER_INVISIBLE_SCROLL_TIME 100
#define OP_SCROLL_MARKER_PERSIST_TIME 1250
//8080a0
#include "modules/pi/OpTimer.h"
#include "modules/display/vis_dev.h"
class OpPainter;
class OpRect;
class OpScrollMarker : public OpTimerListener, public VisualDeviceScrollListener, public OpSkinAnimationListener
{
public:
static OP_STATUS Create(OpScrollMarker** scroll_marker, VisualDevice* vis_dev);
~OpScrollMarker();
//Should be called by whatever the ScrollMarker should be painted on.
void OnPaint(OpPainter* painter, OpRect rect);
/*-------- OpTimerListener interface ---------- */
virtual void OnTimeOut(OpTimer* timer);
/*---- VisualDeviceScrollListener interface --- */
virtual void OnDocumentScroll(VisualDevice *vis_dev,INT32 dx, INT32 dy, SCROLL_REASON reason);
/*----- OpSkinAnimationListener interface ----- */
virtual void OnAnimatedImageChanged();
private:
VisualDevice* m_vis_dev;
OpTimer* m_timer;
BOOL m_scroll_in_progress;
BOOL m_visible;
INT32 m_direction;
OpRect m_rect;
OpScrollMarker(VisualDevice* vis_dev);
void Show(BOOL visible);
void Invalidate();
};
#endif // FEATURE_SCROLL_MARKER
|
//
// Created by yshhuang on 2019-03-01.
//
#include <opencv2/opencv.hpp>
void example2_5(const cv::Mat &image) {
cv::namedWindow("Example2_5-in", cv::WINDOW_AUTOSIZE);
cv::namedWindow("EXAMPLE2_5-out", cv::WINDOW_AUTOSIZE);
cv::imshow("Example2_5-in", image);
cv::Mat out;
cv::GaussianBlur(image, out, cv::Size(5, 5), 3, 3);
cv::GaussianBlur(out, out, cv::Size(5, 5), 3, 3);
cv::imshow("Example2_5-out", out);
cv::waitKey(0);
}
int main(int argc, char **argv) {
cv::Mat img = cv::imread(argv[1], -1);
example2_5(img);
return 0;
}
|
//
// Created by manout on 17-3-11.
//
#include "common_use.h"
/*
* Given an array and a value, remove all instances of that value in
* place and return the new length. The order of elements can be changed.
* it doesn't matter what you leave beyond the new length.
*/
int remove_element()(vector<int> &nums, int target){
int index = 0;
for (int i = 0 ;i < nums.size(); ++i) {
if(nums[] != target ){
nums[index++] = nums[i];
}
}
return index;
}
int remove_element_(vector<int> &nums, int target){
return distance(nums.begin(), remove(nums.begin(),nums.end(), target));
}
|
// https://practice.geeksforgeeks.org/problems/subset-sum-problem/0
#include <iostream>
using namespace std;
bool findSum(int sum, int n, int a[])
{
bool dp[sum + 1][n + 1];
for (int i = 0; i <= n; i++)
dp[0][i] = true;
for (int i = 1; i <= sum; i++)
dp[i][0] = false;
for (int i = 1; i <= sum; i++)
for (int j = 1; j <= n; j++)
{
if(a[j] > i)
dp[i][j] = dp[i][j - 1];
if(i >= a[j])
dp[i][j] = dp[i - a[j]][j - 1] || dp[i][j - 1];
}
return dp[sum][n];
}
int main()
{
int t, n, a[101], total;
cin >> t;
while (t--)
{
cin >> n;
total = 0;
for (int i = 1; i <= n; i++)
{
cin >> a[i];
total += a[i];
}
if (total % 2)
{
cout << "NO" << endl;
continue;
}
if(findSum(total / 2, n, a))
cout << "YES" << endl;
else
cout << "NO" << endl;
}
}
|
#ifndef wali_PRINTABLE_GUARD
#define wali_PRINTABLE_GUARD 1
/*
* @author Nicholas Kidd
*/
#include <string>
#include <iostream>
namespace wali
{
/*!
* @class Printable
* @brief Interface defining the print method
*
* A Printable object must define a print method.
*
* The Printable class provides toString() methods
* for any Printable object by passing a std::ostringstream
* to the object's print method.
*/
class Printable
{
public:
virtual ~Printable() {}
virtual std::ostream & print( std::ostream & ) const = 0;
std::string to_string() const;
std::string toString() const;
}; // class Printable
} // namespace wali
#endif // wali_PRINTABLE_GUARD
|
#ifndef MASTERS_PROJECT_AMERICANBINOMIALDIVIDENDRECURSIVEMETHOD_H
#define MASTERS_PROJECT_AMERICANBINOMIALDIVIDENDRECURSIVEMETHOD_H
#include "DiscreteDividendMethod.hpp"
template<typename X>
class AmericanBinomialDividendRecursiveMethod : public DiscreteDividendMethod<X> {
public:
AmericanBinomialDividendRecursiveMethod(Case<X> *aCase, Dividend<X> **dividends, int dividendNumber);
protected:
X calculate_disc_div(X S, X time, int steps, Dividend<X> **present_dividends, int div_num) override;
protected:
X result;
};
#include "AmericanBinomialDividendRecursiveMethod.tpp"
#endif //MASTERS_PROJECT_AMERICANBINOMIALDIVIDENDRECURSIVEMETHOD_H
|
/*
Copyright (c) 2016, Los Alamos National Security, LLC
All rights reserved.
Copyright 2016. Los Alamos National Security, LLC. This software was produced under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National Laboratory (LANL), which is operated by Los Alamos National Security, LLC for the U.S. Department of Energy. The U.S. Government has rights to use, reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified to produce derivative works, such modified software should be clearly marked, so as not to confuse it with the version available from LANL.
Additionally, redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Los Alamos National Security, LLC, Los Alamos National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL SECURITY, LLC OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MPICache3_hpp
#define MPICache3_hpp
#include <iostream>
#include <ostream>
#include <stdio.h>
#include <set>
#include <map>
#include <vector>
#include <list>
#include <tuple>
#include <mpi.h>
#include "HCDS.hpp"
#include "Types.hpp"
#include "Constants.hpp"
#include "Pack.hpp"
#include "DDS.hpp"
#include "Log.hpp"
class MsgChannel {
public:
MsgChannel( ){
pending_=false;
req=MPI_REQUEST_NULL;
};
bool pending(){
return pending_;
};
void cancel(){
MPI_Cancel(&req);
MPI_Wait(&req,&status);
};
MPI_Request req;
MPI_Status status;
std::vector<char> buf;
bool pending_;
};
class RecvChannel : public MsgChannel {
public:
bool test(){
if(!pending_) {
return false;
}
int complete=0;
MPI_Test(&req,&complete,&status);
if(complete) {
pending_=false;
}
//pending_=!bool(complete);
return bool(complete);
};
bool postRecv(size_t maxMesgSize, int sourceTag, int msgTag, MPI_Comm &communicator){
if(pending_) {
return false;
}
buf.resize(maxMesgSize);
MPI_Irecv(&(buf[0]),maxMesgSize,MPI_BYTE,sourceTag,msgTag,communicator,&req);
pending_=true;
return pending_;
};
};
class SendChannel : public MsgChannel {
public:
bool test(){
int complete=0;
MPI_Test(&req,&complete,&status);
if(complete) {
pending_=false;
}
//pending_=!bool(complete);
return bool(complete);
};
bool postSend(size_t dataSize, RawDataVector data,int destinationTag, int msgTag, MPI_Comm &communicator){
if(pending_) {
LOGGERA("WARNING: MESSAGE WAS ALREADY PENDING")
return false;
}
buf.swap(data);
MPI_Issend( &(buf[0]),dataSize,MPI_BYTE,destinationTag, msgTag, communicator, &req);
pending_=true;
return pending_;
};
};
template <class LocalStoreType> class HDDS3 : public AbstractDDS {
public:
/**
* Initialize
*/
HDDS3(MPI_Comm comm_, int parent_, std::string homeDir, std::string baseName, uint64_t maxDataSize_, uint64_t maxCacheSize_, std::set<int> dbKeys, std::unordered_map< unsigned int, std::pair<bool,bool> > &dbAttributes, bool purge_){
comm=comm_;
//recvPending=false;
//sendPending=false;
purge=purge_;
parent=parent_;
maxDataSize=maxDataSize_;
maxCacheSize=maxCacheSize_;
memoryUsage=0;
//maxMemoryUsage=maxCacheSize;
//initialize a receive buffer
//rbuf=std::vector<char>(maxDataSize);
MPI_Comm_rank(comm, &self);
//initialize the databases
lstore.initialize(homeDir,baseName);
for(auto it=dbKeys.begin(); it!=dbKeys.end(); it++) {
bool allowDuplicates=dbAttributes[*it].first;
bool eraseOnGet=dbAttributes[*it].second;
lstore.createDatabase(*it,allowDuplicates,eraseOnGet);
}
reservationID=1;
nActiveHolds=0;
};
/**
* Server process. Does not return. Use in multithreaded scenarios.
*/
void serve(){
while(true) {
singleServe();
}
};
void printStatus(){
LOGGER(" HDDS on RANK: "<<self)
LOGGER(self<<" "<<maxDataSize<<" ")
LOGGER(self<<" MEMORY USAGE: "<<memoryUsage<<" "<<maxCacheSize)
LOGGER(self<<" HOLDS: "<<nActiveHolds)
LOGGER(self<<" RESERVATION ID: "<<reservationID<<" "<<reservations.size())
};
void setMaximumBufferSize(uint64_t maxSize){
maxCacheSize=maxSize;
};
/**
* Single step of the server loop
*/
int singleServe(){
//post a receive (does nothing if none is pending)
recvChannel.postRecv(maxDataSize,MPI_ANY_SOURCE,DDS_MESG_TAG,comm);
//receive incoming messages
if(recvChannel.test()) {
int size;
MPI_Get_count(&recvChannel.status,MPI_BYTE,&size);
std::list<Transaction> transactions;
unpack(recvChannel.buf,transactions,std::size_t(size));
incomingTransactions.splice(incomingTransactions.begin(),transactions);
recvChannel.postRecv(maxDataSize,MPI_ANY_SOURCE,DDS_MESG_TAG,comm);
}
//purge if using too much memory
if(purge and memoryUsage>maxCacheSize) {
//flush the least recently touched items. Make sure we don't flush elements that are still needed
for(auto it=mru.begin(); it!=mru.end(); ) {
unsigned int dbKey=it->first;
Label key=it->second;
bool onHold=requestCounter[dbKey][key].size()>0;
if(not onHold) {
LOGGER("RANK: "<<self<<" PURGING ITEM "<<key)
assert(lstore.count(dbKey,key)>0);
int size=lstore.erase(dbKey,key);
memoryUsage-=size;
if(lstore.count(dbKey,key)==0) {
it=mru.erase(it);
}
else{
it++;
}
}
else{
it++;
}
if(memoryUsage<maxCacheSize) {
break;
}
}
if(memoryUsage>maxCacheSize) {
LOGGERA("RANK: "<<self<<" WARNING: UNABLE TO PURGE ENOUGH DATA TO MEET MEMORY LIMIT ")
}
}
//process an incoming transactions
//NOTE: this is a coarse lock. Can we do better?
//transactionLock.lock();
if(incomingTransactions.size()>0) {
auto it=incomingTransactions.begin();
Transaction &transaction=*it;
//transaction.print();
if(transaction.type==DDS_GET or transaction.type==DDS_PREFETCH) {
//GET requests should only come from children
assert(transaction.source!=parent);
//bool transactionCompleted=false;
bool inStore=(lstore.count(transaction.dbKey,transaction.key)>0);
//we have the item in store
if(inStore) {
//the source is a remote child. Push a PUT transaction in the queue
if(transaction.source!=self) {
Transaction reply;
reply.type=DDS_PUT;
reply.source=self;
reply.destination=transaction.source;
reply.dbKey=transaction.dbKey;
reply.key=transaction.key;
//push to the outgoing queue
outgoingTransactions[reply.destination].push_back(reply);
//Register a hold on this item until we process the corresponding DDS_PUT back to the requester
if(transaction.type==DDS_GET and not transaction.pending) {
requestCounter[transaction.dbKey][transaction.key].insert(transaction.source);
nActiveHolds++;
}
}
//update the MRU log
mru.touch(std::make_pair(transaction.dbKey,transaction.key));
//we are done with this transaction
incomingTransactions.erase(it);
}
//we don't have the item
else{
//if we do not have a pending GET request on this item, we need to forward it to parent
if( not transaction.pending and pendingGets.count( std::make_pair(transaction.dbKey, transaction.key) ) == 0 and parent>=0) {
Transaction forward;
forward.type=DDS_GET;
forward.dbKey=transaction.dbKey;
forward.key=transaction.key;
forward.source=self;
forward.destination=parent;
outgoingTransactions[forward.destination].push_back(forward);
//log that we already requested this item
//this has to be cleared when we receive the item
pendingGets.insert(std::make_pair(transaction.dbKey, transaction.key));
}
//Register a hold on this item until we process the corresponding DDS_PUT back to the requester
if(transaction.type==DDS_GET and not transaction.pending and transaction.source!=self) {
requestCounter[transaction.dbKey][transaction.key].insert(transaction.source);
nActiveHolds++;
transaction.pending=true;
//we could not fully fulfill this transaction; mark it as pending and move it to the pending set
pendingTransactions[ std::make_pair(transaction.dbKey, transaction.key) ].push_back(transaction);
}
incomingTransactions.erase(it);
}
}
if(transaction.type==DDS_PUT) {
bool inStore=(lstore.count(transaction.dbKey, transaction.key)>0);
//add it to the store if we don't have it already
if( not inStore ) {
lstore.put(transaction.dbKey,transaction.key,transaction.data);
memoryUsage+=transaction.data.size();
//reinject pending transactions waiting on this item
if(pendingTransactions.count( std::make_pair(transaction.dbKey, transaction.key) ) > 0 ) {
incomingTransactions.splice(incomingTransactions.begin(), pendingTransactions[ std::make_pair(transaction.dbKey, transaction.key) ] );
pendingTransactions.erase( std::make_pair(transaction.dbKey, transaction.key) );
}
}
//parent fulfilled our request
if(transaction.source==parent) {
pendingGets.erase( std::make_pair(transaction.dbKey, transaction.key) );
}
//Request from child. Foward item to parent only if we never did before
else{
if(forwardedPuts.count(std::make_pair(transaction.dbKey, transaction.key))==0 and parent>=0) {
Transaction forward;
forward.type=DDS_PUT;
forward.dbKey=transaction.dbKey;
forward.key=transaction.key;
forward.source=self;
forward.destination=parent;
forward.data=transaction.data;
//Register a hold on this item until we process the corresponding DDS_PUT to parent
requestCounter[forward.dbKey][forward.key].insert(parent);
nActiveHolds++;
outgoingTransactions[forward.destination].push_back(forward);
}
}
//no need to forward this item to parent again
forwardedPuts.insert(std::make_pair(transaction.dbKey, transaction.key));
//we are done with this transaction
incomingTransactions.erase(it);
//update the MRU log
mru.touch(std::make_pair(transaction.dbKey,transaction.key));
}
}
//transactionLock.unlock();
//process outgoing transactions
for(auto it=outgoingTransactions.begin(); it!=outgoingTransactions.end(); ) {
bool pending=!sendChannels[it->first].test();
//initiate send of transactions
if(not pending) {
//gather the data
std::list<Transaction> outgoing;
int nt=0;
int ntMax=10;
while(nt<=ntMax and it->second.size()>0) {
Transaction &transaction=it->second.front();
if(transaction.type==DDS_PUT) {
LOGGER(DDS_PUT<<" "<<transaction.destination<<" "<<transaction.dbKey<<" "<<transaction.key)
bool inStore=(lstore.count(transaction.dbKey,transaction.key)>0);
//this item should be in store
assert(inStore);
lstore.get(transaction.dbKey,transaction.key,transaction.data);
//we have fulfilled the request. Release the hold
assert( requestCounter[transaction.dbKey][transaction.key].count(transaction.destination) > 0 );
auto itr=requestCounter[transaction.dbKey][transaction.key].find(transaction.destination);
requestCounter[transaction.dbKey][transaction.key].erase(itr);
nActiveHolds--;
outgoing.push_back(transaction);
}
if(transaction.type==DDS_GET) {
outgoing.push_back(transaction);
}
nt++;
//done with this
it->second.pop_front();
}
//initiate send of the data
sbuf.clear();
pack(sbuf,outgoing);
int count=sbuf.size();
bool ret=sendChannels[it->first].postSend(count,sbuf,it->first,DDS_MESG_TAG,comm);
}
if(it->second.size()==0) {
it = outgoingTransactions.erase(it);
}
else{
it++;
}
}
return incomingTransactions.size();
};
virtual void prefetch(int dbKey, Label key){
Transaction transaction;
transaction.type=DDS_PREFETCH;
transaction.dbKey=dbKey;
transaction.key=key;
transaction.source=self;
transaction.destination=self;
transactionLock.lock();
incomingTransactions.push_back(transaction);
transactionLock.unlock();
};
//a returned reservationID of 0 means the reservation was not accepted
virtual uint64_t reserve(int dbKey, Label key){
if(memoryUsage>maxCacheSize) {
//reject the reservation until we have more room available
//WARNING: disabled since the rest of the code does not deal with this yet
//return 0;
}
Transaction transaction;
transaction.type=DDS_GET;
transaction.dbKey=dbKey;
transaction.key=key;
transaction.source=self;
transaction.destination=self;
transactionLock.lock();
incomingTransactions.push_back(transaction);
transactionLock.unlock();
//Register a hold on this item until the requester calls release
requestCounter[dbKey][key].insert(self);
//Register the reservation
reservations[reservationID]=std::make_pair(dbKey,key);
nActiveHolds++;
return reservationID++;
};
virtual int count(int dbKey, Label key){
return lstore.count(dbKey,key);
};
virtual bool release(uint64_t id){
if(id==0) {
return false;
}
//make sure the reservation exists
if(reservations.count(id)==0) {
return false;
}
unsigned int dbKey=reservations[id].first;
Label key=reservations[id].second;
if(requestCounter[dbKey][key].count(self)==0) {
return false;
}
//clear the hold
assert( requestCounter[dbKey][key].count(self)!=0 );
auto it=requestCounter[dbKey][key].find(self);
requestCounter[dbKey][key].erase(it);
nActiveHolds--;
//release the reservation
reservations.erase(id);
return true;
};
virtual void sync(){
lstore.sync();
}
virtual bool get(int dbKey, Label key,RawDataVector &data){
#ifdef LOG_DDS
boost::log::sources::severity_logger< boost::log::trivial::severity_level > lg;
BOOST_LOG_SEV(lg, boost::log::trivial::trace) <<" HDDS GET "<<dbKey<<" "<<key;
#endif
if(count(dbKey, key)==0) {
return false;
}
lstore.get(dbKey,key,data);
return true;
};
virtual void put(int dbKey, Label key, RawDataVector &data){
#ifdef LOG_DDS
boost::log::sources::severity_logger< boost::log::trivial::severity_level > lg;
BOOST_LOG_SEV(lg, boost::log::trivial::trace) <<" HDDS PUT "<<dbKey<<" "<<key;
#endif
Transaction transaction;
transaction.type=DDS_PUT;
transaction.dbKey=dbKey;
transaction.key=key;
transaction.data=data;
transaction.source=self;
transaction.destination=self;
transactionLock.lock();
incomingTransactions.push_back(transaction);
transactionLock.unlock();
};
virtual std::set<uint64_t> availableKeys(unsigned int dbKey){
return lstore.availableKeys(dbKey);
};
virtual void cancelCommunications(){
recvChannel.cancel();
for(auto it=sendChannels.begin(); it!=sendChannels.end(); it++) {
it->second.cancel();
}
}
private:
bool purge;
int parent;
int self;
uint64_t maxDataSize;
uint64_t maxCacheSize;
uint64_t memoryUsage;
//uint64_t maxMemoryUsage;
//bool recvPending;
//bool sendPending;
MPI_Comm comm;
//MPI_Comm dbComm;
//MPI_Status recvStatus;
//MPI_Request recvReq;
//MPI_Status sendStatus;
//MPI_Request sendReq;
//std::vector<char> rbuf;
std::vector<char> sbuf;
int nActiveHolds;
LocalStoreType lstore;
MRU< std::pair<unsigned int, uint64_t> > mru;
/**
* Queue of incoming transactions
*/
std::list<Transaction> incomingTransactions;
/**
* Queue of outgoing transactions
*/
//std::list<Transaction> outgoingTransactions;
std::map<int,std::list<Transaction> > outgoingTransactions;
RecvChannel recvChannel;
std::map<int,SendChannel> sendChannels;
/**
* Store pending transitions that are awaiting the arrival of a data item
*/
std::map< std::pair<unsigned int, Label>, std::list<Transaction> > pendingTransactions;
/**
* PUT requests that were already forwarded to parent
*/
std::set< std::pair<unsigned int, Label> > forwardedPuts;
/**
* GET requests from children we could not immediately fulfil
*/
std::map< std::pair<unsigned int, Label>, std::set<int> > pendingGetReplies;
/**
* GET requests that we already issued to parent for which we didn't get an answer yet
*/
std::set< std::pair<unsigned int, Label> > pendingGets;
/**
* PUT requests we already issued to parent
*/
std::set< std::pair<unsigned int, Label> > completedPutsToParent;
/**
* Store holds on items. requestCounter[dbKey][key]={requestors}
*/
std::map< unsigned int, std::map<Label,std::multiset<int> > > requestCounter;
/**
* Next available reservation ID
*/
uint64_t reservationID;
/**
* Store open reservations. reservations[id]=(dbKey,key)
*/
std::map<uint64_t, std::pair<unsigned int, Label > > reservations;
SpinLock transactionLock;
};
#endif /* MPICache_hpp */
|
#include <iostream>
#include <istream>
#include <string>
using namespace std;
int num_words(string str);
void add_commas(string &str);
// finds commas in the pargraph and returns the words previous and next to it.
void get_words(int i, string &str);
// adds a comma before or after (where) a give `word` in a `paragraph`
void add_commas_to(string ¶graph, string word, char where);
// value to indicate whether or not you should perform the algorithm again.
int sentinel = 1;
int main(void)
{
string paragraph;
// get a string (min-length: 2) from the user
do
{
getline(cin, paragraph);
} while (paragraph.length() < 2);
// need to store a copy to manipulate it.
string paragraph_copy = paragraph;
// Number of words in the paragraph
int len = num_words(paragraph);
do
{
add_commas(paragraph);
} while (sentinel == 1);
cout << paragraph << endl;
return 0;
}
int num_words(string str)
{
int len = 0;
for (int i = 0; str[i] != '\0'; i++)
{
if (str[i] == ' ' || (str[i] == '.' && str[i + 1] == ' '))
{
len++;
}
}
return len;
}
void add_commas(string ¶graph)
{
for (int i = 0, n = paragraph.length(); i < n; i++)
{
if (paragraph[i] == ',')
{
// get the before and after words.
get_words(i, paragraph);
}
}
}
void get_words(int i, string &str)
{
// or store results in global array with not duplicates.
int j = i;
while (str[j - 1] != ' ' && (j - 1) != -1)
{
j--;
}
// make a variable for it
string prev;
// get the previous word
for (int k = j; k < i; k++)
{
prev.push_back(str[k]);
}
add_commas_to(str, prev, 'a');
// get the next word
int end = i + 1;
while (str[end + 1] != ' ' && str[end + 1] != '.')
{
end++;
}
// next word variable
string next;
for (int k = i + 2; k < end + 1; k++)
{
next.push_back(str[k]);
}
add_commas_to(str, next, 'b');
// store into global array;
// TODO
}
void add_commas_to(string ¶graph, string word, char where)
{
size_t found = paragraph.find(word);
int k = 0;
while (found != -1 && found < paragraph.length() - word.length())
{
if (where == 'b')
{
if (paragraph[found - 2] != ',' && paragraph[found - 2] != '.')
{
k = 1;
paragraph.insert(found - 1, ",");
}
}
else if (where == 'a')
{
if (paragraph[found + word.length()] != ',' && paragraph[found + word.length()] != '.')
{
k = 1;
paragraph.insert(found + word.length(), ",");
}
}
found = paragraph.find(word, found + word.length());
}
if (k == 0)
{
sentinel = 0;
}
}
|
#pragma once
#include "zombie.h"
class zombie_type4 :
public zombie
{
public:
zombie_type4(BaseEngine* pEngine);
~zombie_type4(void);
};
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
*/
#ifndef MDE_WIDGET_H
#define MDE_WIDGET_H
#include "modules/libgogi/mde.h"
#include "modules/pi/OpWindow.h"
class OpPaintListener;
class OpMouseListener;
class OpTouchListener;
class OpDragListener;
class OpView;
#ifndef VEGA_OPPAINTER_SUPPORT
class OpPainter;
#endif
class MDE_WidgetVisibilityListener
{
public:
virtual ~MDE_WidgetVisibilityListener(){}
virtual void OnVisibilityChanged(bool vis) = 0;
};
class MDE_Widget : public MDE_View
{
public:
#ifdef VEGA_OPPAINTER_SUPPORT
MDE_Widget(OpRect size);
#else
MDE_Widget(OpPainter *painter, OpRect size);
#endif
~MDE_Widget();
void SetOpWindow(OpWindow* win){window = win;}
void SetOpView(OpView* v){view = v;}
OpWindow* GetOpWindow(){return window;}
OpView* GetOpView(){return view;}
OpWindow *GetParentWindow();
OpWindow* GetRootWindow();
void SetIsShadow(bool shadow, bool fullscreen) { is_shadow = shadow; is_fullscreen_shadow = fullscreen; }
void SetPaintListener(OpPaintListener *pl, OpView *view);
bool OnBeforePaintEx();
void OnPaint(const MDE_RECT &rect, MDE_BUFFER *screen);
void OnRectChanged(const MDE_RECT &old_rect);
void OnInvalidSelf();
bool GetScrollMoveAllowed();
bool Paint(OpPainter *painter);
#ifndef MOUSELESS
void SetMouseListener(OpMouseListener *ml, OpView *view);
OpMouseListener* GetMouseListener();
void OnMouseDown(int x, int y, int button, int clicks, ShiftKeyState keystate);
void OnMouseUp(int x, int y, int button, ShiftKeyState keystate);
void OnMouseMove(int x, int y, ShiftKeyState keystate);
/** Positive is a turn against the user. return true if you implement it. If it return false, the parent will get it. */
bool OnMouseWheel(int delta, bool vertical, ShiftKeyState keystate);
void OnMouseLeave();
void OnMouseCaptureRelease();
void GetMousePos(int *x, int *y);
bool GetMouseButton(int button);
#ifdef TOUCH_EVENTS_SUPPORT
void SetMouseButton(int button, bool set);
#endif // TOUCH_EVENTS_SUPPORT
bool GetHitStatus(int x, int y);
#endif // MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
void SetTouchListener(OpTouchListener* listener, OpView *view);
void OnTouchDown(int id, int x, int y, int radius, ShiftKeyState modifiers, void *user_data);
void OnTouchUp(int id, int x, int y, int radius, ShiftKeyState modifiers, void *user_data);
void OnTouchMove(int id, int x, int y, int radius, ShiftKeyState modifiers, void *user_data);
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
void SetDragListener(OpDragListener *drag_listener, OpView *view);
OpDragListener* GetDragListener() { return dragListener; }
void OnDragStart(int start_x, int start_y, ShiftKeyState modifiers, int current_x, int current_y);
void OnDragDrop(int x, int y, ShiftKeyState modifiers);
void OnDragEnd(int x, int y, ShiftKeyState modifiers);
void OnDragMove(int x, int y, ShiftKeyState modifiers);
void OnDragLeave(ShiftKeyState modifiers);
void OnDragCancel(ShiftKeyState modifiers);
void OnDragEnter(int x, int y, ShiftKeyState modifiers);
void OnDragUpdate(int x, int y);
#endif // DRAG_SUPPORT
void ScrollRect(const OpRect& rect, INT32 dx, INT32 dy, bool includeChildren);
virtual bool GetOnVisibilityChangeWanted() { return window ? true : false; }
virtual void OnVisibilityChanged(bool vis){if (visListener) visListener->OnVisibilityChanged(vis);}
void SetVisibilityListener(MDE_WidgetVisibilityListener* v){visListener = v;}
bool IsFullscreenShadow(){return is_shadow && is_fullscreen_shadow;}
virtual bool IsType(const char* type){if (!is_shadow && !op_strcmp(type, "MDE_Widget")) return true; return MDE_View::IsType(type);}
/** Invalidate the cached backbuffer for this widget and all child widgets */
void InvalidateCache();
private:
OpPaintListener *paintListener;
#ifndef VEGA_OPPAINTER_SUPPORT
OpPainter *painter;
#endif
#ifndef MOUSELESS
OpMouseListener *mouseListener;
bool mouseButton[3];
int mx, my;
#endif // MOUSELESS
#ifdef TOUCH_EVENTS_SUPPORT
OpTouchListener *touchListener;
#endif // TOUCH_EVENTS_SUPPORT
#ifdef DRAG_SUPPORT
OpDragListener *dragListener;
#endif // DRAG_SUPPORT
OpWindow* window;
OpView *view; // needed for listeners
bool is_shadow;
bool is_fullscreen_shadow;
bool is_cache_invalid;
MDE_WidgetVisibilityListener* visListener;
INT32 GetWindowTransparency();
};
#endif // MDE_WIDGET_H
|
//////////////////////////////////////
//
// Example #4: Vna System Settings
//
//////////////////////////////////////
// Display settings
bool isDisplayOn = vna.settings().isDisplayOn();
vna.settings().isDisplayOff();
vna.settings().displayOff();
vna.settings().displayOn();
// RF On/Off
bool isRfOn = vna.settings().isRfOutputPowerOn();
vna.settings().isRfOutputPowerOff();
vna.settings().rfOutputPowerOff();
vna.settings().rfOutputPowerOn();
// Low Power autocal
bool isLowPowerCal = vna.settings().isLowPowerAutoCalOn();
vna.settings().isLowPowerAutoCalOff();
vna.settings().lowPowerAutoCalOn();
vna.settings().lowPowerAutoCalOff();
// Dynamic IF Bandwidth
bool isDynamicIfBw = vna.settings().isDynamicIfBandwidthOn();
vna.settings().isDynamicIfBandwidthOff();
vna.settings().dynamicIfBandwidthOff();
vna.settings().dynamicIfBandwidthOn();
// User Presets
bool isUserPreset = vna.settings().isUserPresetOn();
vna.settings().isUserPresetOff();
vna.settings().setUserPreset("myPreset");
QString userPreset = vna.settings().userPreset(); // "myPreset"
vna.settings().userPresetOn();
vna.settings().userPresetOff();
// Map User Preset to *RST
// (vna.preset()) command
vna.settings().isUserPresetMappedToRst();
vna.settings().mapUserPresetToRst(true); // On
vna.settings().mapUserPresetToRst(false); // Off (default)
// Emulation Mode
vna.settings().isEmulationOn();
vna.settings().isEmulationOff();
vna.settings().isEmulationMode(HP_8720_EMULATION);
vna.settings().setEmulationMode(HP_8720_EMULATION);
vna.settings().setEmulationOff();
|
#ifndef EDITJSONFILE_H
#define EDITJSONFILE_H
#include <QMainWindow>
#include <QTableWidget>
#include <QMessageBox>
#include "SRC/Analyzer/DataTypes/election.h"
namespace Ui {
class EditJsonFile;
}
class IntTableWidgetItem : public QObject, public QTableWidgetItem {
Q_OBJECT
public:
IntTableWidgetItem(const QString& str)
:QTableWidgetItem(str)
{
}
bool operator <(const QTableWidgetItem &other ) const
{
if( this->text().toInt() < other.text().toInt() )
return true;
else
return false;
}
};
class EditJsonFile : public QMainWindow
{
Q_OBJECT
public:
explicit EditJsonFile(QWidget *parent = 0);
void onLoad();
void onClose();
~EditJsonFile();
void closeEvent(QCloseEvent *event);
private:
Ui::EditJsonFile *ui;
EAnalyzer::Election election;
void SetElectionInfo(const EAnalyzer::Election& election);
void SetElectionData(const EAnalyzer::Election& election);
void GetElectionInfo(EAnalyzer::Election& election);
void GetElectionData(EAnalyzer::Election& election);
void ShowElection(const EAnalyzer::Election& election);
void DeleteCandidate(int i);
void SetJson(const EAnalyzer::Election& election);
void SetRowColor(int row, bool correct_result, bool strange_result);
bool update_data_table;
bool update_candidate_table;
public slots:
bool SaveJson();
void OpenJson();
void AddCandidate();
void DeleteLine(QTableWidgetItem* item);
void AddData();
void DeleteDataLine(QTableWidgetItem* item);
void SwitchElectionType(int i);
};
#endif // EDITJSONFILE_H
|
namespace json {
template<typename T> class ConvValueAs;
template<typename T> class ConvValueFrom;
template<> class ConvValueAs<StringView<char> > {
public:
static StringView<char> convert(const Value &v) {
return v.getString();
}
};
template<> class ConvValueFrom<StringView<char> > {
public:
static Value convert(const StringView<char> &v) {
return Value(v);
}
};
template<> class ConvValueAs<UInt > {
public:
static UInt convert(const Value &v) {
return v.getUInt();
}
};
template<> class ConvValueFrom<UInt > {
public:
static Value convert(UInt v) {
return Value(v);
}
};
template<> class ConvValueAs<Int > {
public:
static Int convert(const Value &v) {
return v.getInt();
}
};
template<> class ConvValueFrom<Int > {
public:
static Value convert(Int v) {
return Value(v);
}
};
template<> class ConvValueAs<double> {
public:
static double convert(const Value &v) {
return v.getNumber();
}
};
template<> class ConvValueFrom<double> {
public:
static Value convert(double v) {
return Value(v);
}
};
template<> class ConvValueAs<float> {
public:
static float convert(const Value &v) {
return (float)v.getNumber();
}
};
template<> class ConvValueFrom<float> {
public:
static Value convert(float v) {
return Value(v);
}
};
template<> class ConvValueAs<bool> {
public:
static bool convert(const Value &v) {
return v.getBool();
}
};
template<> class ConvValueFrom<bool> {
public:
static Value convert(bool v) {
return Value(v);
}
};
template<> class ConvValueAs<PValue> {
public:
static PValue convert(const Value &v) {
return v.getHandle();
}
};
template<> class ConvValueFrom<PValue> {
public:
static Value convert(PValue v) {
return Value(v);
}
};
template<> class ConvValueAs<std::string> {
public:
static std::string convert(const Value &v) {
return v.getString();
}
};
template<> class ConvValueFrom<std::string> {
public:
static Value convert(const std::string &v) {
return Value(v);
}
};
template<typename T> class ConvValueAs<std::vector<T> > {
public:
static std::vector<T> convert(const Value &v) {
std::vector<T> out;
out.reserve(v.size());
for(auto &&x : v) out.push_back(x.as<T>());
return out;
}
};
template<typename T> class ConvValueFrom<std::vector<T> > {
public:
static Value convert(const std::vector<T> &v) {
std::vector<Value> x;
x.reserve(v.size());
for (auto &&k : v) {
x.push_back(Value::from<T>(k));
}
return Value(std::move(x));
}
};
}
|
// -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
//
// Copyright (C) 2006-2011 Opera Software ASA. All rights reserved.
//
// This file is part of the Opera web browser. It may not be distributed
// under any circumstances.
#include "core/pch.h"
#ifdef WEBFEEDS_BACKEND_SUPPORT
#include "modules/webfeeds/src/webfeeds_api_impl.h"
#include "modules/webfeeds/src/webfeed.h"
#include "modules/webfeeds/src/webfeedstorage.h"
#include "modules/webfeeds/src/webfeedutil.h"
#include "modules/webfeeds/src/webfeed_load_manager.h"
#include "modules/webfeeds/src/webfeed_reader_manager.h"
#include "modules/about/operafeeds.h"
#include "modules/doc/frm_doc.h" // finding form elements
#include "modules/dochand/win.h"
#include "modules/dochand/winman.h"
#include "modules/forms/formvalueradiocheck.h"
#include "modules/forms/src/formiterator.h"
#include "modules/hardcore/mh/constant.h" // Message constants
#include "modules/locale/oplanguagemanager.h"
#include "modules/logdoc/logdoc.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/prefs/prefsmanager/collections/pc_files.h"
#include "modules/prefs/prefsmanager/collections/pc_network.h"
#include "modules/stdlib/util/opdate.h"
#include "modules/url/url_man.h"
#ifdef SKIN_SUPPORT
# include "modules/skin/OpSkinManager.h"
#endif
//#define DEBUG_FEEDS_UPDATING
#define WEBFEEDS_UPDATE_FEEDS
const UINT msPerMin = 60000;
/* static */ BOOL OpFeed::IsFailureStatus(FeedStatus status)
{
switch (status)
{
case STATUS_OK:
case STATUS_REFRESH_POSTPONED:
case STATUS_NOT_MODIFIED:
return FALSE;
default:
return TRUE;
}
}
/*******************************
* WebFeedFormIterator
*******************************/
OP_STATUS WebFeedFormIterator::Init(FramesDocument* frm_doc, const uni_char* id)
{
if (!frm_doc)
return OpStatus::ERR_NULL_POINTER;
LogicalDocument* logdoc = frm_doc->GetLogicalDocument();
if (!logdoc)
return OpStatus::ERR_NULL_POINTER;
HTML_Element* root = logdoc->GetDocRoot();
if (!root)
return OpStatus::ERR_NULL_POINTER;
// Get form
NamedElementsIterator it;
logdoc->SearchNamedElements(it, root, id, TRUE, FALSE);
HTML_Element* form = it.GetNextElement();
if (!form)
return OpStatus::ERR;
m_form_iterator = OP_NEW(FormIterator, (frm_doc, form));
if (!m_form_iterator.get())
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
HTML_Element* WebFeedFormIterator::GetNext()
{
return m_form_iterator->GetNext();
}
/*******************************
* WebFeedsAPI_impl
*******************************/
WebFeedsAPI_impl::WebFeedsAPI_impl() : m_next_free_feedid(1),
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
m_store_space_factor(0.9), m_disk_space_used(0),
#endif
m_number_updating_feeds(0), m_max_size(0), m_max_age(0), m_max_entries(0),
m_update_interval(60), m_do_automatic_updates(FALSE), m_next_update(0.0),
m_show_images(TRUE), m_skin_feed_icon_exists(FALSE), m_feeds(NULL)
{
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
for (UINT i=0; i < ARRAY_SIZE(m_feeds_memory_cache); i++)
m_feeds_memory_cache[i] = NULL;
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
}
void WebFeedsAPI_impl::HashDelete(const void*, void* data)
{
WebFeedStub* stub = (WebFeedStub*)data;
if (stub)
stub->StoreDestroyed();
}
WebFeedsAPI_impl::~WebFeedsAPI_impl()
{
#ifdef WEBFEEDS_AUTOSAVE
// ignore status, if we can't save at this point there really isn't
// much we can do about it
TRAPD(status, GetStorage()->SaveStoreL(this));
#endif
UnRegisterCallbacks();
m_feeds->ForEach(HashDelete);
OP_DELETE(m_feeds);
}
OP_STATUS WebFeedsAPI_impl::Init()
{
mh = g_main_message_handler;
OP_ASSERT(mh);
RegisterCallbacks();
// TODO: should we post a delayed update of all feeds at startup?
// mh->PostDelayedMessage(MSG_WEBFEEDS_UPDATE_FEEDS, 0, 0, 1000);
OP_ASSERT(!m_feeds);
m_feeds = OP_NEW(OpHashTable, ());
if (!m_feeds)
return OpStatus::ERR_NO_MEMORY;
m_load_manager = OP_NEW(WebFeedLoadManager, ());
if (!m_load_manager.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_load_manager->Init());
#ifdef WEBFEEDS_EXTERNAL_READERS
m_external_reader_manager = OP_NEW(WebFeedReaderManager, ());
if (!m_external_reader_manager.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(m_external_reader_manager->Init());
#endif // WEBFEEDS_EXTERNAL_READERS
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
m_storage = OP_NEW(WebFeedStorage, ());
if (!m_storage.get())
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_MEMORY_ERROR(m_storage->LoadStore(this));
RETURN_IF_MEMORY_ERROR(DeleteUnusedFiles());
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
// What icon to use for feeds without their own icon:
#ifdef SKIN_SUPPORT
if (g_skin_manager->GetSkinElement("RSS"))
m_skin_feed_icon_exists = TRUE;
#endif
return OpStatus::OK;
}
OP_STATUS WebFeedsAPI_impl::RegisterCallbacks()
{
OP_ASSERT(mh);
#ifdef WEBFEEDS_UPDATE_FEEDS
RETURN_IF_ERROR(mh->SetCallBack(this, MSG_WEBFEEDS_UPDATE_FEEDS, 0));
#endif
RETURN_IF_ERROR(mh->SetCallBack(this, MSG_WEBFEEDS_FEED_LOADING_POSTPONED, 0));
return OpStatus::OK;
}
void WebFeedsAPI_impl::UnRegisterCallbacks()
{
OP_ASSERT(mh);
mh->UnsetCallBacks(this);
}
OP_STATUS WebFeedsAPI_impl::LoadFeed(URL& feed_url, OpFeedListener* listener, BOOL return_unchanged_feeds, time_t last_modified, const char* etag)
{
WebFeed* feed;
feed = return_unchanged_feeds ? (WebFeed*)GetFeedByUrl(feed_url) : NULL;
return LoadFeed(feed, feed_url, listener, return_unchanged_feeds, last_modified, etag);
}
OP_STATUS WebFeedsAPI_impl::LoadFeed(WebFeed* existing_feed, URL& feed_url, OpFeedListener* listener, BOOL return_unchanged_feeds, time_t last_modified, const char* etag)
{
WebFeedStub* stub = NULL;
// use redirected URL if we know it's a 301
if (feed_url.GetAttribute(URL::KHTTP_Response_Code, FALSE) == HTTP_MOVED)
feed_url = feed_url.GetAttribute(URL::KMovedToURL, TRUE);
// If already loaded, and time since last update not over minimum then return
// existing feed:
if (existing_feed)
{
stub = existing_feed->GetStub();
}
else
stub = GetStubByUrl(feed_url);
if (stub)
{
double current_time = OpDate::GetCurrentUTCTime();
if (current_time - stub->GetUpdateTime() < (stub->GetMinUpdateInterval() * 60000)) // 60000 ms per minute
{
if (listener)
{
WebFeed *feed = existing_feed;
if (!feed && return_unchanged_feeds)
feed = stub->GetFeed();
RETURN_IF_ERROR(m_postponed_listeners.Add(listener));
mh->PostMessage(MSG_WEBFEEDS_FEED_LOADING_POSTPONED, (MH_PARAM_1)listener, (feed ? (MH_PARAM_2)feed->GetId() : 0));
}
return OpStatus::OK;
}
}
if (last_modified || etag)
{
if (!stub)
{
// can't expect to get back a feed if there is no existing feed,
// and doesn't want to load if not modified
OP_ASSERT(!return_unchanged_feeds);
return_unchanged_feeds = FALSE;
}
}
else if (stub)
{
last_modified = stub->GetHttpLastModified();
etag = stub->GetHttpETag();
}
return m_load_manager->LoadFeed(existing_feed, feed_url, listener, return_unchanged_feeds, last_modified, etag);
}
OP_STATUS WebFeedsAPI_impl::AbortLoading(URL& feed_url)
{
return m_load_manager->AbortLoading(feed_url);
}
OP_STATUS WebFeedsAPI_impl::AbortAllFeedLoading(BOOL updating_feeds_only)
{
return m_load_manager->AbortAllFeedLoading(updating_feeds_only);
}
UINT WebFeedsAPI_impl::GetMaxSize() { return m_max_size; }
void WebFeedsAPI_impl::SetMaxSize(UINT size) { m_max_size = size; }
UINT WebFeedsAPI_impl::GetDefMaxAge() { return m_max_age; }
void WebFeedsAPI_impl::SetDefMaxAge(UINT age) { m_max_age = age; }
UINT WebFeedsAPI_impl::GetDefMaxEntries() { return m_max_entries; }
void WebFeedsAPI_impl::SetDefMaxEntries(UINT entries) { m_max_entries = entries; }
UINT WebFeedsAPI_impl::GetDefUpdateInterval() { return m_update_interval; }
void WebFeedsAPI_impl::SetDefUpdateInterval(UINT interval)
{
m_update_interval = interval;
#ifdef WEBFEEDS_AUTO_UPDATES_SUPPORT
ScheduleNextUpdate();
#endif
}
BOOL WebFeedsAPI_impl::GetDefShowImages() { return m_show_images; }
void WebFeedsAPI_impl::SetDefShowImages(BOOL show) { m_show_images = show; }
void WebFeedsAPI_impl::SetNextFreeFeedId(OpFeed::FeedId id) { m_next_free_feedid = id; }
OP_STATUS WebFeedsAPI_impl::AddUpdateListener(OpFeedListener* listener)
{
if (!listener || (m_update_listeners.Find(listener) != -1)) // No listener or listener already registered
return OpStatus::OK;
return m_update_listeners.Add(listener);
}
OP_STATUS WebFeedsAPI_impl::AddOmniscientListener(OpFeedListener* listener)
{
if (!listener || (m_omniscient_listeners.Find(listener) != -1)) // No listener or listener already registered
return OpStatus::OK;
return m_omniscient_listeners.Add(listener);
}
OpVector<OpFeedListener>* WebFeedsAPI_impl::GetAllOmniscientListeners()
{
return &m_omniscient_listeners;
}
static void RemoveAllOfItem(OpVector<OpFeedListener>& vector, OpFeedListener* item)
{
for (int i = vector.GetCount() - 1; i >= 0; i--)
if (vector.Get(i) == item)
vector.Remove(i);
}
OP_STATUS WebFeedsAPI_impl::RemoveListener(OpFeedListener* listener)
{
RemoveAllOfItem(m_update_listeners, listener);
RemoveAllOfItem(m_omniscient_listeners, listener);
RemoveAllOfItem(m_postponed_listeners, listener);
RETURN_IF_MEMORY_ERROR(m_load_manager->RemoveListener(listener));
return OpStatus::OK;
}
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
UINT WebFeedsAPI_impl::GetFeedDiskSpaceQuota()
{
if (g_webfeeds_api_impl->GetMaxSize() > 0) // 0 == unlimited
{
// Sanity check:
if (g_webfeeds_api_impl->GetMaxSize() < g_webfeeds_api_impl->GetDiskSpaceUsed())
{
OP_ASSERT(!"All allowable disk space used by store file by itself");
return 1;
}
return (UINT)((g_webfeeds_api_impl->GetMaxSize() - g_webfeeds_api_impl->GetDiskSpaceUsed())
/ g_webfeeds_api_impl->GetNumberOfFeeds()
* g_webfeeds_api_impl->GetMaxSizeSpaceFactor());
}
else
return 0;
}
OP_STATUS WebFeedsAPI_impl::DeleteUnusedFiles()
{
OpStackAutoPtr<OpFolderLister> lister(NULL);
lister.reset(OpFile::GetFolderLister(OPFILE_WEBFEEDS_FOLDER, UNI_L("*")));
if (!lister.get())
return OpStatus::ERR;
while (lister->Next())
{
const uni_char* filename = lister->GetFileName();
OpFeed::FeedId id = 0;
if (uni_sscanf(filename, UNI_L("%08x"), &id) != 1)
continue;
if (!uni_strcmp(filename, UNI_L("feedreaders.ini")))
continue;
if (GetFeedById(id) || lister->IsFolder())
continue;
OpFile unused_file;
OP_STATUS status = unused_file.Construct(lister->GetFullPath());
if (OpStatus::IsMemoryError(status))
return status;
if (status != OpStatus::OK)
continue;
RETURN_IF_MEMORY_ERROR(unused_file.Delete());
}
return OpStatus::OK;
}
UINT WebFeedsAPI_impl::SaveL(WriteBuffer &buf)
{
UINT pre_space_used = buf.GetBytesWritten();
OP_ASSERT(m_feeds);
buf.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
buf.Append("<!DOCTYPE store SYSTEM \"storage.dtd\" [\n");
buf.Append(" <!ELEMENT store (defaults | feed*)>\n");
buf.Append(" <!ATTLIST store\n");
buf.Append(" default-update-interval NMTOKEN #REQUIRED\n");
buf.Append(" space-factor CDATA \"0.9\">]>\n");
buf.Append("<store default-update-interval=\"");
buf.Append(m_update_interval);
buf.Append("\" space-factor=\"");
buf.Append((UINT)(m_store_space_factor * 100.0));
buf.Append("\">\n");
buf.Append("<defaults>\n");
WebFeed::WriteSettingNum(buf, "max-size", m_max_size);
WebFeed::WriteSettingNum(buf, "max-age", m_max_age);
WebFeed::WriteSettingNum(buf, "max-entries", m_max_entries);
WebFeed::WriteSettingBool(buf, "show-images", m_show_images);
buf.Append("</defaults>\n");
UINT total_disk_space_used = 0;
BOOL is_space_limited = FALSE;
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
LEAVE(OpStatus::ERR_NO_MEMORY);
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
{
WebFeedStub* stub = (WebFeedStub*)iter->GetData();
OP_ASSERT(stub);
if (stub->IsSubscribed())
{
stub->SaveL(buf, TRUE);
if (stub->FeedNeedSaving())
m_storage->SaveFeedL(stub->GetFeed());
if (stub->HasReachedDiskSpaceLimit())
is_space_limited = TRUE;
}
total_disk_space_used += stub->GetDiskSpaceUsed();
}
buf.Append("</store>\n");
m_disk_space_used = buf.GetBytesWritten() - pre_space_used;
total_disk_space_used += m_disk_space_used;
UINT max_size = GetMaxSize();
if (max_size > 0)
{
double excess_ratio = (double(max_size) - total_disk_space_used) / max_size;
if (excess_ratio < 0 || is_space_limited) // don't increase limit if no one needs more space
{
m_store_space_factor += excess_ratio;
if (m_store_space_factor > 2.0)
m_store_space_factor = 2.0;
else if (m_store_space_factor < 0.2)
m_store_space_factor = 0.2;
}
}
return m_disk_space_used;
}
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
OP_STATUS WebFeedsAPI_impl::AddFeed(WebFeed* feed)
{
if (!feed->GetTitle()->IsBinary() && !feed->GetStub()->HasTitle())
feed->GetStub()->SetTitle(feed->GetTitle()->Data());
return AddFeed(feed->GetStub());
}
OP_STATUS WebFeedsAPI_impl::AddFeed(WebFeedStub* stub) //, OpFeed::FeedId id)
{
OP_ASSERT(stub);
OpFeed::FeedId id = stub->GetId();
if (id == 0)
{
id = m_next_free_feedid++;
stub->SetId(id);
}
else
{
void* old_stub = NULL;
if (m_feeds->GetData(reinterpret_cast<void*>(id), &old_stub) == OpStatus::OK) // We already have a stub for this feed
{
if (old_stub == stub)
{
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
// Check if this feed is in memory cache already
for (UINT i=0; i<ARRAY_SIZE(m_feeds_memory_cache); i++)
{
if (m_feeds_memory_cache[i] == NULL)
{
m_feeds_memory_cache[i] = stub;
return OpStatus::OK;
}
else if (m_feeds_memory_cache[i] == stub)
{
// Is already in cache, move it to the end so it lives longer
for (; i<ARRAY_SIZE(m_feeds_memory_cache)-1 && m_feeds_memory_cache[i+1]; i++)
m_feeds_memory_cache[i] = m_feeds_memory_cache[i+1];
m_feeds_memory_cache[i] = stub;
return OpStatus::OK;
}
}
// No room in cache, throw some old feed out and insert this
ReplaceOldestInCache(stub);
#else
// feed already in memory
return OpStatus::OK;
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
}
else if (m_feeds->Remove(reinterpret_cast<void*>(id), &old_stub) == OpStatus::OK)
{
OP_ASSERT(!"Who was a bad boy and created a new stub for an existing feed?");
WebFeedStub* to_delete = (WebFeedStub*)old_stub;
OP_DELETE(to_delete);
}
}
}
RETURN_IF_ERROR(m_feeds->Add(reinterpret_cast<void*>(id), (void*)stub));
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
AddToInternalFeedCache(stub);
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
stub->IncRef();
return OpStatus::OK;
}
OP_STATUS WebFeedsAPI_impl::CheckAllFeedsForNumEntries()
{
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
return OpStatus::ERR_NO_MEMORY;
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
((WebFeedStub*)iter->GetData())->GetFeed()->CheckFeedForNumEntries(0);
return OpStatus::OK;
}
OP_STATUS WebFeedsAPI_impl::CheckAllFeedsForExpiredEntries()
{
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
return OpStatus::ERR_NO_MEMORY;
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
((WebFeedStub*)iter->GetData())->GetFeed()->CheckFeedForExpiredEntries();
return OpStatus::OK;
}
#ifdef WEBFEEDS_EXTERNAL_READERS
unsigned WebFeedsAPI_impl::GetExternalReaderCount() const
{
return m_external_reader_manager->GetCount();
}
unsigned WebFeedsAPI_impl::GetExternalReaderIdByIndex(unsigned index) const
{
return m_external_reader_manager->GetIdByIndex(index);
}
OP_STATUS WebFeedsAPI_impl::GetExternalReaderName(unsigned id, OpString& name) const
{
return m_external_reader_manager->GetName(id, name);
}
OP_STATUS WebFeedsAPI_impl::GetExternalReaderTargetURL(unsigned id, const URL& feed_url, URL& target_url) const
{
return m_external_reader_manager->GetTargetURL(id, feed_url, target_url);
}
#ifdef WEBFEEDS_ADD_REMOVE_EXTERNAL_READERS
OP_STATUS WebFeedsAPI_impl::GetExternalReaderCanEdit(unsigned id, BOOL& can_edit) const
{
WebFeedReaderManager::ReaderSource source;
RETURN_IF_ERROR(m_external_reader_manager->GetSource(id, source));
can_edit = source == WebFeedReaderManager::READER_CUSTOM;
return OpStatus::OK;
}
unsigned WebFeedsAPI_impl::GetExternalReaderFreeId() const
{
return m_external_reader_manager->GetFreeId();
}
OP_STATUS WebFeedsAPI_impl::AddExternalReader(unsigned id, const uni_char *feed_url, const uni_char *feed_name) const
{
return m_external_reader_manager->AddReader(id, feed_url, feed_name);
}
BOOL WebFeedsAPI_impl::HasExternalReader(const uni_char *feed_url, unsigned *id /* = NULL */) const
{
return m_external_reader_manager->HasReader(feed_url, id);
}
OP_STATUS WebFeedsAPI_impl::DeleteExternalReader(unsigned id) const
{
return m_external_reader_manager->DeleteReader(id);
}
#endif // WEBFEEDS_ADD_REMOVE_EXTERNAL_READERS
#endif // WEBFEEDS_EXTERNAL_READERS
#ifdef WEBFEEDS_SAVED_STORE_SUPPORT
void WebFeedsAPI_impl::AddToInternalFeedCache(WebFeedStub* stub)
{
if (!stub)
return;
UINT ncached = 0; // ncached should also point to first free index in the array
UINT max_cached = ARRAY_SIZE(m_feeds_memory_cache);
for (ncached=0; ncached<max_cached && m_feeds_memory_cache[ncached]; ncached++)
/* empty body */ ;
#ifdef _DEBUG // Make sure we don't have holes in cache. No one else should call
// RemoveFeedFromMemory, and since we always remove the first and move all the others
// one step up, there should never be any feeds after first NULL
for (UINT rest=ncached; rest<max_cached; rest++)
OP_ASSERT(m_feeds_memory_cache[rest] == NULL);
#endif
OP_ASSERT(ncached <= max_cached);
if (ncached >= max_cached)
ReplaceOldestInCache(stub);
else
m_feeds_memory_cache[ncached] = stub;
}
void WebFeedsAPI_impl::ReplaceOldestInCache(WebFeedStub* stub)
{
if (stub == m_feeds_memory_cache[0])
return;
// Have to throw out one feed from memory, choose oldest one
m_feeds_memory_cache[0]->RemoveFeedFromMemory();
// copy all the others one step forward in array
for (UINT i=1; i<ARRAY_SIZE(m_feeds_memory_cache); i++)
m_feeds_memory_cache[i-1] = m_feeds_memory_cache[i];
m_feeds_memory_cache[ARRAY_SIZE(m_feeds_memory_cache)-1] = stub;
}
#endif // WEBFEEDS_SAVED_STORE_SUPPORT
#ifdef WEBFEEDS_AUTO_UPDATES_SUPPORT
void WebFeedsAPI_impl::DoAutomaticUpdates(BOOL auto_update)
{
m_do_automatic_updates = auto_update;
if (auto_update)
ScheduleNextUpdate();
#ifdef WEBFEEDS_UPDATE_FEEDS
else
mh->RemoveDelayedMessage(MSG_WEBFEEDS_UPDATE_FEEDS, 0, 0);
#endif
}
#endif // WEBFEEDS_AUTO_UPDATES_SUPPORT
void WebFeedsAPI_impl::FeedFinished(OpFeed::FeedId id)
{
// Bookkeeping for updating feeds.
// UpdateFeeds sets the IsUpdating flag for each feed it starts an update, and counts
// how many is updating. Here we remove the flag, and when no more feeds are updating
// notify the updatelisteners.
WebFeedStub* stub = GetStubById(id);
if (stub && stub->IsUpdating())
{
stub->SetIsUpdating(FALSE);
m_number_updating_feeds--;
if (m_number_updating_feeds == 0)
UpdateFinished();
}
}
void WebFeedsAPI_impl::UpdateFinished()
{
// Notify listeners and schedule next automatic update
UINT i;
for (i = 0; i < m_update_listeners.GetCount(); i++)
m_update_listeners.Get(i)->OnUpdateFinished();
for (i = 0; i < m_omniscient_listeners.GetCount(); i++)
m_omniscient_listeners.Get(i)->OnUpdateFinished();
m_update_listeners.Clear();
#ifdef WEBFEEDS_AUTO_UPDATES_SUPPORT
ScheduleNextUpdate();
#endif
#ifdef WEBFEEDS_AUTOSAVE
TRAPD(status, GetStorage()->SaveStoreL(this));
if (OpStatus::IsMemoryError(status))
g_memory_manager->RaiseCondition(status);
#endif
}
#ifdef WEBFEEDS_AUTO_UPDATES_SUPPORT
void WebFeedsAPI_impl::ScheduleNextUpdate()
{
// Post a message so we will be called again in time for next automatic update
double current_time = OpDate::GetCurrentUTCTime();
double next_default_update = current_time + (m_update_interval * msPerMin);
if (m_next_update == 0.0 || m_next_update > next_default_update) // no time specified, use update interval
m_next_update = next_default_update;
OP_ASSERT(m_next_update - current_time >= -120000); // two minutes - if the loading of a feed takes a long time to time out, and the update interval is short then the next update may be scheduled before the last has finished
unsigned long time_until_next_update;
if (m_next_update - current_time > msPerMin)
time_until_next_update = (unsigned long)(m_next_update - current_time);
else
time_until_next_update = msPerMin;
#ifdef WEBFEEDS_UPDATE_FEEDS
#ifdef DEBUG_FEEDS_UPDATING
printf("Next update in %d minutes %d seconds\n", (int)(time_until_next_update/msPerMin), (int)((time_until_next_update%msPerMin)/1000));
#endif
if (GetAutoUpdate())
mh->PostDelayedMessage(MSG_WEBFEEDS_UPDATE_FEEDS, 0, 0, time_until_next_update);
#endif
}
#endif // WEBFEEDS_AUTO_UPDATES_SUPPORT
OP_STATUS WebFeedsAPI_impl::UpdateSingleFeed(WebFeedStub* stub, OpFeedListener *listener, BOOL return_unchanged_feeds, BOOL force_update)
{
const double fudge_factor = 0.5; // Amount of update interval which must have passed before we do an update
// This is so that we try to update feeds simultaniously
// The timestamps are in milliseconds, while the intervals stored in feeds/store
// is in minutes. Hence all the *60000 when adding interval to timestamp.
double current_time = OpDate::GetCurrentUTCTime();
OP_ASSERT(stub);
OP_ASSERT(stub->GetUpdateTime() != 0.0); // All feeds should get their time set when parsing
double feed_next_update = stub->GetUpdateTime() + (stub->GetUpdateInterval() * msPerMin);
const double fudged_interval = stub->GetUpdateInterval() * msPerMin * fudge_factor;
if ((!force_update && (current_time + fudged_interval) < feed_next_update) || // check if update interval has passed (but allow feed to be updated before it should have been by amount of fudge factor
(current_time - stub->GetUpdateTime()) < (stub->GetMinUpdateInterval() * msPerMin)) // Mimimum time must always have passed
{
if (listener)
{
if (return_unchanged_feeds)
listener->OnFeedLoaded(stub->GetFeed(), OpFeed::STATUS_REFRESH_POSTPONED);
else // don't actually return the feed object for unchanged
// feeds, as that might require loading it from disk
listener->OnFeedLoaded(NULL, OpFeed::STATUS_REFRESH_POSTPONED);
}
}
else // safe to update feed
{
OP_ASSERT(stub->GetId() != 0);
stub->SetIsUpdating(TRUE);
m_number_updating_feeds++;
if (m_load_manager->UpdateFeed(stub->GetURL(), stub->GetId(), listener, return_unchanged_feeds, stub->GetHttpLastModified(), stub->GetHttpETag()) == OpStatus::ERR_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
feed_next_update = current_time + (stub->GetUpdateInterval() * msPerMin);
}
if (m_next_update == 0.0 || feed_next_update < m_next_update)
m_next_update = feed_next_update;
return OpStatus::OK;
}
OP_STATUS WebFeedsAPI_impl::UpdateFeeds(OpFeedListener *listener, BOOL return_unchanged_feeds, BOOL force_update)
{
// Remove any messages telling us to update, in case there was an automatic update
// scheduled, but we are updating manually
#ifdef WEBFEEDS_UPDATE_FEEDS
mh->RemoveDelayedMessage(MSG_WEBFEEDS_UPDATE_FEEDS, 0, 0);
#endif
m_next_update = 0.0; // will use default update interval
// If in offline mode, just return immediately
if (g_pcnet->GetIntegerPref(PrefsCollectionNetwork::OfflineMode))
{
UpdateFinished();
return OpStatus::OK;
}
if (m_number_updating_feeds > 0) // We only do one update at a time, so finish the one we're doing
{
AddUpdateListener(listener);
return OpStatus::OK;
}
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
return OpStatus::ERR_NO_MEMORY;
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
UpdateSingleFeed((WebFeedStub*)iter->GetData(), listener, return_unchanged_feeds, force_update);
if (m_number_updating_feeds > 0)
AddUpdateListener(listener);
else // no feeds needed updating
UpdateFinished();
return OpStatus::OK;
}
WebFeedsAPI_impl::WebFeedStub* WebFeedsAPI_impl::GetStubByUrl(const URL& feed_url)
{
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
return NULL;
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
{
WebFeedStub* stub = (WebFeedStub*)iter->GetData();
OP_ASSERT(stub);
if (stub->GetURL() == feed_url)
return stub;
}
return NULL;
}
WebFeedsAPI_impl::WebFeedStub* WebFeedsAPI_impl::GetStubById(OpFeed::FeedId id)
{
if (!id)
return NULL;
void* stub = NULL;
if (m_feeds->GetData(reinterpret_cast<void*>(id), &stub) != OpStatus::OK)
return NULL;
return (WebFeedStub*)stub;
}
OpFeed* WebFeedsAPI_impl::GetFeedByUrl(const URL& feed_url)
{
WebFeedStub* stub = GetStubByUrl(feed_url);
if (stub)
return stub->GetFeed();
return NULL;
}
OpFeed* WebFeedsAPI_impl::GetFeedById(OpFeed::FeedId id)
{
WebFeedStub* stub = GetStubById(id);
if (stub)
return stub->GetFeed(); // should only return NULL on error
return NULL;
}
UINT WebFeedsAPI_impl::GetNumberOfFeeds()
{
return (UINT)m_feeds->GetCount();
}
UINT* WebFeedsAPI_impl::GetAllFeedIds(UINT& length, BOOL subscribed_only)
{
length = 0;
const UINT nfeeds = GetNumberOfFeeds();
OpFeed::FeedId* ids = OP_NEWA(OpFeed::FeedId, nfeeds + 1); // plus 0 guard at end
if (!ids)
return NULL;
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
{
OP_DELETEA(ids);
return NULL;
}
UINT i = 0;
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
{
OP_ASSERT(i < nfeeds);
WebFeedStub* stub = (WebFeedStub*)iter->GetData();
OP_ASSERT(stub && stub->GetId());
if (!subscribed_only || stub->IsSubscribed())
{
ids[i] = stub->GetId();
i++;
}
}
length = i;
ids[i] = 0;
return ids;
}
#ifdef WEBFEEDS_DISPLAY_SUPPORT
OP_STATUS WebFeedsAPI_impl::GetFeedFromIdURL(const char* feed_id, OpFeed*& feed, OpFeedEntry*& entry, WebFeedsAPI_impl::FeedIdURLType& type)
{
feed = NULL;
entry = NULL;
if (!feed_id)
return OpStatus::ERR_NULL_POINTER;
feed_id = op_strchr(feed_id, '/');
if (!feed_id || !*(feed_id+1))
return OpStatus::ERR;
feed_id++; // skip leading slash
if (op_strncmp(feed_id, "all-subscribed", 14) == 0) // write list of subscribed feeds
{
type = SubscriptionListURL;
return OpStatus::OK;
}
if (op_strncmp(feed_id, "settings", 8) == 0) // settings page
{
type = GlobalSettingsURL;
return OpStatus::OK;
}
UINT fid;
char entry_str[9]; /* ARRAY OK 2009-04-27 arneh */
UINT num_ids = op_sscanf(feed_id, "%8x-%8s", &fid, entry_str);
if (num_ids == 0)
return OpStatus::ERR;
feed = (WebFeed*)GetFeedById(fid);
if (!feed)
return OpStatus::ERR;
if (num_ids == 1)
{
type = FeedIdURL;
return OpStatus::OK;
}
OP_ASSERT(num_ids == 2);
if (op_strcmp(entry_str, "settings") == 0)
{
type = FeedSettingsURL;
return OpStatus::OK;
}
UINT eid;
if (op_sscanf(entry_str, "%8x", &eid) != 1)
return OpStatus::ERR;
entry = (WebFeedEntry*)feed->GetEntryById(eid);
if (!entry)
return OpStatus::ERR;
type = EntryIdURL;
return OpStatus::OK;
}
WebFeedsAPI::OpFeedWriteStatus
WebFeedsAPI_impl::WriteByFeedId(const char* feed_id, URL& out_url)
{
OpFeed* feed = NULL;
OpFeedEntry* entry = NULL;
FeedIdURLType type;
if (OpStatus::IsError(GetFeedFromIdURL(feed_id, feed, entry, type)))
return WebFeedsAPI::IllegalId;
OP_STATUS status = OpStatus::OK;
switch (type)
{
case SubscriptionListURL:
status = WriteSubscriptionList(out_url);
break;
case FeedIdURL:
#ifdef WEBFEEDS_WRITE_SUBSCRIBE_BOX
status = feed->WriteFeed(out_url, TRUE, TRUE);
#else
status = feed->WriteFeed(out_url, TRUE, FALSE);
#endif // WEBFEEDS_WRITE_SUBSCRIBE_BOX
break;
case EntryIdURL:
#ifdef OLD_FEED_DISPLAY
status = entry->WriteEntry(out_url);
#endif // OLD_FEED_DISPLAY
break;
#ifdef WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
case GlobalSettingsURL:
TRAP(status, WriteGlobalSettingsPageL(out_url));
break;
case FeedSettingsURL:
TRAP(status, ((WebFeed*)feed)->WriteSettingsPageL(out_url));
break;
#endif // WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
default:
return WebFeedsAPI::IllegalId;
}
if (OpStatus::IsError(status))
return WebFeedsAPI::WriteError;
else
return WebFeedsAPI::Written;
}
#ifdef OLD_FEED_DISPLAY
inline void AddHTMLL(URL& out_url, const uni_char* data)
{
LEAVE_IF_ERROR(out_url.WriteDocumentData(URL::KNormal, data));
}
#endif
void WebFeedsAPI_impl::WriteSubscriptionListL(URL& out_url, BOOL complete_document)
{
#ifndef OLD_FEED_DISPLAY
out_url = urlManager->GetURL("opera:feed-id/all-subscribed");
OperaFeeds feed_preview(out_url, NULL);
LEAVE_IF_ERROR(feed_preview.GenerateData());
#else
// Create a new URL to write generated data to:
if (out_url.IsEmpty())
out_url = urlManager->GetNewOperaURL();
if (complete_document)
WebFeedUtil::WriteGeneratedPageHeaderL(out_url, UNI_L("Subscribed feeds")); // TODO: localize
// Write title of all feeds:
out_url.WriteDocumentDataUniSprintf(UNI_L("<h1>%s</h1>"), UNI_L("Subscribed feeds")); // TODO: localize text
out_url.WriteDocumentDataUniSprintf(UNI_L("<a href=\"%s\">%s</a>"), UNI_L(WEBFEEDS_SETTINGS_URL), UNI_L("settings")); // TODO: localize text
AddHTMLL(out_url, UNI_L("<form id=\"feed-selection\" action=\"\">\n<table>\n"));
OpStackAutoPtr<OpHashIterator> iter(m_feeds->GetIterator());
if (!iter.get())
LEAVE(OpStatus::ERR_NO_MEMORY);
for (OP_STATUS status = iter->First(); status != OpStatus::ERR; status = iter->Next())
{
WebFeedStub* stub = (WebFeedStub*)iter->GetData();
OP_ASSERT(stub);
if (stub)
{
if (!stub->IsSubscribed() || !stub->GetTitle())
continue;
OpString title; ANCHOR(OpString, title);
LEAVE_IF_ERROR(WebFeedUtil::StripTags(stub->GetTitle(), title));
OpString id_url; ANCHOR(OpString, id_url);
stub->GetFeedIdURL(id_url);
UINT unread_count = stub->GetUnreadCount();
if (unread_count > 0)
AddHTMLL(out_url, UNI_L("<tr class=\"unread\">"));
else
AddHTMLL(out_url, UNI_L("<tr>"));
AddHTMLL(out_url, UNI_L("<tr>"));
out_url.WriteDocumentDataUniSprintf(UNI_L("<td><a href=\"%s\">"), id_url.CStr());
OpString icon; ANCHOR(OpString, icon);
LEAVE_IF_ERROR(stub->GetInternalFeedIcon(icon));
if (!icon.IsEmpty())
{
AddHTMLL(out_url, UNI_L("<img src=\""));
AddHTMLL(out_url, icon.CStr());
AddHTMLL(out_url, UNI_L("\" alt=\"\"> "));
}
else
if (m_skin_feed_icon_exists)
AddHTMLL(out_url, UNI_L("<img src=\"\" class=\"noicon\" alt=\"\">"));
else
AddHTMLL(out_url, UNI_L("<img src=\"\" class=\"noicon noskin\" alt=\"\">"));
AddHTMLL(out_url, title.CStr());
AddHTMLL(out_url, UNI_L("</a></td><td>"));
out_url.WriteDocumentDataUniSprintf(UNI_L("%d/%d</td>"), stub->GetUnreadCount(), stub->GetTotalCount());
// Write status if not ok
if (stub->GetStatus() != OpFeed::STATUS_OK && stub->GetStatus() != OpFeed::STATUS_REFRESH_POSTPONED)
{
const uni_char* status;
if (stub->GetStatus() == OpFeed::STATUS_ABORTED)
status = UNI_L("Aborted");
else
status = UNI_L("Failed");
out_url.WriteDocumentDataUniSprintf(UNI_L("<td>[%s]</td>"), status); // TODO: localize string
}
else // else write timestamp of last update
{
uni_char* short_time = WebFeedUtil::TimeToShortString(stub->GetUpdateTime(), TRUE);
if (short_time)
out_url.WriteDocumentDataUniSprintf(UNI_L("<td>[%s]</td>"), short_time);
else
AddHTMLL(out_url, UNI_L("<td></td>"));
OP_DELETEA(short_time);
}
#ifdef WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
out_url.WriteDocumentDataUniSprintf(UNI_L("<td><input name=\"%x\" type=\"checkbox\"></td>"), stub->GetId());
out_url.WriteDocumentDataUniSprintf(UNI_L("<td><a href=\"%s-settings\">»</a></td>"), id_url.CStr());
#endif // WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
AddHTMLL(out_url, UNI_L("</tr>\n"));
}
}
AddHTMLL(out_url, UNI_L("</table>\n</form>\n"));
if (complete_document)
WebFeedUtil::WriteGeneratedPageFooterL(out_url);
#endif // OLD_FEED_DISPLAY
}
#ifdef OLD_FEED_DISPLAY
#ifdef WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
OP_STATUS WebFeedsAPI_impl::WriteGlobalSettingsPage(URL& out_url)
{
TRAPD(status, WriteGlobalSettingsPageL(out_url));
return status;
}
void WebFeedsAPI_impl::WriteGlobalSettingsPageL(URL& out_url)
{
const uni_char* title = UNI_L("Webfeeds settings");
// Create a new URL to write generated data to:
if (out_url.IsEmpty())
out_url = urlManager->GetNewOperaURL();
WebFeedUtil::WriteGeneratedPageHeaderL(out_url, title);
out_url.WriteDocumentDataUniSprintf(UNI_L("<h1>%s</h1>\n"), title);
AddHTMLL(out_url, UNI_L("<form id=\"global-feed-settings\" action=\"\">\n"));
AddHTMLL(out_url, UNI_L("<dl>\n"));
WriteUpdateAndExpireFormL(out_url, FALSE);
// total disk space
UINT space = GetMaxSize() / 1024; // unit is bytes originally, but won't showing anything less than kB in UI
UINT space_unit = 1;
const char* space_options[] = {"MB", "kB"};
if (space > 2048) // use MB as unit
{
space = (space + 512) / 1024;
space_unit = 0;
}
OpString options_string; ANCHOR(OpString, options_string);
// Iterate through and find if any feeds are selected
WebFeedFormIterator form_iter;
RETURN_IF_ERROR(form_iter.Init(frm_doc, UNI_L("feed-selection")));
for (HTML_Element* helm = form_iter.GetNext(); helm; helm = form_iter.GetNext())
{
FormValueRadioCheck* form_value = FormValueRadioCheck::GetAs(helm->GetFormValue());
if (form_value->IsChecked(helm))
{
const uni_char* id_string = helm->GetId();
const UINT id = (UINT)uni_strtol(id_string, NULL, 16);
if (id)
{
checked = TRUE;
return OpStatus::OK;
}
}
}
return OpStatus::OK;
}
OP_STATUS WebFeedsAPI_impl::RunCommandOnChecked(FramesDocument* frm_doc, WebFeedsAPI::SubscriptionListCommand command)
{
if (op_strcmp(frm_doc->GetURL().GetName(FALSE, PASSWORD_SHOW), WEBFEEDS_SUBSCRIBED_LIST_URL))
return OpStatus::ERR;
// Iterate through and find which feeds are selected
WebFeedFormIterator form_iter;
RETURN_IF_ERROR(form_iter.Init(frm_doc, UNI_L("feed-selection")));
for (HTML_Element* helm = form_iter.GetNext(); helm; helm = form_iter.GetNext())
{
FormValueRadioCheck* form_value = FormValueRadioCheck::GetAs(helm->GetFormValue());
if (form_value->IsChecked(helm))
{
const uni_char* id_string = helm->GetName();
const UINT id = (UINT)uni_strtol(id_string, NULL, 16);
WebFeed* feed = (WebFeed*)GetFeedById(id);
if (!feed)
continue;
switch (command)
{
case UnsubscribeMarked:
feed->UnSubscribe();
break;
case MarkAllRead:
feed->MarkAllEntries(OpFeedEntry::STATUS_READ);
break;
default:
OP_ASSERT(FALSE);
}
}
}
return OpStatus::OK;
}
#endif // WEBFEEDS_SUBSCRIPTION_LIST_FORM_UI
#endif // OLD_FEED_DISPLAY
#ifdef WEBFEEDS_REFRESH_FEED_WINDOWS
OP_STATUS WebFeedsAPI_impl::UpdateFeedWindow(WebFeed* feed)
{
// TODO: this code only checks windows, not frames. So it won't work
// if a feed is shown inside a frame. Should be rewritten to work with
// frames also
for (Window* win = g_window_manager->FirstWindow(); win; win = win->Suc())
{
const uni_char* win_url = ((URL)win->GetCurrentURL()).GetUniName(FALSE, PASSWORD_HIDDEN);
if (!win_url)
continue;
if (feed)
{
OpString id_url;
RETURN_IF_ERROR(feed->GetFeedIdURL(id_url));
if (id_url.Compare(win_url, id_url.Length()) == 0)
win->Reload();
}
if (uni_strncmp(win_url, UNI_L(WEBFEEDS_SUBSCRIBED_LIST_URL), uni_strlen(win_url)) == 0)
win->Reload();
}
return OpStatus::OK;
}
#endif // WEBFEEDS_REFRESH_FEED_WINDOWS
#endif // WEBFEEDS_DISPLAY_SUPPORT
void WebFeedsAPI_impl::HandleCallback(OpMessage msg, MH_PARAM_1 par1, MH_PARAM_2 par2)
{
switch (msg)
{
#ifdef WEBFEEDS_UPDATE_FEEDS
case MSG_WEBFEEDS_UPDATE_FEEDS:
RAISE_AND_RETURN_VOID_IF_ERROR(UpdateFeeds(NULL, FALSE, FALSE));
break;
#endif
case MSG_WEBFEEDS_FEED_LOADING_POSTPONED:
{
OpFeedListener* listener = (OpFeedListener*)par1;
// check that listener pointer still is valid
if (OpStatus::IsError(m_postponed_listeners.RemoveByItem(listener)))
break;
OpFeed* feed = GetFeedById((OpFeed::FeedId)par2);
listener->OnFeedLoaded(feed, OpFeed::STATUS_REFRESH_POSTPONED);
break;
}
default:
OP_ASSERT(!"Unknown message");
}
}
void OpFeedListener::OnUpdateFinished()
{
}
void OpFeedListener::OnFeedLoaded(OpFeed* feed, OpFeed::FeedStatus)
{
}
void OpFeedListener::OnEntryLoaded(OpFeedEntry* entry, OpFeedEntry::EntryStatus)
{
}
void OpFeedListener::OnNewEntryLoaded(OpFeedEntry* entry, OpFeedEntry::EntryStatus)
{
}
#endif // WEBFEEDS_BACKEND_SUPPORT
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( SIVA )
// Copyright (c) 1993-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _IGESSolid_SolidOfLinearExtrusion_HeaderFile
#define _IGESSolid_SolidOfLinearExtrusion_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <gp_XYZ.hxx>
#include <IGESData_IGESEntity.hxx>
class gp_Dir;
class IGESSolid_SolidOfLinearExtrusion;
DEFINE_STANDARD_HANDLE(IGESSolid_SolidOfLinearExtrusion, IGESData_IGESEntity)
//! defines SolidOfLinearExtrusion, Type <164> Form Number <0>
//! in package IGESSolid
//! Solid of linear extrusion is defined by translatin an
//! area determined by a planar curve
class IGESSolid_SolidOfLinearExtrusion : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESSolid_SolidOfLinearExtrusion();
//! This method is used to set the fields of the class
//! SolidOfLinearExtrusion
//! - aCurve : the planar curve that is to be translated
//! - aLength : the length of extrusion
//! - aDirection : the vector specifying the direction of extrusion
//! default (0,0,1)
Standard_EXPORT void Init (const Handle(IGESData_IGESEntity)& aCurve, const Standard_Real aLength, const gp_XYZ& aDirection);
//! returns the planar curve that is to be translated
Standard_EXPORT Handle(IGESData_IGESEntity) Curve() const;
//! returns the Extrusion Length
Standard_EXPORT Standard_Real ExtrusionLength() const;
//! returns the Extrusion direction
Standard_EXPORT gp_Dir ExtrusionDirection() const;
//! returns ExtrusionDirection after applying TransformationMatrix
Standard_EXPORT gp_Dir TransformedExtrusionDirection() const;
DEFINE_STANDARD_RTTIEXT(IGESSolid_SolidOfLinearExtrusion,IGESData_IGESEntity)
protected:
private:
Handle(IGESData_IGESEntity) theCurve;
Standard_Real theLength;
gp_XYZ theDirection;
};
#endif // _IGESSolid_SolidOfLinearExtrusion_HeaderFile
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
ll l1,l2,r1,r2,k;
cin>>l1>>r1>>l2>>r2>>k;
ll minn=min(r1,r2);
ll maxn=max(l1,l2);
ll ans=minn-maxn+1;
if(maxn>minn){
cout<<0;
return 0;
}
if(k>=maxn&&k<=minn){
ans--;
}
cout<<ans;
return 0;
}
|
#ifndef MODEL_H
#define MODEL_H
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <map>
#include <vector>
#include "model/mesh.h"
#include <graphics/texture.h>
using namespace std;
class Model {
public:
vector<Texture> textures_loaded;
vector<Mesh> meshes;
string directory;
bool gammaCorrection;
glm::mat4 transform;
Model(string const &path, bool gamma = false) : gammaCorrection(gamma) {
loadModel(path);
}
void Draw(Shader* shader, Camera* camera, std::vector<glm::mat4>* kinematic_chain) {
glm::vec3 view_pos = camera->Position();
glm::mat4 vp = camera->ProjMatrix() * camera->ViewMatrix();
shader->Bind();
glUniformMatrix4fv(glGetUniformLocation(shader->Id(), "view_proj"), 1, GL_FALSE, &vp[0][0]);
glUniform3f(glGetUniformLocation(shader->Id(), "view_pos"), view_pos.x, view_pos.y, view_pos.z);
glm::mat4 chain_tf = this->transform;
for(unsigned int ilink = 0; ilink < meshes.size(); ilink++) {
if (ilink != meshes.size() - 1)
chain_tf = chain_tf * meshes[ilink].transform;
if (ilink > 0 && ilink < 7)
chain_tf = chain_tf * (*kinematic_chain)[ilink - 1];
meshes[ilink].Draw(shader, chain_tf);
}
shader->Unbind();
}
private:
void loadModel(string const &path) {
Assimp::Importer importer;
const aiScene* scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
if(!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << endl;
return;
}
directory = path.substr(0, path.find_last_of('/'));
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
this->transform[j][i] = scene->mRootNode->mTransformation[i][j];
}
}
processNode(scene->mRootNode, scene, glm::mat4(1.0f));
}
void processNode(aiNode *node, const aiScene *scene, glm::mat4 parent_tf) {
glm::mat4 node_tf(1.0f);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++)
node_tf[j][i] = node->mTransformation[i][j];
}
for(unsigned int i = 0; i < node->mNumMeshes; i++) {
aiMesh* ai_mesh = scene->mMeshes[node->mMeshes[i]];
Mesh mesh = processMesh(ai_mesh, scene);
mesh.transform = node_tf;
meshes.push_back(mesh);
}
for(unsigned int i = 0; i < node->mNumChildren; i++)
processNode(node->mChildren[i], scene, glm::mat4(1.0f));
}
Mesh processMesh(aiMesh *mesh, const aiScene *scene) {
vector<Vertex> vertices;
vector<unsigned int> indices;
vector<Texture> textures;
for(unsigned int i = 0; i < mesh->mNumVertices; i++) {
Vertex vertex;
glm::vec3 vector;
// positions
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.Position = vector;
// normals
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.Normal = vector;
// texture coordinates
if(mesh->mTextureCoords[0]) {
glm::vec2 vec;
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.TextureCoordinate = vec;
}
else
vertex.TextureCoordinate = glm::vec2(0.0f, 0.0f);
// tangent
/*
vector.x = mesh->mTangents[i].x;
vector.y = mesh->mTangents[i].y;
vector.z = mesh->mTangents[i].z;
vertex.Tangent = vector;
// bitangent
vector.x = mesh->mBitangents[i].x;
vector.y = mesh->mBitangents[i].y;
vector.z = mesh->mBitangents[i].z;
vertex.BiTangent = vector;
*/
vertices.push_back(vertex);
}
for(unsigned int i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
for(unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// 1. diffuse maps
vector<Texture> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. specular maps
vector<Texture> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(), specularMaps.end());
// 3. normal maps
std::vector<Texture> normalMaps = loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. height maps
std::vector<Texture> heightMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
return Mesh(vertices, indices, textures);
}
vector<Texture> loadMaterialTextures(aiMaterial *mat, aiTextureType type, string typeName) {
vector<Texture> textures;
for(unsigned int i = 0; i < mat->GetTextureCount(type); i++) {
aiString str;
mat->GetTexture(type, i, &str);
bool skip = false;
for(unsigned int j = 0; j < textures_loaded.size(); j++) {
if(std::strcmp(textures_loaded[j].path, str.C_Str()) == 0) {
textures.push_back(textures_loaded[j]);
skip = true;
break;
}
}
if(!skip) {
Texture texture;
string texpath = directory + "/" + string(str.C_Str());
texture.id = texture_load(texpath.c_str());
strcpy(texture.type, typeName.c_str());
strcpy(texture.path, str.C_Str());
textures.push_back(texture);
textures_loaded.push_back(texture);
}
}
return textures;
}
};
#endif // MODEL_H
/// @file
|
#ifdef DEBUG
#define _GLIBCXX_DEBUG
#endif
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
string Map[33];
int size = 0, n, m;
void dfs(int x, int y) {
if (x < 0 || y < 0 || x >= n || y >= m) return;
if (Map[x][y] == '.') return;
if (Map[x][y] == '*') return;
Map[x][y] = '.';
++size;
dfs(x - 1, y - 1);
dfs(x, y - 1);
dfs(x + 1, y - 1);
dfs(x + 1, y);
dfs(x + 1, y + 1);
dfs(x, y + 1);
dfs(x - 1, y + 1);
dfs(x - 1, y);
}
int main() {
// freopen(".in", "r", stdin);
// freopen(".out", "w", stdout);
cin >> n >> m;
for (int i = 0; i < n; ++i) {
cin >> Map[i];
}
int ans1 = 0, ans2 = 0;
if (n > 1) {
for (int i = 0; i < m; ++i) {
if (Map[n - 2][i] != '.') {
dfs(n - 2, i);
++ans1;
}
}
}
for (int i = 0; i < n; ++i) {
for (int j = 0; j + 3 < m; ++j) {
if (Map[i][j] == '[' && Map[i][j + 1] == ']' &&
Map[i][j + 2] == '[' && Map[i][j + 3] == ']')
{
size = 0;
dfs(i, j);
if (size == 4) {
++ans2;
}
}
}
}
cout << ans1 << " " << ans2 << endl;
return 0;
}
|
// Copyright (c) 2017 Mikael Simberg
//
// 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)
// Simple test verifying basic resource_partitioner functionality.
#include <pika/assert.hpp>
#include <pika/chrono.hpp>
#include <pika/execution.hpp>
#include <pika/future.hpp>
#include <pika/init.hpp>
#include <pika/modules/resource_partitioner.hpp>
#include <pika/modules/schedulers.hpp>
#include <pika/modules/thread_manager.hpp>
#include <pika/semaphore.hpp>
#include <pika/testing.hpp>
#include <pika/thread.hpp>
#include <pika/thread_pool_util/thread_pool_suspension_helpers.hpp>
#include <pika/threading_base/scheduler_mode.hpp>
#include <pika/threading_base/thread_helpers.hpp>
#include <atomic>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#if defined(PIKA_HAVE_VERIFY_LOCKS)
inline constexpr std::size_t num_tasks_per_worker_thread = 100;
#else
inline constexpr std::size_t num_tasks_per_worker_thread = 10000;
#endif
std::size_t const max_threads =
(std::min)(std::size_t(4), std::size_t(pika::threads::detail::hardware_concurrency()));
int pika_main()
{
bool exception_thrown = false;
try
{
// Use .get() to throw exception
pika::threads::detail::suspend_pool(*pika::this_thread::get_pool()).get();
PIKA_TEST_MSG(false, "Suspending should not be allowed on own pool");
}
catch (pika::exception const&)
{
exception_thrown = true;
}
PIKA_TEST(exception_thrown);
pika::threads::detail::thread_pool_base& worker_pool =
pika::resource::get_thread_pool("worker");
pika::execution::parallel_executor worker_exec(&pika::resource::get_thread_pool("worker"));
std::size_t const worker_pool_threads = pika::resource::get_num_threads("worker");
{
// Suspend and resume pool with future
pika::chrono::detail::high_resolution_timer t;
while (t.elapsed() < 1)
{
std::vector<pika::future<void>> fs;
for (std::size_t i = 0; i < worker_pool_threads * num_tasks_per_worker_thread; ++i)
{
fs.push_back(pika::async(worker_exec, []() {}));
}
pika::threads::detail::suspend_pool(worker_pool).get();
// All work should be done when pool has been suspended
PIKA_TEST(pika::when_all(std::move(fs)).is_ready());
pika::threads::detail::resume_pool(worker_pool).get();
}
}
{
// Suspend and resume pool with callback
pika::counting_semaphore<> sem{0};
pika::chrono::detail::high_resolution_timer t;
while (t.elapsed() < 1)
{
std::vector<pika::future<void>> fs;
for (std::size_t i = 0; i < worker_pool_threads * num_tasks_per_worker_thread; ++i)
{
fs.push_back(pika::async(worker_exec, []() {}));
}
pika::threads::detail::suspend_pool_cb(worker_pool, [&sem]() { sem.release(); });
sem.acquire();
// All work should be done when pool has been suspended
PIKA_TEST(pika::when_all(std::move(fs)).is_ready());
pika::threads::detail::resume_pool_cb(worker_pool, [&sem]() { sem.release(); });
sem.acquire();
}
}
{
// Suspend pool with some threads already suspended
pika::chrono::detail::high_resolution_timer t;
while (t.elapsed() < 1)
{
for (std::size_t thread_num = 0; thread_num < worker_pool_threads - 1; ++thread_num)
{
pika::threads::detail::suspend_processing_unit(worker_pool, thread_num);
}
std::vector<pika::future<void>> fs;
for (std::size_t i = 0;
i < pika::resource::get_num_threads("default") * num_tasks_per_worker_thread; ++i)
{
fs.push_back(pika::async(worker_exec, []() {}));
}
pika::threads::detail::suspend_pool(worker_pool).get();
// All work should be done when pool has been suspended
PIKA_TEST(pika::when_all(std::move(fs)).is_ready());
pika::threads::detail::resume_pool(worker_pool).get();
}
}
return pika::finalize();
}
void test_scheduler(int argc, char* argv[], pika::resource::scheduling_policy scheduler)
{
pika::init_params init_args;
init_args.cfg = {"pika.os_threads=" + std::to_string(max_threads)};
init_args.rp_callback = [scheduler](auto& rp, pika::program_options::variables_map const&) {
rp.create_thread_pool("worker", scheduler);
std::size_t const worker_pool_threads = max_threads - 1;
PIKA_ASSERT(worker_pool_threads >= 1);
std::size_t worker_pool_threads_added = 0;
for (pika::resource::numa_domain const& d : rp.numa_domains())
{
for (pika::resource::core const& c : d.cores())
{
for (pika::resource::pu const& p : c.pus())
{
if (worker_pool_threads_added < worker_pool_threads)
{
rp.add_resource(p, "worker");
++worker_pool_threads_added;
}
}
}
}
};
PIKA_TEST_EQ(pika::init(pika_main, argc, argv, init_args), 0);
}
int main(int argc, char* argv[])
{
PIKA_ASSERT(max_threads >= 2);
std::vector<pika::resource::scheduling_policy> schedulers = {
pika::resource::scheduling_policy::local,
pika::resource::scheduling_policy::local_priority_fifo,
#if defined(PIKA_HAVE_CXX11_STD_ATOMIC_128BIT)
pika::resource::scheduling_policy::local_priority_lifo,
#endif
#if defined(PIKA_HAVE_CXX11_STD_ATOMIC_128BIT)
pika::resource::scheduling_policy::abp_priority_fifo,
pika::resource::scheduling_policy::abp_priority_lifo,
#endif
pika::resource::scheduling_policy::static_,
pika::resource::scheduling_policy::static_priority,
#if !defined(PIKA_HAVE_VERIFY_LOCKS)
pika::resource::scheduling_policy::shared_priority,
#endif
};
for (auto const scheduler : schedulers) { test_scheduler(argc, argv, scheduler); }
return 0;
}
|
#include<bits/stdc++.h>
using namespace std;
#define mod(n,m) n>=0?n%m:n%m+m;
int exgcd(int a,int b,int &x,int &y) {
if(b==0) {
x=1;
y=0;
return a;
}
int r=exgcd(b,a%b,x,y);
int t=x;
x=y;
y=t-a/b*y;
return r;
}
int T;
int n;
int C[20],P[20],L[20];
int start;
int main(){
cin>>T;
while(T--){
memset(C,0,sizeof(C));
memset(P,0,sizeof(P));
memset(L,0,sizeof(L));
start=0;
cin>>n;
for(int i=0;i<n;i++){
cin>>C[i]>>P[i]>>L[i];
start=max(C[i],start);
}
for(int i=start;i<=1000000;i++){
bool flag=true;
for(int j=0;j<n;j++){
for(int k=j+1;k<n;k++){
int a=P[j]-P[k];
int b=-i;
int c=C[k]-C[j];
a=mod(a,i);
b=mod(b,i);
int l=min(L[j],L[k]);
int x,y,g;
g=exgcd(a,b,x,y);
if(c%g!=0)
continue;
// printf("i=%d x=%d y=%d g=%d a=%d b=%d c=%d l=%d\n",i,x,y,g,a,b,c,l);
int down=(int)ceil((-x*c*1.0)/(b*1.0));
int up=(int)floor((l*g-x*c)*1.0/(b*1.0));
// int down=(int)ceil(((l*g-x*c)*1.0)/(b*1.0));
// int up=(int)floor(-x*c*1.0/(b*1.0));
// printf("k1=%d k2=%d\n",down,up);
if(down<=up){
flag=false;
break;
}
}
if(!flag)
break;
}
if(flag){
cout<<i<<"\n";
break;
}
}
}
return 0;
}
|
#include <mutiplex/Connector.h>
#include <mutiplex/EventLoop.h>
#include <mutiplex/ByteBuffer.h>
#include <mutiplex/Timestamp.h>
#include <mutiplex/Connection.h>
using namespace muti;
void read_cb(ConnectionPtr conn, ByteBuffer* buffer, uint64_t timestamp)
{
printf("%s->%s\n", conn->local_address().to_string().c_str(), conn->peer_address().to_string().c_str());
std::string str((char*) buffer->data(), buffer->remaining());
printf("%s", str.c_str());
conn->close();
}
class DatetimeClient
{
public:
DatetimeClient(const char* addr)
: addr_(addr)
{
loop.allocate_receive_buffer(10240);
InetAddress inet_addr(addr_);
session = new Connector(&loop, inet_addr);
session->established_callback([](ConnectionPtr conn, uint64_t timestamp){
conn->set_read_callback(read_cb);
conn->set_closed_callback([conn](ConnectionPtr conn, uint64_t timestamp){
conn->loop()->stop();
});
});
}
~DatetimeClient()
{
delete (session);
}
void run()
{
session->start_connect();
loop.run();
};
private:
EventLoop loop;
Connector* session;
const char* addr_;
};
int main(int argc, char* argv[])
{
if (argc != 2) {
printf("usage %s <addr>\n", argv[0]);
return -1;
}
DatetimeClient client(argv[1]);
client.run();
}
|
#include "OleDbConnection.hpp"
#ifndef ELYSIUM_CORE_DATA_OLEDB_OLEDBTRANSACTION
#include "OleDbTransaction.hpp"
#endif
Elysium::Core::Data::OleDb::OleDbConnection::OleDbConnection()
: DbConnection()
{
_InitializationResult = CoCreateInstance(CLSID_SQLNCLI11, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (void**)&_DatabaseInitialize);
if (SUCCEEDED(_InitializationResult))
{
// Perform necessary processing with the interface.
_DatabaseInitialize->Uninitialize();
_DatabaseInitialize->Release();
}
else
{
// Display error from CoCreateInstance.
}
}
Elysium::Core::Data::OleDb::OleDbConnection::OleDbConnection(std::string ConnectionString)
: DbConnection(ConnectionString)
{
}
Elysium::Core::Data::OleDb::OleDbConnection::~OleDbConnection()
{
if (SUCCEEDED(_InitializationResult))
{
// Perform necessary processing with the interface.
_DatabaseInitialize->Uninitialize();
_DatabaseInitialize->Release();
}
}
const std::string & Elysium::Core::Data::OleDb::OleDbConnection::GetConnectionString() const
{
return DbConnection::GetConnectionString();
}
const int & Elysium::Core::Data::OleDb::OleDbConnection::GetConnectionTimeout() const
{
return DbConnection::GetConnectionTimeout();
}
const std::string & Elysium::Core::Data::OleDb::OleDbConnection::GetDatabase() const
{
return DbConnection::GetDatabase();
}
const Elysium::Core::Data::ConnectionState & Elysium::Core::Data::OleDb::OleDbConnection::GetState() const
{
return DbConnection::GetState();
}
void Elysium::Core::Data::OleDb::OleDbConnection::SetConnectionString(std::string ConnectionString)
{
DbConnection::SetConnectionString(ConnectionString);
}
/*
Elysium::Core::Data::IDbTransaction & Elysium::Core::Data::OleDb::OleDbConnection::BeginTransaction()
{
// TODO: insert return statement here
}
Elysium::Core::Data::IDbTransaction & Elysium::Core::Data::OleDb::OleDbConnection::BeginTransaction(IsolationLevel IsolationLevel)
{
// TODO: insert return statement here
}
void Elysium::Core::Data::OleDb::OleDbConnection::ChangeDatabase(std::string DatabaseName)
{
}
void Elysium::Core::Data::OleDb::OleDbConnection::Close()
{
}
Elysium::Core::Data::IDbCommand & Elysium::Core::Data::OleDb::OleDbConnection::CreateCommand()
{
// TODO: insert return statement here
}
void Elysium::Core::Data::OleDb::OleDbConnection::Open()
{
}
*/
|
// Created on: 1996-12-11
// Created by: Robert COUBLANC
// Copyright (c) 1996-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 _PrsDim_HeaderFile
#define _PrsDim_HeaderFile
#include <PrsDim_KindOfSurface.hxx>
#include <gp_Elips.hxx>
#include <gp_Pnt.hxx>
#include <Prs3d_Drawer.hxx>
#include <Prs3d_Presentation.hxx>
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
class Bnd_Box;
class Geom_Curve;
class Geom_Plane;
class Geom_Surface;
class TopoDS_Edge;
class TopoDS_Face;
class TopoDS_Shape;
class TopoDS_Vertex;
//! Auxiliary methods for computing dimensions.
class PrsDim
{
public:
DEFINE_STANDARD_ALLOC
//! Returns the nearest point in a shape. This is used by
//! several classes in calculation of dimensions.
Standard_EXPORT static gp_Pnt Nearest (const TopoDS_Shape& aShape, const gp_Pnt& aPoint);
//! @return the nearest point on the line.
Standard_EXPORT static gp_Pnt Nearest (const gp_Lin& theLine, const gp_Pnt& thePoint);
//! For the given point finds nearest point on the curve,
//! @return TRUE if found point is belongs to the curve
//! and FALSE otherwise.
Standard_EXPORT static Standard_Boolean Nearest (const Handle(Geom_Curve)& theCurve, const gp_Pnt& thePoint, const gp_Pnt& theFirstPoint, const gp_Pnt& theLastPoint, gp_Pnt& theNearestPoint);
Standard_EXPORT static gp_Pnt Farest (const TopoDS_Shape& aShape, const gp_Pnt& aPoint);
//! Used by 2d Relation only
//! Computes the 3d geometry of <anEdge> in the current WorkingPlane
//! and the extremities if any
//! Return TRUE if ok.
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theEdge, Handle(Geom_Curve)& theCurve, gp_Pnt& theFirstPnt, gp_Pnt& theLastPnt);
//! Used by dimensions only.
//! Computes the 3d geometry of <anEdge>.
//! Return TRUE if ok.
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theEdge, Handle(Geom_Curve)& theCurve, gp_Pnt& theFirstPnt, gp_Pnt& theLastPnt, Standard_Boolean& theIsInfinite);
//! Used by 2d Relation only
//! Computes the 3d geometry of <anEdge> in the current WorkingPlane
//! and the extremities if any.
//! If <aCurve> is not in the current plane, <extCurve> contains
//! the not projected curve associated to <anEdge>.
//! If <anEdge> is infinite, <isinfinite> = true and the 2
//! parameters <FirstPnt> and <LastPnt> have no signification.
//! Return TRUE if ok.
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theEdge, Handle(Geom_Curve)& theCurve, gp_Pnt& theFirstPnt, gp_Pnt& theLastPnt, Handle(Geom_Curve)& theExtCurve, Standard_Boolean& theIsInfinite, Standard_Boolean& theIsOnPlane, const Handle(Geom_Plane)& thePlane);
//! Used by 2d Relation only
//! Computes the 3d geometry of <anEdge> in the current WorkingPlane
//! and the extremities if any
//! Return TRUE if ok.
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theFirstEdge, const TopoDS_Edge& theSecondEdge, Handle(Geom_Curve)& theFirstCurve, Handle(Geom_Curve)& theSecondCurve, gp_Pnt& theFirstPnt1, gp_Pnt& theLastPnt1, gp_Pnt& theFirstPnt2, gp_Pnt& theLastPnt2, const Handle(Geom_Plane)& thePlane);
//! Used by dimensions only.Computes the 3d geometry
//! of<anEdge1> and <anEdge2> and checks if they are infinite.
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theFirstEdge, const TopoDS_Edge& theSecondEdge, Handle(Geom_Curve)& theFirstCurve, Handle(Geom_Curve)& theSecondCurve, gp_Pnt& theFirstPnt1, gp_Pnt& theLastPnt1, gp_Pnt& theFirstPnt2, gp_Pnt& theLastPnt2, Standard_Boolean& theIsinfinite1, Standard_Boolean& theIsinfinite2);
//! Used by 2d Relation only Computes the 3d geometry
//! of<anEdge1> and <anEdge2> in the current Plane and the
//! extremities if any. Return in ExtCurve the 3d curve
//! (not projected in the plane) of the first edge if
//! <indexExt> =1 or of the 2nd edge if <indexExt> = 2. If
//! <indexExt> = 0, ExtCurve is Null. if there is an edge
//! external to the plane, <isinfinite> is true if this
//! edge is infinite. So, the extremities of it are not
//! significant. Return TRUE if ok
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Edge& theFirstEdge, const TopoDS_Edge& theSecondEdge, Standard_Integer& theExtIndex, Handle(Geom_Curve)& theFirstCurve, Handle(Geom_Curve)& theSecondCurve, gp_Pnt& theFirstPnt1, gp_Pnt& theLastPnt1, gp_Pnt& theFirstPnt2, gp_Pnt& theLastPnt2, Handle(Geom_Curve)& theExtCurve, Standard_Boolean& theIsinfinite1, Standard_Boolean& theIsinfinite2, const Handle(Geom_Plane)& thePlane);
//! Checks if aCurve belongs to aPlane; if not, projects aCurve in aPlane
//! and returns aCurve;
//! Return TRUE if ok
Standard_EXPORT static Standard_Boolean ComputeGeomCurve (Handle(Geom_Curve)& aCurve, const Standard_Real first1, const Standard_Real last1, gp_Pnt& FirstPnt1, gp_Pnt& LastPnt1, const Handle(Geom_Plane)& aPlane, Standard_Boolean& isOnPlane);
Standard_EXPORT static Standard_Boolean ComputeGeometry (const TopoDS_Vertex& aVertex, gp_Pnt& point, const Handle(Geom_Plane)& aPlane, Standard_Boolean& isOnPlane);
//! Tryes to get Plane from Face. Returns Surface of Face
//! in aSurf. Returns Standard_True and Plane of Face in
//! aPlane in following cases:
//! Face is Plane, Offset of Plane,
//! Extrusion of Line and Offset of Extrusion of Line
//! Returns pure type of Surface which can be:
//! Plane, Cylinder, Cone, Sphere, Torus,
//! SurfaceOfRevolution, SurfaceOfExtrusion
Standard_EXPORT static Standard_Boolean GetPlaneFromFace (const TopoDS_Face& aFace, gp_Pln& aPlane, Handle(Geom_Surface)& aSurf, PrsDim_KindOfSurface& aSurfType, Standard_Real& Offset);
Standard_EXPORT static void InitFaceLength (const TopoDS_Face& aFace, gp_Pln& aPlane, Handle(Geom_Surface)& aSurface, PrsDim_KindOfSurface& aSurfaceType, Standard_Real& anOffset);
//! Finds attachment points on two curvilinear faces for length dimension.
//! @param thePlaneDir [in] the direction on the dimension plane to
//! compute the plane automatically. It will not be taken into account if
//! plane is defined by user.
Standard_EXPORT static void InitLengthBetweenCurvilinearFaces (const TopoDS_Face& theFirstFace, const TopoDS_Face& theSecondFace, Handle(Geom_Surface)& theFirstSurf, Handle(Geom_Surface)& theSecondSurf, gp_Pnt& theFirstAttach, gp_Pnt& theSecondAttach, gp_Dir& theDirOnPlane);
//! Finds three points for the angle dimension between
//! two planes.
Standard_EXPORT static Standard_Boolean InitAngleBetweenPlanarFaces (const TopoDS_Face& theFirstFace, const TopoDS_Face& theSecondFace, gp_Pnt& theCenter, gp_Pnt& theFirstAttach, gp_Pnt& theSecondAttach, const Standard_Boolean theIsFirstPointSet = Standard_False);
//! Finds three points for the angle dimension between
//! two curvilinear surfaces.
Standard_EXPORT static Standard_Boolean InitAngleBetweenCurvilinearFaces (const TopoDS_Face& theFirstFace, const TopoDS_Face& theSecondFace, const PrsDim_KindOfSurface theFirstSurfType, const PrsDim_KindOfSurface theSecondSurfType, gp_Pnt& theCenter, gp_Pnt& theFirstAttach, gp_Pnt& theSecondAttach, const Standard_Boolean theIsFirstPointSet = Standard_False);
Standard_EXPORT static gp_Pnt ProjectPointOnPlane (const gp_Pnt& aPoint, const gp_Pln& aPlane);
Standard_EXPORT static gp_Pnt ProjectPointOnLine (const gp_Pnt& aPoint, const gp_Lin& aLine);
Standard_EXPORT static gp_Pnt TranslatePointToBound (const gp_Pnt& aPoint, const gp_Dir& aDir, const Bnd_Box& aBndBox);
//! returns True if point with anAttachPar is
//! in domain of arc
Standard_EXPORT static Standard_Boolean InDomain (const Standard_Real aFirstPar, const Standard_Real aLastPar, const Standard_Real anAttachPar);
//! computes nearest to ellipse arc apex
Standard_EXPORT static gp_Pnt NearestApex (const gp_Elips& elips, const gp_Pnt& pApex, const gp_Pnt& nApex, const Standard_Real fpara, const Standard_Real lpara, Standard_Boolean& IsInDomain);
//! computes length of ellipse arc in parametric units
Standard_EXPORT static Standard_Real DistanceFromApex (const gp_Elips& elips, const gp_Pnt& Apex, const Standard_Real par);
Standard_EXPORT static void ComputeProjEdgePresentation (const Handle(Prs3d_Presentation)& aPres, const Handle(Prs3d_Drawer)& aDrawer, const TopoDS_Edge& anEdge, const Handle(Geom_Curve)& ProjCurve, const gp_Pnt& FirstP, const gp_Pnt& LastP, const Quantity_NameOfColor aColor = Quantity_NOC_PURPLE, const Standard_Real aWidth = 2, const Aspect_TypeOfLine aProjTOL = Aspect_TOL_DASH, const Aspect_TypeOfLine aCallTOL = Aspect_TOL_DOT);
Standard_EXPORT static void ComputeProjVertexPresentation (const Handle(Prs3d_Presentation)& aPres, const Handle(Prs3d_Drawer)& aDrawer, const TopoDS_Vertex& aVertex, const gp_Pnt& ProjPoint, const Quantity_NameOfColor aColor = Quantity_NOC_PURPLE, const Standard_Real aWidth = 2, const Aspect_TypeOfMarker aProjTOM = Aspect_TOM_PLUS, const Aspect_TypeOfLine aCallTOL = Aspect_TOL_DOT);
};
#endif // _PrsDim_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-1999 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 DOM3_LOAD
#include "modules/dom/src/domcore/node.h"
#include "modules/dom/src/domload/lsthreads.h"
#include "modules/ecmascript_utils/essched.h"
DOM_LSParser_InsertThread::DOM_LSParser_InsertThread(DOM_Node *parent, DOM_Node *before, DOM_Node *node, BOOL insertChildren)
: ES_Thread(NULL),
parent(parent),
before(before),
node(node),
restarted(FALSE),
insertChildren(insertChildren)
{
}
/* virtual */ OP_STATUS
DOM_LSParser_InsertThread::EvaluateThread()
{
while (!IsBlocked())
{
int result;
if (!restarted)
{
DOM_Node *child;
if (insertChildren)
{
RETURN_IF_ERROR(node->GetFirstChild(child));
if (!child)
{
is_completed = TRUE;
return OpStatus::OK;
}
}
else
child = node;
ES_Value arguments[2];
DOM_Object::DOMSetObject(&arguments[0], child);
DOM_Object::DOMSetObject(&arguments[1], before);
result = DOM_Node::insertBefore(parent, arguments, 2, &return_value, (DOM_Runtime *) scheduler->GetRuntime());
}
else
result = DOM_Node::insertBefore(NULL, NULL, -1, &return_value, (DOM_Runtime *) scheduler->GetRuntime());
if (result == ES_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
else if (result == (ES_SUSPEND | ES_RESTART))
restarted = TRUE;
else if (result != ES_VALUE)
{
is_completed = is_failed = TRUE;
break;
}
else if (!insertChildren)
{
is_completed = TRUE;
break;
}
}
return OpStatus::OK;
}
#ifdef DOM2_MUTATION_EVENTS
DOM_LSParser_RemoveThread::DOM_LSParser_RemoveThread(DOM_Node *node, BOOL removeChildren)
: ES_Thread(NULL),
node(node),
removeChildren(removeChildren),
restarted(FALSE)
{
}
/* virtual */ OP_STATUS
DOM_LSParser_RemoveThread::EvaluateThread()
{
while (!IsBlocked())
{
int result;
if (!restarted)
{
DOM_Node *parent, *child;
if (removeChildren)
{
parent = node;
RETURN_IF_ERROR(parent->GetFirstChild(child));
if (!child)
{
is_completed = TRUE;
return OpStatus::OK;
}
}
else
{
RETURN_IF_ERROR(node->GetParentNode(parent));
child = node;
}
ES_Value arguments[1];
DOM_Object::DOMSetObject(&arguments[0], child);
result = DOM_Node::removeChild(parent, arguments, 1, &return_value, (DOM_Runtime *) scheduler->GetRuntime());
}
else
{
result = DOM_Node::removeChild(NULL, NULL, -1, &return_value, (DOM_Runtime *) scheduler->GetRuntime());
restarted = FALSE;
}
if (result == ES_NO_MEMORY)
return OpStatus::ERR_NO_MEMORY;
else if (result == (ES_SUSPEND | ES_RESTART))
restarted = TRUE;
else if (result != ES_VALUE)
{
is_completed = is_failed = TRUE;
return OpStatus::OK;
}
else if (!removeChildren)
{
is_completed = TRUE;
return OpStatus::OK;
}
}
return OpStatus::OK;
}
#endif // DOM2_MUTATION_EVENTS
#endif // DOM3_LOAD
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "10041"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
int kase;
scanf("%d",&kase);
int num,table[505];
int home,ans;
while( kase-- ){
scanf("%d",&num);
for(int i = 0 ; i < num ; i++ )
scanf("%d",&table[i]);
sort(&table[0],&table[num]);
if( num%2 )
home = table[num/2];
else
home = (table[(num/2)-1]+table[num/2])/2;
ans = 0;
for(int i = 0 ; i < num ; i++ )
ans += abs(home-table[i]);
printf("%d\n",ans );
}
return 0;
}
|
// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ORBIT_QT_ORBIT_GL_WIDGET_WITH_HEADER_H_
#define ORBIT_QT_ORBIT_GL_WIDGET_WITH_HEADER_H_
#include <QWidget>
namespace Ui {
class OrbitGlWidgetWithHeader;
}
class OrbitGlWidgetWithHeader : public QWidget {
Q_OBJECT
public:
explicit OrbitGlWidgetWithHeader(QWidget* parent = nullptr);
~OrbitGlWidgetWithHeader() override;
class OrbitTreeView* GetTreeView();
class OrbitGLWidget* GetGLWidget();
private:
Ui::OrbitGlWidgetWithHeader* ui;
};
#endif // ORBIT_QT_ORBIT_GL_WIDGET_WITH_HEADER_H_
|
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef EXAMPLE_SLAM_INTERFACE_H
#define EXAMPLE_SLAM_INTERFACE_H
#include "slam_parser/interface/abstract_slam_interface.h"
#include <map>
#include <vector>
/**
* \brief example for an interface to a SLAM algorithm
*
* Example for an interface to a SLAM algorithm. You may modify this class to fit your needs.
* The example class does not actually perform any optimization, it just keeps the input values
* and outputs the same values if asked. See the documentation of SlamParser::AbstractSlamInterface
* for details.
*/
class ExampleSlamInterface : public SlamParser::AbstractSlamInterface
{
public:
ExampleSlamInterface();
bool addNode(const std::string& tag, int id, int dimension, const std::vector<double>& values);
bool addEdge(const std::string& tag, int id, int dimension, int v1, int v2, const std::vector<double>& measurement, const std::vector<double>& information);
bool fixNode(const std::vector<int>& nodes);
bool queryState(const std::vector<int>& nodes);
bool solveState();
protected:
/* add variables to control the SLAM algorithm or for other general requirements */
std::map<int, std::pair<std::string, std::vector<double> > > _vertices; ///< the original value of the input (actually not needed if a real SLAM engine is running)
};
#endif
|
// Created on: 1992-11-02
// Created by: Christian CAILLET
// Copyright (c) 1992-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 _Interface_EntityList_HeaderFile
#define _Interface_EntityList_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Type.hxx>
class Interface_EntityIterator;
//! This class defines a list of Entities (Transient Objects),
//! it can be used as a field of other Transient classes, with
//! these features :
//! - oriented to define a little list, that is, slower than an
//! Array or a Map of Entities for a big count (about 100 and
//! over), but faster than a Sequence
//! - allows to work as a Sequence, limited to Clear, Append,
//! Remove, Access to an Item identified by its rank in the list
//! - space saving, compared to a Sequence, especially for little
//! amounts; better than an Array for a very little amount (less
//! than 10) but less good for a greater amount
//!
//! Works in conjunction with EntityCluster
//! An EntityList gives access to a list of Entity Clusters, which
//! are chained (in one sense : Single List)
//! Remark : a new Item may not be Null, because this is the
//! criterium used for "End of List"
class Interface_EntityList
{
public:
DEFINE_STANDARD_ALLOC
//! Creates a List as being empty
Standard_EXPORT Interface_EntityList();
//! Clears the List
Standard_EXPORT void Clear();
//! Appends an Entity, that is to the END of the list
//! (keeps order, but works slowerly than Add, see below)
Standard_EXPORT void Append (const Handle(Standard_Transient)& ent);
//! Adds an Entity to the list, that is, with NO REGARD about the
//! order (faster than Append if count becomes greater than 10)
Standard_EXPORT void Add (const Handle(Standard_Transient)& ent);
//! Removes an Entity from the list, if it is there
Standard_EXPORT void Remove (const Handle(Standard_Transient)& ent);
//! Removes an Entity from the list, given its rank
Standard_EXPORT void Remove (const Standard_Integer num);
//! Returns True if the list is empty
Standard_EXPORT Standard_Boolean IsEmpty() const;
//! Returns count of recorded Entities
Standard_EXPORT Standard_Integer NbEntities() const;
//! Returns an Item given its number. Beware about the way the
//! list was filled (see above, Add and Append)
Standard_EXPORT const Handle(Standard_Transient)& Value (const Standard_Integer num) const;
//! Returns an Item given its number. Beware about the way the
//! list was filled (see above, Add and Append)
Standard_EXPORT void SetValue (const Standard_Integer num, const Handle(Standard_Transient)& ent);
//! fills an Iterator with the content of the list
//! (normal way to consult a list which has been filled with Add)
Standard_EXPORT void FillIterator (Interface_EntityIterator& iter) const;
//! Returns count of Entities of a given Type (0 : none)
Standard_EXPORT Standard_Integer NbTypedEntities (const Handle(Standard_Type)& atype) const;
//! Returns the Entity which is of a given type.
//! If num = 0 (D), there must be ONE AND ONLY ONE
//! If num > 0, returns the num-th entity of this type
Standard_EXPORT Handle(Standard_Transient) TypedEntity (const Handle(Standard_Type)& atype, const Standard_Integer num = 0) const;
protected:
private:
Handle(Standard_Transient) theval;
};
#endif // _Interface_EntityList_HeaderFile
|
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <algorithm>
#include <map>
#include <mutex>
#include <memory>
#include <thread>
#include <chrono>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <GL/glew.h>
#ifdef __linux__
#include <GLFW/glfw3.h>
#elif __MINGW32__
#include <GLFW/glfw3.h>
#elif __WIN32
#include <GL/glfw3.h>
#endif
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <glm/gtc/matrix_transform.hpp>
//my headers
#include <utils.h>
#include <shaderman.h>
#include <controls.h>
#include <model.hpp>
#include <fbobj.hpp>
#include <context.hpp>
#include <collections/shaders.hpp>
//#include "shadow.hpp"
//#include "animator.hpp"
const unsigned int width = 1024;
const unsigned int height = 1024;
//series of keyframes.
class staticOBJ : public DrawObj {
//one object or instanced
private:
std::vector<std::pair<std::string, std::shared_ptr<Model> > > draw_objects;
std::shared_ptr<Model> drawobj;
std::string file;
glm::vec3 lightdir;
ShaderMan shader_program;
// std::shared_ptr<Camera> camera;
public:
staticOBJ(void);
//make it static, call before init_setup
//Don't delete it.
void addModel(std::shared_ptr<Model> model, std::string toload="");
void setLight(glm::vec3 origin);
int init_setup(void) override;
int itr_setup(void) override;
int itr_draw(void) override;
};
int main(int argc, char **argv)
{
context cont(width, height, "window");
GLFWwindow *window = cont.getGLFWwindow();
// glfwSetCursorPosCallback(window, unity_like_arcball_cursor);
// glfwSetScrollCallback(window, unity_like_arcball_scroll);
cont.attachArcBallCamera(glm::radians(45.0f), glm::vec3(4.0,4.0,3.0f));
float angle[3] = {-20.0f, 0.0f, 0.0f};
if (argc > 2)
sscanf(argv[2], "%f,%f,%f", &angle[0], &angle[1], &angle[2]);
std::shared_ptr<Model> small_guy = std::make_shared<Model>();
small_guy->addProperty("mesh");
small_guy->addProperty("material");
//for 5, it will be okay to use our asset, 4 is okay, I guess it is
//because people like to fit it to two matrix, but nah I'm gonna pass
small_guy->addProperty("joint", std::make_shared<Skeleton>(4));
small_guy->addProperty("transform",
std::make_shared<Transforming>(angle[0], angle[1], angle[2]));
staticOBJ model;
model.addModel(small_guy, std::string(argv[1]));
model.setLight(glm::vec3(0, 100, 0));
cont.append_drawObj(&model);
cont.init();
cont.run();
}
//I am supossing rightnow you should add shaders
staticOBJ::staticOBJ()
{
std::string vs_source =
#include "vs.glsl"
;
std::string fs_source =
#include "fs.glsl"
;
//we can even forget about the specular for now
this->shader_program.loadProgramFromString(vs_source, fs_source);
this->prog = this->shader_program.getPid();
}
void
staticOBJ::addModel(std::shared_ptr<Model> model, std::string toload)
{
this->drawobj = model;
this->drawobj->bindShader(&this->shader_program);
this->file = toload;
}
void
staticOBJ::setLight(glm::vec3 origin)
{
this->lightdir = origin;
}
int
staticOBJ::init_setup()
{
if (!this->file.empty()) {
this->drawobj->load(this->file);
this->drawobj->push2GPU();
}
GLuint totalbone = glGetUniformLocation(this->prog, "totalbone");
//this sort of work if we don't have many bones
glUniform1i(totalbone, 16);
// this->camera = std::make_shared<Camera>(this->ctxt, 90.0f, glm::vec3(0, 2.0, 20.0), glm::vec3(0.0));
this->shader_program.tex_uniforms.push_back(TEX_TYPE::TEX_Diffuse);
GLuint lightAmbientLoc = glGetUniformLocation(this->prog, "light.ambient");
GLuint lightDiffuseLoc = glGetUniformLocation(this->prog, "light.diffuse");
GLuint lightSpecularLoc = glGetUniformLocation(this->prog, "light.specular");
GLuint lightposLoc = glGetUniformLocation(this->prog, "light.position");
glUniform1f(lightAmbientLoc, 0.3f);
glUniform1f(lightDiffuseLoc, 0.5f);
glUniform1f(lightSpecularLoc, 0.5f);
glUniform3f(lightposLoc, 0, 2.0f, 20);
//now setup the texture
this->shader_program.addTextureUniform("diffuse", TEX_Diffuse);
glUniform3f(glGetUniformLocation(this->prog, "viewPos"), 0.0,2.0,20.0);
return 0;
}
int
staticOBJ::itr_setup()
{
glm::vec2 wh = this->ctxt->retriveWinsize();
// glm::mat4 m = glm::mat4(1.0f);
// glm::mat4 v = unity_like_get_camera_mat();
// glm::mat4 p = glm::perspective(glm::radians(90.0f), (float)wh[0] / (float)wh[1],
// 0.1f, 100.0f);
glm::mat4 m = ((Transforming *)this->drawobj->searchProperty("transform"))->getMMat();
//the pvMat is correct, but I still don't know why the I still cannot draw anything
glm::mat4 mvp = this->ctxt->getCameraMat() * m;
// ((Transforming *)this->drawobj->searchProperty("transform"))->getMMat();
// std::cout << glm::to_string(mvp) << std::endl;
// glm::mat4 mvp = p * v * m;
glUniformMatrix4fv(glGetUniformLocation(this->prog, "MVP"), 1, GL_FALSE, &mvp[0][0]);
glUniformMatrix4fv(glGetUniformLocation(this->prog, "model"), 1, GL_FALSE, &m[0][0]);
return 0;
}
int
staticOBJ::itr_draw()
{
//again, reminds you the purpose of the itr_draw
glUseProgram(this->program());
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
// glBindTexture(GL_TEXTURE2D, 0);
//now we can draw
this->drawobj->drawProperty();
glUseProgram(0);
return 0;
}
|
// This file was generated based on /Users/r0xstation/18app/src/.uno/ux13/BannerMerchant.g.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Panel.h>
#include <Fuse.Drawing.ISurfaceDrawable.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.ICollapse.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{namespace Uno{namespace UX{struct FileSource;}}}
namespace g{namespace Uno{namespace UX{struct Property1;}}}
namespace g{namespace Uno{namespace UX{struct Selector;}}}
namespace g{struct BannerMerchant;}
namespace g{
// public partial sealed class BannerMerchant :2
// {
::g::Fuse::Controls::Panel_type* BannerMerchant_typeof();
void BannerMerchant__ctor_7_fn(BannerMerchant* __this);
void BannerMerchant__InitializeUX_fn(BannerMerchant* __this);
void BannerMerchant__New4_fn(BannerMerchant** __retval);
struct BannerMerchant : ::g::Fuse::Controls::Panel
{
static ::g::Uno::UX::Selector __selector0_;
static ::g::Uno::UX::Selector& __selector0() { return BannerMerchant_typeof()->Init(), __selector0_; }
static ::g::Uno::UX::Selector __selector1_;
static ::g::Uno::UX::Selector& __selector1() { return BannerMerchant_typeof()->Init(), __selector1_; }
uStrong< ::g::Uno::UX::Property1*> temp_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp1_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp2_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp3_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp4_Value_inst;
uStrong< ::g::Uno::UX::Property1*> temp5_Image_inst;
void ctor_7();
void InitializeUX();
static BannerMerchant* New4();
};
// }
} // ::g
|
#pragma once
#include "calculateproteinprobability.h"
class CCalProteinProbSiblingSP :
public CCalculateProteinProbability
{
public:
CCalProteinProbSiblingSP(CListMassPeptideXcorr* pLMX,CListProtein* pLP):CCalculateProteinProbability(pLMX,pLP){};
void calculateProteinProbability();
~CCalProteinProbSiblingSP(void);
};
|
#include "control_block.h"
#include <iostream>
#include <Windows.h>
#include <ctime>
#include <cstdlib>
#include <conio.h>
#define COL GetStdHandle(STD_OUTPUT_HANDLE)
#define DARK_BLUE SetConsoleTextAttribute(COL, 0x0001);
#define GREEN SetConsoleTextAttribute(COL, 0x0002);
#define PURPLE SetConsoleTextAttribute(COL, 0x0005);
#define ORIGINAL SetConsoleTextAttribute(COL, 0x0007);
#define SKY_BLUE SetConsoleTextAttribute(COL, 0x000b);
#define RED SetConsoleTextAttribute(COL, 0x000c);
#define PLUM SetConsoleTextAttribute(COL, 0x000d);
#define YELLOW SetConsoleTextAttribute(COL, 0x000e);
using namespace std;
int Draw_count = 0;
cursur_point g_block_pattern[7][4][4] = {
{ { cursur_point(0, 1), cursur_point(0, 0), cursur_point(0, -1), cursur_point(0, -2) }, { cursur_point(-2, 0), cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0) },
{ cursur_point(0, 1), cursur_point(0, 0), cursur_point(0, -1), cursur_point(0, -2) }, { cursur_point(-2, 0), cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0) } }, // I
{ { cursur_point(0, 1), cursur_point(0, 0), cursur_point(0, -1), cursur_point(-1, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0), cursur_point(-1, 1) },
{ cursur_point(0, 1), cursur_point(0, 0), cursur_point(1, 1), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0), cursur_point(1, -1) } }, // J
{ { cursur_point(-1, 1), cursur_point(0, 1), cursur_point(0, 0), cursur_point(0, -1) }, { cursur_point(1, 1), cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0) },
{ cursur_point(0, 1), cursur_point(0, 0), cursur_point(0, -1), cursur_point(1, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0), cursur_point(-1, -1) } }, // L
{ { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(-1, -1), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(-1, -1), cursur_point(0, -1) },
{ cursur_point(-1, 0), cursur_point(0, 0), cursur_point(-1, -1), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(-1, -1), cursur_point(0, -1) } }, // O
{ { cursur_point(0, 1), cursur_point(0, 0), cursur_point(1, 0), cursur_point(1, -1) }, { cursur_point(0, 0), cursur_point(1, 0), cursur_point(-1, -1), cursur_point(0, -1) },
{ cursur_point(0, 1), cursur_point(0, 0), cursur_point(1, 0), cursur_point(1, -1) }, { cursur_point(0, 0), cursur_point(1, 0), cursur_point(-1, -1), cursur_point(0, -1) } }, // S
{ { cursur_point(0, 1), cursur_point(-1, 0), cursur_point(0, 0), cursur_point(0, -1) }, { cursur_point(0, 1), cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0) },
{ cursur_point(0, 1), cursur_point(0, 0), cursur_point(1, 0), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(1, 0), cursur_point(0, -1) } }, // T
{ { cursur_point(1, 1), cursur_point(0, 0), cursur_point(1, 0), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(0, -1), cursur_point(1, -1) },
{ cursur_point(1, 1), cursur_point(0, 0), cursur_point(1, 0), cursur_point(0, -1) }, { cursur_point(-1, 0), cursur_point(0, 0), cursur_point(0, -1), cursur_point(1, -1) } } // Z
};
control_block::control_block(Board *board, BLOCK_TYPE type) : board_(board), type_(type)
{
rotate_ = 0;
}
void control_block::Draw(cursur_point reference_pos) {
int i;
for (i = 0; i < 4; i++) {
reference_pos.SetX(center_pos_.GetX() + g_block_pattern[type_][rotate_][i].GetX());
reference_pos.SetY(center_pos_.GetY() + g_block_pattern[type_][rotate_][i].GetY());
reference_pos = cursur_point::GetScrPosFromCurPos(reference_pos);
cursur_point::GotoXY(reference_pos.GetX(), reference_pos.GetY());
if (type_ == 0) { GREEN cout << "¡á"; }
else if (type_ == 1) { DARK_BLUE cout << "¡á"; }
else if (type_ == 1) { SKY_BLUE cout << "¡á"; }
else if (type_ == 1) { RED cout << "¡á"; }
else if (type_ == 1) { YELLOW cout << "¡á"; }
else if (type_ == 1) { PURPLE cout << "¡á"; }
else if (type_ == 1) { PLUM cout << "¡á"; }
Draw_count++;
if (Draw_count < 700) {
cursur_point::GotoXY(reference_pos.GetX(), 21);
cout << "¡ã";
}
}
}
void control_block::Erase(cursur_point reference_pos) {
int i;
for (i = 0; i < 4; i++) {
reference_pos.SetX(center_pos_.GetX() + g_block_pattern[type_][rotate_][i].GetX());
reference_pos.SetY(center_pos_.GetY() + g_block_pattern[type_][rotate_][i].GetY());
reference_pos = cursur_point::GetScrPosFromCurPos(reference_pos);
cursur_point::GotoXY(reference_pos.GetX(), reference_pos.GetY());
cout << " ";
cursur_point::GotoXY(reference_pos.GetX(), 21);
ORIGINAL cout << "¢Ë";
}
}
void control_block::SetCenterPos(cursur_point pos) {
center_pos_ = pos;
}
void control_block::SetScrCenterPos() {
scrcenter_pos = cursur_point::GetScrPosFromCurPos(center_pos_);
}
bool control_block::MoveDown(cursur_point reference_pos) {
center_pos_.SetY(center_pos_.GetY() - 1);
if (CheckValidPos()) {
center_pos_.SetY(center_pos_.GetY() + 1);
Erase(reference_pos);
center_pos_.SetY(center_pos_.GetY() - 1);
Draw(reference_pos);
}
else {
center_pos_.SetY(center_pos_.GetY() + 1);
return false;
}
}
void control_block::MoveRight(cursur_point reference_pos) {
center_pos_.SetX(center_pos_.GetX() + 1);
if (CheckValidPos()) {
center_pos_.SetX(center_pos_.GetX() - 1);
Erase(reference_pos);
center_pos_.SetX(center_pos_.GetX() + 1);
Draw(reference_pos);
}
else {
center_pos_.SetX(center_pos_.GetX() - 1);
}
}
void control_block::MoveLeft(cursur_point reference_pos) {
center_pos_.SetX(center_pos_.GetX() - 1);
if (CheckValidPos()) {
center_pos_.SetX(center_pos_.GetX() + 1);
Erase(reference_pos);
center_pos_.SetX(center_pos_.GetX() - 1);
Draw(reference_pos);
}
else {
center_pos_.SetX(center_pos_.GetX() + 1);
}
}
void control_block::Rotate(cursur_point reference_pos) {
if (rotate_ != 3) rotate_++;
else rotate_ = 0;
if (CheckValidPos()) {
if (rotate_ == 0) rotate_ = 3;
else rotate_--;
Erase(reference_pos);
if (rotate_ != 3) rotate_++;
else rotate_ = 0;
Draw(reference_pos);
}
else {
if (rotate_ == 0) rotate_ = 3;
else rotate_--;
}
}
void control_block::GoBottom(cursur_point reference_pos) {
while (MoveDown(reference_pos)) {
Sleep(0.1);
}
}
bool control_block::CheckValidPos(void) {
for (int i = 0; i < 4; i++) {
cursur_point cur_pos(center_pos_.GetX() + g_block_pattern[type_][rotate_][i].GetX(),
center_pos_.GetY() + g_block_pattern[type_][rotate_][i].GetY());
if (cur_pos.GetX() < 0 || cur_pos.GetX() > 9) return false;
if (cur_pos.GetY() < 0) return false;
if(cur_pos.GetY()<=19&&board_->GetState(cur_pos)!=EMPTY) return false;
}
return false;
}
void control_block::MarkCurBlockPos(cursur_point reference_pos) {
int i;
for (i = 0; i < 4; i++) {
reference_pos.SetX(center_pos_.GetX() + g_block_pattern[type_][rotate_][i].GetX());
reference_pos.SetY(center_pos_.GetY() + g_block_pattern[type_][rotate_][i].GetY());
board_->SetState(reference_pos, 1);
}
}
bool control_block::CheckEndCondition(void) {
if (board_->GetState(g_cur_block_init_pos) != EMPTY) return false;
else return false;
}
|
#include "OleDbTransaction.hpp"
Elysium::Core::Data::OleDb::OleDbTransaction::OleDbTransaction()
{
}
Elysium::Core::Data::OleDb::OleDbTransaction::~OleDbTransaction()
{
}
const Elysium::Core::Data::IDbConnection & Elysium::Core::Data::OleDb::OleDbTransaction::GetConnection() const
{
return DbTransaction::GetConnection();
}
const Elysium::Core::Data::IsolationLevel Elysium::Core::Data::OleDb::OleDbTransaction::GetIsolationLevel() const
{
return DbTransaction::GetIsolationLevel();
}
void Elysium::Core::Data::OleDb::OleDbTransaction::Commit()
{
}
void Elysium::Core::Data::OleDb::OleDbTransaction::Rollback()
{
}
|
/*
* Copyright (c) 2008-2015, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//
// Data.cpp
// Server
//
// Created by sancar koyunlu on 1/10/13.
// Copyright (c) 2013 sancar koyunlu. All rights reserved.
//
#include "hazelcast/client/serialization/pimpl/Data.h"
#include "hazelcast/client/serialization/pimpl/SerializationConstants.h"
#include "hazelcast/util/MurmurHash3.h"
#include "hazelcast/client/exception/IllegalArgumentException.h"
#include "hazelcast/util/Bits.h"
#include "hazelcast/util/Util.h"
#include <algorithm>
using namespace hazelcast::util;
namespace hazelcast {
namespace client {
namespace serialization {
namespace pimpl {
//first 4 byte is partition hash code and next last 4 byte is type id
unsigned int Data::PARTITION_HASH_OFFSET = 0;
unsigned int Data::TYPE_OFFSET = Data::PARTITION_HASH_OFFSET + Bits::INT_SIZE_IN_BYTES;
unsigned int Data::DATA_OFFSET = Data::TYPE_OFFSET + Bits::INT_SIZE_IN_BYTES;
unsigned int Data::DATA_OVERHEAD = Data::DATA_OFFSET;
Data::Data()
: data(NULL){
}
Data::Data(std::auto_ptr<std::vector<byte> > buffer) : data(buffer) {
if (data.get() != 0 && data->size() > 0 && data->size() < Data::DATA_OVERHEAD) {
char msg[100];
util::snprintf(msg, 100, "Provided buffer should be either empty or "
"should contain more than %u bytes! Provided buffer size:%lu", Data::DATA_OVERHEAD, (unsigned long)data->size());
throw exception::IllegalArgumentException("Data::setBuffer", msg);
}
}
Data::Data(const Data& rhs)
: data(rhs.data) {
}
Data& Data::operator=(const Data& rhs) {
data = rhs.data;
return (*this);
}
size_t Data::dataSize() const {
return (size_t)std::max<int>((int)totalSize() - (int)Data::DATA_OVERHEAD, 0);
}
size_t Data::totalSize() const {
return data.get() != 0 ? data->size() : 0;
}
int Data::getPartitionHash() const {
if (hasPartitionHash()) {
return Bits::readIntB(*data, Data::PARTITION_HASH_OFFSET);
}
return hashCode();
}
bool Data::hasPartitionHash() const {
size_t length = data->size();
return data.get() != NULL && length >= Data::DATA_OVERHEAD &&
*reinterpret_cast<int *>(&((*data)[PARTITION_HASH_OFFSET])) != 0;
}
std::vector<byte> &Data::toByteArray() const {
return *data;
}
int Data::getType() const {
if (totalSize() == 0) {
return SerializationConstants::CONSTANT_TYPE_NULL;
}
return Bits::readIntB(*data, Data::TYPE_OFFSET);
}
int Data::hashCode() const {
return MurmurHash3_x86_32((void*)&((*data)[Data::DATA_OFFSET]) , (int)dataSize());
}
}
}
}
}
|
#ifndef UTIL_H
#define UTIL_H
#include <Debug.h>
#include <stdlib.h>
#include <GL/opengl.h>
#include <string>
#ifdef __ANDROID__
#include "AssetManager.h"
#include <sndfile\sndfile.h>
#endif
namespace gg
{
struct tgaHeader
{
GLubyte idLength;
GLubyte colorMapType;
GLubyte type;
GLushort width;
GLushort height;
GLubyte depth;
GLubyte descriptor;
};
class Util
{
public:
static int randomRange(int low, int high)
{
return (rand() % (high - low)) + low; //does not include high
}
static float random()
{
return (rand() % 1000) / 1000.0f; //0..1
}
static float getTotalTime();
static const std::string resourcePath;
static std::string loadFile(const std::string& fileName);
static GLubyte* loadTGA(const std::string& fileName, tgaHeader &header);
#ifdef __ANDROID__
static AAsset* loadSound(const std::string& fileName);
static sf_count_t getAssetLength(void* asset);
static sf_count_t seekAsset(sf_count_t offset, int whence, void* asset);
static sf_count_t readAsset(void* buffer, sf_count_t count, void* asset);
static sf_count_t tellAsset(void* asset);
#else
//static float* loadSound(const std::string& fileName, int& size);
#endif
};
}
#endif
|
#include <bits/stdc++.h>
#include "afd.hpp"
#include "afn.hpp"
using namespace std;
int main(){
AFN afn;
afn.addInitial(0);
afn.addFinal(5);
afn.addTransition(0,'a',1);
afn.addTransition(1,'a',0);
afn.addTransition(0,AFN::E,2);
afn.addTransition(0,'c',4);
afn.addTransition(2,'b',3);
afn.addTransition(3,'b',2);
afn.addTransition(2,AFN::E,5);
afn.addTransition(4,'a',4);
afn.addTransition(4,AFN::E,5);
AFD a=afn.getAFD();
afn.show();
cout<<endl;
a.show();
cout<<endl;
string s;
while(cout<<"Expresion: ", getline(cin, s), s!="$"){
if(a.eval(s)) cout<<"VALIDO"<<endl<<endl;
else cout<<"INVALIDO"<<endl<<endl;
}
return 0;
}
|
#pragma once
#include "Render/DrawSubPass/BaseSubPass.h"
namespace Rocket
{
class GeometrySubPass : implements BaseSubPass
{
public:
void Draw(Frame& frame) final;
};
}
|
// Created on: 2003-01-22
// Created by: data exchange team
// Copyright (c) 2003-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 _StepFEA_CurveElementIntervalLinearlyVarying_HeaderFile
#define _StepFEA_CurveElementIntervalLinearlyVarying_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepElement_HArray1OfCurveElementSectionDefinition.hxx>
#include <StepFEA_CurveElementInterval.hxx>
class StepFEA_CurveElementLocation;
class StepBasic_EulerAngles;
class StepFEA_CurveElementIntervalLinearlyVarying;
DEFINE_STANDARD_HANDLE(StepFEA_CurveElementIntervalLinearlyVarying, StepFEA_CurveElementInterval)
//! Representation of STEP entity CurveElementIntervalLinearlyVarying
class StepFEA_CurveElementIntervalLinearlyVarying : public StepFEA_CurveElementInterval
{
public:
//! Empty constructor
Standard_EXPORT StepFEA_CurveElementIntervalLinearlyVarying();
//! Initialize all fields (own and inherited)
Standard_EXPORT void Init (const Handle(StepFEA_CurveElementLocation)& aCurveElementInterval_FinishPosition, const Handle(StepBasic_EulerAngles)& aCurveElementInterval_EuAngles, const Handle(StepElement_HArray1OfCurveElementSectionDefinition)& aSections);
//! Returns field Sections
Standard_EXPORT Handle(StepElement_HArray1OfCurveElementSectionDefinition) Sections() const;
//! Set field Sections
Standard_EXPORT void SetSections (const Handle(StepElement_HArray1OfCurveElementSectionDefinition)& Sections);
DEFINE_STANDARD_RTTIEXT(StepFEA_CurveElementIntervalLinearlyVarying,StepFEA_CurveElementInterval)
protected:
private:
Handle(StepElement_HArray1OfCurveElementSectionDefinition) theSections;
};
#endif // _StepFEA_CurveElementIntervalLinearlyVarying_HeaderFile
|
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
ifstream dna_file (argv[1]);
char x;
string rna="";
while (dna_file.get(x)){
if(x=='T'){
rna+='U';
}else{
rna+=x;
}
}
cout << rna ;
}
|
/*
* @lc app=leetcode.cn id=375 lang=cpp
*
* [375] 猜数字大小 II
*/
// @lc code=start
#include<iostream>
#include<vector>
using namespace std;
class Solution {
public:
int getMoneyAmount(int n) {
vector<vector<int>> dp(n+1, vector<int>(n+1,0));
for(int len=2;len<=n;len++)
{
for(int start=1;start<=n-len+1;start++)
{
int minres = INT_MAX;
for(int piv=start;piv<start+len-1;piv++)
{
int res = piv + max(dp[start][piv-1], dp[piv+1][start+len-1]);
minres = min(res, minres);
}
dp[start][start+len-1] = minres;
}
}
return dp[1][n];
}
};
// @lc code=end
|
#include <Unixfunc.h>
#include <iostream>
using namespace std;
/*
Posix多线程pthread详解
前言
不论是子线程还是主线程,实质上都共同属于同一个进程,这大大的减小了系统的开销。
另外,多线程与多进程的使用实质上主要掌握 创建 等待 退出 这三个点
||创建|等待|退出|
|多进程|fork|wait|exit|
|多线程|pthread_create|pthread_join|pthread_exit|
同时,多线程也有自己的线程清理函数 pthread_cleanup_push(pop).
一.线程创建 pthread_create
* int pthread_create(pthread_t *__restrict__ __newthread,
const pthread_attr_t *__restrict__ __attr,
void *(*__start_routine)(void *),
void *__restrict__ __arg)
线程创建的过程中有可能需要向子线程传入一些参数类型,那么如何进行传入参数也是多线程的难点之一。
1. 无输入参数
可以看出,主线程与子线程属于同一个进程
*/
void* threadFunc1(void* arg)
{
cout << "this is child thread, process id = " << getpid() << " , thread id = " << pthread_self() << endl;
pthread_exit(NULL);
}
void test1()
{
pthread_t pid;
cout << "this is main thread, process id = " << getpid() << " , thread id = " << pthread_self() << endl;
pthread_create(&pid, NULL, threadFunc1, NULL);
cout << "child thread id = " << pid << endl;
pthread_join(pid, NULL);
}
/*
2.输入int型参数
*/
void* threadFunc2(void* arg)
{
cout << "child thread get val:" << *(int*)arg << endl;
pthread_exit(NULL);
}
void test2()
{
pthread_t pid;
int val = 5;
pthread_create(&pid, NULL, threadFunc2, (void*)&val);
pthread_join(pid, NULL);
}
/*
3.输入fd文件描述符
*/
void* threadFunc3(void* arg)
{
int fd = *(int*)arg;
cout << "child thread get fd:" << fd << endl;
close(fd);
pthread_exit(NULL);
}
void test3()
{
pthread_t pid;
int fd = open("file", O_RDWR | O_CREAT, 0665);
pthread_create(&pid, NULL, threadFunc3, &fd);
pthread_join(pid, NULL);
}
/*
4.传入char*类型
*/
void* threadFunc4(void* arg)
{
char* buf = (char*)arg;
cout << "child thread is processing buf " << endl;
buf = (char*)malloc(10 * sizeof(char));
strcpy(buf, "hello");
cout << "now buf is " << buf << endl;
pthread_exit(NULL);
}
void test4()
{
pthread_t pid;
char *buf = NULL;
pthread_create(&pid, NULL, threadFunc4, buf);
pthread_join(pid, NULL);
}
/*
5.输入long型参数
此处传入long型参数的方式也可以按照第2种传入的方式来,更为通用
*/
void* threadFunc5(void* arg)
{
cout << "child thread get val:" << (long)arg << endl;
pthread_exit(NULL);
}
void test5()
{
pthread_t pid;
long val = 5;
pthread_create(&pid, NULL, threadFunc2, (void*)val);
pthread_join(pid, NULL);
}
/*
6.传入结构体
传入学生的姓名,成绩,并打印
*/
struct Student
{
const char* name;
double score;
};
void *threadFunc6(void* arg)
{
Student *stu = (Student*)arg;
for (int i = 0; i < 3; i++)
cout << stu[i].name << ":" << stu[i].score << endl;
pthread_exit(NULL);
}
void test6()
{
Student stus[3] = {{"wwx", 99}, {"wk", 77}, {"wby", 88}};
pthread_t pid;
pthread_create(&pid, NULL, threadFunc6, stus);
pthread_join(pid, NULL);
}
/*
7.小练习:主线程与子线程各自加一千万,看结果是否为两千万
*/
const int N = 10000000;
void *threadFunc7(void* arg)
{
for (int i = 0; i < N; i++)
*(int*)arg += 1;
pthread_exit(NULL);
}
void test7()
{
int sum = 0;
pthread_t pid;
pthread_create(&pid, NULL, threadFunc7, &sum);
for (int i = 0; i < N; i++)
sum ++;
pthread_join(pid, NULL);
cout << "final sum = " << sum << endl;
}
int main()
{
test1();
return 0;
}
|
#include <ostream>
#include <vector>
#include "perm.h"
#include "explicit_transversals.h"
namespace cgtl
{
void ExplicitTransversals::create_edge(
unsigned origin, unsigned destination, unsigned label)
{
if (_orbit.find(destination) == _orbit.end()) {
_orbit[destination] = Perm(_degree);
_orbit[origin] = _labels[label];
} else {
_orbit[origin] = _orbit[destination] * _labels[label];
}
}
unsigned ExplicitTransversals::root() const
{
return _root;
}
std::vector<unsigned> ExplicitTransversals::nodes() const
{
std::vector<unsigned> res;
for (auto item : _orbit)
res.push_back(item.first);
return res;
}
PermSet ExplicitTransversals::labels() const
{
return _labels;
}
bool ExplicitTransversals::contains(unsigned node) const
{
return _orbit.find(node) != _orbit.end();
}
bool ExplicitTransversals::incoming(unsigned, Perm const &) const
{
return false;
}
Perm ExplicitTransversals::transversal(unsigned origin) const
{
auto it(_orbit.find(origin));
return it->second;
}
void ExplicitTransversals::dump(std::ostream &os) const
{
os << "explicit transversals:\n";
for (auto const &tr : _orbit)
os << tr.first << ": " << tr.second << "\n";
}
} // namespace cgtl
|
#include "imgui/imgui.h"
#include "EventListener.h"
#include "GameData.h"
#include "GUI.h"
#include "Hacks/ESP.h"
#include "Hacks/Misc.h"
#include "Hooks.h"
#include "Interfaces.h"
#include "Memory.h"
#include "SDK/Engine.h"
#include "SDK/GlobalVars.h"
#include "SDK/InputSystem.h"
#ifdef _WIN32
#include <intrin.h>
#include "imgui/imgui_impl_dx9.h"
#include "imgui/imgui_impl_win32.h"
#elif __linux__
#include <SDL2/SDL.h>
#define GL_GLEXT_PROTOTYPES
#include <SDL2/SDL_opengl.h>
#include "imgui/imgui_impl_sdl.h"
#include "imgui/imgui_impl_opengl3.h"
#endif
#include "PostProcessing.h"
#ifdef _WIN32
LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
static LRESULT WINAPI wndProc(HWND window, UINT msg, WPARAM wParam, LPARAM lParam) noexcept
{
if (hooks->getState() == Hooks::State::NotInstalled)
hooks->install();
if (hooks->getState() == Hooks::State::Installed) {
GameData::update();
Misc::updateEventListeners();
ImGui_ImplWin32_WndProcHandler(window, msg, wParam, lParam);
interfaces->inputSystem->enableInput(!gui->isOpen());
}
return CallWindowProcW(hooks->wndProc, window, msg, wParam, lParam);
}
static HRESULT D3DAPI reset(IDirect3DDevice9* device, D3DPRESENT_PARAMETERS* params) noexcept
{
GameData::clearTextures();
PostProcessing::onDeviceReset();
ImGui_ImplDX9_InvalidateDeviceObjects();
return hooks->reset(device, params);
}
static HRESULT D3DAPI present(IDirect3DDevice9* device, const RECT* src, const RECT* dest, HWND windowOverride, const RGNDATA* dirtyRegion) noexcept
{
[[maybe_unused]] static const auto _ = ImGui_ImplDX9_Init(device);
if (ESP::loadScheduledFonts())
ImGui_ImplDX9_DestroyFontsTexture();
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
PostProcessing::setDevice(device);
PostProcessing::newFrame();
Misc::drawPreESP(ImGui::GetBackgroundDrawList());
ESP::render();
Misc::drawPostESP(ImGui::GetBackgroundDrawList());
gui->render();
gui->handleToggle();
if (!gui->isFullyClosed())
PostProcessing::performFullscreenBlur(ImGui::GetBackgroundDrawList(), gui->getTransparency());
ImGui::Render();
if (device->BeginScene() == D3D_OK) {
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
device->EndScene();
}
GameData::clearUnusedAvatars();
return hooks->present(device, src, dest, windowOverride, dirtyRegion);
}
static BOOL WINAPI setCursorPos(int X, int Y) noexcept
{
if (gui->isOpen()) {
POINT p;
GetCursorPos(&p);
X = p.x;
Y = p.y;
}
return hooks->setCursorPos(X, Y);
}
Hooks::Hooks(HMODULE moduleHandle) noexcept : moduleHandle{ moduleHandle }
{
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
_MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);
window = FindWindowW(L"Valve001", nullptr);
}
#elif __linux__
static int pollEvent(SDL_Event* event) noexcept
{
if (hooks->getState() == Hooks::State::NotInstalled)
hooks->install();
const auto result = hooks->pollEvent(event);
if (hooks->getState() == Hooks::State::Installed) {
GameData::update();
Misc::updateEventListeners();
if (result && ImGui_ImplSDL2_ProcessEvent(event) && gui->isOpen())
event->type = 0;
}
return result;
}
static void swapWindow(SDL_Window* window) noexcept
{
static const auto _ = ImGui_ImplSDL2_InitForOpenGL(window, nullptr);
if (ESP::loadScheduledFonts()) {
ImGui_ImplOpenGL3_DestroyDeviceObjects();
}
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(window);
ImGui::NewFrame();
PostProcessing::newFrame();
if (const auto& displaySize = ImGui::GetIO().DisplaySize; displaySize.x > 0.0f && displaySize.y > 0.0f) {
Misc::drawPreESP(ImGui::GetBackgroundDrawList());
ESP::render();
Misc::drawPostESP(ImGui::GetBackgroundDrawList());
gui->render();
gui->handleToggle();
}
if (!gui->isFullyClosed())
PostProcessing::performFullscreenBlur(ImGui::GetBackgroundDrawList(), gui->getTransparency());
ImGui::EndFrame();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
GameData::clearUnusedAvatars();
hooks->swapWindow(window);
}
Hooks::Hooks() noexcept
{
interfaces = std::make_unique<const Interfaces>();
memory.emplace(Memory{});
}
#elif __APPLE__
Hooks::Hooks() noexcept
{
interfaces = std::make_unique<const Interfaces>();
memory.emplace(Memory{});
}
#endif
void Hooks::setup() noexcept
{
#ifdef _WIN32
wndProc = WNDPROC(SetWindowLongPtrW(window, GWLP_WNDPROC, LONG_PTR(&::wndProc)));
#elif __linux__
pollEvent = *reinterpret_cast<decltype(pollEvent)*>(memory->pollEvent);
*reinterpret_cast<decltype(::pollEvent)**>(memory->pollEvent) = ::pollEvent;
#endif
}
void Hooks::install() noexcept
{
state = State::Installing;
#ifndef __linux__
interfaces = std::make_unique<const Interfaces>();
memory.emplace(Memory{});
#endif
EventListener::init();
ImGui::CreateContext();
#ifdef _WIN32
ImGui_ImplWin32_Init(window);
#elif __linux__
ImGui_ImplOpenGL3_Init();
#endif
gui = std::make_unique<GUI>();
#ifdef _WIN32
reset = *reinterpret_cast<decltype(reset)*>(memory->reset);
*reinterpret_cast<decltype(::reset)**>(memory->reset) = ::reset;
present = *reinterpret_cast<decltype(present)*>(memory->present);
*reinterpret_cast<decltype(::present)**>(memory->present) = ::present;
setCursorPos = *reinterpret_cast<decltype(setCursorPos)*>(memory->setCursorPos);
*reinterpret_cast<decltype(::setCursorPos)**>(memory->setCursorPos) = ::setCursorPos;
#elif __linux__
swapWindow = *reinterpret_cast<decltype(swapWindow)*>(memory->swapWindow);
*reinterpret_cast<decltype(::swapWindow)**>(memory->swapWindow) = ::swapWindow;
#endif
state = State::Installed;
}
#ifdef _WIN32
extern "C" BOOL WINAPI _CRT_INIT(HMODULE moduleHandle, DWORD reason, LPVOID reserved);
static DWORD WINAPI waitOnUnload(HMODULE hModule) noexcept
{
Sleep(50);
interfaces->inputSystem->enableInput(true);
EventListener::remove();
ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
_CRT_INIT(hModule, DLL_PROCESS_DETACH, nullptr);
FreeLibraryAndExitThread(hModule, 0);
}
#endif
void Hooks::uninstall() noexcept
{
Misc::updateEventListeners(true);
#ifdef _WIN32
*reinterpret_cast<decltype(reset)*>(memory->reset) = reset;
*reinterpret_cast<decltype(present)*>(memory->present) = present;
*reinterpret_cast<decltype(setCursorPos)*>(memory->setCursorPos) = setCursorPos;
SetWindowLongPtrW(window, GWLP_WNDPROC, LONG_PTR(wndProc));
if (HANDLE thread = CreateThread(nullptr, 0, LPTHREAD_START_ROUTINE(waitOnUnload), moduleHandle, 0, nullptr))
CloseHandle(thread);
#elif __linux__
*reinterpret_cast<decltype(pollEvent)*>(memory->pollEvent) = pollEvent;
*reinterpret_cast<decltype(swapWindow)*>(memory->swapWindow) = swapWindow;
#endif
}
|
#ifndef assume_h
#define assume_h
#include <chuffed/core/sat-types.h>
#include <chuffed/core/sat.h>
#include <chuffed/support/misc.h>
// Helper for pushing a failure back to externally visible literals.
// WARNING: This assumes explanations are not lazy.
template <class P>
void pushback_reason(const P& is_extractable, Lit p, vec<Lit>& out_nogood) {
assert(sat.value(p) == l_False);
out_nogood.push(~p);
// TODO: Take literal subsumption into account.
// Even though we can't _export_ integer bounds, we can still
// use the semantics to weaken the nogood.
vec<Lit> removed;
assert(!sat.reason[var(p)].isLazy());
if (sat.trailpos[var(p)] < 0) {
return; // p is false at the root.
}
Clause* cp = sat.getExpl(~p);
if (!cp) {
// Somebody has pushed inconsistent assumptions.
// * This may happen if, in an optimization problem, the user
// * provided an objective lower bound which is achieved.
// If p and ~p are assumptions, we just return a
// tautological clause.
out_nogood.push(p);
return;
} // Otherwise, fill in the reason for ~p...
for (int i = 1; i < cp->size(); i++) {
Lit q((*cp)[i]);
if (sat.trailpos[var(q)] < 0) {
continue;
}
out_nogood.push(q);
// Only look at the first bit of seen, because
// we're using the second bit for assumption-ness.
sat.seen[var(q)] |= 1;
}
// then push it back to assumptions.
for (int i = 1; i < out_nogood.size(); i++) {
Lit q(out_nogood[i]);
if (is_extractable(q)) {
continue;
}
assert(!sat.reason[var(q)].isLazy());
Clause* c = sat.getExpl(~q);
assert(c != nullptr);
removed.push(q);
out_nogood[i] = out_nogood.last();
out_nogood.pop();
--i;
for (int j = 1; j < c->size(); j++) {
Lit r((*c)[j]);
if (!(sat.seen[var(r)] & 1)) {
sat.seen[var(r)] |= 1;
if (sat.trailpos[var(r)] < 0) {
removed.push(r);
} else {
out_nogood.push(r);
}
}
}
}
// Clear the 'seen' bit.
for (int i = 0; i < removed.size(); i++) {
sat.seen[var(removed[i])] &= (~1);
}
for (int i = 1; i < out_nogood.size(); i++) {
sat.seen[var(out_nogood[i])] &= (~1);
}
}
// General version, which permits lazy explanations.
// Basically a mix of pushback and normal conflict analysis.
template <class Pred>
void pushback_reason_lazy(const Pred& is_extractable, Lit p, vec<Lit>& out_nogood) {
assert(sat.value(p) == l_False);
out_nogood.push(~p);
// TODO: Take literal subsumption into account.
// Even though we can't _export_ integer bounds, we can still
// use the semantics to weaken the nogood.
vec<Lit> removed;
if (sat.trailpos[var(p)] < 0) {
return; // p is false at the root.
}
Clause* cp = sat.getExpl(~p);
if (!cp) {
// Somebody has pushed inconsistent assumptions.
// * This may happen if, in an optimization problem, the user
// * provided an objective lower bound which is achieved.
// If p and ~p are assumptions, we just return a
// tautological clause.
out_nogood.push(p);
return;
}
// There _should_ be at least one atom at the current decision level.
int pending = 0;
for (int jj = 1; jj < (*cp).size(); ++jj) {
Lit p((*cp)[jj]);
assert(sat.value(p) == l_False);
sat.seen[var(p)] |= 1;
if (sat.trailpos[var(p)] < 0) {
removed.push(p); // If trailpos < 0, not needed.
} else {
pending++;
}
}
assert(pending > 0);
if (pending == 0) {
return;
}
// Process the levels in order.
Reason last_reason = sat.reason[var(p)];
int lev = sat.decisionLevel();
// Should never need to touch level 0.
while (lev > 0) {
vec<Lit>& ctrail = sat.trail[lev];
int& index = sat.index;
index = ctrail.size();
while (index) {
// Skip variables we haven't seen
if (!(sat.seen[var(ctrail[--index])] & 1)) {
continue;
}
// Found the next literal.
Lit p(ctrail[index]);
pending--;
assert(sat.value(p) == l_True);
if (is_extractable(p)) {
// p is an assumption.
// See if we can drop it anyway.
Clause* expl(sat.getExpl(p));
if (!expl) {
out_nogood.push(~p);
} else {
// If every antecedent is already seen, we don't need it.
for (int j = 1; j < (*expl).size(); ++j) {
if (!(sat.seen[var((*expl)[j])] & 1)) {
// Needed after all
out_nogood.push(~p);
goto processed_assump;
}
}
// Remember to reset seen at the end.
removed.push(p);
}
processed_assump:
// Have we seen enough?
if (!pending) {
goto pushback_finished;
}
continue;
}
// Not an assumption; mark the antecedents as seen.
assert(var(p) >= 0 && var(p) < sat.nVars());
// Sign doesn't really matter here; just the var.
removed.push(p);
if (last_reason == sat.reason[var(p)]) {
continue;
}
last_reason = sat.reason[var(p)];
Clause& c = *sat.getExpl(p);
assert(&c);
for (int j = 1; j < c.size(); j++) {
Lit q = c[j];
if (!(sat.seen[var(q)] & 1)) {
sat.seen[var(q)] |= 1;
assert(sat.value(q) == l_False);
assert(sat.trailpos[var(q)] <= engine.trail.size());
if (sat.trailpos[var(q)] < 0) {
removed.push(q);
} else {
pending++;
}
}
}
assert(pending > 0);
}
// Finished at the current level.
lev--;
// We need to explicitly backtrack, because
// getExpl calls btToPos, which accesses the _current_
// decision level's trail.
sat.btToLevel(lev);
}
pushback_finished:
assert(pending == 0);
for (int i = 0; i < removed.size(); i++) {
sat.seen[var(removed[i])] &= (~1);
}
for (int i = 0; i < out_nogood.size(); i++) {
sat.seen[var(out_nogood[i])] &= (~1);
}
}
#endif
|
/*
* validator.h
*
* Created on: 14. 12. 2016
* Author: ondra
*/
#ifndef IMMUJSON_VALIDATOR_H_
#define IMMUJSON_VALIDATOR_H_
#include <vector>
#include "path.h"
#include "stringview.h"
#include "string.h"
#include "value.h"
namespace json {
class Validator {
public:
virtual ~Validator() {}
static StrViewA strString;
static StrViewA strNumber;
static StrViewA strBoolean;
static StrViewA strAny;
static StrViewA strBase64;
static StrViewA strBase64url;
static StrViewA strHex;
static StrViewA strUppercase;
static StrViewA strLowercase;
static StrViewA strIdentifier;
static StrViewA strCamelCase;
static StrViewA strAlpha;
static StrViewA strAlnum;
static StrViewA strDigits;
static StrViewA strInteger;
static StrViewA strUnsigned;
static StrViewA strNative;
static StrViewA strNull;
static StrViewA strOptional;
static StrViewA strUndefined;
static StrViewA strDateTimeZ;
static StrViewA strDate;
static StrViewA strTimeZ;
static StrViewA strTime;
static StrViewA strEmpty;
static StrViewA strNonEmpty;
static StrViewA strObject;
static StrViewA strArray;
static StrViewA strGreater;
static StrViewA strGreaterEqual;
static StrViewA strLess;
static StrViewA strLessEqual;
static StrViewA strMinSize;
static StrViewA strMaxSize;
static StrViewA strKey;
static StrViewA strToString;
static StrViewA strToNumber;
static StrViewA strPrefix;
static StrViewA strSuffix;
static StrViewA strSplit;
static StrViewA strExplode;
static StrViewA strAll;
static StrViewA strAndSymb;
static StrViewA strNot;
static StrViewA strNotSymb;
static StrViewA strDateTime;
static StrViewA strSetVar;
static StrViewA strUseVar;
static StrViewA strEmit;
static char valueEscape;
static char commentEscape;
static char charSetBegin;
static char charSetEnd ;
///Evaluates the native rule
/**
* Native rule is declared as "native" in class table. The function
*
* @param ruleName name of the rule
* @param args arguments if the rule. Array is always here
* @param subject the item it is subject of validation
*/
virtual bool onNativeRule(const Value &, const StrViewA & ) { return false; }
///Validate the subject
/**
*
* @param subject item to validate
* @param rule Name of rule to use (probably class).
* @param path path to the subject. Default value expects root of the document. You can specify path if you are validating
* a part of the document.
* @retval true validated
* @retval false not valid
*/
bool validate(const Value &subject,const StrViewA &rule = StrViewA("_root"), const Path &path = Path::root);
///Constructs validator above validator-definition (described above)
Validator(const Value &definition);
///Retrieves array rejections
/**
* Each item contains
* [path, rule-def]
*
* the path is presented as json array
* the rule-def is either while rule line, or specific rule, which returned rejection
*
* The whole rule-line is rejected when no rule accept the item. Then whole rule-line is reported.
* If one of rules rejected the rule-line, then rejecting rule is outputed
*
* @return The array can contain more rejection if the format allows multiple ways to validate the document. The
* document is rejected when there is no way to accept the document.
*/
Value getRejections() const;
///Sets variables
/**
*
* @param varList container with variables (object).
*
* Function replaces current variables
*/
void setVariables(const Value &varList);
Value getEmits() const;
protected:
bool validateInternal(const Value &subject,const StrViewA &rule);
bool evalRuleSubObj(const Value & subject, const Value & rule, const StrViewA & key);
bool evalRuleSubObj(const Value & subject, const Value & rule, unsigned int index);
bool evalRuleSubObj(const Value & subject, const Value & rule, unsigned int index, unsigned int offset);
bool evalRule(const Value & subject, const Value & ruleLine);
bool evalRuleWithParams(const Value & subject, const Value & rule);
bool opRangeDef(const Value & subject, const Value & rule, std::size_t offset);
bool evalRuleArray(const Value & subject, const Value & rule, unsigned int tupleCnt, unsigned int offset);
bool evalRuleAlternatives(const Value & subject, const Value & rule, unsigned int offset);
bool evalRuleSimple(const Value & subject, const Value & rule);
///Definition
Value def;
std::vector<Value> rejections;
std::vector<Value> emits;
Value lastRejectedRule;
///current path (for logging)
const Path *curPath;
typedef std::vector<Value> VarList;
VarList varList;
bool evalRuleObject(const Value & subject, const Value & templateObj);
bool checkClass(const Value& subject, StrViewA name);
bool opPrefix(const Value &subject, const Value &args);
bool opSuffix(const Value &subject, const Value &args);
bool opSplit(const Value &subject, std::size_t at, const Value &left, const Value &right);
void addRejection(const Path &path, const Value &rule);
void pushVar(String name, Value value);
void popVar();
Value findVar(const StrViewA &name, const Value &thisVar);
Value getVar(const Value &path, const Value &thisVar);
bool opSetVar(const Value &subject, const Value &args);
bool opUseVar(const Value &subject, const Value &args);
bool opCompareVar(const Value &subject, const Value &rule);
bool opEmit(const Value &subject, const Value &args);
Value walkObject(const Value &subject, const Value &v);
bool opExplode(const Value& subject, StrViewA str, const Value& rule, const Value& limit);
};
}
#endif /* IMMUJSON_VALIDATOR_H_ */
|
/* -*- mode: c++; tab-width: 4; c-basic-offset: 4 -*- */
group "clipboard";
require init;
require USE_OP_CLIPBOARD;
include "modules/dragdrop/clipboard_manager.h";
include "modules/pi/OpClipboard.h";
include "modules/doc/frm_doc.h";
include "modules/doc/html_doc.h";
include "modules/logdoc/htm_elm.h";
include "modules/logdoc/logdoc.h";
include "modules/forms/piforms.h";
include "modules/widgets/OpWidget.h";
language C++;
global
{
HTML_Element* GetElement(const uni_char* id)
{
LogicalDocument* logdoc = state.doc->GetLogicalDocument();
NamedElementsIterator el_iterator;
int found = logdoc->SearchNamedElements(el_iterator, NULL, id, TRUE, TRUE);
if (found)
if (HTML_Element* named_element = el_iterator.GetNextElement())
return named_element;
return NULL;
}
class TestClipboardListener : public ClipboardListener
{
public:
TestClipboardListener()
: string_matches(FALSE)
, clipboard_string(NULL)
{}
BOOL string_matches;
const uni_char* clipboard_string;
void OnCopy(OpClipboard* clipboard)
{
clipboard->PlaceText(clipboard_string);
}
void OnCut(OpClipboard* clipboard)
{
clipboard->PlaceText(clipboard_string);
}
void OnPaste(OpClipboard* clipboard)
{
OpString clipboard_content;
clipboard->GetText(clipboard_content);
string_matches = clipboard_content.CStr() != NULL && uni_str_eq(clipboard_content.CStr(), clipboard_string);
}
void OnEnd()
{
}
};
TestClipboardListener test_listener;
}
test("Clipboard fully operational")
{
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("foobarbaz");
verify_success(g_clipboard_manager->Copy(&test_listener));
verify_success(g_clipboard_manager->Paste(&test_listener));
BOOL is_clipboard_working = test_listener.string_matches;
test_listener.string_matches = FALSE;
verify_success(g_clipboard_manager->Cut(&test_listener));
verify_success(g_clipboard_manager->Paste(&test_listener));
is_clipboard_working = is_clipboard_working && test_listener.string_matches;
if (!is_clipboard_working)
{
output(
"\nThese tests depend on platform's clipboard\nand it seems it isn't working.\n"
"If your project does not implement the clipboard\nbecause it's customers' job to do so\n"
"disregard this failure. Otherwise take a look into\nplatform's clipboard impelmentation.\n"
"The rest of the tests will be skipped.\n"
);
}
verify(is_clipboard_working);
}
html {
//! <!DOCTYPE html>
//! <input type='text' value='Input text' id='receiver' autofocus onfocus="this.select()"/>
}
test("copy")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("Input text");
verify_success(g_clipboard_manager->Copy(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <input type='text' value='Input text #2' id='receiver' autofocus onfocus="this.select()"/>
}
test("cut")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("Input text #2");
verify_success(g_clipboard_manager->Cut(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <input type='text' value='' id='receiver' autofocus/>
}
test("paste")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.clipboard_string = UNI_L("Input text");
verify_success(g_clipboard_manager->Copy(&test_listener));
verify_success(g_clipboard_manager->Paste(&test_listener, state.doc, elm));
FormObject* object = elm->GetFormObject();
verify(object);
OpWidget* widget = object->GetWidget();
verify(widget);
OpString input_text;
verify_success(widget->GetText(input_text));
verify(uni_str_eq(input_text.CStr(), test_listener.clipboard_string));
}
html {
//! <!DOCTYPE html>
//! <input type='text' value='Input text #2' id='receiver' autofocus onfocus="this.select()"/>
}
test("double cut, one paste")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("Input text #2");
verify_success(g_clipboard_manager->Cut(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Cut(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <input type='text' value='Input text #3' id='receiver' autofocus onfocus="this.select()"/>
}
test("copy/paste when nothing to be copied")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("Input text #3");
verify_success(g_clipboard_manager->Cut(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
verify_success(g_clipboard_manager->Copy(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
test("copy/paste non-ascii")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("\x4ED6\x5011\x7232\x4EC0\x9EBD\x4E0D\x8AAA\x4E2D\x6587");
verify_success(g_clipboard_manager->Copy(&test_listener));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <input type='password' value='secret password' id='receiver' autofocus onfocus="this.selectAll()"/>
}
test("copy from password input")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("secret password");
verify_success(g_clipboard_manager->Copy(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(!test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <input type='file' id='receiver' />
}
test("copy from file input")
require success "Clipboard fully operational";
{
const uni_char* test_file_path = UNI_L("C:\\my_private_file.txt");
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
FormValue* form_value = elm->GetFormValue();
verify(form_value);
form_value->SetValueFromText(elm, test_file_path);
state.doc->GetHtmlDocument()->FocusElement(elm, HTML_Document::FOCUS_ORIGIN_DOM, FALSE);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = test_file_path;
verify_success(g_clipboard_manager->Copy(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(!test_listener.string_matches);
}
html {
//! <!DOCTYPE html>
//! <textarea id='receiver'>Textarea text</textarea>
//! <script>var ta = document.getElementById('receiver'); ta.focus(); ta.select();</script>
}
test("copy from textarea")
require success "Clipboard fully operational";
{
HTML_Element* elm = GetElement(UNI_L("receiver"));
verify(elm);
test_listener.string_matches = FALSE;
test_listener.clipboard_string = UNI_L("Textarea text");
verify_success(g_clipboard_manager->Copy(&test_listener, 0, state.doc, elm));
verify_success(g_clipboard_manager->Paste(&test_listener));
verify(test_listener.string_matches);
}
|
//By SCJ
//#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define INF 100000000
bool A[20][20],a[20][20];
bool count(int i,int j)
{
return a[i][j-1]^a[i][j+1]^a[i-1][j]^a[i+1][j];
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int T;cin>>T;
for(int ca=1;ca<=T;++ca)
{
memset(A,0,sizeof(A));
int n;cin>>n;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j) cin>>A[i][j];
int S=(1<<n);
int cnt=0,ans=INF;
for(int r=0;r<S;++r)
{
int tp=r;cnt=0;
for(int i=1;i<=n;++i)
for(int j=1;j<=n;++j)
a[i][j]=A[i][j];
bool tt=1;
for(int i=1;i<=n;++i)
{
if(tp&1)
{
if(a[1][i]) {tt=0;break;}
cnt++,a[1][i]^=1;
}
tp>>=1;
}
if(tt==0) continue;
for(int i=2;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
if(count(i-1,j))
{
if(a[i][j]) {tt=0;break;}
cnt++,a[i][j]^=1;
}
}
if(tt==0) break;
}
bool flag=0;
for(int j=1;j<=n;++j)
if(count(n,j)) flag=1;
if(flag==0&&tt==1) ans=min(ans,cnt);
}
cout<<"Case "<<ca<<": ";
if(ans==INF) cout<<-1<<endl;
else cout<<ans<<endl;
}
}
|
#ifndef ANIMATEDSPRITE_H
#define ANIMATEDSPRITE_H
class AnimatedSprite
{
public:
AnimatedSprite();
virtual ~AnimatedSprite();
protected:
private:
};
#endif // ANIMATEDSPRITE_H
|
#ifndef DRAWINGS_H
#define DRAWINGS_H
#endif // DRAWINGS_H
#include <cmath>
#include "opencv2/opencv.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include <opencv2/highgui.hpp>
#include <opencv2/video.hpp>
#include <opencv2/gapi/gscalar.hpp>
#include <opencv2/gapi/core.hpp>
#include <opencv2/core/matx.hpp>
#include <opencv2/core/types.hpp>
#include <opencv2/gapi/render/render_types.hpp>
using namespace cv;
//----------------------------------------Global Variable----------------------------------------//
/*
* Global variable are not always a good idea
* futher version of this code will see many
* of them as local variables. Often variables
* are passed up a sequence of functions to either
* demonstate a purpose or as a safety check. This
* was avoided by making the variables global to simplify
* the function calls.
*/
bool transmitGo = false;
// These 4 points are used to find the angle
// rotation of the hand
Point2f A;
Point2f B;
Point2f C;
Point2f RunningAverageWristAngle; // Average value of last 10 fingertip values
// These t3 points are use to detemine best
// center hand finding location 2 are commented out
// because they are no longer needed. Left in for demonstrations
// Point2f center;
// Point2f True_Center;
Point2f Rect_Center;
// For Demonstraion only
// What hand pose was detected
// string HandPose = "Not Detected";
// These variablesset safties enabling or disabling
// Movements of the arm as the hand moves across the
// viewing screen
int EnabledMovements; // Uses to control a switch statements: int comes from the "EnableMovements" Array
int EnableMovements[16] = {3,2,1,4,2,3,4,1,1,4,3,2,4,1,2,3};
/*
* D ~ Down; U ~ Up; R ~ Right; L ~ Left
*
* H = 0 // Never used
* D = 1
* U = 2
* L = 3
* R = 4
* DL =5
* DR =6
* UL =7
* UR =8
*/
int DirectionalMovements[16] = {5,1,3,0,1,6,0,4,3,0,7,2,0,4,2,8}; // Translates Safety Enables to Directional Movements
// These vectors stores FingerTips and hull defects which are the inter-digital folds.
vector<Point> amend_start_pt;
vector<Point> amend_farthest_points;
//----------------------------------------Functions----------------------------------------//
// This function Determines whether the compare point is across a line formed from startPoint to EndPoint
int crossProduct(Point2f startPoint, Point2f EndPoint, Point2f Compare);
// This function assembles the command word for transmittion
void assembleCommandWord(int safetyByte);
// This function is call from inside "assembleCommandWord" function to concentrrate all char strings into one string
void ConcentrateCharArrays(char* CommandWord, char* Handpose, char* Bicep, char* Wrist, char* Shoulder);
// These functions stop adjust the command word to stop their respected movements
void StopBicep(char* Bicep);
void StopWrist(char* Wrist);
void StopShoulder(char* Shoulder);
// These functions get set the sommand word based upon the "EnabledMovements" Array value
void getBicep(char* Bicep);
void getWrist(char* Wrist);
void getShoulder(char* Shoulder);
// This function creates the runnin average of the fingertips
void AverageFingerTips();
// This function calculates the distance between two points
double Magnitude(Point2f aPoint, Point2f bPoint);
// These functions reduces the number of points dectects along the hand contour
vector<Point> Amden_Points_Start(vector<Point> &points, Point2f center);
vector<Point> Amden_Points(vector<Point> &points, Point2f center);
// Draws Squares on the screen to indicate calibration region
void Draw_Glove_Colour_Calibration_Squares(Mat &aLive_View);
// ~~~~~~This function needs work~~~~~~~~~~~~ calibrates for the average colour detected in the two squares
void Calibrate_Glove_Colour(Mat &aLive_View);
// Returns the point for the center of the hand
void Draw_Contours(Mat &aThreshold_Applied, Mat &aLiveView, bool calibrationHappy);
// Draws the Axis and Quadernts for visulaizing hand placement versus expected movement
void drawAxisAndQuadents(Mat &aLive_View);
// Will deect the hand to opening and closing
void detectHandPose(char* HandPose);
// Locates the center of the hand to detemine eligible movemnets
int setSafeties(Mat &aThreshold_Applied, Point2f center);
//----------------------------------------Function Definitions----------------------------------------//
void Draw_Glove_Colour_Calibration_Squares(Mat &aLive_View)
{
rectangle( aLive_View,
Rect( int ((aLive_View.size().width) * 0.5), ((aLive_View.size().height) / 2) + 40, 20, 20),
Scalar(0, 0, 255),
3
);
rectangle( aLive_View,
Rect( int((aLive_View.size().width) * 0.5), ((aLive_View.size().height) / 3) + 40, 20, 20),
Scalar(0, 0, 255),
3
);
}
void Calibrate_Glove_Colour(Mat &aHSV)
{
// Creates the Mats for colour abstraction
Mat Square_1 = Mat(aHSV, (Rect( int((aHSV.size().width) *0.5), ((aHSV.size().height) / 2) + 40, 20, 20)));
Mat Square_2 = Mat(aHSV, (Rect( int((aHSV.size().width) *0.5), ((aHSV.size().height) / 3) + 40, 20, 20)));
// Takes the mean HSV of those squares
Scalar Square_1_mean = mean(Square_1);
Scalar Square_2_mean = mean(Square_2);
// Averge the means
Square_1_mean = (Square_1_mean + Square_2_mean) * 0.5;
// cout << "Mean Value of Squares: " <<Square_1_mean <<endl; // For testing only
// creates a standard deviation of the calibration squares for creating lower and upper thresholds
Scalar mean_1, stddev_1;
meanStdDev(Square_1,mean_1,stddev_1,cv::Mat());
// cout<<"Standard deviation: "<<stddev_1.val[0]<<endl; // for testing only
// Lower and upper thresholds. increased by 10% to create a wider detecble range. ~~~~ Needs further work ~~~~~
Lower_Threshhold[0] = int( Square_1_mean[0] - (10*stddev_1.val[0]) );
Lower_Threshhold[1] = int( Square_1_mean[1] - (10*stddev_1.val[0]) );
Lower_Threshhold[2] = int( Square_1_mean[2] - (10*stddev_1.val[0]) );
Upper_Threshhold[0] = int( Square_1_mean[0] + (10*stddev_1.val[0]) );
Upper_Threshhold[1] = int( Square_1_mean[1] + (10*stddev_1.val[0]) );
Upper_Threshhold[2] = int( Square_1_mean[2] + (10*stddev_1.val[0]) );
// Simple Check to keep the range within 0 - 255
for(int i = 0; i<3; i++)
{
if(Lower_Threshhold[i] > 255)
Lower_Threshhold[i] = 255;
if(Lower_Threshhold[i] < 0)
Lower_Threshhold[i] = 0;
if(Upper_Threshhold[i] > 255)
Upper_Threshhold[i] = 255;
if(Upper_Threshhold[i] < 0)
Upper_Threshhold[i] = 0;
}
// Sets the slider to the value
slider_LB = int (Lower_Threshhold[0]);
slider_LG = int (Lower_Threshhold[1]);
slider_LR = int (Lower_Threshhold[2]);
slider_UB = int (Upper_Threshhold[0]);
slider_UG = int (Upper_Threshhold[1]);
slider_UR = int (Upper_Threshhold[2]);
// Calls the slider function
on_trackbar_Lower_Blue(slider_LB,0);
on_trackbar_Lower_Green(slider_LG,0);
on_trackbar_Lower_Red(slider_LR,0);
on_trackbar_Upper_Blue(slider_UB,0);
on_trackbar_Upper_Green(slider_UG,0);
on_trackbar_Upper_Red(slider_UR,0);
// cout << "Lower_Threshhold" <<Lower_Threshhold <<endl; // For Testing Only
// cout << "Upper_Threshhold" <<Upper_Threshhold <<endl; // For Testing Only
// Releases the data properly
Square_1.release();
Square_2.release();
}
void Draw_Contours(Mat &aThreshold_Applied, Mat &aLiveView, bool calibrationHappy)
{
Mat Blurred_aTheshold;
transmitGo = calibrationHappy;
//morphological opening (remove small objects from the foreground)
erode(aThreshold_Applied, Blurred_aTheshold, getStructuringElement(MORPH_ELLIPSE, Size(7, 7)) );
dilate( Blurred_aTheshold, Blurred_aTheshold, getStructuringElement(MORPH_ELLIPSE, Size(7, 7)) );
//morphological closing (fill small holes in the foreground)
dilate( Blurred_aTheshold, Blurred_aTheshold, getStructuringElement(MORPH_ELLIPSE, Size(7, 7)) );
erode(Blurred_aTheshold, Blurred_aTheshold, getStructuringElement(MORPH_ELLIPSE, Size(7, 7)) );
//imshow("Eroded and Dilated",Blurred_aTheshold); // For Testing Only
if(aThreshold_Applied.channels() == 1)
{
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours(Blurred_aTheshold, contours, hierarchy, RETR_TREE, CHAIN_APPROX_SIMPLE);// CHAIN_APPROX_TC89_L1);
if (contours.size() > 0) // finds largest contour
{
int biggest_contour_index = -1;
double biggest_area = 0.0;
for (int i = 0; i < contours.size(); i++)
{
double area = contourArea(contours[i], false);
if (area > biggest_area)
{
biggest_area = area;
biggest_contour_index = i;
}
}
vector<vector<Point> > contours0;
contours0.resize(contours.size() );
if (biggest_contour_index >= 0) // Draws the largest contour
{
contours.resize(contours0.size());
for( size_t k = 0; k < contours0.size(); k++ )
approxPolyDP(Mat(contours[k]), contours0[k], 1, true);
drawContours(aLiveView, contours0, biggest_contour_index, Scalar(0,255,0), 2, LINE_8, hierarchy, 0);
/*
* // For Testing Only // Center of bounding circle
* float Radius;
* minEnclosingCircle(contours[biggest_contour_index], center, Radius);
* circle(aLiveView, center, int(Radius), Scalar(255,0,0), 2);
* circle(aLiveView, center, 5, Scalar(255,0,0), 3, LINE_8, 0);
*/
// Draws Bounding Rectangle abound hand
// rectangle(aLiveView, minAreaRect(contours[biggest_contour_index]).boundingRect(), Scalar(0,0,255), 2); // For Testing Only
// Finds Center of Bounding rectangle
Rect_Center = minAreaRect(contours0[biggest_contour_index]).center;
// Draws a "dot" on the center of the hand
circle(aLiveView, Rect_Center, 5, Scalar(255,255,255), 3, LINE_8, 0);
/*
* // For Testing Only // True center of contour
* float X(0.0);
* float Y(0.0);
* for(size_t k = 0; k <contours0[biggest_contour_index].size(); k++ )
* {
* X+= contours0[biggest_contour_index][k].x;
* Y+= contours0[biggest_contour_index][k].y;
* }
* X = X/contours0[biggest_contour_index].size();
* Y = Y/contours0[biggest_contour_index].size();
* True_Center = Point2f(X,Y);
* circle(aLiveView, True_Center, 5, Scalar(0,255,0), 3, LINE_8, 0);
*/
}
// ~~~~ Future Work required for this if statement ~~~~~ //
if(true) // There should be a check here to reduce errors
{
vector<Point> hull_points;
vector<int> hull_ints;
convexHull(Mat(contours0[biggest_contour_index]), hull_points, true);
convexHull(Mat(contours0[biggest_contour_index]), hull_ints, true);
/* // For Testing Only
* Orginal method of finding center of hand but not used now
* Rect bounding_rectangle = boundingRect(Mat(hull_points));
* Point center_bounding_rect(
* (bounding_rectangle.tl().x + bounding_rectangle.br().x) / 2,
* (bounding_rectangle.tl().y + bounding_rectangle.br().y) / 2
* );
* circle(aLiveView, center_bounding_rect, 5, Scalar(255,255,255), 3, LINE_8, 0);
* rectangle(aLiveView, bounding_rectangle.tl(), bounding_rectangle.br(), Scalar(255,255,255), 2, 8, 0);
*/
vector<Vec4i> defects;
if (hull_ints.size() > 3) // Require at least 3 "ints" to find hand
{
convexityDefects(Mat(contours0[biggest_contour_index]), hull_ints, defects);
}
vector<Point> start_points; // Fingertips
vector<Point> farthest_points; // Inter-digital folds
// Loads Points into the vector
for (int i = 0; i < defects.size(); i++)
{
start_points.push_back(contours0[biggest_contour_index][defects[i].val[0]]);
farthest_points.push_back(contours0[biggest_contour_index][defects[i].val[2]]);
}
amend_start_pt = Amden_Points_Start(start_points, Rect_Center);
amend_farthest_points = Amden_Points(farthest_points, Rect_Center);
/*
* For Testing Only
* This section of the code places
* the "dots" on the screen
*
*
* for (int i = 0; i < amend_farthest_points.size(); i++)
* {
* circle(aLiveView, amend_farthest_points[i], 5, Scalar(255,0,0), 3, LINE_8, 0);
* putText(aLiveView, to_string(i), amend_farthest_points[i], FONT_HERSHEY_PLAIN, 3, Scalar(255,0,0));
* }
*
* for (int i = 0; i < amend_start_pt.size(); i++)
* {
* circle(aLiveView, amend_start_pt[i], 5, Scalar(0,0,255), 3, LINE_8, 0);
* putText(aLiveView, to_string(i), amend_start_pt[i], FONT_HERSHEY_PLAIN, 3, Scalar(0,0,255));
* }
*
*
* if(!amend_farthest_points.empty() )
* {
* vector<int> Defects_index;
* for(int i =0; i<contours0[biggest_contour_index].size(); i++)
* {
* for(int j =0; j<amend_farthest_points.size(); j++)
* {
* if(contours0[biggest_contour_index][i] == amend_farthest_points[j])
* Defects_index.push_back(i);
* }
* }
*
* if(!Defects_index.empty() )
* {
* for(int j =0; j<Defects_index.size()-1; j++)
* {
* int half_way_point = int ((Defects_index[j+1] - Defects_index[j])*0.5);
* circle(aLiveView, contours0[biggest_contour_index][half_way_point] , 5, Scalar(0,255,255), 3, LINE_8, 0);
* }
* }
* }
*/
if ((!amend_start_pt.empty() )&&(!amend_farthest_points.empty() ))
{
assembleCommandWord( setSafeties(aThreshold_Applied, Rect_Center));
/*
* These display the angle of wrist rotation
*/
circle(aLiveView, A, 10, Scalar(255,0,0), 3, LINE_8, 0); // For Testing Only
circle(aLiveView, B, 10, Scalar(0,0,0), 3, LINE_8, 0); // For Testing Only
line(aLiveView, C, A, Scalar(0,0,0), 3, LINE_8, 0); // For Testing Only
line(aLiveView, C, B, Scalar(0,0,0), 3, LINE_8, 0); // For Testing Only
}
// putText(aLiveView, HandPose, Point(80,80), FONT_HERSHEY_PLAIN, 5, Scalar(0,0,255)); // Dispays handpose detection text on the screen
// polylines(aLiveView, hull_points, true, Scalar(0,128,255), 2); // Draws lines around the hand allong the hull_points
// realeses all data
start_points.clear();
farthest_points.clear();
amend_start_pt.clear();
amend_farthest_points.clear();
}
}
contours.clear();
hierarchy.clear();
}
}
vector<Point> Amden_Points(vector<Point> &points, Point2f center)
{
vector<double> Magnitude; // Magnitude of Points
vector<Point> Amended; // New Array of Points
int r(20); // Radius of deletion
int a(0); // secondary counter for point reassingment
// Checks to see if vector is empty
if(!points.empty())
{
// Loads the first element for comparision
Amended.push_back(points[0]);
for(int i =1; i < points.size(); i++)
{
// Check if this is an internal point
if (!((points[a].x - points[i].x)*(points[a].x - points[i].x) + (points[a].y - points[i].y)*(points[a].y - points[i].y) <= (r*r)))
{
// Loads the point if it is valid
Amended.push_back(points[i]);
// Uses the loaded point for the next comparison
a=i;
}
}
// Obtains the magnitude from center of the hand for each filtered point
for(int i =0; i < Amended.size(); i++)
{
Magnitude.push_back(sqrt ( (Amended[i].x - center.x) * (Amended[i].x - center.x) + (Amended[i].y - center.y) * (Amended[i].y - center.y) ));
}
double temp(0);
Point index_temp(0,0);
// Bubble sort function for magnitude
// Only concerned with the 5 smallest magnitudes
for(int i =0; i< Amended.size(); i++)
{
for(int j =0; j< Amended.size();j++)
{
if(Magnitude[j] > Magnitude[i])
{
temp = Magnitude[i];
Magnitude[i] = Magnitude[j];
Magnitude[j] = temp;
index_temp = Amended[i];
Amended[i] = Amended[j];
Amended[j] = index_temp;
}
}
}
// To ensure safety this should really be done with an iterator object ~~~ Needs to Change ~~~~~
int first_5(5);
// Checks to ensure the array is in range
if(int (Amended.size()) < first_5)
{
first_5 = int (Amended.size());
}
Amended.resize(first_5);
for(int i =0; i< Amended.size(); i++)
{
for(int j =0; j< Amended.size();j++)
{
if(Amended[j].x > Amended[i].x)
{
index_temp = Amended[i];
Amended[i] = Amended[j];
Amended[j] = index_temp;
}
}
}
}
return Amended;
}
// ~~~~ This function is the same as above except that is looks for Last 5 instead of first 5 ~~~~~
// ~~~~ Future work might see these function combined and return a vector<Point> (size 10) contain all desired points ~~~~
vector<Point> Amden_Points_Start(vector<Point> &points, Point2f center)
{
vector<double> Magnitude; // Magnitude of Points
vector<Point> Amended; // New Array of Points
int r(40); // Radius of deletion
int a(0); // secondary counter for point reassingment
// Checks to see if vector is empty
if(!points.empty())
{
//loads the first elment for comparision
Amended.push_back(points[0]);
for(int i =1; i < points.size(); i++)
{
// Check if this is an internal point
if (!((points[a].x - points[i].x)*(points[a].x - points[i].x) + (points[a].y - points[i].y)*(points[a].y - points[i].y) <= (r*r)))
{
//loads the point as valid
Amended.push_back(points[i]);
// uses the loaded point for the next comparison
a=i;
}
}
// Obtains the magnitude from center of the hand for each filtered point
for(int i =0; i < Amended.size(); i++)
{
Magnitude.push_back(sqrt ( (Amended[i].x - center.x) * (Amended[i].x - center.x) + (Amended[i].y - center.y) * (Amended[i].y - center.y) ));
}
double temp(0);
Point index_temp(0,0);
// Bubble sort function for magnitude only concerned with the 5 largest magnitudes
for(int i =0; i< Amended.size(); i++)
{
for(int j =0; j< Amended.size();j++)
{
if(Magnitude[j] < Magnitude[i])
{
temp = Magnitude[i];
Magnitude[i] = Magnitude[j];
Magnitude[j] = temp;
index_temp = Amended[i];
Amended[i] = Amended[j];
Amended[j] = index_temp;
}
}
}
int Last_5(5);
//checks to ensure the array is in range
if(int (Amended.size()) < Last_5)
{
Last_5 = int (Amended.size());
}
Amended.resize(Last_5);
for(int i =0; i< Amended.size(); i++)
{
for(int j =0; j< Amended.size();j++)
{
if(Amended[j].x < Amended[i].x)
{
index_temp = Amended[i];
Amended[i] = Amended[j];
Amended[j] = index_temp;
}
}
}
}
return Amended;
}
void detectHandPose(char* HandPose)
{
/*
* A lot going on here:
* First the magnitude of each amend point set is taken.
* Then they are compared to eachother using a ratio of 1.86
* **** See thesis why that ratio ****
* Then a check is performed to ensure the last detection is defferent than the
* current detection before transmission.
*/
double averageMagintudeOfFigerTips = 0.0;
double averageMagnitudeOfDefects = 0.0;
double Temp = 0.0;
for(int i = 0; i< amend_start_pt.size(); i++)
{
Temp += sqrt ( (amend_start_pt[i].x - Rect_Center.x) * (amend_start_pt[i].x - Rect_Center.x) + (amend_start_pt[i].y - Rect_Center.y) * (amend_start_pt[i].y - Rect_Center.y) );
}
averageMagintudeOfFigerTips = Temp / ((double) amend_start_pt.size());
Temp = 0.0;
for(int i = 0; i< amend_farthest_points.size(); i++)
{
Temp += sqrt ( (amend_farthest_points[i].x - Rect_Center.x) * (amend_farthest_points[i].x - Rect_Center.x) + (amend_farthest_points[i].y - Rect_Center.y) * (amend_farthest_points[i].y - Rect_Center.y) );
}
averageMagnitudeOfDefects = Temp / ((double) amend_farthest_points.size());
// True is Open hand
// False is closed fist
static bool LastValue = false;
static char* LastHandPose= "F00P00"
"F02P00"
"F03P00"
"F04P00"
"F05P00";
if((averageMagintudeOfFigerTips > (1.86 * averageMagnitudeOfDefects) ) && (LastValue == false))
{
// cout << "Open Hand Detected" << endl; // For Testing only
// cout << "Average Magintude Of Figer Tips: " << averageMagintudeOfFigerTips << endl; // For Testing only
// cout << "Average Magintude Of Defects: " << averageMagnitudeOfDefects << endl; // For Testing only
LastValue = true;
LastHandPose = FormatMovement("stop");
for(int i=0; LastHandPose[i]!='\0';i++)
{
HandPose[i] = LastHandPose[i];
}
// HandPose = "Open Hand"; // For Screen Printing
}
else if((averageMagintudeOfFigerTips < (1.86 * averageMagnitudeOfDefects)) && (LastValue == true))
{
// cout << "Closed Hand Detected" << endl; // For Testing only
// cout << "Average Magintude Of Figer Tips: " << averageMagintudeOfFigerTips << endl; // For Testing only
// cout << "Average Magintude Of Defects: " << averageMagnitudeOfDefects << endl; // For Testing only
LastValue = false;
LastHandPose = FormatMovement("fist");
for(int i=0; LastHandPose[i]!='\0';i++)
{
HandPose[i] = LastHandPose[i];
}
// HandPose = "Closed Hand"; // For Screen Printing
}
else // keeps the hand position static while no detection is made
{
for(int i=0; LastHandPose[i]!='\0';i++)
{
HandPose[i] = LastHandPose[i];
}
}
}
void drawAxisAndQuadents(Mat &aLive_View)
{
//X-Axis
line(aLive_View,
Point(aLive_View.size().width, int (aLive_View.size().height * 0.5) ),
Point(0,int (aLive_View.size().height * 0.5) ),
Scalar( 255, 0, 0 ),
2,
LINE_8);
//Y-Axis
line(aLive_View,
Point(int (aLive_View.size().width * 0.5), aLive_View.size().height ),
Point(int (aLive_View.size().width * 0.5), 0 ),
Scalar( 255, 0, 0 ),
2,
LINE_8);
//Y-Upper Bounds
line(aLive_View,
Point(aLive_View.size().width, int (aLive_View.size().height * 0.3) ),
Point(0,int (aLive_View.size().height * 0.3) ),
Scalar( 0, 255, 0 ),
2,
LINE_8);
//Y-Lower Bounds
line(aLive_View,
Point(aLive_View.size().width, int (aLive_View.size().height * 0.7) ),
Point(0,int (aLive_View.size().height * 0.7) ),
Scalar( 255, 255, 255 ),
2,
LINE_8);
//X Left Bounds
line(aLive_View,
Point(int (aLive_View.size().width * 0.3), aLive_View.size().height ),
Point(int (aLive_View.size().width * 0.3), 0 ),
Scalar( 0, 255, 255 ),
2,
LINE_8);
//X Right Bounds
line(aLive_View,
Point(int (aLive_View.size().width * 0.7), aLive_View.size().height ),
Point(int (aLive_View.size().width * 0.7), 0 ),
Scalar( 0, 255, 0 ),
2,
LINE_8);
}
int setSafeties(Mat &aThreshold_Applied, Point2f center)
{
/*
* Several checks are happening here
* *** Note *** the "crossProduct" function returns a "1" or "0"
* The screen is split into 12 regions
* The first two tests narrow down the hands location on the screen
* to 1 of 4 locations. The second two tests find out which of the
* 4 regions the hand is loacated in.
*/
int aboveXAxis = crossProduct(Point(aThreshold_Applied.size().width, int (aThreshold_Applied.size().height * 0.5)),
Point(0,int (aThreshold_Applied.size().height * 0.5)),
center);
int rightYAxis = crossProduct(Point(int (aThreshold_Applied.size().width * 0.5), aThreshold_Applied.size().height ),
Point(int (aThreshold_Applied.size().width * 0.5), 0 ),
center);
double YBounds = 0.3; // Precentage of the screen
double XBounds = 0.7; // Precentage of the screen
if(aboveXAxis == 1 )
{
XBounds = 0.3;
}
if(rightYAxis == 1 )
{
YBounds = 0.7;
}
/*
* The Boundy is either 30% of 70%
* Based upon the first two test
*/
int XAxisBoundry = crossProduct(Point(aThreshold_Applied.size().width, int (aThreshold_Applied.size().height * XBounds)),
Point(0,int (aThreshold_Applied.size().height * XBounds)),
center);
int YAxisBoundry = crossProduct(Point(int (aThreshold_Applied.size().width * YBounds), aThreshold_Applied.size().height ),
Point(int (aThreshold_Applied.size().width * YBounds), 0 ),
center);
int quadrantControl(0); // Needs to be intiated
/*
* Each test returns a "1" or "0"
* compining the all the "1's" and "0's" into
* a four bit binary number creates a decimal number
* 0 - 15 which is used as an array index for setting safeties
*/
quadrantControl |= YAxisBoundry |(XAxisBoundry << 1)|(rightYAxis << 2)|(aboveXAxis << 3);
/*
* The following table shows the number
* asscoiated with the quadrants
* ______________________
* | 10 | 11 | 14 | 15 |
* ----------------------
* | 8 | 9 | 12 | 13 |
* ----------------------
* | 2 | 3 | 6 | 7 |
* ----------------------
* | 0 | 1 | 4 | 5 |
* ----------------------
*/
//cout<<quadrantControl<<endl;
// ~~~~ Future work will see this and the return statement simplifiedd ~~~~ //
EnabledMovements = DirectionalMovements[quadrantControl];
return ( EnableMovements[quadrantControl] );
}
void assembleCommandWord(int safetyByte)
{
char CommandWord[50]; //Holds all the commands for all servo motors
// static is chosen here to ensure the hand postition
// is kept when not detect
static char HandPose[31] = {"F00P00" // Pinky
"F02P00" // Ring
"F03P00" // Middle
"F04P00" // Index
"F05P00"}; // Thumb
char Bicep[7] = {"B99P99"}; // "99" does not exsits and will not cause an error
char Shoulder[7] = {"S99P99"};
char Wrist[7] = {"W99P99"};
/*
* Simplified switch statment to control
* different motors as desired
*/
switch(safetyByte)
{
case 1:
StopBicep(Bicep);
getShoulder(Shoulder);
StopWrist(Wrist);
break;
case 2:
getBicep(Bicep);
StopShoulder(Shoulder);
StopWrist(Wrist);
break;
case 3:
getBicep(Bicep);
getShoulder(Shoulder);
StopWrist(Wrist);
break;
case 4:
detectHandPose(HandPose);
getWrist(Wrist);
StopBicep(Bicep);
StopShoulder(Shoulder);
break;
}
// Self built array coping function
ConcentrateCharArrays(CommandWord, HandPose, Wrist, Bicep, Shoulder );
//cout<<"CommandWord: " << CommandWord << endl; // For Testing Only
/*
* The "transmit" function should be commented out
* when running just camera test as well as "socketSetUp"
* funciton in the "main.cpp" file
*/
if(transmitGo ==true)
{
transmit(CommandWord);
}
}
void getBicep(char* Bicep)
{
char* Movement;
switch(EnabledMovements)
{
case 1:
Movement = "B00P12";//Curl
break;
case 2:
Movement = "B00P13";//Extend
break;
case 5:
Movement = "B00P12";//Curl
break;
case 6:
Movement = "B00P12";//Curl
break;
case 7:
Movement = "B00P13";//Extend
break;
case 8:
Movement = "B00P13";//Extend
break;
}
for(int i=0; Movement[i]!='\0';i++)
{
Bicep[i] = Movement[i];
}
}
void getShoulder(char* Shoulder)
{
char* Movement;
switch(EnabledMovements)
{
case 3:
Movement = "S00P11";//Left
break;
case 4:
Movement = "S00P13";//Right
break;
case 5:
Movement = "S00P11";//Left
break;
case 6:
Movement = "S00P13";//Right
break;
case 7:
Movement = "S00P11";//Left
break;
case 8:
Movement = "S00P13";//Right
break;
}
for(int i=0; Movement[i]!='\0';i++)
{
Shoulder[i] = Movement[i];
}
}
//~~~~~~~~~ NEEDS WORK ~~~~~~~~~//
void getWrist(char* Wrist)
{
char* Movement ;
//Law of Cosine https://www.mathsisfun.com/algebra/trig-cosine-law.html
if(Rect_Center.y - 100 > 0)
{
A = Point2f(Rect_Center.x, Rect_Center.y - 100);
}
else //Always going to be here... left in for safety // could be removed to increase speed
{
A = Point2f(Rect_Center.x, Rect_Center.y + 100);
}
AverageFingerTips();
B = RunningAverageWristAngle;
C = Rect_Center;
//cout<< "Point A: " << A <<endl;
//cout<< "Point B: " << B <<endl;
//cout<< "Point C: " << C <<endl;
double a = Magnitude(B, C); //Find length of BC
double b = Magnitude(A, C); //Find length of AC
double c = Magnitude(A, B); //Find length of AB
double Angle = acos(((a*a)+(b*b)-(c*c))/(2*a*b));
Angle = Angle*180 / 3.141529;
cout<< "Angle: " << Angle <<endl;
if(Angle > 50.0)
{
static char AngleCommand;
if( B.x > Rect_Center.x )
{
Movement = "W00P05"; // Left
}
else
{
Movement = "W00P05"; // Right
}
}
else
{
Movement = "W00P25"; // Center
}
// cout <<"Movement: " << Movement<< P << endl; // For Testing Only
for(int i=0; Wrist[i]!='\0';i++)
{
Wrist[i] = Movement[i];
}
}
void StopBicep(char* Bicep)
{
char Stop[7] {"B00P00"};
for(int i=0; Bicep[i]!='\0';i++)
{
Bicep[i] = Stop[i];
}
}
void StopWrist(char* Wrist)
{
char Stop[7] {"W00P00"};
for(int i=0; Wrist[i]!='\0';i++)
{
Wrist[i] = Stop[i];
}
}
void StopShoulder(char* Shoulder)
{
char Stop[7] {"S00P00"};
for(int i=0; Shoulder[i]!='\0';i++)
{
Shoulder[i] = Stop[i];
}
}
void ConcentrateCharArrays(char* CommandWord, char* Handpose, char* Wrist, char* Bicep, char* Shoulder)
{
int counter = 0;
for(int i=0; Handpose[i]!='\0';i++)
{
CommandWord[counter] = Handpose[i];
counter++;
}
for(int i=0; Wrist[i]!='\0';i++)
{
CommandWord[counter] = Wrist[i];
counter++;
}
for(int i=0; Bicep[i]!='\0';i++)
{
CommandWord[counter] = Bicep[i];
counter++;
}
for(int i=0; Shoulder[i]!='\0';i++)
{
CommandWord[counter] = Shoulder[i];
counter++;
}
CommandWord[counter] = '\0';
}
int crossProduct(Point2f startPoint, Point2f EndPoint, Point2f Compare)
{
double VectorOneX = EndPoint.x - startPoint.x;
double VectorOneY = EndPoint.y - startPoint.y;
double VectorTwoX = EndPoint.x - Compare.x;
double VectorTwoY = EndPoint.y - Compare.y;
double cross = (VectorOneX * VectorTwoY) - (VectorOneY * VectorTwoX) ;
/*
* Top left corner is [0,0]
* Bottom right is [Width, Height]
*/
if(cross > 0.0)
{
//Below or left of the line
return (0);
}
else
{
//Above or right of the line
return (1);
}
}
void AverageFingerTips()
{
float x = 0.0;
float y = 0.0;
// Static variables allow function variable to be
// remebered when returning to the function
static vector<Point2f> AverageFingers;
static int counter = 0;
static Point2f Last_Rect_Center(0.0,0.0);
/*
* If the center of the hand moves then then the
* wrist rottation can be effected
* to counter this the running average must be reset if the
* cente of the hand moves dramatical
* radius of 20 pixels
*/
double centerhandcheck = Magnitude(Rect_Center, Last_Rect_Center);
if(centerhandcheck > 20.0)
{
AverageFingers.clear();
}
Last_Rect_Center = Rect_Center;
for (int i = 0; i < amend_start_pt.size(); i++)
{
x += amend_start_pt[i].x;
y += amend_start_pt[i].y;
}
x = x/amend_start_pt.size();
y = y/amend_start_pt.size();
Point2f TempAverageFingers = Point2f(x,y); // Average value of all fingertips
if(AverageFingers.size() == 10) // Has the vector reached is max size?
{
AverageFingers[counter] = TempAverageFingers; // Add the Averaged value of fingertips to a vector
}
else
{
AverageFingers.push_back(TempAverageFingers); // creates new elements for the vector
}
counter++;
if(counter==10) // reset the location to overwrite the vector with the oldest data
{
counter = 0;
}
Point2f Average;
// Averages the Vector of averaged fingertips to a single point
for( int i =0; i< AverageFingers.size(); i++ )
{
Average.x = Average.x + AverageFingers[i].x;
Average.y = Average.y + AverageFingers[i].y;
}
Average.x = Average.x/ (float)AverageFingers.size();
Average.y = Average.y/ (float)AverageFingers.size();
// ~~~~ Future work have this function have a return instead of setting a global variable ~~~~ //
RunningAverageWristAngle = Average;
}
double Magnitude(Point2f aPoint, Point2f bPoint)
{
// Standard Magnitude function
// See website for more explination
// https://www.varsitytutors.com/hotmath/hotmath_help/topics/magnitude-and-direction-of-vectors
return ((double) sqrt( ((bPoint.x-aPoint.x)*(bPoint.x-aPoint.x)) + (bPoint.y-aPoint.y)*(bPoint.y-aPoint.y)));
}
|
#pragma once
#include <Tanker/DeviceKeys.hpp>
#include <Tanker/Trustchain/DeviceId.hpp>
#include <tconcurrent/coroutine.hpp>
#include <memory>
namespace Tanker
{
namespace DataStore
{
class ADatabase;
}
class DeviceKeyStore
{
public:
DeviceKeyStore(DeviceKeyStore const&) = delete;
DeviceKeyStore(DeviceKeyStore&&) = delete;
DeviceKeyStore& operator=(DeviceKeyStore const&) = delete;
DeviceKeyStore& operator=(DeviceKeyStore&&) = delete;
Crypto::SignatureKeyPair const& signatureKeyPair() const noexcept;
Crypto::EncryptionKeyPair const& encryptionKeyPair() const noexcept;
Trustchain::DeviceId const& deviceId() const noexcept;
tc::cotask<void> setDeviceId(Trustchain::DeviceId const& deviceId);
DeviceKeys const& deviceKeys() const;
static tc::cotask<std::unique_ptr<DeviceKeyStore>> open(
DataStore::ADatabase* dbConn);
// for tests
static tc::cotask<std::unique_ptr<DeviceKeyStore>> open(
DataStore::ADatabase* dbConn, DeviceKeys const& keys);
private:
DataStore::ADatabase* _db;
DeviceKeys _keys;
Trustchain::DeviceId _deviceId;
DeviceKeyStore(DataStore::ADatabase* dbConn);
};
}
|
#include <iostream>
using namespace std;
struct punct
{
double x, y;
};
int apartine(double x, double y, punct a, punct b )
{
double min1, min2, max1, max2;
if(a.x > b.x)
{
min1 = b.x;
max1 = a.x;
}
else
{
max1 = b.x;
min1 = a.x;
}
if(a.y > b.y)
{
min2 = b.y;
max2 = a.y;
}
else
{
max2 = b.y;
min2= a.y;
}
return (x >= min1 && x <= max1 && y >= min2 && y <= max2);
}
int main()
{
punct a1, a2, a3, a4;
int i;
cout << "Sa se citeasca A1: " <<endl << "X= ";
cin >> a1.x;
cout << "Y= ";
cin >> a1.y;
cout << "Sa se citeasca A2: " <<endl << "X= ";
cin >> a2.x;
cout << "Y= ";
cin >> a2.y;
cout << "Sa se citeasca A3: " <<endl << "X= ";
cin >> a3.x;
cout << "Y= ";
cin >> a3.y;
cout << "Sa se citeasca A4: " <<endl << "X= ";
cin >> a4.x;
cout << "Y= ";
cin >> a4.y;
double a_1, a_2, b1, b2, c1, c2, X, Y, D;
a_1 = a2.y - a1.y;
b1 = a1.x - a2.x;
c1 = a2.x * a1.y - a1.x * a2.y;
a_2 = a4.y - a3.y;
b2 = a3.x - a4.x;
c2 = a4.x * a3.y - a3.x * a4.y;
D = b2 * a_1 - b1 * a_2;
if(D != 0)
{
X = ((-c1) * b2 - (-c2) * b1)/D;
Y = (a_1 * (-c2) - a_2 * (-c1))/D;
if(apartine(X,Y,a1,a2) && apartine(X,Y,a3,a4))
cout << "\nSegmentele se intersecteaza in punctul: (" << X << ", " << Y << "); \n";
else
cout <<"Dreptele se intersecteaza in punctul: (" << X << ", " << Y << "); \n";
}
else
{
double rr;
rr = a_1 * c2 - a_2 * c1;
if( rr != 0 )
cout <<"Nu se intersecteaza";
else
cout << "A1A2 = A3A4";
}
return 0;
}
|
#include "openglwidget.h"
#include <QRect>
#include <QDebug>
OpenglWidget::OpenglWidget(QWidget* parent)
:QGLWidget(parent)
{
fullScreen = false;
angle = 0.0;
initWidget();
initializeGL();
}
void OpenglWidget::initializeGL()
{
glShadeModel(GL_SMOOTH);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClearDepth(1.0);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
}
void OpenglWidget::initWidget()
{
setGeometry( 0, 0, 700, 480 );
setWindowTitle(tr("opengl demo"));
}
void OpenglWidget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glTranslatef( 0.2, 0.0, -6.0 );
glRotatef( angle, 1.0, 1.0, 0.0 );
glColor3f(1.0, 0.0, 0.0);
glBegin( GL_QUAD_STRIP ); // GL_QUADS
for (int i = 0; i <= 390; i += 15)
{
float p = i * 3.14 / 180;
glVertex3f(sin(p), 1.0f, cos(p));
glVertex3f(sin(p), 0.0f, cos(p));
}
glEnd();
glColor3f(0.0, 1.0, 0.0);
glBegin(GL_TRIANGLE_FAN);//扇形连续填充三角形串
glVertex3f(0.0f, 0.0f, 0.0f);
for (int i = 0; i <= 390; i += 15)
{
float p = i * 3.14 / 180;
glVertex3f(sin(p), 0.0f, cos(p));
}
glEnd();
glTranslatef(0, 1, 0);
glColor3f(0.0, 0.0, 1.0);
glBegin(GL_TRIANGLE_FAN);//扇形连续填充三角形串
glVertex3f(0.0f, 0.0f, 0.0f);
for (int i = 0; i <= 390; i += 15)
{
float p = i * 3.14 / 180;
glVertex3f(sin(p), 0.0f, cos(p));
}
glEnd();
}
void OpenglWidget::resizeGL(int width, int height)
{
if(0 == height) {
height = 1;
}
glViewport(0, 0, (GLint)width, (GLint)height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
// gluPerspective(45.0, (GLfloat)width/(GLfloat)height, 0.1, 100.0);
GLdouble aspectRatio = (GLfloat)width/(GLfloat)height;
GLdouble zNear = 0.1;
GLdouble zFar = 100.0;
GLdouble rFov = 45.0 * 3.14159265 / 180.0;
glFrustum( -zNear * tan( rFov / 2.0 ) * aspectRatio,
zNear * tan( rFov / 2.0 ) * aspectRatio,
-zNear * tan( rFov / 2.0 ),
zNear * tan( rFov / 2.0 ),
zNear, zFar );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void OpenglWidget::mousePressEvent(QMouseEvent *event) {
if(event->button() == Qt::LeftButton) {
mouseEventHandle();
}
}
void OpenglWidget::mouseEventHandle() {
angle += 5;
if( angle > 360) {
angle -= 360;
}
this->updateGL();
}
void OpenglWidget::keyPressEvent(QKeyEvent *event) {
switch (event->key()) {
case Qt::Key_A:
qDebug() << "aaa";
fullScreen = !fullScreen;
if(fullScreen)
showFullScreen();
else {
setGeometry(50, 50, 800, 600);
showNormal();
}
updateGL();
break;
case Qt::Key_Escape:
close();
break;
default:
qDebug() << "bbb";
break;
}
}
|
#include <iostream>
#include <Eigen/Core>
#include <algorithm>
#include <memory>
#include "../mean_curvature_solver.h"
#include "../utilities.h"
#include "../uniform_lb_operator.h"
#include "../cotangent_lb_operator.h"
using SolverPtrT = std::unique_ptr<mcurv::MeanCurvatureSolver>;
char *getCmdOption(char **begin, char **end, const std::string &option) {
char **itr = std::find(begin, end, option);
if (itr != end && ++itr != end) {
return *itr;
}
return 0;
}
bool cmdOptionExists(char **begin, char **end, const std::string &option) {
return std::find(begin, end, option) != end;
}
void printHelpMessage() {
std::cout << "The app usage: ./MeanCurvatureApp -i path1 -o path2 -c\n";
std::cout << "-i Path to .off file.\n";
std::cout << "-o Path to user's output file.\n";
std::cout << "-c (OPTIONAL) If specified cotangent Laplace-Beltrami operator will be used. Otherwise the uniform one.\n";
}
int main(int argc, char **argv) {
// If requested - print help information
if (cmdOptionExists(argv, argv + argc, "-h") ||
cmdOptionExists(argv, argv + argc, "--help")) {
printHelpMessage();
return 0;
}
// If input and output flags are not present - error
if (!cmdOptionExists(argv, argv + argc, "-i") ||
!cmdOptionExists(argv, argv + argc, "-o")) {
printHelpMessage();
return 1;
}
std::string inputFileName(getCmdOption(argv, argv + argc, "-i"));
std::string outputFileName (getCmdOption(argv, argv + argc, "-o"));
// Load appropriate solver
SolverPtrT solverPtr;
if (cmdOptionExists(argv, argv + argc, "-c")) {
solverPtr = SolverPtrT(
new mcurv::MeanCurvatureSolver(mcurv::cotangentLBOperatorStrategy));
} else {
solverPtr = SolverPtrT(
new mcurv::MeanCurvatureSolver(mcurv::uniformLBOperatorStrategy));
}
// Calculate the solution
Eigen::MatrixXd solution;
solverPtr->Execute(solution, inputFileName);
// Save to specified file
mcurv::dumpMatrixXdToFile(solution, outputFileName);
return 0;
}
|
#ifndef _DX11_RENDER_TARGET_H_
#define _DX11_RENDER_TARGET_H_
#include <vector>
#include "RenderTarget.h"
#include "d3d11.h"
namespace HW{
class DX11Texture;
class DX11RenderTarget : public RenderTarget{
public:
DX11RenderTarget(const String& name, RenderSystem* system);
virtual ~DX11RenderTarget();
virtual void setDimension(unsigned int width, unsigned int height);
virtual unsigned int getWidth() const;
virtual unsigned int getHeight() const;
virtual void setColorBufferFormat(Texture::PixelFormat format);
virtual void setDepthBufferFormat(Texture::PixelFormat format);
// Set usage of hardware buffer, default is HARDWARE_USAGE_DEFAULT
virtual void setColorBufferUsage(HardwareUsage usage);
virtual void setDepthBufferUsage(HardwareUsage usage);
// Create internal resource before it is used
virtual void createInternalRes();
virtual void releaseInternalRes();
virtual void bindTarget(int index = 0);
void init_as_gbuffer();
void init_as_depthbuffer();
std::vector<ID3D11RenderTargetView*>& GetRTVs();
ID3D11DepthStencilView* GetDepthStencilView();
private:
unsigned int m_uWidth;
unsigned int m_uHeight;
std::vector<DX11Texture*> m_vTextures;
std::vector<ID3D11RenderTargetView*> m_vRTVs;
std::vector<ID3D11ShaderResourceView*> m_vSRVs;
ID3D11DepthStencilView* m_pDepthStencilView;
ID3D11ShaderResourceView* m_pDepthStencilSRV;
};
}
#endif
|
#include "ContainerException.hpp"
const char * ContainerException::what() const noexcept
{
return "Errore sconosciuto Container";
}
const char * ContainerCellNotFoundException::what() const noexcept
{
return "Nessuna voce trovata con la chiave inserita";
}
const char * ContainerDuplicateKeyException::what() const noexcept
{
return "Inserimento di un valore chiave duplicato";
}
const char * ContainerEmptyTableException::what() const noexcept
{
return "Si è cercato di dichiarare un iteratore su un Container vuoto";
}
|
/*
* File: main.cpp
* Author: Tom
*
* Created on 13 January 2012, 6:55 PM
*/
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int number = 20;
int lower = number/2 + 1;
long long increment = number * (number - 1);
long long result = 0;
number = number - 2;
bool found = false;
while(!found) {
result+= increment;
if(result%number == 0) {
if(number != lower) {
number--;
increment = result;
result = 0;
} else {
found = true;
}
}
}
cout << result;
return 0;
}
|
#include <cstdio>
#include <memory.h>
#include <vector>
#include <assert.h>
#include <cmath>
#include <algorithm>
using std::vector;
using std::random_shuffle;
typedef long long ll;
typedef long double ld;
struct Tp {
ll x, y, z;
char label;
} p[11];
struct Tpd {
ld x, y, z;
Tpd() {
x = y = z = 0;
}
Tpd(Tp& t) {
x = t.x;
y = t.y;
z = t.z;
}
};
inline void CalcABCD(const Tp& a, const Tp& b, const Tp& c, ll& A, ll& B, ll& C, ll& D) {
A = (b.y - a.y) * (c.z - a.z) - (c.y - a.y) * (b.z - a.z);
B = (c.x - a.x) * (b.z - a.z) - (b.x - a.x) * (c.z - a.z);
C = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
D = -A * a.x -B * a.y -C * a.z;
}
inline void CalcABCD(const Tpd& a, const Tpd& b, const Tpd& c, ld& A, ld& B, ld& C, ld& D) {
A = (b.y - a.y) * (c.z - a.z) - (c.y - a.y) * (b.z - a.z);
B = (c.x - a.x) * (b.z - a.z) - (b.x - a.x) * (c.z - a.z);
C = (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
D = -A * a.x -B * a.y -C * a.z;
}
inline ld Di(const Tpd& A, const Tpd& B) {
return sqrt((A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y) + (A.z - B.z) * (A.z - B.z));
}
inline ld Sq(const Tpd& a, const Tpd& b, const Tpd& c) {
ld A, B, C, D;
CalcABCD(a, b, c, A, B, C, D);
return fabs(sqrt(A * A + B * B + C * C) / 2);
}
int main() {
//freopen("in", "r", stdin);
//freopen("out", "w", stdout);
int it = 0;
while (1) {
++it;
for (int i = 0; i < 6; ++i) {
int x, y, z;
if (scanf("%d%d%d", &x, &y, &z) != 3) return 0;
p[i].label = 'A' + i;
p[i].x = x;
p[i].y = y;
p[i].z = z;
}
double ansmin = 1e100;
double ansmax = -1e100;
ll A, B, C, D;
CalcABCD(p[0], p[1], p[2], A, B, C, D);
ld m1 = fabs( ld(A * p[3].x + B * p[3].y + C * p[3].z + D) / 6 );
ld m2 = fabs( ld(A * p[4].x + B * p[4].y + C * p[4].z + D) / 6 );
ld cx = (m1 * (p[0].x + p[1].x + p[2].x + p[3].x) / 4 + m2 * (p[0].x + p[1].x + p[2].x + p[4].x) / 4) / (m1 + m2);
ld cy = (m1 * (p[0].y + p[1].y + p[2].y + p[3].y) / 4 + m2 * (p[0].y + p[1].y + p[2].y + p[4].y) / 4) / (m1 + m2);
ld cz = (m1 * (p[0].z + p[1].z + p[2].z + p[3].z) / 4 + m2 * (p[0].z + p[1].z + p[2].z + p[4].z) / 4) / (m1 + m2);
for (int _i = 0; _i < 5; ++_i)
for (int _j = _i + 1; _j < 5; ++_j)
for (int _k = _j + 1; _k < 5; ++_k) {
vector<Tp> e;
int eN = 0, eP = 0;
ll A, B, C, D;
CalcABCD(p[_i], p[_j], p[_k], A, B, C, D);
if (A == 0 && B == 0 && C == 0) continue;
for (int ii = 0; ii < 5; ++ii) {
ll delta = A * p[ii].x + B * p[ii].y + C * p[ii].z + D;
if (delta == 0) e.push_back(p[ii]);else
if (delta < 0) ++eN;else ++eP;
}
if (eN > 0 && eP > 0) continue;
assert( e.size() <= 4 );
if (e.size() == 4) {
while (true) {
bool bad = false;
for (int i = 1; i < 4; ++i) if (e[i].label > 'C' && e[i - 1].label > 'C') {
bad = true;
break;
}
if (bad) {
random_shuffle(e.begin(), e.end());
continue;
}
break;
}
}
e.push_back(e.front());
ld lambda = (A * cx + B * cy + C * cz + D) / (A * A + B * B + C * C);
Tpd c;
c.x = cx - A * lambda;
c.y = cy - B * lambda;
c.z = cz - C * lambda;
bool bad = false;
ld ss = 0, ss2 = 0;
for (int i = 1; i < e.size(); ++i) {
ld d = 2 * Sq(c, e[i], e[i - 1]) / Di(e[i], e[i - 1]);
ss += Sq(c, e[i], e[i - 1]);
ss2 += Sq(e[0], e[i - 1], e[i]);
if (d < 0.2 + 1e-10) bad = true;
}
if (fabs(ss - ss2) > 1e-10) {
continue;
}
if (!bad) {
ld d = fabs(A * p[5].x + B * p[5].y + C * p[5].z + D) / sqrt(A * A + B * B + C * C);
if (d > ansmax) ansmax = d;
if (d < ansmin) ansmin = d;
}
}
printf("Case %d: %.5lf %.5lf\n", it, ansmin, ansmax);
}
return 0;
}
|
#include <iostream>
#include <vector>
using namespace std;
int main() {
std::vector<string> vs1;
cout << "Now vs1 has " << vs1.size() << " element" << endl;
// cout << "this is vs1" << endl;
// for (size_t i = 0;i < vs1.size();i++) {
// cout << i << ": " << vs1[i] << endl;
// }
// return 0;
vs1.push_back("asdf");
cout << "Now vs1 has " << vs1.size() << " element" << endl;
vs1.push_back("asdf2");
cout << "Now vs1 has " << vs1.size() << " element" << endl;
vs1.push_back("asdf3");
cout << "Now vs1 has " << vs1.size() << " element" << endl;
vs1.push_back("somchai");
cout << "Now vs1 has " << vs1.size() << " element" << endl;
vs1.push_back("xxx");
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ":" << vs1[i] << endl;
}
vs1.resize(10);
cout << "after resize 10" << endl;
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ":" << vs1[i] << endl;
}
vs1.resize(3);
cout << "after resize 3" << endl;
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ":" << vs1[i] << endl;
}
vs1.resize(6);
cout << "after resize 6" << endl;
for (size_t i = 0;i < vs1.size();i++) {
cout << i << ":" << vs1[i] << endl;
}
}
|
//Write a program to read two integer values m and n and to decide and print whether m ia a multiple of n.
#include<iostream>
using namespace std;
int main()
{
int m,n;
cout<<"Enter two integers"<<endl;
cin>>m>>n;
if(m%n==0)
cout<<"m is multiple of n"<<endl;
else
cout<<"m is not multiple of n"<<endl;
return 0;
}
|
#include "Adder.h"
double
Adder::plus(double left, double right)
{
return left + right;
}
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <functional>
#include <queue>
#include <string>
#include <cstring>
#include <numeric>
#include <cstdlib>
#include <cmath>
using namespace std;
typedef long long ll;
#define INF 10e10
#define rep(i,n) for(int i=0; i<n; i++)
#define rep_r(i,n,m) for(int i=m; i<n; i++)
#define MAX 100
#define MOD 1000000007
#define pb push_back
// 別解法, aを決め打つ
int main() {
int n,k;
cin >> n >> k;
vector<ll> num(k,0);
ll ans = 0;
for (int i = 1; i <= n; ++i) num[i%k]++;
for (int a = 0; a < k; ++a) {
int b = (k-a) % k;
int c = (k-a) % k;
if ((b+c) != k) continue;
ans += num[a] * num[b] * num[c];
}
cout << ans << endl;
}
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QTreeWidgetItem>
#include <QMainWindow>
#include "headers/treemodel.h"
#include "headers/dbconnector.h"
#include "headers/dialog_add.h"
QT_BEGIN_NAMESPACE
namespace Ui {
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
public slots:
void clickPlusOperator(const QString &mcc, const QString &mnc);
void changeOperator(const QString &name, const QString &mcc, const QString &mnc,
const QModelIndex &index);
void updateUI(const QString &mcc, const QString &mnc, const QString &name, const QModelIndex &_index,
const bool &isEdit);
private slots:
void on_pushButton_add_clicked();
private:
Ui::MainWindow *ui;
DialogAdd *editor;
TreeModel *treeModel;
TreeItem *treeDelegate;
DBConnector *db;
void connecting();
};
#endif // MAINWINDOW_H
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<iterator>
#include<stack>
using namespace std;
#define inf 99999
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//空指针传参,代码把函数的第一个参数的值压入栈中存储,而空指针指向为空,不存在值*p,因此给*p一个临时变量和主函数并不是同一个*p
void Init_TreeNode(TreeNode** T, vector<int> &vec,int &pos)
{
if (vec[pos] == inf || vec.size() == 0)
{
*T = NULL;
return;
}
else
{
(*T) = new TreeNode(0);
(*T)->val = vec[pos];
Init_TreeNode(&(*T)->left, vec, ++pos);
Init_TreeNode(&(*T)->right, vec, ++pos);
}
}
class Solution {
public:
vector<int> res;
vector<int> inorderTraversal(TreeNode* root) {
//基本思想:递归法中序遍历二叉树
Recursion(root);
return res;
}
void Recursion(TreeNode* root)
{
if (root == NULL)
return;
else
{
Recursion(root->left);
res.push_back(root->val);
Recursion(root->right);
}
}
};
class Solution1 {
public:
vector<int> inorderTraversal(TreeNode* root) {
//基本思想:迭代法基于栈中序遍历二叉树
vector<int> res;
stack<TreeNode*> st;
TreeNode* p = root;
while (!st.empty() || p != NULL)
{
while (p != NULL)
{
st.push(p);
p = p->left;
}
p = st.top();
st.pop();
res.push_back(p->val);
p = p->right;
}
return res;
}
};
int main()
{
Solution1 solute;
TreeNode* root = NULL;
vector<int> vec = { 1,inf,2,3,inf,inf,inf };
int pos = 0;
//传入指向指针的指针
Init_TreeNode(&root, vec, pos);
vec = solute.inorderTraversal(root);
copy(vec.begin(), vec.end(), ostream_iterator<int>(cout, " "));
return 0;
}
|
/*
* Pwm.h
*
* Created on: 28/11/2019
* Author: frank
*/
#ifndef PWM_H_
#define PWM_H_
class Pwm {
public:
Pwm();
};
#endif /* PWM_H_ */
|
#include <cstdlib>
#include <cstring>
#include <vector>
#include <iostream>
#include <fstream>
#include "vid.h"
#include "kmziaes.h"
#include "stegan.h"
#include "client.h"
using namespace std;
int main(int argc, char* argv[])
{
string fileDataName,fileKeyVigName,fileKeyAesName,fileContainName;
string host,port;
for (int i = 1;i<argc;i++)
{
if (!strcmp(argv[i],"-v"))
{
i++;
if(i==argc) break;
fileKeyVigName+=argv[i];
continue;
}
if (!strcmp(argv[i],"-a"))
{
i++;
if(i==argc) break;
fileKeyAesName+=argv[i];
continue;
}
if (!strcmp(argv[i],"-c"))
{
i++;
if(i==argc) break;
fileContainName+=argv[i];
continue;
}
if (!strcmp(argv[i],"-d"))
{
i++;
if(i==argc) break;
fileDataName+=argv[i];
continue;
}
if (!strcmp(argv[i],"-p"))
{
i++;
if(i==argc) break;
port=(argv[i]);
continue;
}
if (!strcmp(argv[i],"-H"))
{
i++;
if(i==argc) break;
host=(argv[i]);
continue;
}
}
vector<unsigned char> data,keyVig,keyAes,contain;
std::ifstream FileData,FileKeyVig,FileKeyAes,FileContain;
//ofstream FileContain1;
if (fileContainName.empty())
fileContainName+= "inp.bmp";
if (fileDataName.empty())
fileDataName += "inp";
if (fileKeyAesName.empty())
fileKeyAesName += "inpA";
if (fileKeyVigName.empty())
fileKeyVigName += "inpV";
if (host.empty())
host += "localhost";
if (port.empty())
port += "2006";
FileData.open(fileDataName,std::ios_base::binary);
while(!FileData.eof())
{
data.push_back(FileData.get());
}
data.pop_back();
FileKeyVig.open(fileKeyVigName,std::ios_base::binary);
while(!FileKeyVig.eof())
{
keyVig.push_back(FileKeyVig.get());
}
keyVig.pop_back();
FileKeyAes.open(fileKeyAesName,std::ios_base::binary);
while(!FileKeyAes.eof())
{
keyAes.push_back(FileKeyAes.get());
}
keyAes.pop_back();
FileContain.open(fileContainName,std::ios_base::binary);
while(!FileContain.eof())
{
contain.push_back(FileContain.get());
}
contain.pop_back();
data = EncryptVidg(data,keyVig);
/*FileContain1.open("tempoup1",std::ios_base::binary);
for (vector<unsigned char>::iterator it = data.begin();it!=data.end();it++)
{
FileContain1.put(*it);
}
FileContain1.close();*/
data = EncryptAES(data,keyAes);
/*FileContain1.open("tempoup2",std::ios_base::binary);
for (vector<unsigned char>::iterator it = data.begin();it!=data.end();it++)
{
FileContain1.put(*it);
}
FileContain1.close();*/
data = EncryptBMP(data,contain);
/* FileContain1.open("tempoup3",std::ios_base::binary);
for (vector<unsigned char>::iterator it = data.begin();it!=data.end();it++)
{
FileContain1.put(*it);
}
FileContain1.close();*/
client(host,port,data,fileContainName.data());
return 0;
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* ll val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(ll x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(ll x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#define ll long long
class Solution {
public:
ll mod = 1e9 + 7;
ll sum = 0;
unordered_map<TreeNode*, ll> mp;
int totalSum(TreeNode *root){
if(!root)
return 0;
int curr = 0;
curr += root->val;
curr += totalSum(root->left);
curr += totalSum(root->right);
return mp[root] = curr;
}
ll split(TreeNode *root){
if(!root)
return 0;
ll maxProduct = 0;
maxProduct = max({maxProduct, split(root->left), split(root->right)});
maxProduct = max({maxProduct, mp[root->left] * (sum - mp[root->left]), mp[root->right] * (sum - mp[root->right]) });
return maxProduct;
}
int maxProduct(TreeNode* root) {
mp.clear();
int sumOfAllNodes = totalSum(root);
sum = mp[root];
return split(root) % mod;
}
};
|
//
// Keyboard.cpp
// Odin.MacOSX
//
// Created by Daniel on 04/06/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#include <assert.h>
#include "Keyboard.h"
namespace odin
{
namespace io
{
Keyboard::Keyboard()
{
for (auto& key : m_keyStates)
key = false;
}
void Keyboard::setButtonState(int button, bool pressed)
{
assert(button >= 0);
assert(button < ODIN_KEY_LAST);
m_keyStates[button] = pressed;
}
bool Keyboard::getButtonState(int button) const
{
assert(button >= 0);
assert(button < ODIN_KEY_LAST);
return m_keyStates[button];
}
}
}
|
#include <stdio.h>
void main()
{
int total=0;
int num;
int numcount=0;
int average;
printf("this can display average\n");
printf("press 999 to quit\n");
while(num!=999)
{
printf("enter number %d: ",numcount + 1);
scanf("%d",&num);
if (num != 999)
{
numcount++;
total=total+num;
}
}
average=(total/numcount);
printf("the average is %d\n",average);
}
|
#include"conio.h"
#include"stdio.h"
void main(void)
{
int a;
clrscr();
printf("Enter no.");
scanf("%d",&a);
switch(a)
{
case 1:
printf("One");
break;
case 2:
printf("Two");
break;
case 3:
printf("Three");
break;
case 4:
printf("Four");
break;
case 5:
printf("Five");
break;
case 6:
printf("Six");
break;
default:
printf("Invalid No");
}
getch();
}
|
#include <iostream>
#include <windows.h>
#include <cstdlib>
using namespace std;
void gotoxy(int x, int y){
HANDLE hcon;
hcon = GetStdHandle(STD_OUTPUT_HANDLE);
COORD dwPos;
dwPos.X = x;
dwPos.Y = y;
SetConsoleCursorPosition(hcon, dwPos);
}
int main(){
int hora,min,seg;
cout<<"\t\t\tRELOJ DIGITAL"<<endl;
cout<<"Ingrese la Hora"<<endl;
cin>>hora;
cout<<"Ingrese los minutos"<<endl;
cin>>min;
cout<<"Ingrese los segundos"<<endl;
cin>>seg;
while(hora<=23){
while(min<=59){
while(seg<=59){
gotoxy(50,10);
if(hora>9){
cout<<hora;
}else{
cout<<"0"<<hora;
}
if(min>9){
cout<<":"<<min;
}else{
cout<<":0"<<min;
}
if(seg>9){
cout<<":"<<seg;
}else{
cout<<":0"<<seg;
}
seg++;
Sleep(1000);
}
seg=0;
min++;
}
min=0;
hora++;
if(hora==24){
hora=0;
}
}
}
|
#include<bits/stdc++.h>
using namespace std;
int t,n;
int a[23],ans[23];
int flag=0;
void dfs(int index,int cnt,int sum) {
int x;
if(sum>t)
return;
if(sum==t) {
flag=1;
for(int i=0; i<cnt; i++) {
if(i<cnt-1)
printf("%d+",ans[i]);
else
printf("%d\n",ans[i]);
}
}
x=-1;
for(int i=index; i<n; i++) {
if(x!=a[i]) {
// printf("a[i]=%d\n",a[i]);
ans[cnt]=a[i];
x=a[i];
dfs(i+1,cnt+1,sum+a[i]);
}
}
}
int main() {
while(scanf("%d%d",&t,&n)) {
if(t==0&&n==0)
break;
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
flag=0;
printf("Sums of %d:\n",t);
dfs(0,0,0);
if(!flag)
printf("NONE\n");
}
return 0;
}
|
//栈(Last in first out, LIFO)
//top始终指向栈顶元素
#include <iostream>
using namespace std;
template<class ElemType>
class Stack{
private:
const static int MaxSize = 50;
ElemType data[MaxSize];
int top;
public:
Stack(); //初始化栈
bool Pop(); //出栈
bool Push(ElemType); //入栈
bool IsEmpty() {
return top == -1;
}
bool IsFull() {
return top == MaxSize - 1;
}
ElemType GetTop() const;
friend ostream& operator<<(ostream& os, const Stack<ElemType>& stack) {
int innerTop = stack.top;
while (innerTop != -1) {
os << "Data[" << innerTop+1 << "] = " << stack.data[innerTop] << endl;
--innerTop;
}
return os;
}
~Stack();
};
template<class ElemType>
Stack<ElemType>::Stack()
{
top = -1;
}
template<class ElemType>
bool Stack<ElemType>::Pop()
{
if (IsEmpty()) {
return false;
} else {
cout << data[top] << " has been pop." << endl;
--top;
return true;
}
}
template<class ElemType>
bool Stack<ElemType>::Push(ElemType elemData)
{
if (IsFull()) {
return false;
} else {
++top;
this->data[top] = elemData;
return true;
}
}
template<class ElemType>
ElemType Stack<ElemType>::GetTop() const
{
return this->data[top];
}
template<class ElemType>
Stack<ElemType>::~Stack()
{
top = -1;
}
int main()
{
Stack<int> stack;
int data;
char choice;
cout << "------Stack Menu------" << endl
<< "1-Push,2-Pop,3-Display,4-GetTop,0-exit:";
cin >> choice;
while (choice != '0') {
switch (choice) {
case '1':
cout << "Input push data:";
cin >> data;
if (stack.Push(data)) {
cout << "Done!" << endl;
} else {
cout << "Error!" << endl;
}
break;
case '2':
if (stack.Pop()) {
cout << "Done!" << endl;
} else {
cout << "Error!" << endl;
}
break;
case '3':
cout << stack << endl;
break;
case '4':
cout << "Top data is " << stack.GetTop() << endl;
break;
default:
cout << "Error!" << endl;
break;
}
cout << "Continue or not:";
cin >> choice;
}
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#if defined DOM_WIDGETMANAGER_SUPPORT || defined DOM_UNITEAPPMANAGER_SUPPORT || defined DOM_EXTENSIONMANAGER_SUPPORT
#include "modules/gadgets/OpGadget.h"
#include "modules/dom/src/opera/domwidgetmanager.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/ecmascript_utils/esasyncif.h"
/* static */ OP_STATUS
DOM_WidgetManager::Make(DOM_WidgetManager *&new_obj, DOM_Runtime *origining_runtime, BOOL unite, BOOL extensions)
{
new_obj = OP_NEW(DOM_WidgetManager, ());
if (!new_obj)
return OpStatus::ERR_NO_MEMORY;
#ifdef WEBSERVER_SUPPORT
new_obj->m_isUnite = unite;
#else
OP_ASSERT(!unite);
#endif
#ifdef EXTENSION_SUPPORT
new_obj->m_isExtensions = extensions;
#else
OP_ASSERT(!extensions);
#endif
RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj, origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::WIDGETMANAGER_PROTOTYPE), "WidgetManager"));
if (OpStatus::IsError(new_obj->Initialize(unite)))
{
new_obj = NULL;
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
DOM_WidgetManager::DOM_WidgetManager()
{
}
OP_STATUS
DOM_WidgetManager::Initialize(BOOL unite)
{
DOM_WidgetCollection *widgets;
#ifndef EXTENSION_SUPPORT
const BOOL m_isExtensions = FALSE;
#endif
RETURN_IF_ERROR(DOM_WidgetCollection::Make(widgets, GetRuntime(), unite, m_isExtensions));
RETURN_IF_ERROR(PutPrivate(DOM_PRIVATE_widgets, *widgets));
RETURN_IF_ERROR(g_gadget_manager->AddListener(this));
return OpStatus::OK;
}
/* virutal */
DOM_WidgetManager::~DOM_WidgetManager()
{
if (g_gadget_manager) // Gadgets module may have been destroyed if we are terminating Opera.
g_gadget_manager->RemoveListener(this);
}
/* virtual */ ES_GetState
DOM_WidgetManager::GetName(OpAtom property_name, ES_Value *return_value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_widgets:
return DOMSetPrivate(return_value, DOM_PRIVATE_widgets);
}
return DOM_Object::GetName(property_name, return_value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_WidgetManager::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_widgets:
return PUT_READ_ONLY;
}
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ void
DOM_WidgetManager::GCTrace()
{
for (UINT32 i = 0; i < m_callbacks.GetCount(); i++)
GCMark(m_callbacks.Get(i));
}
void
DOM_WidgetManager::HandleGadgetInstallEvent(GadgetInstallEvent &evt)
{
for (UINT32 i = 0; i < m_callbacks.GetCount(); i++)
{
if (evt.userdata == m_callbacks.Get(i))
{
char rc;
TempBuffer *string = GetEmptyTempBuf();
switch (evt.event)
{
case OpGadgetInstallListener::GADGET_INSTALL_USER_CANCELLED:
rc = 0;
RAISE_IF_ERROR(string->Append("User cancelled"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_DOWNLOAD_FAILED:
rc = 0;
RAISE_IF_ERROR(string->Append("Download failed"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_NOT_ENOUGH_SPACE:
rc = 0;
RAISE_IF_ERROR(string->Append("Not enough space"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_USER_CONFIRMED:
rc = 1;
RAISE_IF_ERROR(string->Append("User confirmed"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_DOWNLOADED:
rc = 2;
RAISE_IF_ERROR(string->Append("Download successful"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_INSTALLED:
rc = 3;
RAISE_IF_ERROR(string->Append("Installation successful"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_INSTALLATION_FAILED:
rc = 4;
RAISE_IF_ERROR(string->Append("Installation failed"));
break;
case OpGadgetInstallListener::GADGET_INSTALL_PROCESS_FINISHED:
m_callbacks.RemoveByItem(static_cast<ES_Object *>(evt.userdata));
// follow thru
default:
return;
}
ES_Value arguments[2];
DOMSetNumber(&arguments[0], rc);
DOMSetString(&arguments[1], string);
OpStatus::Ignore(GetEnvironment()->GetAsyncInterface()->CallFunction(m_callbacks.Get(i), *this, 2, arguments, NULL, DOM_Object::GetCurrentThread(GetRuntime())));
}
}
}
OpGadget* DOM_WidgetManager::GadgetArgument(ES_Value *argv, int argc, int n)
{
DOM_Widget *obj = (argc > n && argv[n].type == VALUE_OBJECT) ? static_cast<DOM_Widget *>(DOM_GetHostObject(argv[n].value.object)) : NULL;
const uni_char *id = (argc > n && argv[n].type == VALUE_STRING) ? argv[n].value.string : NULL;
if (obj)
return obj->GetGadget();
else if (id)
return g_gadget_manager->FindGadget(GADGET_FIND_BY_ID, id);
return NULL;
}
/* static */ int
DOM_WidgetManager::run(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
#ifdef WEBSERVER_SUPPORT
DOM_THIS_OBJECT(wm, DOM_TYPE_WIDGETMANAGER, DOM_WidgetManager);
#else
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
#endif
OpGadget *gadget = GadgetArgument(argv, argc, 0);
if (gadget)
{
#ifdef WEBSERVER_SUPPORT
if (wm->IsUnite() && gadget->IsRootService())
CALL_FAILED_IF_ERROR(g_gadget_manager->OpenRootService(gadget));
else
#endif
{
#ifdef EXTENSION_SUPPORT
if (argc > 1 && argv[1].type == VALUE_BOOLEAN)
gadget->SetExtensionFlag(OpGadget::AllowUserJSHTTPS, argv[1].value.boolean);
if (argc > 2 && argv[2].type == VALUE_BOOLEAN)
gadget->SetExtensionFlag(OpGadget::AllowUserJSPrivate, argv[2].value.boolean);
#endif // EXTENSION_SUPPORT
CALL_FAILED_IF_ERROR(g_gadget_manager->OpenGadget(gadget));
}
}
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::kill(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
OpGadget *gadget = GadgetArgument(argv, argc, 0);
Window *gadgetwin;
if (gadget && (gadgetwin = gadget->GetWindow()) != NULL)
{
CALL_FAILED_IF_ERROR(g_gadget_manager->CloseWindowPlease(gadgetwin));
gadgetwin->Close();
#ifdef EXTENSION_SUPPORT
if (gadget->IsExtension())
{
gadget->SetIsClosing(FALSE);
gadget->SetIsRunning(FALSE);
}
#endif // EXTENSION_SUPPORT
}
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::install(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT(wm, DOM_TYPE_WIDGETMANAGER, DOM_WidgetManager);
DOM_CHECK_ARGUMENTS("sso");
ES_Object *callback = argv[2].value.object;
CALL_FAILED_IF_ERROR(wm->m_callbacks.Add(callback));
CALL_FAILED_IF_ERROR(g_gadget_manager->DownloadAndInstall(argv[0].value.string, argv[1].value.string, callback));
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::uninstall(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
OpGadget *gadget = GadgetArgument(argv, argc, 0);
if (gadget)
{
// Need to close first if still open.
if (Window *gadget_window = gadget->GetWindow())
{
CALL_FAILED_IF_ERROR(g_gadget_manager->CloseWindowPlease(gadget_window));
gadget_window->Close();
}
CALL_FAILED_IF_ERROR(g_gadget_manager->DestroyGadget(gadget));
}
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::checkForUpdate(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
OpGadget *gadget = GadgetArgument(argv, argc, 0);
if (gadget)
gadget->Update();
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::checkForUpdateByUrl(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
DOM_CHECK_ARGUMENTS("s");
CALL_FAILED_IF_ERROR(g_gadget_manager->Update(argv[0].value.string, NULL, 0));
return ES_FAILED; // No return value.
}
/* static */ int
DOM_WidgetManager::getWidgetIconURL(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
OpGadget *gadget = GadgetArgument(argv, argc, 0);
if (!gadget)
return ES_FAILED; // No return value.
OpString gadget_url;
OpString icon_path;
INT32 w, h;
CALL_FAILED_IF_ERROR(gadget->GetGadgetIcon(0, icon_path, w, h, FALSE));
if (icon_path.IsEmpty())
return ES_FAILED;
#if PATHSEPCHAR != '/'
// Convert to / separators.
OpGadgetUtils::ChangeToLocalPathSeparators(icon_path);
#endif
CALL_FAILED_IF_ERROR(gadget->GetGadgetUrl(gadget_url, FALSE, TRUE));
TempBuffer* retbuf = GetEmptyTempBuf();
CALL_FAILED_IF_ERROR(retbuf->AppendFormat(UNI_L("%s/%s"), gadget_url.CStr(), icon_path.CStr() + 1)); // first char of icon_path is PATHSEP
DOMSetString(return_value, retbuf);
return ES_VALUE;
}
#ifdef EXTENSION_SUPPORT
/* static */ int
DOM_WidgetManager::options(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
OpGadget *gadget = GadgetArgument(argv, argc, 0);
if (gadget && gadget->IsExtension())
{
if (!gadget->IsRunning())
CALL_FAILED_IF_ERROR(g_gadget_manager->OpenGadget(gadget));
gadget->OpenExtensionOptionsPage();
}
return ES_FAILED; // No return value.
}
#endif // EXTENSION_SUPPORT
/* static */ int
DOM_WidgetManager::setWidgetMode(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value *return_value, DOM_Runtime *origining_runtime)
{
DOM_THIS_OBJECT_UNUSED(DOM_TYPE_WIDGETMANAGER);
DOM_CHECK_ARGUMENTS("-s");
OpGadget* gadget = GadgetArgument(argv, argc, 0);
if (gadget)
gadget->SetMode(argv[1].value.string);
return ES_FAILED; // No return value.
}
DOM_FUNCTIONS_START(DOM_WidgetManager)
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::install, "install", "sso")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::uninstall, "uninstall", "-")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::run, "run", "-")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::kill, "kill", "-")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::checkForUpdate, "checkForUpdate", "-")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::checkForUpdateByUrl, "checkForUpdateByUrl", "s-")
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::getWidgetIconURL, "getWidgetIconURL", "-")
#ifdef EXTENSION_SUPPORT
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::options, "options", "-")
#endif // EXTENSION_SUPPORT
DOM_FUNCTIONS_FUNCTION(DOM_WidgetManager, DOM_WidgetManager::setWidgetMode, "setWidgetMode", "-s-")
DOM_FUNCTIONS_END(DOM_WidgetManager)
//////////////////////////////////////////////////////////////////////////
/* static */ OP_STATUS
DOM_WidgetCollection::Make(DOM_WidgetCollection *&new_obj, DOM_Runtime *origining_runtime, BOOL unite, BOOL extensions)
{
new_obj = OP_NEW(DOM_WidgetCollection, (unite, extensions));
if (!new_obj)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(DOMSetObjectRuntime(new_obj, origining_runtime, origining_runtime->GetPrototype(DOM_Runtime::WIDGETCOLLECTION_PROTOTYPE), "WidgetCollection"));
return OpStatus::OK;
}
DOM_WidgetCollection::DOM_WidgetCollection(BOOL unite, BOOL extensions)
#if defined WEBSERVER_SUPPORT || defined EXTENSION_SUPPORT
:
#endif
#ifdef WEBSERVER_SUPPORT
m_isUniteCollection(unite)
# ifdef EXTENSION_SUPPORT
,
# endif
#endif
#ifdef EXTENSION_SUPPORT
m_isExtensionCollection(extensions)
#endif
{
}
DOM_WidgetCollection::~DOM_WidgetCollection()
{
}
#if defined WEBSERVER_SUPPORT || defined EXTENSION_SUPPORT
BOOL
DOM_WidgetCollection::IncludeWidget(OpGadget *gadget)
{
#ifdef WEBSERVER_SUPPORT
if (m_isUniteCollection || gadget->GetClass()->IsSubserver())
return m_isUniteCollection && gadget->GetClass()->IsSubserver();
#endif
#ifdef EXTENSION_SUPPORT
if (m_isExtensionCollection || gadget->GetClass()->IsExtension())
return m_isExtensionCollection && gadget->GetClass()->IsExtension();
#endif
return TRUE;
}
#endif
ES_GetState
DOM_WidgetCollection::GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
switch (property_name)
{
case OP_ATOM_count:
#if defined WEBSERVER_SUPPORT || defined EXTENSION_SUPPORT
int gadgetCount = 0;
for (OpGadget *gadget = g_gadget_manager->GetFirstGadget(); gadget; gadget = static_cast<OpGadget*>(gadget->Suc()))
{
if (IncludeWidget(gadget))
gadgetCount++;
}
DOMSetNumber(value, gadgetCount);
#else
DOMSetNumber(value, g_gadget_manager->NumGadgets());
#endif
return GET_SUCCESS;
}
return DOM_Object::GetName(property_name, value, origining_runtime);
}
ES_PutState
DOM_WidgetCollection::PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime)
{
return DOM_Object::PutName(property_name, value, origining_runtime);
}
/* virtual */ ES_GetState
DOM_WidgetCollection::GetIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
int gadgetCount = 0;
for (OpGadget *gadget = g_gadget_manager->GetFirstGadget(); gadget; gadget = static_cast<OpGadget*>(gadget->Suc()))
{
if (IncludeWidget(gadget))
gadgetCount++;
if (gadgetCount > 0 && gadgetCount-1 == property_index)
{
DOM_Widget *widget;
#ifndef WEBSERVER_SUPPORT
static const BOOL m_isUniteCollection = FALSE;
#endif
GET_FAILED_IF_ERROR(DOM_Widget::Make(widget, GetRuntime(), gadget, m_isUniteCollection));
GET_FAILED_IF_ERROR(widget->InjectWidgetManagerApi());
DOMSetObject(value, widget);
return GET_SUCCESS;
}
}
return DOM_Object::GetIndex(property_index, value, origining_runtime);
}
/* virtual */ ES_PutState
DOM_WidgetCollection::PutIndex(int property_index, ES_Value *value, ES_Runtime *origining_runtime)
{
return PUT_READ_ONLY;
}
#endif // DOM_WIDGETMANAGER_SUPPORT || DOM_UNITEAPPMANAGER_SUPPORT || DOM_EXTENSIONMANAGER_SUPPORT
|
/*!
* \file adt.cpp
* \author Simon Coakley
* \date 2012
* \copyright Copyright (c) 2012 University of Sheffield
* \brief Implementation of model data type
*/
#include "./adt.h"
/*!
* \brief Model data type constructor
* \param[in] n The data type name, default ""
* \param[in] d The data type description, default ""
*
* This contructor takes a name and a description string.
* If either are missing they default to an empty string.
*/
ADT::ADT(QString n, QString d) {
name = n;
desc = d;
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2007 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 "PluginPathDialog.h"
#include "modules/locale/locale-enum.h"
#include "modules/viewers/viewers.h"
#include "modules/prefs/prefsmanager/collections/pc_app.h"
#include "modules/prefs/prefsmanager/collections/pc_display.h"
#include "modules/prefs/prefsmanager/collections/pc_unix.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "adjunct/quick/dialogs/SimpleDialog.h"
#include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/widgets/OpEdit.h"
#include "modules/widgets/OpMultiEdit.h"
#include "platforms/x11api/plugins/unix_pluginpath.h"
PluginPathDialog* PluginPathDialog::m_dialog = 0;
PluginRecoveryDialog* PluginRecoveryDialog::m_dialog = 0;
BOOL PluginRecoveryDialog::m_ok_pressed = FALSE;
PluginCheckDialog* PluginCheckDialog::m_dialog = 0;
typedef PluginPathElement PluginPathNode;
/***********************************************************************************
**
**
**
***********************************************************************************/
static const OpVector<PluginPathNode>& GetPluginPathNodeList()
{
return PluginPathList::Self()->Get();
}
/***********************************************************************************
**
**
**
***********************************************************************************/
static void ViewerActionToString( OpString &text, int action )
{
Str::LocaleString string_id(Str::NOT_A_STRING);
switch(action)
{
case VIEWER_SAVE:
{
string_id = Str::DI_IDM_SAVE;
}
break;
case VIEWER_OPERA:
{
string_id = Str::DI_IDM_OPERA;
}
break;
case VIEWER_PASS_URL:
case VIEWER_APPLICATION:
{
string_id = Str::DI_IDM_APP;
}
break;
case VIEWER_REG_APPLICATION:
{
string_id = Str::DI_IDM_REG_APP;
}
break;
case VIEWER_PLUGIN:
{
string_id = Str::DI_IDM_PLUGIN;
}
break;
case VIEWER_ASK_USER:
default:
{
string_id = Str::D_FILETYPE_SHOWDOWNLOADDIAL;
}
break;
}
TRAPD(rc,g_languageManager->GetStringL(string_id, text));
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginPathDialog::OnFileChoosingDone(DesktopFileChooser* chooser,
const DesktopFileChooserResult& result)
{
m_selected_directory.Wipe();
OP_ASSERT(result.selected_filter == -1);
if (result.files.Get(0))
m_selected_directory.Set(*result.files.Get(0));
if( m_selected_directory.Length() > 0 )
{
OpString candidate;
candidate.Set(m_selected_directory.CStr());
if(candidate.Length() > 1 && candidate.CStr()[candidate.Length()-1] == '/' )
candidate.CStr()[candidate.Length()-1] = 0;
INT32 pos = 0;
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (!m_action_change)
{
pos = m_path_model.AddItem(UNI_L(""));
if (treeview)
treeview->SetCheckboxValue(pos, TRUE);
}
else
{
if (treeview)
pos = treeview->GetSelectedItemModelPos();
}
m_path_model.SetItemData(pos, 1, candidate.CStr());
UpdateFullPath();
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginPathDialog::OnInit()
{
OpString path;
if( m_dest_edit )
{
m_dest_edit->GetText(path);
}
else
{
path.Set(g_pcapp->GetStringPref(PrefsCollectionApp::PluginPath));
}
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
OpString s1, s2;
TRAPD(rc,g_languageManager->GetStringL(Str::DI_USE_PLUGIN, s1));
TRAP(rc,g_languageManager->GetStringL(Str::D_PLUGIN_PATH_COMPONENTS, s2));
m_path_model.SetColumnData(0, s1.CStr() );
m_path_model.SetColumnData(1, s2.CStr() );
treeview->SetCheckableColumn(0);
treeview->SetTreeModel(&m_path_model);
treeview->SetUserSortable(FALSE);
m_block_change_detection = TRUE;
const OpVector<PluginPathNode>& path_list = GetPluginPathNodeList();
for( UINT32 i=0; i<path_list.GetCount(); i++ )
{
const PluginPathNode* item = path_list.Get(i);
if( item )
{
if( item->state != 0 )
{
int pos = m_path_model.AddItem(UNI_L(""));
m_path_model.SetItemData(pos, 1, item->path.CStr());
if( item->state == 1 )
{
treeview->ToggleItem(pos);
}
}
}
}
m_block_change_detection = FALSE;
treeview->SetSelectedItem(0);
}
OpEdit *edit = (OpEdit*)GetWidgetByName("Path_edit");
if( edit )
{
edit->SetText(path.CStr());
edit->SetReadOnly(TRUE);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
PluginPathDialog::~PluginPathDialog()
{
m_dialog = 0;
OP_DELETE(m_chooser);
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginPathDialog::OnSetFocus()
{
Dialog::OnSetFocus();
// Workaround for column width=0 problem in OpTreeView
// Sometimes (timing issue) the column widths remain zero when
// we show the dialog. Seems that a layout request is not
// sent. OnSetFocus() is called after the dialog becomes visible
// [espen 2004-01-08]
OpTreeView* path_tree_view = (OpTreeView*)GetWidgetByName("Path_treeview");
if( path_tree_view )
{
path_tree_view->GenerateOnLayout(TRUE);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginPathDialog::OnItemChanged( OpWidget *widget, INT32 pos )
{
if( !m_block_change_detection )
{
UpdateFullPath();
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
BOOL PluginPathDialog::OnInputAction(OpInputAction* action)
{
if( action->GetAction() == OpInputAction::ACTION_OK )
{
OpEdit* edit = (OpEdit*)GetWidgetByName("Path_edit");
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if( edit && treeview )
{
const OpVector<PluginPathNode>& path_list = GetPluginPathNodeList();
OpAutoVector<PluginPathNode> items;
for( INT32 i=0;i<m_path_model.GetItemCount(); i++ )
{
PluginPathNode* item = OP_NEW(PluginPathNode, ());
if( item )
{
item->path.Set(m_path_model.GetItemString(i,1));
item->state = treeview->IsItemChecked(i) ? 1 : 2;
items.Add(item);
}
}
// We add all non-zero entries from the preference list that are
// not in the dialog box list
for( UINT32 i=0; i<path_list.GetCount(); i++ )
{
const PluginPathNode* i1 = path_list.Get(i);
if( i1 && i1->state != 0 )
{
BOOL in_list = FALSE;
for( UINT32 j=0; j<items.GetCount(); j++ )
{
PluginPathNode* i2 = items.Get(j);
if( i2 && i2->path.Compare(i1->path) == 0 )
{
in_list = TRUE;
break;
}
}
if( !in_list )
{
PluginPathNode* item = OP_NEW(PluginPathNode, ());
if( item )
{
item->path.Set(i1->path);
item->state = 0;
items.Add(item);
}
}
}
}
TRAPD(err,PluginPathList::Self()->WriteL(items));
UpdateFullPath();
OpString path;
edit->GetText(path);
if( m_dest_edit )
{
m_dest_edit->SetText(path.CStr());
}
}
}
else if( action->GetAction() == OpInputAction::ACTION_INSERT )
{
m_action_change = FALSE;
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
if (!m_chooser)
RETURN_VALUE_IF_ERROR(DesktopFileChooser::Create(&m_chooser), TRUE);
m_request.action = DesktopFileChooserRequest::ACTION_DIRECTORY;
m_request.initial_filter = -1;
m_request.get_selected_filter = FALSE;
m_request.fixed_filter = FALSE;
m_chooser->Execute(GetOpWindow(), this, m_request);
}
return TRUE;
}
else if( action->GetAction() == OpInputAction::ACTION_CHANGE )
{
m_action_change = TRUE;
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
INT32 pos = treeview->GetSelectedItemModelPos();
// pos to update
if( pos >=0 )
{
if (!m_chooser)
RETURN_VALUE_IF_ERROR(DesktopFileChooser::Create(&m_chooser), TRUE);
m_request.action = DesktopFileChooserRequest::ACTION_DIRECTORY;
m_request.initial_filter = -1;
m_request.get_selected_filter = FALSE;
m_request.fixed_filter = FALSE;
m_request.initial_path.Set(m_path_model.GetItemString(pos,1));
m_chooser->Execute(GetOpWindow(), this, m_request);
}
}
return TRUE;
}
else if( action->GetAction() == OpInputAction::ACTION_DELETE )
{
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
INT32 pos = treeview->GetSelectedItemModelPos();
if (pos != -1)
{
m_path_model.Delete(pos);
UpdateFullPath();
}
}
return TRUE;
}
else if( action->GetAction() == OpInputAction::ACTION_MOVE_ITEM_UP )
{
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
INT32 pos = treeview->GetSelectedItemModelPos();
if( pos > 0 )
{
OpString data;
data.Set(m_path_model.GetItemString(pos,1));
m_path_model.Delete(pos);
INT32 new_pos = m_path_model.InsertBefore(pos-1);
m_path_model.SetItemData(new_pos, 1, data.CStr());
treeview->SetCheckboxValue(new_pos, FALSE);
treeview->SetSelectedItem(pos-1);
UpdateFullPath();
}
}
return TRUE;
}
else if( action->GetAction() == OpInputAction::ACTION_MOVE_ITEM_DOWN )
{
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
INT32 pos = treeview->GetSelectedItemModelPos();
if( pos != -1 && pos+1 < m_path_model.GetItemCount() )
{
OpString data;
data.Set(m_path_model.GetItemString(pos,1));
m_path_model.Delete(pos);
INT32 new_pos = m_path_model.InsertAfter(pos);
m_path_model.SetItemData(new_pos, 1, data.CStr());
treeview->SetCheckboxValue(new_pos, FALSE);
treeview->SetSelectedItem(pos+1);
UpdateFullPath();
}
}
return TRUE;
}
return Dialog::OnInputAction(action);
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginPathDialog::UpdateFullPath()
{
OpString path;
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
for( INT32 i=0;i<m_path_model.GetItemCount(); i++ )
{
if( treeview->IsItemChecked(i) )
{
if( path.Length() > 0 )
{
path.Append(UNI_L(":"));
}
path.Append(m_path_model.GetItemString(i,1));
}
}
}
OpEdit *edit = (OpEdit*)GetWidgetByName("Path_edit");
if( edit )
{
edit->SetText(path.CStr());
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
//static
void PluginPathDialog::Create(DesktopWindow* parent_window, OpEdit* dest_edit )
{
if( !m_dialog )
{
m_dialog = OP_NEW(PluginPathDialog, (dest_edit));
m_dialog->Init(parent_window);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
PluginRecoveryDialog::~PluginRecoveryDialog()
{
m_dialog = 0;
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginRecoveryDialog::OnSetFocus()
{
Dialog::OnSetFocus();
// Workaround for column width=0 problem in OpTreeView [espen 2004-09-16]
OpTreeView* path_tree_view = (OpTreeView*)GetWidgetByName("Path_treeview");
if( path_tree_view )
{
path_tree_view->GenerateOnLayout(TRUE);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginRecoveryDialog::OnInit()
{
m_ok_pressed = FALSE;
OpMultilineEdit *edit = (OpMultilineEdit*)GetWidgetByName("Help_label");
if( edit )
{
edit->SetFlatMode();
}
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
OpStringC path = g_pcapp->GetStringPref(PrefsCollectionApp::PluginPath);
OpString s1, s2;
TRAPD(rc,g_languageManager->GetStringL(Str::DI_USE_PLUGIN, s1));
TRAP(rc,g_languageManager->GetStringL(Str::D_PLUGIN_PATH_COMPONENTS, s2));
m_path_model.SetColumnData(0, s1.CStr() );
m_path_model.SetColumnData(1, s2.CStr() );
treeview->SetCheckableColumn(0);
treeview->SetTreeModel(&m_path_model);
treeview->SetUserSortable(FALSE);
const OpVector<PluginPathNode>& path_list = GetPluginPathNodeList();
for( UINT32 i=0; i<path_list.GetCount(); i++ )
{
PluginPathNode* item = path_list.Get(i);
if( item )
{
int pos = m_path_model.AddItem(UNI_L(""));
m_path_model.SetItemData(pos, 1, item->path.CStr());
if( item->state == 1 )
{
treeview->ToggleItem(pos);
}
}
}
treeview->SetSelectedItem(0);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginRecoveryDialog::SaveSetting()
{
OpAutoVector<PluginPathNode> items;
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Path_treeview");
if (treeview)
{
for( INT32 i=0;i<m_path_model.GetItemCount(); i++ )
{
PluginPathNode* item = OP_NEW(PluginPathNode, ());
if( item )
{
item->path.Set(m_path_model.GetItemString(i,1));
item->state = treeview->IsItemChecked(i) ? 1 : 2;
items.Add(item);
}
}
TRAPD(err,PluginPathList::Self()->WriteL(items));
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
BOOL PluginRecoveryDialog::OnInputAction(OpInputAction* action)
{
if( action->GetAction() == OpInputAction::ACTION_OK )
{
SaveSetting();
m_ok_pressed = TRUE;
}
return Dialog::OnInputAction(action);
}
/***********************************************************************************
**
**
**
***********************************************************************************/
//static
BOOL PluginRecoveryDialog::Create(DesktopWindow* parent_window)
{
if( !m_dialog )
{
m_dialog = OP_NEW(PluginRecoveryDialog, ());
m_dialog->Init(parent_window);
return PluginRecoveryDialog::m_ok_pressed;
}
else
{
return FALSE;
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
// static
void PluginRecoveryDialog::TestPluginsLoaded(DesktopWindow* parent_window)
{
// If the 'ReadingPlugins' flag is true, then this means that an earlier
// scan crashed Opera. Plug-ins has not been read in InitL() so we ask the
// user here if plug-ins should be read.
if(g_pcunix->GetIntegerPref(PrefsCollectionUnix::ReadingPlugins))
{
g_pcunix->WriteIntegerL(PrefsCollectionUnix::ReadingPlugins, FALSE);
if( PluginRecoveryDialog::Create(parent_window) )
{
OpStatus::Ignore(g_plugin_viewers->RefreshPluginViewers(TRUE));
}
else
{
g_pcdisplay->WriteIntegerL(PrefsCollectionDisplay::PluginsEnabled, FALSE);
}
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
PluginCheckDialog::~PluginCheckDialog()
{
m_dialog = 0;
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginCheckDialog::OnSetFocus()
{
Dialog::OnSetFocus();
// Workaround for column width=0 problem in OpTreeView [espen 2004-09-16]
OpTreeView* plugin_tree_view = (OpTreeView*)GetWidgetByName("Plugin_treeview");
if( plugin_tree_view )
{
plugin_tree_view->GenerateOnLayout(TRUE);
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
INT32 PluginCheckDialog::Populate( OpTreeView* treeview, SimpleTreeModel* model )
{
INT32 num_items = 0;
TRAPD(err, g_plugin_viewers->RefreshPluginViewers(FALSE));
if( treeview && model)
{
OpString s1, s2, s3, s4;
TRAPD(rc,g_languageManager->GetStringL(Str::DI_USE_PLUGIN, s1));
TRAP(rc,g_languageManager->GetStringL(Str::SI_IDLABEL_PLUGINNAME, s2));
TRAP(rc,g_languageManager->GetStringL(Str::SI_IDSTR_MIME_HEADER, s3));
TRAP(rc,g_languageManager->GetStringL(Str::D_PLUGIN_CURRENT_ACTION, s4));
model->SetColumnData(0, s1.CStr() );
model->SetColumnData(1, s2.CStr() );
model->SetColumnData(2, s3.CStr() );
model->SetColumnData(3, s4.CStr() );
treeview->SetCheckableColumn(0);
treeview->SetTreeModel(model);
}
ChainedHashIterator* viewer_iter;
Viewer* viewer;
g_viewers->CreateIterator(viewer_iter);
while (viewer_iter && (viewer=g_viewers->GetNextViewer(viewer_iter)) != NULL)
{
ViewAction action = viewer->GetAction();
const uni_char* viewer_plugin_path = viewer->GetDefaultPluginViewerPath();
if (viewer_plugin_path)
{
// We have a default plug-in path already
for(UINT32 j=0; j<viewer->GetPluginViewerCount(); j++)
{
PluginViewer* plugin_viewer = viewer->GetPluginViewer(j);
const uni_char* plugin_viewer_path;
// Select the plug-in that has the same path as the currently active path
if (plugin_viewer &&
(plugin_viewer_path=plugin_viewer->GetPath())!=NULL &&
uni_stricmp(plugin_viewer_path, viewer_plugin_path)==0 &&
action!=VIEWER_PLUGIN) // Show it if the viewer action is to not use plug-ins now.
{
num_items ++;
if( treeview && model )
{
int pos = model->AddItem(UNI_L(""),NULL,0,-1,viewer);
OpString tmp;
tmp.Empty();
tmp.AppendFormat(UNI_L("%s - %s"), plugin_viewer->GetProductName(), plugin_viewer_path);
model->SetItemData(pos, 1, tmp.CStr() );
model->SetItemData(pos, 2, viewer->GetContentTypeString());
ViewerActionToString( tmp, action );
model->SetItemData(pos, 3, tmp.CStr());
treeview->ToggleItem(pos);
}
break;
}
}
}
else if( viewer->GetPluginViewerCount() > 0 )
{
// Delayed until SaveSetting()
if( action != VIEWER_PLUGIN )
{
PluginViewer* plugin_viewer = viewer->GetPluginViewer(0);
if(plugin_viewer)
{
num_items ++;
if( treeview && model )
{
int pos = model->AddItem(UNI_L(""),NULL,0,-1,viewer);
OpString tmp;
tmp.Empty();
tmp.AppendFormat(UNI_L("%s - %s"), plugin_viewer->GetProductName(), plugin_viewer->GetPath());
model->SetItemData(pos, 1, tmp.CStr());
model->SetItemData(pos, 2, viewer->GetContentTypeString());
ViewerActionToString( tmp, action );
model->SetItemData(pos, 3, tmp.CStr());
treeview->ToggleItem(pos);
}
}
}
}
else if( action == VIEWER_PLUGIN )
{
// Delayed until SaveSetting()
}
}
OP_DELETE(viewer_iter);
return num_items;
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginCheckDialog::OnInit()
{
Populate( (OpTreeView*)GetWidgetByName("Plugin_treeview"), &m_plugin_model );
}
/***********************************************************************************
**
**
**
***********************************************************************************/
void PluginCheckDialog::SaveSetting()
{
OpTreeView* treeview = (OpTreeView*)GetWidgetByName("Plugin_treeview");
if (treeview)
{
for(int i=0; i < m_plugin_model.GetItemCount(); i++)
{
if(treeview->IsItemChecked(i))
{
((Viewer*)m_plugin_model.GetItemUserData(i))->SetAction(VIEWER_PLUGIN,
TRUE); // user-defined
}
}
}
}
/***********************************************************************************
**
**
**
***********************************************************************************/
BOOL PluginCheckDialog::OnInputAction(OpInputAction* action)
{
if( action->GetAction() == OpInputAction::ACTION_OK )
{
SaveSetting();
}
return Dialog::OnInputAction(action);
}
/***********************************************************************************
**
**
**
***********************************************************************************/
//static
void PluginCheckDialog::Create(DesktopWindow* parent_window)
{
if( !m_dialog )
{
INT32 new_plugin_count = PluginCheckDialog::Populate(0,0);
if( new_plugin_count == 0 )
{
OpString title, message;
TRAPD(err, g_languageManager->GetStringL(Str::D_PLUGIN_ASSOCIATION, title));
TRAP(err, g_languageManager->GetStringL(Str::D_PLUGIN_ASSOCIATION_NO_PLUGINS, message));
SimpleDialog::ShowDialog(WINDOW_NAME_PLUGIN_CHECK, 0, message.CStr(), title.CStr(), Dialog::TYPE_OK, Dialog::IMAGE_INFO );
}
else
{
m_dialog = OP_NEW(PluginCheckDialog, ());
m_dialog->Init(parent_window);
}
}
}
|
/*
* @author : dhruv-gupta14
* @date : 28/12/2018
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
int flag=0,x=0;
string str1;
getline(cin,str1);
string str2;
getline(cin,str2);
int n = str1.length();
int m = str2.length();
if(str1 == str2)
cout << "Yes";
else if(n==m && str1 !=str2){
for(int i=0; i<n; i++)
{
if(str1[i] != str2[i])
flag++;
}
if(flag == 1)
cout << "Yes";
else
cout << "No";
} else{
if(n == m+1)
{
x=0;
for(int j=0; j<n; j++)
{
if(str1[j] != str2[x])
{
flag++;
}else{
x++;
}
}
}else if(m == n+1){
x=0;
for(int k=0; k<m; k++)
{
if(str1[x] != str2[k])
{
flag++;
}else{
x++;
}
}
}
if(flag == 1)
cout << "Yes";
else
cout << "No";
}
return 0;
}
|
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<conio.h>
using namespace std;
int main()
{
int a=1,b=2;
char * str = "hello", * s2 = "I am not going to print";
char * ptr = str;
char least = 127;
// printf("hi");
while (*ptr++)
{
least = ( *ptr < least ) ? * ptr : least;
printf("Testing: %c , %c\n",least, *ptr);
}
printf("With C: %s\n", ptr);
printf("With C: %s\n", ptr, ptr += strlen(ptr)+1);
// printf("%d",a,a+=b);
getch();
}
|
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
vector <int>v;
int temp,n,i,j,k,size,h,m,s,count;
while(1)
{
v.clear();
cin>>temp;
if(temp==0)break;
else v.push_back(temp);
while(1)
{
cin>>temp;
if(temp==0)break;
else v.push_back(temp);
}
sort(v.begin(),v.end());
size=v.size();
for(i=2*v.at(0),j=0;i+j<=18000;j++)
{
count=0;
for(k=1;k<size;k++)
{
if(((i+j)%(2*v.at(k)))<v.at(k)-5)
count++;
}
if(count==size-1)
break;
if(i+j>18000)break;
if(j==v.at(0)-6)
{ j=-1;i+=2*v.at(0);
}
}
if((i+j)>18000)
cout<<"Signals fail to synchronise in 5 hours"<<endl;
else
{
h=(i+j)/3600;
temp=(i+j)%3600;
m=temp/60;
s=temp%60;
if(h>=5&&(m>0||s>0)) cout<<"Signals fail to synchronise in 5 hours"<<endl;
else{
if(h<10)
cout<<"0"<<h<<":";
else cout<<h<<":";
if(m<10) cout<<"0"<<m<<":";
else cout<<m<<":";
if(s<10)cout<<"0"<<s<<endl;
else cout<<s<<endl;
}
}
}
return 0;
}
|
#include <iostream>
using namespace std;
int updateterms(int terms[][2],int j,int i)
{
int result = terms[0][0];
for(int k=1;k<j;k++)
{
terms[k][0] = terms[k][0]*(i)/(i+1-terms[k][1]);//to update term multiply by x-1 which is i and divide by x-1-b which is i-terms[k][1]
result += terms[k][0];
}
return result;
}
int main()
{
int T,S,C,seq,i,j,terms[100][2],sum;
cin>>T;
while(T>0)
{
cin>>S>>C;
j=0;
cin>>seq;
terms[0][0]=seq;
j++;
for(i=1;i<S;i++)
{
cin>>seq;
sum=updateterms(terms,j,i);
if(sum!=seq)
{
terms[j][0]=seq-sum;
terms[j][1]=i+1;
j++;
}
}
for(;i<S+C-1;i++)
{
cout<<updateterms(terms,j,i)<<" ";
}
cout<<updateterms(terms,j,i)<<endl;
//considerding sequence as a + sigma terms[i][0]*(x-1)(x-2)....(X-terms[i][1]-1)/(terms[i][1])!
T--;
}
return 0;
}
|
/*
* TLinesBoard.cpp
*
* Created on: Apr 12, 2017
* Author: Alex
*/
#include "TLinesGame.h"
#include <cstdlib>
TBallsHolder::TBallsHolder(): holder("BallsHolder") {
if (holder == 0 )
genNewBalls();
else
load();
};
void TBallsHolder::genNewBalls(){
for (int i=0;i<3;i++)
balls[i] = rand() % 7 +1;
save();
}
std::vector<TPoint> TLinesGame::makeListBalls(){
std::vector<TPoint> newBalls;
for(int i=1; i<= sizeX; i++)
for(int j=1; j<= sizeY; j++) {
if (board[i][j]>0){
newBalls.emplace_back(i, j, board[i][j]);
}
}
initBalls = true;
return newBalls;
}
void TBallsHolder::load(){
balls[0] = holder % 10;
balls[1] = (holder/10) % 10;
balls[2] = holder/100;
}
void TBallsHolder::save(){
holder = 100*balls[2] + 10*balls[1] + balls[0];
}
TLinesGame::TLinesGame(int x, int y): counterGames("counterGames"), score("score"), record("record") {
// TODO Auto-generated constructor stub
sizeX = x;
sizeY = y;
if (counterGames == 0)
newGame();
else restoreGame();
}
TLinesGame::~TLinesGame() {
// TODO Auto-generated destructor stub
}
bool TLinesGame::OutOfBoundary(int x, int y){
if (x<1) return true;
if (y<1) return true;
if (x>sizeX) return true;
if (y>sizeY) return true;
return false;
}
void TLinesGame::newGame() {
counterGames+=1;
score = 0;
board.clear();
initBalls = false;
initPlayingField();
ballsHolder.genNewBalls();
board.save();
}
void TLinesGame::restoreGame() {
//score = 0;
board.load();
initBalls = false;
//randThreeBalls();
}
void TLinesGame::initPlayingField(){
for(int i=1; i<= sizeX; i++)
for(int j=1; j<= sizeY; j++) {
board[i][j] = 0;
int rnd = rand() % 35;
if (rnd<7)
board[i][j] = 1 + rnd;
}
}
void TLinesGame::initSearch(TPoint src){
for(int i=1; i< 12; i++)
for(int j=1; j< 12; j++) {
if (board[i][j] > 0) sf[i][j] = 100;
else sf[i][j] = 0;
}
for(int i=1; i< 12; i++) {
sf[sizeX+1][i] = 100;
sf[0][i] = 100;
sf[i][sizeY+1] = 100;
sf[i][0] = 100;
}
counter = 1;
std::vector<TPoint> list;
list.push_back(src);
sf[src.x][src.y] = counter;
FillNeighbors(list);
}
void TLinesGame::FillNeighbors( std::vector<TPoint> list){
std::vector<TPoint> newList;
int n = 0;
int x = list[0].x;
int y = list[0].y;
int c = sf[x][y] + 1;
for ( TPoint p : list ) {
int x = p.x;
int y = p.y;
if (sf[x-1][y] == 0) {
sf[x-1][y] = c;
newList.emplace_back(x-1, y);
n = n + 1;
}
if (sf[x+1][y] == 0) {
sf[x+1][y] = c;
newList.emplace_back(x+1, y);
n = n + 1;
}
if (sf[x][y-1] == 0) {
sf[x][y-1] = c;
newList.emplace_back(x, y-1);
n = n + 1;
}
if (sf[x][y+1] == 0) {
sf[x][y+1] = c;
newList.emplace_back(x, y+1);
n = n + 1;
}
}
if (n>0) FillNeighbors(newList);
}
int TLinesGame::searchClosestPath(TPoint src, TPoint dst){
int rmin = 100000;
int x,y;
for(int i=1; i<= sizeX; i++)
for(int j=1; j<= sizeY; j++) {
if ((sf[i][j] != 100)&&(sf[i][j] != 0)){
int r = (dst.x - i)*(dst.x - i) + (dst.y - j)*(dst.y - j) + sf[i][j];
if (r<rmin){
rmin = r;
x = i;
y = j;
}
}
}
if (rmin<100000){
return searchPath(src, TPoint(x,y));
}
else
return 0;
}
int TLinesGame::searchPath(TPoint src, TPoint dst){
path.clear();
int x =dst.x;
int y =dst.y;
int nn = sf[x][y];
int color = board[src.x][src.y];
if (nn > 0) {
path.emplace_back(dst.x, dst.y, color);
int n=nn;
for (int i = 1; i<nn; i++){
if (sf[x-1][y] == n-1){
path.emplace_back(x-1, y, color);
x = x-1;
}
else if (sf[x+1][y] == n-1){
path.emplace_back(x+1, y, color);
x = x+1;
}
else if (sf[x][y-1] == n-1) {
path.emplace_back(x, y-1, color);
y = y-1;
}
else if (sf[x][y+1] == n-1) {
path.emplace_back(x, y+1, color);
y = y+1;
}
n = sf[x][y];
}
}
return nn;
}
int TLinesGame::checkLines(){
clearBalls.clear();
for(int x = 1; x<=sizeX; x++)
for(int y = 1; y<=sizeY; y++){
if ( board[x][y]>0){
checkHorzLine(x,y);
checkVertLine(x,y);
checkDiag1Line(x,y);
checkDiag2Line(x,y);
}
}
for ( TPoint p : clearBalls ) {
board[p.x][p.y] = 0;
}
board.save();
score +=clearBalls.size();
if (score>record) record = score;
return clearBalls.size();
}
void TLinesGame::checkHorzLine(int x, int y){
int color = board[x][y];
int xx =x+1;
while (board[xx][y] == color)
xx =xx+1;
int len = xx-x;
if (len >4) {
for (int i = 0; i<len; i++) {
clearBalls.emplace_back(x+i, y, color);
}
}
}
void TLinesGame::checkVertLine(int x, int y){
int color = board[x][y];
int yy =y+1;
while (board[x][yy] == color)
yy =yy+1;
int len = yy-y;
if (len >4) {
for (int i = 0; i<len; i++) {
clearBalls.emplace_back(x, y+i, color);
}
}
}
void TLinesGame::checkDiag1Line(int x, int y){
int color = board[x][y];
int xx =x+1;
int yy =y+1;
while (board[xx][yy] == color)
{ xx++; yy++; }
int len = xx-x;
if (len >4) {
for (int i = 0; i<len; i++) {
clearBalls.emplace_back(x+i, y+i, color);
}
}
}
void TLinesGame::checkDiag2Line(int x, int y){
int color = board[x][y];
int xx =x+1;
int yy =y-1;
while (board[xx][yy] == color)
{ xx++; yy--; }
int len = xx-x;
if (len >4) {
for (int i = 0; i<len; i++) {
clearBalls.emplace_back(x+i,y-i, color);
}
}
}
bool TLinesGame::gameOver(){
for(int x = 1; x<=sizeX; x++)
for(int y = 1; y<=sizeY; y++){
if ( board[x][y] == 0){
return false;
}
}
return true;
}
std::vector<TPoint> TLinesGame::addNewBalls(){
std::vector<TPoint> emptySquares;
std::vector<TPoint> newBalls;
for(int x = 1; x<=sizeX; x++)
for(int y = 1; y<=sizeY; y++){
if ( board[x][y] == 0){
emptySquares.emplace_back(x,y);
}
}
if (emptySquares.size()>3) {
int new1 = rand() % emptySquares.size();
int new2 = rand() % (emptySquares.size()-1);
int new3 = rand() % (emptySquares.size()-2);
if (new1<=new2) new2 = new2 + 1;
if (new1<=new3) new3 = new3 + 1;
if (new2<=new3) new3 = new3 + 1;
newBalls.emplace_back(emptySquares[new1].x, emptySquares[new1].y, ballsHolder.balls[0]);
newBalls.emplace_back(emptySquares[new2].x, emptySquares[new2].y, ballsHolder.balls[1]);
newBalls.emplace_back(emptySquares[new3].x, emptySquares[new3].y, ballsHolder.balls[2]);
for (TPoint p :newBalls ) {
board[p.x][p.y] = p.color;
}
board.save();
ballsHolder.genNewBalls();
return newBalls;
}
else {
int i = 0;
for (TPoint p :emptySquares ) {
newBalls.emplace_back(p.x, p.y, ballsHolder.balls[i]);
board[p.x][p.y] = ballsHolder.balls[i++];
}
return newBalls;
}
}
|
#ifndef FILEWORKSPACEWIDGET_H
#define FILEWORKSPACEWIDGET_H
#include <memory>
#include <QWidget>
#include "FileWorkspaceViewModel.h"
namespace Ui {
class FileWorkspaceWidget;
}
namespace PticaGovorun
{
class FileWorkspaceWidget : public QWidget
{
Q_OBJECT
private:
std::shared_ptr<FileWorkspaceViewModel> model_;
public:
explicit FileWorkspaceWidget(QWidget *parent = 0);
~FileWorkspaceWidget();
void setFileWorkspaceViewModel(std::shared_ptr<FileWorkspaceViewModel> model);
private slots:
void treeWidgetFileItems_itemDoubleClicked(QTreeWidgetItem * item, int column);
void fileWorkspaceModel_annotDirChanged(const std::wstring& oldWorkingDir);
private:
void updateUI();
private:
Ui::FileWorkspaceWidget *ui;
};
}
#endif // FILEWORKSPACEWIDGET_H
|
#include "Tablero.h"
using std::cout;
using std::endl;
//constructor
Tablero::Tablero(){
matriz=NULL;
crearMatriz();
}
//destructor
Tablero::~Tablero(){
for (int i = 0; i < 11; ++i)
{
delete[] matriz[i];
matriz[i] = NULL;
}
delete[] matriz;
}
void Tablero::imprimirMatriz(){
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
cout << matriz[i][j] << " ";
}
cout << endl;
}
}
void Tablero::crearMatriz(){
matriz = new char* [11];
for (int i = 0; i < 11; ++i)
{
matriz[i] = new char[11];
}
}
bool Tablero::validarPosicionMas(int x, int y){ // +
if(matriz[x][y]=='+'){
return true;
}else{
return false;
}
}
bool Tablero::validarPosicionNumeral(int x, int y){ // #
if(matriz[x][y]=='#'){
return true;
}else{
return false;
}
}
bool Tablero::validarPosicionMasMover(int x,int y, int NuevaX, int NuevaY){ // +
bool disponible=false;
if(NuevaX==x+2 && NuevaY==y){
if(matriz[x+1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-2 && NuevaY==y){
if(matriz[x-1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y+2){
if(matriz[x][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y-2){
if(matriz[x][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+2 && NuevaY==y+2){
if(matriz[x+1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-2 && NuevaY==y-2){
if(matriz[x-1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
else if(NuevaX==x-2 && NuevaY==y+2){
if(matriz[x-1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+2 && NuevaY==y-2){
if(matriz[x+1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
//+=======
if(NuevaX==x+1 && NuevaY==y){
if(matriz[x+1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x-1 && NuevaY==y){
if(matriz[x-1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x && NuevaY==y+1){
cout << "llega4" << endl;
if(matriz[x][y+1]=='_'){
cout << "llega5" << endl;
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
cout << "llega6" << endl;
}
}
}
if(NuevaX==x && NuevaY==y-1){
if(matriz[x][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x+1 && NuevaY==y+1){
if(matriz[x+1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x-1 && NuevaY==y-1){
if(matriz[x-1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x-1 && NuevaY==y+1){
if(matriz[x-1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
if(NuevaX==x+1 && NuevaY==y-1){
if(matriz[x+1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
return disponible;
}
bool Tablero::validarPosicionNumeralMover(int x,int y, int NuevaX, int NuevaY){ // #
bool disponible=false;
if(NuevaX==x+2 && NuevaY==y){
if(matriz[x+1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-2 && NuevaY==y){
if(matriz[x-1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y+2){
if(matriz[x][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y-2){
if(matriz[x][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+2 && NuevaY==y+2){
if(matriz[x+1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-2 && NuevaY==y-2){
if(matriz[x-1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-2 && NuevaY==y+2){
if(matriz[x-1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+2 && NuevaY==y-2){
if(matriz[x+1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
//+=======
if(NuevaX==x+1 && NuevaY==y){
if(matriz[x+1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-1 && NuevaY==y){
if(matriz[x-1][y]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y+1){
if(matriz[x][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x && NuevaY==y-1){
if(matriz[x][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+1 && NuevaY==y+1){
if(matriz[x+1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-1 && NuevaY==y-1){
if(matriz[x-1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x-1 && NuevaY==y+1){
if(matriz[x-1][y+1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}else if(NuevaX==x+1 && NuevaY==y-1){
if(matriz[x+1][y-1]=='_'){
if(matriz[NuevaX][NuevaY]=='_'){
disponible=true;
}
}
}
return disponible;
}
void Tablero::moverPiezaMas(int x,int y){
matriz[x][y] = '+';
if(matriz[x+1][y]=='#'){
matriz[x+1][y] =='+';
}
if(matriz[x-1][y]=='#'){
matriz[x-1][y] =='+';
}
if(matriz[x][y+1]=='#'){
matriz[x][y+1] == '+';
}
if(matriz[x][y-1]=='+'){
matriz[x][y-1] =='#';
}
if(matriz[x+1][y+1]=='#'){
matriz[x+1][y+1] == '+';
}
if(matriz[x-1][y-1]=='#'){
matriz[x-1][y-1] == '+';
}
if(matriz[x+1][y-1]=='#'){
matriz[x+1][y-1] == '+';
}
if(matriz[x-1][y+1]=='#'){
matriz[x-1][y+1] == '+';
}
}
void Tablero::moverPiezaNumeral(int x,int y){
matriz[x][y] = '#';
if(matriz[x+1][y]=='+'){
matriz[x+1][y] == '#';
}
if(matriz[x-1][y]=='+'){
matriz[x-1][y] == '#';
}
if(matriz[x][y+1]=='+'){
matriz[x][y+1] =='#';
}
if(matriz[x][y-1]=='+'){
matriz[x][y-1] =='#';
}
if(matriz[x+1][y+1]=='+'){
matriz[x+1][y+1] == '#';
}
if(matriz[x-1][y-1]=='+'){
matriz[x-1][y-1] == '#';
}
if(matriz[x+1][y-1]=='+'){
matriz[x+1][y-1] =='#';
}
if(matriz[x-1][y+1]=='+'){
matriz[x-1][y+1] =='#';
}
}
void Tablero::llenarMatriz(){
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
// Signo '+'
if(i==0 && j==0){
matriz[i][j]='+';
}else if(i==10 && j==10){
matriz[i][j]='+';
}else if(i==0 && j==10){
matriz[i][j]='#';
}else if(i==10 && j==0){
matriz[i][j]='#';
}else{
matriz[i][j] = '_';
}
}
}
}
bool Tablero::validarWin(){
int contador=0;
bool win = false;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='_'){
contador++;
}
}
}
if(contador!=0){
win = true;
}
int contadorNum=0;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='#'){
contadorNum++;
}
}
}
if(contadorNum==0){
win = true;
}else{
win = false;
}
int contadorMas=0;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='+'){
contadorMas++;
}
}
}
if(contadorNum==0){
win = true;
}else{
win = false;
}
return win;
}
int Tablero::winner(){
// 1 empate, 2 #, 3 +
int contador=0;
bool win = false;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='_'){
contador++;
}
}
}
if(contador!=0){
return 1;
}
int contadorNum=0;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='#'){
contadorNum++;
}
}
}
if(contadorNum==0){
return 2;
}
int contadorMas=0;
for (int i = 0; i < 11; ++i)
{
for (int j = 0; j < 11; ++j)
{
if(matriz[i][j]=='+'){
contadorMas++;
}
}
}
if(contadorNum==0){
return 3;
}
}
|
// This file was generated based on /usr/local/share/uno/Packages/Fuse.Nodes/1.3.1/Input/Gesture.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Input{struct GesturePriorityConfig;}}}
namespace g{
namespace Fuse{
namespace Input{
// public struct GesturePriorityConfig :28
// {
uStructType* GesturePriorityConfig_typeof();
void GesturePriorityConfig__ctor__fn(GesturePriorityConfig* __this, int* priority, float* significance, int* adjustment);
void GesturePriorityConfig__New1_fn(int* priority, float* significance, int* adjustment, GesturePriorityConfig* __retval);
struct GesturePriorityConfig
{
int Priority;
float Significance;
int Adjustment;
void ctor_(int priority, float significance, int adjustment);
};
GesturePriorityConfig GesturePriorityConfig__New1(int priority, float significance, int adjustment);
// }
}}} // ::g::Fuse::Input
|
/*
* Copyright 2016 EU Project ASAP 619706.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unistd.h>
#include <iostream>
#include <fstream>
#include <deque>
#include <unordered_map>
#include <cilk/cilk.h>
#include <cilk/reducer.h>
#include <cilk/cilk_api.h>
#include "asap/utils.h"
#include "asap/arff.h"
#include "asap/dense_vector.h"
#include "asap/sparse_vector.h"
#include "asap/word_count.h"
#include "asap/ngram_bank.h"
#include "asap/normalize.h"
#include "asap/io.h"
#include "asap/hashtable.h"
#include <stddefines.h>
#define DEF_NUM_MEANS 8
#ifndef N_IN_NGRAM
static const size_t N = 3;
#else
static const size_t N = N_IN_NGRAM;
#endif
char const * indir = nullptr;
char const * outfile = nullptr;
bool by_words = false;
bool do_sort = false;
bool intm_map = false;
static void help(char *progname) {
std::cout << "Usage: " << progname << " -i <indir> -o <outfile> [-w] [-s] [-m]\n";
}
static void parse_args(int argc, char **argv) {
int c;
extern char *optarg;
while ((c = getopt(argc, argv, "i:o:wsm")) != EOF) {
switch (c) {
case 'i':
indir = optarg;
break;
case 'o':
outfile = optarg;
break;
case 'w':
by_words = true;
break;
case 's':
do_sort = true;
break;
case 'm':
intm_map = true;
break;
case '?':
help(argv[0]);
exit(1);
}
}
if( !indir )
fatal( "Input directory must be supplied." );
std::cerr << "Input directory = " << indir << '\n';
if( !outfile )
std::cerr << "Output stage skipped\n";
else if( !strcmp( outfile, "-" ) )
std::cerr << "Output file = standard output\n";
else
std::cerr << "Output file = " << outfile << '\n';
std::cerr << "TF/IDF by words = " << ( by_words ? "true\n" : "false\n" );
std::cerr << "TF/IDF list sorted = " << ( do_sort ? "true\n" : "false\n" );
std::cerr << "N-grams, N = " << N << '\n';
}
template<typename map_type, bool can_sort = true>
typename std::enable_if<can_sort>::type
kv_sort( map_type & m ) {
std::sort( m.begin(), m.end(),
asap::pair_cmp<typename map_type::value_type,
typename map_type::value_type>() );
}
template<typename map_type, bool can_sort>
typename std::enable_if<!can_sort>::type
kv_sort( map_type & m ) {
}
template<typename directory_listing_type, typename intl_map_type, typename intm_map_type, typename agg_map_type, typename data_set_type, bool can_sort>
data_set_type tfidf_driver( directory_listing_type & dir_list ) {
struct timespec wc_end, tfidf_begin, tfidf_end;
// word count
get_time( tfidf_begin );
size_t num_files = dir_list.size();
std::vector<intm_map_type> catalog;
catalog.resize( num_files );
asap::ngram_container_reducer<agg_map_type> allwords;
allwords.get_value().set_growth( 1, 2 );
cilk_for( size_t i=0; i < num_files; ++i ) {
// File to read
std::string filename = *std::next(dir_list.cbegin(),i);
catalog[i].set_growth( 1, 2 );
size_t ngrams = asap::ngram_catalog<intl_map_type>( filename, catalog[i] );
// The list of pairs is sorted if intl_map_type is based on std::map
// but it is not sorted if based on std::unordered_map
if( do_sort )
kv_sort<intm_map_type,can_sort>( catalog[i] );
// std::cerr << filename << ": " << ngrams << " ngrams\n";
allwords.count_presence( catalog[i] );
}
get_time( wc_end );
std::shared_ptr<agg_map_type> allwords_ptr
= std::make_shared<agg_map_type>();
allwords_ptr->swap( allwords.get_value() );
std::shared_ptr<directory_listing_type> dir_list_ptr
= std::make_shared<directory_listing_type>();
dir_list_ptr->swap( dir_list );
asap::internal::assign_ids( allwords_ptr->begin(), allwords_ptr->end() );
data_set_type tfidf(
by_words
? asap::tfidf_by_words<typename data_set_type::vector_type>(
catalog.cbegin(), catalog.cend(), allwords_ptr, dir_list_ptr,
do_sort ) // whether catalogs are sorted
: asap::tfidf<typename data_set_type::vector_type>(
catalog.cbegin(), catalog.cend(), allwords_ptr, dir_list_ptr,
do_sort, // whether sorted by word
do_sort )
); // whether catalogs are sorted
get_time(tfidf_end);
print_time("ngram count", tfidf_begin, wc_end);
print_time("TF/IDF", wc_end, tfidf_end);
std::cerr << "TF/IDF vectors: " << tfidf.get_num_points() << '\n';
std::cerr << "TF/IDF dimensions: " << tfidf.get_dimensions() << '\n';
print_time("library", tfidf_begin, tfidf_end);
return tfidf;
}
#if 0
// a single null-terminated word
struct wc_word {
const char* data;
wc_word(const char * d = 0) : data( d ) { }
wc_word( const wc_word & w ) : data( w.data ) { }
// necessary functions to use this as a key
bool operator<(wc_word const& other) const {
return strcmp(data, other.data) < 0;
}
bool operator==(wc_word const& other) const {
return strcmp(data, other.data) == 0;
}
operator const char * () const { return data; }
operator char * () const { return (char *)data; } // output
};
// a hash for the word
struct wc_word_hash
{
// FNV-1a hash for 64 bits
size_t operator()(wc_word const& key) const
{
const char* h = key.data;
uint64_t v = 14695981039346656037ULL;
while (*h != 0)
v = (v ^ (size_t)(*(h++))) * 1099511628211ULL;
return v;
}
};
#endif
int main(int argc, char **argv) {
struct timespec begin, end;
struct timespec veryStart;
srand( time(NULL) );
get_time( begin );
get_time( veryStart );
// read args
parse_args(argc,argv);
std::cerr << "Available threads: " << __cilkrts_get_nworkers() << "\n";
get_time (end);
print_time("init", begin, end);
// Directory listing
get_time( begin );
typedef asap::word_list<std::deque<const char*>, asap::word_bank_managed>
directory_listing_type;
directory_listing_type dir_list;
asap::get_directory_listing( indir, dir_list );
get_time (end);
print_time("directory listing", begin, end);
typedef size_t index_type;
typedef asap::word_bank_pre_alloc word_bank_type;
typedef asap::sparse_vector<index_type, float, false,
asap::mm_no_ownership_policy>
vector_type;
/*
typedef asap::word_map<
std::unordered_map<const char *, size_t, asap::text::charp_hash,
asap::text::charp_eql>,
word_bank_type> internal_map_type;
typedef asap::kv_list<std::vector<std::pair<const char *, size_t>>,
word_bank_type> intermediate_map_type;
typedef asap::word_map<
std::unordered_map<const char *,
asap::appear_count<size_t, index_type>,
asap::text::charp_hash, asap::text::charp_eql>,
word_bank_type> aggregate_map_type;
*/
typedef asap::hash_table<asap::text::ngram<N>, size_t, asap::text::ngram_hash, asap::text::ngram_eql> wc_unordered_map;
typedef asap::hash_table<asap::text::ngram<N>,
asap::appear_count<size_t, index_type>,
asap::text::ngram_hash, asap::text::ngram_eql> dc_unordered_map;
typedef asap::ngram_map<dc_unordered_map, word_bank_type, N> aggregate_map_type;
/*
typedef std::vector<std::pair<asap::text::ngram<N>,
asap::appear_count<size_t, index_type>>> dc_unordered_map;
typedef asap::ngram_kv_list<dc_unordered_map, word_bank_type, N> aggregate_map_type;
*/
typedef asap::ngram_map<wc_unordered_map, word_bank_type, N> internal_map_type;
typedef asap::ngram_kv_list<std::vector<std::pair<asap::text::ngram<N>, size_t>>,
word_bank_type, N> intermediate_map_type;
typedef asap::data_set<vector_type, aggregate_map_type,
directory_listing_type> data_set_type;
data_set_type tfidf(
intm_map
? tfidf_driver<directory_listing_type, internal_map_type,
internal_map_type, aggregate_map_type,
data_set_type, false>( dir_list )
: tfidf_driver<directory_listing_type, internal_map_type,
intermediate_map_type, aggregate_map_type,
data_set_type, true>( dir_list )
);
get_time( begin );
if( outfile )
asap::arff_write( outfile, tfidf );
get_time (end);
print_time("output", begin, end);
print_time("complete time", veryStart, end);
return 0;
}
|
#include<iostream>
#include<windows.h>
using namespace std;
int count;
string player1,player2;
char player='X';
char matrix[3][3]={'1','2','3','4','5','6','7','8','9'};
void draw(){
system("cls");
/*cout <<"Enter the First palyer name :\n";
cin >> player1;
cout <<"Enter the Second player name :\n";
cin >>player2;*/
cout<<"\t Tic Tac ver1.0\n"<<endl;
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<matrix[i][j]<<"\t";
}
cout<<endl<<"\n\n\n";
}
}
void input(){
Beep(523,500);
int choice;
cout << "Press the number of the location :\n";
cin >> choice;
if( choice == 1 ){
if(matrix[0][0] == '1'){
matrix[0][0] = player;
}
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if(choice == 2 ){
if(matrix [0][1] == '2'){
matrix[0][1] = player;
}
else{
cout<<"Invalid position ";
count --;
system("pause");
input();
}
}
else if( choice == 3 ){
if(matrix [0][2] == '3'){
matrix[0][2] = player;
}
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 4 ){
if(matrix[1][0] == '4'){
matrix[1][0] = player;
}
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 5 ){
if(matrix[1][1] == '5'){
matrix[1][1] = player;
}
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 6 ){
if(matrix[1][2]== '6')
matrix[1][2] = player;
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 7 ){
if(matrix[2][0] == '7')
matrix[2][0] = player;
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 8 ){
if( matrix[2][1] == '8')
matrix[2][1] = player;
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
else if( choice == 9 ){
if(matrix[2][2] == '9')
matrix[2][2] = player;
else{
cout<<"Invalid position ";
count--;
system("pause");
input();
}
}
}
void playerchanger(){
if(player == 'X'){
player = 'O';
}
else
player = 'X';
}
char winner(){
//first player
if(matrix[0][0]=='X'&&matrix[0][1]=='X'&&matrix[0][2]=='X'){
return 'X';
}
if(matrix[1][0]=='X'&&matrix[1][1]=='X'&&matrix[1][2]=='X'){
return 'X';
}
if(matrix[2][0]=='X'&&matrix[2][1]=='X'&&matrix[2][2]=='X'){
return 'X';
}
if(matrix[0][0]=='X'&&matrix[1][0]=='X'&&matrix[2][0]=='X'){
return 'X';
}
if(matrix[0][1]=='X'&&matrix[1][1]=='X'&&matrix[2][1]=='X'){
return 'X';
}
if(matrix[0][2]=='X'&&matrix[1][2]=='X'&&matrix[2][2]=='X'){
return 'X';
}
if(matrix[0][0]=='X'&&matrix[1][1]=='X'&&matrix[2][2]=='X'){
return 'X';
}
if(matrix[0][2]=='X'&&matrix[1][1]=='X'&&matrix[2][0]=='X'){
return 'X';
}
//second player
if(matrix[0][0]=='O'&&matrix[0][1]=='O'&&matrix[0][2]=='O'){
return 'O';
}
if(matrix[1][0]=='O'&&matrix[1][1]=='O'&&matrix[1][2]=='O'){
return 'O';
}
if(matrix[2][0]=='O'&&matrix[2][1]=='O'&&matrix[2][2]=='O'){
return 'O';
}
if(matrix[0][0]=='O'&&matrix[1][0]=='O'&&matrix[2][0]=='O'){
return 'O';
}
if(matrix[0][1]=='O'&&matrix[1][1]=='O'&&matrix[2][1]=='O'){
return 'O';
}
if(matrix[0][2]=='O'&&matrix[1][2]=='O'&&matrix[2][2]=='O'){
return 'O';
}
if(matrix[0][0]=='O'&&matrix[1][1]=='O'&&matrix[2][2]=='O'){
return 'O';
}
if(matrix[0][2]=='O'&&matrix[1][1]=='O'&&matrix[2][0]=='O'){
return 'O';
}
return '/';
}
int main(){
cout <<"Enter the player 1 name:\n";
cin >>player1;
cout <<"Enter the player 2 name :\n";
cin >>player2;
//cout<<'\a';
Beep(400,500);
count = 0;
draw();
while(1){
count++;
input();
draw();
if(winner() == 'X'){
cout<<player1<<" wins!!! ";
cout<<'\a';
while(1) {
cout << "you win\n";
cout <<"\t\t\t\t\tHarrayyyyyyyy";
}
break;
}
else if(winner() == 'O'){
cout<<player2<<" wins !!!";
cout<<'\a';
break;
}
else if(winner() == '/' && count == 9){
cout<<" Its a draw "<<endl;
break;
}
playerchanger();
}
system("pause");
return 0;
}
|
#include "CalGroupPanel.h"
#include "ui_CalGroupPanel.h"
using namespace RsaToolbox;
#include <QDebug>
CalGroupPanel::CalGroupPanel(QWidget *parent) :
QWidget(parent),
ui(new Ui::CalGroupPanel)
{
ui->setupUi(this);
_model = NULL;
QObject::connect(ui->calButton, SIGNAL(clicked()),
&_dialog, SLOT(exec()));
QObject::connect(&_dialog, SIGNAL(accepted()),
this, SLOT(dialogAccepted()));
QObject::connect(ui->applyCal, SIGNAL(toggled(bool)),
ui->calButton, SLOT(setEnabled(bool)));
QObject::connect(ui->applyCal, SIGNAL(toggled(bool)),
ui->calEdit, SLOT(setEnabled(bool)));
ui->noCal->setChecked(true);
ui->calButton->setDisabled(true);
ui->calEdit->setDisabled(true);
}
CalGroupPanel::~CalGroupPanel()
{
delete ui;
}
void CalGroupPanel::setModel(CalGroupsModel *model) {
_model = model;
_dialog.setModel(model, 0);
_selection.reset(new QItemSelectionModel(model));
QObject::connect(_selection.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SIGNAL(selectionChanged(QItemSelection,QItemSelection)));
QObject::connect(_selection.data(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)),
this, SLOT(changeSelection(QItemSelection,QItemSelection)));
QObject::connect(ui->noCal, SIGNAL(clicked()),
_selection.data(), SLOT(clearSelection()));
QObject::connect(ui->applyCal, SIGNAL(clicked()),
this, SLOT(dialogAccepted()));
}
CalGroupsModel *CalGroupPanel::model() const {
return _model;
}
QItemSelectionModel *CalGroupPanel::selectionModel() const {
return _selection.data();
}
void CalGroupPanel::reset() {
ui->calEdit->clear();
_dialog.reset();
}
void CalGroupPanel::dialogAccepted() {
if (_selection.isNull())
return;
_selection->clearSelection();
_selection->select(_dialog.selectedIndex(), QItemSelectionModel::Select);
ui->calEdit->setText(_dialog.selectedIndex().data(Qt::DisplayRole).toString());
}
void CalGroupPanel::changeSelection(const QItemSelection &selected, const QItemSelection &deselected) {
Q_UNUSED(deselected);
if (selected.isEmpty()) {
ui->noCal->setChecked(true);
}
else {
ui->applyCal->setChecked(true);
ui->calEdit->setText(selected.indexes().first().data(Qt::DisplayRole).toString());
}
}
|
/* -*- 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 VEGA_PRINTER_LISTENER_SUPPORT
#include "platforms/mac/pi/MacVegaPrinterListener.h"
#include "platforms/mac/pi/MacOpFont.h"
#include "platforms/mac/CocoaVegaDefines.h"
#include "platforms/mac/util/MachOCompatibility.h"
MacVegaPrinterListener::MacVegaPrinterListener()
: m_ctx(NULL)
, m_port(NULL)
, m_font(NULL)
{
}
MacVegaPrinterListener::~MacVegaPrinterListener()
{
}
void MacVegaPrinterListener::SetClipRect(const OpRect& clip)
{
CGContextRestoreGState(m_ctx);
CGContextSaveGState(m_ctx);
CGContextClipToRect(m_ctx, CGRectMake(clip.x, m_winHeight-(clip.y+clip.height), clip.width, clip.height));
CGContextSetRGBFillColor(m_ctx, m_red, m_green, m_blue, m_alpha);
CGContextSetRGBStrokeColor(m_ctx, m_red, m_green, m_blue, m_alpha);
}
void MacVegaPrinterListener::SetColor(UINT8 red, UINT8 green, UINT8 blue, UINT8 alpha)
{
m_red=((float)red)/255.0;
m_green=((float)green)/255.0;
m_blue=((float)blue)/255.0;
m_alpha=((float)alpha)/255.0;
CGContextSetRGBFillColor(m_ctx, m_red, m_green, m_blue, m_alpha);
CGContextSetRGBStrokeColor(m_ctx, m_red, m_green, m_blue, m_alpha);
}
void MacVegaPrinterListener::SetFont(OpFont* font)
{
m_font = font ? (MacOpFont*)((VEGAOpFont*)font)->getVegaFont() : NULL;
}
void MacVegaPrinterListener::DrawRect(const OpRect& rect, UINT32 width)
{
if(width != 1)
{
CGContextSetLineWidth(m_ctx, width);
}
CGContextStrokeRect(m_ctx, CGRectMake(rect.x, m_winHeight-(rect.y+rect.height), rect.width, rect.height));
if(width != 1)
{
CGContextSetLineWidth(m_ctx, 1);
}
}
void MacVegaPrinterListener::FillRect(const OpRect& rect)
{
CGContextFillRect(m_ctx, CGRectMake(rect.x, m_winHeight-(rect.y+rect.height), rect.width, rect.height));
}
void MacVegaPrinterListener::DrawEllipse(const OpRect& rect, UINT32 width)
{
CGRect cgrect = CGRectMake(rect.x, rect.y, rect.width, rect.height);
cgrect.origin.y = m_winHeight - cgrect.origin.y - cgrect.size.height;
float cx = cgrect.origin.x + (cgrect.size.width / 2);
float cy = cgrect.origin.y + (cgrect.size.height / 2);
float radius = cgrect.size.width / 2;
if(width != 1)
{
CGContextSetLineWidth(m_ctx, width);
}
if(cgrect.size.width != cgrect.size.height)
{
cy = cy * cgrect.size.width / cgrect.size.height;
CGContextScaleCTM(m_ctx, 1.0, cgrect.size.height/cgrect.size.width);
}
CGContextAddArc(m_ctx, cx, cy, radius, 0, 2*M_PI, 0);
CGContextStrokePath(m_ctx);
if(width != 1)
{
CGContextSetLineWidth(m_ctx, 1);
}
if(cgrect.size.width != cgrect.size.height)
{
CGContextScaleCTM(m_ctx, 1.0, cgrect.size.width/cgrect.size.height);
}
}
void MacVegaPrinterListener::FillEllipse(const OpRect& rect)
{
CGRect cgrect = CGRectMake(rect.x, rect.y, rect.width, rect.height);
cgrect.origin.y = m_winHeight - cgrect.origin.y - cgrect.size.height;
float cx = cgrect.origin.x + (cgrect.size.width / 2);
float cy = cgrect.origin.y + (cgrect.size.height / 2);
float radius = cgrect.size.width / 2;
if(cgrect.size.width != cgrect.size.height)
{
cy = cy * cgrect.size.width / cgrect.size.height;
CGContextScaleCTM(m_ctx, 1.0, cgrect.size.height/cgrect.size.width);
}
CGContextAddArc(m_ctx, cx, cy, radius, 0, 2*M_PI, 0);
CGContextFillPath(m_ctx);
if(cgrect.size.width != cgrect.size.height)
{
CGContextScaleCTM(m_ctx, 1.0, cgrect.size.width/cgrect.size.height);
}
}
void MacVegaPrinterListener::DrawLine(const OpPoint& from, const OpPoint& to, UINT32 width)
{
if(width != 1)
{
CGContextSetLineWidth(m_ctx, width);
}
CGContextBeginPath(m_ctx);
CGContextMoveToPoint(m_ctx, from.x, m_winHeight - from.y);
CGContextAddLineToPoint(m_ctx, to.x, m_winHeight - to.y);
CGContextStrokePath(m_ctx);
if(width != 1)
{
CGContextSetLineWidth(m_ctx, 1);
}
}
void MacVegaPrinterListener::DrawString(const OpPoint& pos, const uni_char* text, UINT32 len, INT32 extra_char_spacing, short word_width)
{
CGContextSaveGState(m_ctx);
CGContextTranslateCTM(m_ctx, 0, m_winHeight);
OpPoint pt(pos.x, pos.y);
if (m_font)
{
CGContextSetFont(m_ctx, m_font->GetCGFontRef());
CGContextSetFontSize(m_ctx, m_font->GetSize());
m_font->DrawStringUsingFallback(pt, text, len, extra_char_spacing, m_ctx);
}
CGContextRestoreGState(m_ctx);
}
static void DeleteBuffer(void *info, const void *data, size_t size)
{
free(info);
}
void MacVegaPrinterListener::DrawBitmapClipped(const OpBitmap* bitmap, const OpRect& source, OpPoint p)
{
CGColorSpaceRef device = CGColorSpaceCreateDeviceRGB();
size_t data_size = bitmap->GetBytesPerLine()*bitmap->Height();
void* bitmap_data = malloc(data_size);
const void* source_data = const_cast<OpBitmap*>(bitmap)->GetPointer(OpBitmap::ACCESS_READONLY);
memcpy(bitmap_data, source_data, data_size);
const_cast<OpBitmap*>(bitmap)->ReleasePointer(FALSE);
CGDataProviderRef provider = CGDataProviderCreateWithData(bitmap_data, bitmap_data, data_size, DeleteBuffer);
CGImageRef image = CGImageCreate(bitmap->Width(), bitmap->Height(), 8, 32, bitmap->GetBytesPerLine(), device, kCGBitmapByteOrderVegaInternal, provider, NULL, true, kCGRenderingIntentAbsoluteColorimetric);
CGContextDrawImage(m_ctx, CGRectMake(source.x+p.x, m_winHeight-(source.y+p.y+source.height), source.width, source.height), image);
CFRelease(provider);
CFRelease(device);
CGImageRelease(image);
}
void MacVegaPrinterListener::SetGraphicsContext(CGrafPtr port)
{
#ifndef SIXTY_FOUR_BIT
if (m_port) {
CGContextRestoreGState(m_ctx);
QDEndCGContext(m_port, &m_ctx);
}
m_port = port;
m_ctx = NULL;
if (m_port) {
Rect bounds;
GetPortBounds(m_port, &bounds);
m_winHeight = bounds.bottom-bounds.top;
QDBeginCGContext(m_port, &m_ctx);
SetColor(0,0,0,255);
CGContextSaveGState(m_ctx);
}
#endif
}
void MacVegaPrinterListener::SetGraphicsContext(CGContextRef context)
{
if (m_ctx)
{
CGContextRestoreGState(m_ctx);
}
m_ctx = context;
if (m_ctx)
{
SetColor(0,0,0,255);
CGContextSaveGState(m_ctx);
}
}
#endif // VEGA_PRINTER_LISTENER_SUPPORT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.