text
stringlengths
8
6.88M
#include <iostream> using namespace std; int luasPersegi (int sisi){ return (sisi*sisi); } int kelilingPersegi (int sisi){ return 4*sisi; } int main() { int s; cout<<"masukkan sisi persegi :"; cin >> s; cout <<"luas persegi = " << luasPersegi(s)<<endl; cout <<"keliling persegi ="<<kelilingPersegi(s)<<endl; return 0; }
#include<iostream> using namespace std; int main() { int a, b, c, d; int aux; cin >> a >> c >> b >> d; aux = ((b*60)+d) - ((a*60)+c); if(aux<=0) aux += 24*60; cout << "O JOGO DUROU " << aux/60 << " HORA(S) E " << aux%60 << " MINUTO(S)" << endl; return 0; }
#ifndef INTENSITY_HPP #define INTENSITY_HPP #include "globals.hpp" cv::Mat intensityLUT( std::function<unsigned char( unsigned char )> func ); cv::Mat intensityTransform( cv::Mat img, std::function<unsigned char( unsigned char )> func ); cv::Mat intensityTransform_iter( cv::Mat img, std::function<double( double )> func ); unsigned char inverse( unsigned char ); std::function<unsigned char( unsigned char )> logtransform( double c ); std::function<unsigned char( unsigned char )> gammatransform( double c, double r ); std::function<unsigned char( unsigned char )> thresholding( unsigned char threshold ); std::function<unsigned char( unsigned char )> thresholding_2( std::tuple<int, int> threshold ); std::function<unsigned char( unsigned char )> levelslicing( int lower, int upper, int level ); std::function<unsigned char( unsigned char )> bitslicing( unsigned char bitlevel ); cv::Mat testGaussian( cv::Mat Img, double mean, double stddev ); #endif // INTENSITY_HPP
/* https://www.acmicpc.net/problem/8393 */ #include <iostream> using namespace std; int main(void) { int num, total = 0; scanf("%d", &num); for (int i = 1; i <= num; i++) total += i; printf("%d", total); return 0; }
/*************************************************************************** * Copyright (C) 2009 by Dario Freddi * * drf@chakra-project.org * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "Worker_p.h" #include "aqpmabsworkeradaptor.h" #include <QDBusConnection> #include "AqpmAuthorization_p.h" namespace Aqpm { namespace AbsWorker { Worker::Worker(bool temporized, QObject *parent) : QObject(parent) { new AqpmabsworkerAdaptor(this); if (!QDBusConnection::systemBus().registerService("org.chakraproject.aqpmabsworker")) { qDebug() << "another helper is already running"; QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit())); return; } if (!QDBusConnection::systemBus().registerObject("/Worker", this)) { qDebug() << "unable to register service interface to dbus"; QTimer::singleShot(0, QCoreApplication::instance(), SLOT(quit())); return; } setIsTemporized(temporized); setTimeout(3000); startTemporizing(); } Worker::~Worker() { } void Worker::update(const QStringList &targets, bool tarball) { stopTemporizing(); if (!Aqpm::Auth::authorize("org.chakraproject.aqpm.updateabs", message().service())) { emit absUpdated(false); startTemporizing(); return; } m_process = new QProcess(this); connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(slotOutputReady())); connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotAbsUpdated(int, QProcess::ExitStatus))); if (tarball) { m_process->start("abs", QStringList() << targets << "--tarball"); } else { m_process->start("abs", targets); } } void Worker::updateAll(bool tarball) { stopTemporizing(); if (!Aqpm::Auth::authorize("org.chakraproject.aqpm.updateabs", message().service())) { emit absUpdated(false); startTemporizing(); return; } m_process = new QProcess(this); connect(m_process, SIGNAL(readyReadStandardOutput()), this, SLOT(slotOutputReady())); connect(m_process, SIGNAL(finished(int, QProcess::ExitStatus)), this, SLOT(slotAbsUpdated(int, QProcess::ExitStatus))); if (tarball) { m_process->start("abs", QStringList() << "--tarball"); } else { m_process->start("abs"); } } bool Worker::prepareBuildEnvironment(const QString &from, const QString &to) const { stopTemporizing(); if (!Aqpm::Auth::authorize("org.chakraproject.aqpm.preparebuildenvironment", message().service())) { startTemporizing(); return false; } QDir absPDir(from); absPDir.setFilter(QDir::Files | QDir::Hidden | QDir::NoDotAndDotDot | QDir::NoSymLinks); QFileInfoList Plist = absPDir.entryInfoList(); for (int i = 0; i < Plist.size(); ++i) { QString dest(to); if (!dest.endsWith(QChar('/'))) { dest.append(QChar('/')); } dest.append(Plist.at(i).fileName()); qDebug() << "Copying " << Plist.at(i).absoluteFilePath() << " to " << dest; if (!QFile::copy(Plist.at(i).absoluteFilePath(), dest)) { startTemporizing(); return false; } } startTemporizing(); return true; } void Worker::slotAbsUpdated(int code, QProcess::ExitStatus) { if (code == 0) { emit absUpdated(true); } else { emit absUpdated(false); } m_process->deleteLater(); startTemporizing(); } void Worker::slotOutputReady() { emit newOutput(QString::fromLocal8Bit(m_process->readLine(1024))); } } } #include "Worker_p.moc"
#include <bits/stdc++.h> using namespace std; #define MOD 1000000007 #define rep(i, n) for(int i = 0; i < (int)(n); i++) #define rep1(i, n) for(int i = 1; i <= (int)(n); i++) #define show(x) {for(auto i: x){cout << i << " ";} cout<<endl;} #define showm(m) {for(auto i: m){cout << m.x << " ";} cout<<endl;} typedef long long ll; typedef pair<int, int> P; ll gcd(int x, int y){ return y?gcd(y, x%y):x;} ll lcm(ll x, ll y){ return (x*y)/gcd(x,y);} #define SCORE_MAX 105 ll dp[SCORE_MAX][SCORE_MAX][SCORE_MAX]; //[hansei]WA: 条件の見落とし系 int main() { int n, m; cin >> n >> m; rep(i, n){ ll a,b,c,w; cin >> a >> b >> c >> w; dp[a][b][c] = max(w, dp[a][b][c]); } rep(i, SCORE_MAX)rep(j, SCORE_MAX)rep(k, SCORE_MAX){ int id = (i==0)?0:i-1; int jd = (j==0)?0:j-1; int kd = (k==0)?0:k-1; dp[i][j][k] = max(max(dp[id][j][k],dp[i][jd][k]),max(dp[i][j][kd], dp[i][j][k])); } // rep(i,10){ // rep(j,10){ // rep(k,10){ // cout << dp[i][j][k] << " "; // } // cout << endl; // } // cout << endl << "----------"<< endl; // } rep(i, m){ int x,y,z; cin>>x>>y>>z; cout << dp[x][y][z] << endl; } }
#include "test_lib_1.h" int main() { test_lib_1(); return 0; }
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. It may not be distributed * under any circumstances. */ #include "core/pch.h" #include "modules/layout/box/flexitem.h" #include "modules/layout/content/flexcontent.h" #include "modules/layout/traverse/traverse.h" FlexItemBox::FlexItemBox(HTML_Element* element, Content* content) : VerticalBox(element, content), flexorder_prev(NULL), flexorder_next(NULL), z_element(element), left(0), top(0), minimum_margin_height(0), hypothetical_margin_height(0), x(0), y(0), new_main_margin_edge(0), new_cross_margin_edge(0), new_main_margin_size(1000), // any initial value will do, but let's pick something common (that the layout engine is optimized for) new_cross_margin_size(1000), // any initial value will do, but let's pick something common (that the layout engine is optimized for) flexitem_packed_init(0) { } /* virtual */ FlexItemBox::~FlexItemBox() { Out(); } /** Take this item out from the layout stack. */ void FlexItemBox::Out() { FlexItemList* layout_stack = (FlexItemList*) GetList(); if (!layout_stack) { // Not in any stack; nothing to do OP_ASSERT(flexorder_next == NULL); OP_ASSERT(flexorder_prev == NULL); return; } // Remove logically Link::Out(); // Remove from 'order' sorting. if (layout_stack->flexorder_first == this) layout_stack->flexorder_first = flexorder_next; if (layout_stack->flexorder_last == this) layout_stack->flexorder_last = flexorder_prev; if (flexorder_next) flexorder_next->flexorder_prev = flexorder_prev; if (flexorder_prev) flexorder_prev->flexorder_next = flexorder_next; flexorder_next = NULL; flexorder_prev = NULL; } /** Add this item to a layout stack. */ void FlexItemBox::Into(FlexItemList* layout_stack) { FlexItemBox* prev = layout_stack->Last(FALSE); OP_ASSERT(!InList()); OP_ASSERT(flexorder_prev == NULL); OP_ASSERT(flexorder_next == NULL); // Insert logically as last item. Link::Into(layout_stack); // Insert at the appropriate position, sorted by 'order'. while (prev && prev->GetOrder() > order) prev = prev->flexorder_prev; if (prev) { flexorder_next = prev->flexorder_next; flexorder_prev = prev; prev->flexorder_next = this; if (flexorder_next) flexorder_next->flexorder_prev = this; } else { if (layout_stack->flexorder_first) { flexorder_next = layout_stack->flexorder_first; layout_stack->flexorder_first->flexorder_prev = this; } layout_stack->flexorder_first = this; } if (!flexorder_next) layout_stack->flexorder_last = this; } /** Is this box (and potentially also its children) columnizable? */ /* virtual */ BOOL FlexItemBox::IsColumnizable(BOOL require_children_columnizable) const { /* The spec says that flex items may be broken inside, but I say it's too much of a hassle, with our current pagination and columnization design. :) */ return FALSE; } /** Return TRUE if this is a special anonymous flex item for an absolutely positioned child. */ BOOL FlexItemBox::IsAbsolutePositionedSpecialItem() const { HTML_Element* html_element = GetHtmlElement(); if (html_element->Type() != Markup::LAYOUTE_ANON_FLEX_ITEM) return FALSE; for (HTML_Element* child = html_element->FirstChild(); child; child = child->Suc()) if (Box* child_box = child->GetLayoutBox()) return child_box->IsAbsolutePositionedBox(); return FALSE; } /** Set page and column breaking policies on this flex item box. */ void FlexItemBox::SetBreakPolicies(BREAK_POLICY page_break_before, BREAK_POLICY column_break_before, BREAK_POLICY page_break_after, BREAK_POLICY column_break_after) { flexitem_packed.page_break_before = page_break_before; flexitem_packed.column_break_before = column_break_before; flexitem_packed.page_break_after = page_break_after; flexitem_packed.column_break_after = column_break_after; /* The column break bitfields cannot hold 'left' and 'right' values (and they are meaningless in that context anyway): */ OP_ASSERT(column_break_before != BREAK_LEFT && column_break_before != BREAK_RIGHT); OP_ASSERT(column_break_after != BREAK_LEFT && column_break_after != BREAK_RIGHT); } /** Get flexed (horizontal flexbox) or stretched (vertical flexbox) border box width. */ LayoutCoord FlexItemBox::GetFlexWidth(LayoutProperties* cascade) const { LayoutCoord flex_width; if (flexitem_packed.vertical) flex_width = new_cross_margin_size - margin_left - margin_right; else flex_width = new_main_margin_size - margin_left - margin_right; if (flex_width < 0) flex_width = LayoutCoord(0); return flex_width; } /** Get flexed (vertical flexbox) or stretched (horizontal flexbox) border box height. */ LayoutCoord FlexItemBox::GetFlexHeight(LayoutProperties* cascade) const { LayoutCoord stretch_height; if (flexitem_packed.vertical) stretch_height = new_main_margin_size; else if (flexitem_packed.stretch) stretch_height = new_cross_margin_size; else return CONTENT_HEIGHT_AUTO; const HTMLayoutProperties& props = *cascade->GetProps(); stretch_height -= props.margin_top + props.margin_bottom; if (stretch_height < 0) stretch_height = LayoutCoord(0); return stretch_height; } /** Lay out box. */ /* virtual */ LAYST FlexItemBox::Layout(LayoutProperties* cascade, LayoutInfo& info, HTML_Element* first_child, LayoutCoord start_position) { VerticalBoxReflowState* state = InitialiseReflowState(); if (!state) return LAYOUT_OUT_OF_MEMORY; HTML_Element* html_element = cascade->html_element; FlexContent* flexbox = cascade->flexbox; BOOL vertical = flexbox->IsVertical(); OP_ASSERT(!first_child); // Meaningless situation. int reflow_content = html_element->MarkClean(); const HTMLayoutProperties& props = *cascade->GetProps(); flexitem_packed.is_positioned = props.position != CSS_VALUE_static; /* To simplify things (number of classes and amount of code duplication), we create the same box type for flexbox items, regardless positioning scheme, opacity, transforms and z-index. Instead, calculate flags that determine whether or not we should return NULL from methods like GetLocalZElement() and GetLocalStackingContext(), and whether IsPositionedBox() should return FALSE or TRUE. Note that flex items let 'z-index' apply even if 'position' is 'static'. */ flexitem_packed.has_stacking_context = #ifdef CSS_TRANSFORMS props.transforms_cp != NULL || #endif // CSS_TRANSFORMS; props.opacity != 255 || props.z_index != CSS_ZINDEX_auto; flexitem_packed.has_z_element = flexitem_packed.has_stacking_context || flexitem_packed.is_positioned; if (Box::Layout(cascade, info) == LAYOUT_OUT_OF_MEMORY) return LAYOUT_OUT_OF_MEMORY; state->cascade = cascade; state->old_x = x; state->old_y = y; state->old_width = content->GetWidth(); state->old_height = content->GetHeight(); state->old_bounding_box = bounding_box; #ifdef CSS_TRANSFORMS if (state->transform) state->transform->old_transform = state->transform->transform_context->GetCurrentTransform(); #endif // CSS_TRANSFORMS #ifdef LAYOUT_YIELD_REFLOW if (info.force_layout_changed) { space_manager.EnableFullBfcReflow(); reflow_content = ELM_DIRTY; } #endif // LAYOUT_YIELD_REFLOW margin_left = props.margin_left; margin_right = props.margin_right; margin_top = props.margin_top; margin_bottom = props.margin_bottom; modes = props.flexbox_modes; flexitem_packed.border_box_sizing = props.box_sizing == CSS_VALUE_border_box; flexitem_packed.margin_left_auto = props.GetMarginLeftAuto(); flexitem_packed.margin_right_auto = props.GetMarginRightAuto(); flexitem_packed.margin_top_auto = props.GetMarginTopAuto(); flexitem_packed.margin_bottom_auto = props.GetMarginBottomAuto(); if (flexitem_packed.is_positioned) // Store relative offsets. props.GetLeftAndTopOffset(left, top); preferred_main_size = props.flex_basis; if (preferred_main_size <= CONTENT_SIZE_SPECIAL) if (vertical) preferred_main_size = props.content_height; else preferred_main_size = props.content_width; flex_grow = props.flex_grow; flex_shrink = props.flex_shrink; order = props.order; LAYST st = flexbox->GetNewItem(info, cascade, this); if (st != LAYOUT_CONTINUE) return st; if ( #ifdef PAGED_MEDIA_SUPPORT info.paged_media != PAGEBREAK_OFF || #endif // PAGED_MEDIA_SUPPORT cascade->multipane_container) { BREAK_POLICY page_break_before; BREAK_POLICY column_break_before; BREAK_POLICY page_break_after; BREAK_POLICY column_break_after; CssValuesToBreakPolicies(info, cascade, page_break_before, page_break_after, column_break_before, column_break_after); SetBreakPolicies(page_break_before, column_break_before, page_break_after, column_break_after); if (cascade->multipane_container) /* There's an ancestor multi-pane container, but that doesn't have to mean that this item is to be columnized. */ flexitem_packed.in_multipane = flexbox->GetPlaceholder()->IsColumnizable(TRUE); } #ifdef PAGED_MEDIA_SUPPORT /* Under no circumstances break inside flex items, even if that is allowed according to the spec. If we add a page break inside a flex item, that will affect its hypothetical height, because of how our paged media implementation works. That may lead to circular dependencies. */ state->old_paged_media = info.paged_media; info.paged_media = PAGEBREAK_OFF; #endif // PAGED_MEDIA_SUPPORT switch (content->ComputeSize(cascade, info)) { case OpBoolean::IS_TRUE: reflow_content |= ELM_DIRTY; case OpBoolean::IS_FALSE: break; default: OP_ASSERT(!"Unexpected result"); case OpStatus::ERR_NO_MEMORY: return LAYOUT_OUT_OF_MEMORY; } flexitem_packed.visibility_collapse = props.visibility == CSS_VALUE_collapse; flexitem_packed.vertical = vertical; if (vertical) { min_main_size = props.min_height; max_main_size = props.max_height; min_cross_size = props.min_width; max_cross_size = props.max_width; computed_cross_size = props.content_width; main_border_padding = LayoutCoord(props.border.top.width + props.border.bottom.width) + props.padding_top + props.padding_bottom; cross_border_padding = LayoutCoord(props.border.left.width + props.border.right.width) + props.padding_left + props.padding_right; } else { min_main_size = props.min_width; max_main_size = props.max_width; min_cross_size = props.min_height; max_cross_size = props.max_height; computed_cross_size = props.content_height; main_border_padding = LayoutCoord(props.border.left.width + props.border.right.width) + props.padding_left + props.padding_right; cross_border_padding = LayoutCoord(props.border.top.width + props.border.bottom.width) + props.padding_top + props.padding_bottom; } flexitem_packed.stretch = props.flexbox_modes.GetAlignSelf() == FlexboxModes::ASELF_STRETCH && computed_cross_size == CONTENT_SIZE_AUTO; CalculateVisualMarginPos(flexbox, x, y); x += margin_left + left; y += margin_top + top; info.Translate(x, y); #ifdef CSS_TRANSFORMS if (state->transform) if (!state->transform->transform_context->PushTransforms(info, state->transform->translation_state)) return LAYOUT_OUT_OF_MEMORY; #endif if (flexitem_packed.is_positioned) { info.GetRootTranslation(state->previous_root_x, state->previous_root_y); info.SetRootTranslation(info.GetTranslationX(), info.GetTranslationY()); } /* First remove from stacking context. This shouldn't really be necessary, unless flexitem_packed.has_z_element suddenly goes from 1 to 0 (see CORE-49171). We should recreate the layout box object in such cases, but if we don't do that, this class is capable of coping - as long as we make sure we aren't an entry in a stacking context when we shouldn't be. Better cope than crash. */ z_element.Out(); if (flexitem_packed.has_z_element) if (cascade->stacking_context) { // Set up local stacking context, if any. if (flexitem_packed.has_stacking_context) z_element.SetZIndex(props.z_index); // Add this element to parent stacking context. z_element.SetOrder(props.order); cascade->stacking_context->AddZElement(&z_element); } if (!reflow_content) if ( #ifdef PAGED_MEDIA_SUPPORT info.paged_media == PAGEBREAK_ON || #endif props.display_type == CSS_VALUE_list_item && flexbox->IsReversedList()) reflow_content |= ELM_DIRTY; else { /* If there are width changes, they have already been detected by ComputeSize() as usual, but for height changes, we need to check on our own. The height may be stretched in horizontal flexboxes, while it may be flexed in vertical flexboxes. */ LayoutCoord flex_height = GetFlexHeight(cascade); if (flex_height != CONTENT_HEIGHT_AUTO && flex_height != state->old_height) reflow_content |= ELM_DIRTY; } if (reflow_content) { if (flexitem_packed.has_stacking_context) stacking_context.Restart(); if (!space_manager.Restart()) return LAYOUT_OUT_OF_MEMORY; bounding_box.Reset(props.DecorationExtent(info.doc), LayoutCoord(0)); return content->Layout(cascade, info); } else { if (!cascade->SkipBranch(info, FALSE, TRUE)) return LAYOUT_OUT_OF_MEMORY; if (props.display_type == CSS_VALUE_list_item && HasListMarkerBox()) /* Layout of this box is skipped, so list item marker layout will also be skipped. Process numbering, so that later list items still get the correct value. */ flexbox->GetNewListItemValue(cascade->html_element); } return LAYOUT_CONTINUE; } /** Finish reflowing box. */ /* virtual */ LAYST FlexItemBox::FinishLayout(LayoutInfo& info) { VerticalBoxReflowState* state = GetReflowState(); LayoutProperties* cascade = state->cascade; LAYST st = content->FinishLayout(info); if (st != LAYOUT_CONTINUE) return st; space_manager.FinishLayout(); if (flexitem_packed.has_stacking_context) stacking_context.FinishLayout(cascade); cascade->flexbox->FinishNewItem(info, cascade, this); UpdateScreen(info); if (flexitem_packed.is_positioned) info.SetRootTranslation(state->previous_root_x, state->previous_root_y); if (cascade->GetProps()->display_type == CSS_VALUE_list_item && !HasListMarkerBox()) /* Need to process the list number, since if the list marker was not displayed, the number was not processed during marker box layout, but it should still affect numbering of later list items. */ cascade->flexbox->GetNewListItemValue(cascade->html_element); PropagateBottomMargins(info); DeleteReflowState(); return LAYOUT_CONTINUE; } /** Update screen. */ /* virtual */ void FlexItemBox::UpdateScreen(LayoutInfo& info) { VerticalBoxReflowState* state = GetReflowState(); content->UpdateScreen(info); CheckAbsPosDescendants(info); #ifdef CSS_TRANSFORMS TransformContext* transform_context = state->transform ? state->transform->transform_context : NULL; if (transform_context) transform_context->PopTransforms(info, state->transform->translation_state); #endif // CSS_TRANSFORMS #ifdef PAGED_MEDIA_SUPPORT info.paged_media = state->old_paged_media; #endif // PAGED_MEDIA_SUPPORT info.Translate(-x, -y); if (state->old_x != x || state->old_y != y || state->old_width != content->GetWidth() || state->old_height != content->GetHeight() || state->old_bounding_box != bounding_box #ifdef CSS_TRANSFORMS || transform_context && state->transform->old_transform != transform_context->GetCurrentTransform() #endif // CSS_TRANSFORMS ) { #ifdef CSS_TRANSFORMS if (transform_context) { VisualDevice* visual_device = info.visual_device; visual_device->Translate(state->old_x, state->old_y); visual_device->PushTransform(state->transform->old_transform); state->old_bounding_box.Invalidate(visual_device, LayoutCoord(0), LayoutCoord(0), state->old_width, state->old_height); visual_device->PopTransform(); visual_device->Translate(x - state->old_x, y - state->old_y); visual_device->PushTransform(transform_context->GetCurrentTransform()); bounding_box.Invalidate(visual_device, LayoutCoord(0), LayoutCoord(0), content->GetWidth(), content->GetHeight()); visual_device->PopTransform(); visual_device->Translate(-x, -y); } else #endif // CSS_TRANSFORMS { AbsoluteBoundingBox before; AbsoluteBoundingBox bbox; bbox.Set(bounding_box, content->GetWidth(), content->GetHeight()); bbox.Translate(x, y); before.Set(state->old_bounding_box, state->old_width, state->old_height); before.Translate(state->old_x, state->old_y); bbox.UnionWith(before); info.visual_device->UpdateRelative(bbox.GetX(), bbox.GetY(), bbox.GetWidth(), bbox.GetHeight()); } } } /** Propagate bottom margins and bounding box to parents, and walk the dog. */ /* virtual */ void FlexItemBox::PropagateBottomMargins(LayoutInfo& info, const VerticalMargin* bottom_margin, BOOL has_inflow_content) { if (flexitem_packed.visibility_collapse) return; AbsoluteBoundingBox abs_bounding_box; LayoutProperties* cascade = GetCascade(); FlexContent* flexbox = cascade->flexbox; GetBoundingBox(abs_bounding_box, IsOverflowVisible()); #ifdef CSS_TRANSFORMS if (TransformContext* transform_context = GetTransformContext()) transform_context->ApplyTransform(abs_bounding_box); #endif // CSS_TRANSFORMS abs_bounding_box.Translate(x, y); flexbox->UpdateBoundingBox(abs_bounding_box, FALSE); } /** Expand relevant parent containers and their bounding-boxes to contain floating and absolutely positioned boxes. A call to this method is only to be initiated by floating or absolutely positioned boxes. */ /* virtual */ void FlexItemBox::PropagateBottom(const LayoutInfo& info, LayoutCoord bottom, LayoutCoord min_bottom, const AbsoluteBoundingBox& child_bounding_box, PropagationOptions opts) { // A flexbox item has its own space manager, so you never propagate a float past it: OP_ASSERT(opts.type != PROPAGATE_FLOAT); if (flexitem_packed.visibility_collapse) return; ReflowState* state = GetReflowState(); if (opts.type == PROPAGATE_ABSPOS_BOTTOM_ALIGNED) { StackingContext* context = GetLocalStackingContext(); if (context) context->SetNeedsBottomAlignedUpdate(); if (flexitem_packed.is_positioned) { if (!context) state->cascade->stacking_context->SetNeedsBottomAlignedUpdate(); return; } } else if (opts.type != PROPAGATE_ABSPOS_SKIPBRANCH || IsOverflowVisible()) UpdateBoundingBox(child_bounding_box, !flexitem_packed.is_positioned); if (flexitem_packed.is_positioned || opts.type == PROPAGATE_ABSPOS_SKIPBRANCH) { // We either reached a containing element or we already passed it. if (state) /* If we're not in SkipBranch or we reached an element that is still being reflowed, we can safely stop bounding box propagation here. The bounding box will be propagated when layout of this box is finished */ return; /* We've already found a containing element but since it had no reflow state we must be skipping a branch. Switch propagation type (this will enable us to clip such bbox) and continue propagation until we reach first element that is being reflowed. */ opts.type = PROPAGATE_ABSPOS_SKIPBRANCH; } HTML_Element* containing_element = GetContainingElement(); OP_ASSERT(containing_element->GetLayoutBox()->GetFlexContent()); if (FlexContent* flexbox = containing_element->GetLayoutBox()->GetFlexContent()) { AbsoluteBoundingBox abs_bounding_box; if (opts.type == PROPAGATE_ABSPOS_SKIPBRANCH) GetBoundingBox(abs_bounding_box, IsOverflowVisible()); else abs_bounding_box = child_bounding_box; abs_bounding_box.Translate(x, y); flexbox->PropagateBottom(info, abs_bounding_box, opts); } } /** Invalidate the screen area that the box uses. */ /* virtual */ void FlexItemBox::Invalidate(LayoutProperties* parent_cascade, LayoutInfo& info) const { info.Translate(x, y); #ifdef CSS_TRANSFORMS TranslationState translation_state; const TransformContext* transform_context = GetTransformContext(); if (transform_context) if (!transform_context->PushTransforms(info, translation_state)) { info.Translate(-x, -y); return; } #endif // CSS_TRANSFORMS bounding_box.Invalidate(info.visual_device, LayoutCoord(0), LayoutCoord(0), content->GetWidth(), content->GetHeight()); #ifdef CSS_TRANSFORMS if (transform_context) transform_context->PopTransforms(info, translation_state); #endif // CSS_TRANSFORMS info.Translate(-x, -y); } /** Do we need to calculate min/max widths of this box's content? */ /* virtual */ BOOL FlexItemBox::NeedMinMaxWidthCalculation(LayoutProperties* cascade) const { return TRUE; } /** Propagate widths to flexbox. */ /* virtual */ void FlexItemBox::PropagateWidths(const LayoutInfo& info, LayoutCoord min_width, LayoutCoord normal_min_width, LayoutCoord max_width) { LayoutProperties* cascade = GetCascade(); const HTMLayoutProperties& props = *cascade->GetProps(); LayoutCoord border_box_width = props.content_width; LayoutCoord extra_width(0); if (!flexitem_packed.vertical) if (props.flex_basis != CONTENT_SIZE_AUTO) border_box_width = props.flex_basis; if (props.box_sizing == CSS_VALUE_content_box) extra_width = props.GetNonPercentHorizontalBorderPadding(); if (border_box_width >= 0) border_box_width += extra_width; OP_ASSERT(max_width >= normal_min_width); OP_ASSERT(normal_min_width >= min_width); min_width = normal_min_width; if (border_box_width >= 0) max_width = border_box_width; if (!flexitem_packed.vertical && flex_shrink == 0.0) // Not shrinkable. Max width is then used to size the item. min_width = max_width; if (props.max_width >= 0 && !props.GetMaxWidthIsPercent()) { if (max_width > props.max_width + extra_width) max_width = props.max_width + extra_width; if (min_width > props.max_width + extra_width) min_width = props.max_width + extra_width; } if (props.min_width != CONTENT_WIDTH_AUTO && !props.GetMinWidthIsPercent()) { if (max_width < props.min_width + extra_width) max_width = props.min_width + extra_width; if (min_width < props.min_width + extra_width) min_width = props.min_width + extra_width; } if (max_width < min_width) max_width = min_width; LayoutCoord hor_margin(0); if (!props.GetMarginLeftIsPercent()) hor_margin += props.margin_left; if (!props.GetMarginRightIsPercent()) hor_margin += props.margin_right; cascade->flexbox->PropagateMinMaxWidths(info, min_width + hor_margin, max_width + hor_margin); } /** Propagate hypothetical border box height. */ void FlexItemBox::PropagateHeights(LayoutCoord min_border_height, LayoutCoord hyp_border_height) { LayoutCoord new_hypothetical_margin_height = hyp_border_height + margin_top + margin_bottom; LayoutCoord new_minimum_margin_height = min_border_height + margin_top + margin_bottom; if (new_hypothetical_margin_height != hypothetical_margin_height || new_minimum_margin_height != minimum_margin_height) { // This change may trigger another reflow. GetCascade()->flexbox->SetItemHypotheticalHeightChanged(); hypothetical_margin_height = new_hypothetical_margin_height; minimum_margin_height = new_minimum_margin_height; } } /** Propagate the 'order' property from an absolutely positioned child. */ void FlexItemBox::PropagateOrder(int child_order) { if (order != child_order && IsAbsolutePositionedSpecialItem()) order = child_order; } /** Traverse box with children. */ void FlexItemBox::Traverse(TraversalObject* traversal_object, LayoutProperties* parent_lprops) { HTML_Element* html_element = GetHtmlElement(); TraverseType old_traverse_type = traversal_object->GetTraverseType(); OP_ASSERT(flexitem_packed.has_z_element || !flexitem_packed.has_stacking_context); OP_ASSERT(flexitem_packed.has_z_element || !flexitem_packed.is_positioned); if (!flexitem_packed.visibility_collapse && (!flexitem_packed.has_z_element || traversal_object->IsTarget(html_element) && old_traverse_type != TRAVERSE_BACKGROUND)) { TraverseInfo traverse_info; RootTranslationState root_translation_state; LayoutProperties* layout_props = NULL; HTML_Element* containing_element = parent_lprops->html_element; BOOL traverse_descendant_target = FALSE; traversal_object->Translate(x, y); if (flexitem_packed.is_positioned) traversal_object->SyncRootScrollAndTranslation(root_translation_state); #ifdef CSS_TRANSFORMS TransformContext* transform_context = GetTransformContext(); TranslationState transforms_translation_state; if (transform_context) { OP_BOOLEAN status = transform_context->PushTransforms(traversal_object, transforms_translation_state); switch (status) { case OpBoolean::ERR_NO_MEMORY: traversal_object->SetOutOfMemory(); case OpBoolean::IS_FALSE: if (traversal_object->GetTarget()) traversal_object->SwitchTarget(containing_element); traversal_object->RestoreRootScrollAndTranslation(root_translation_state); traversal_object->Translate(-x, -y); return; } } #endif // CSS_TRANSFORMS HTML_Element* old_target = traversal_object->GetTarget(); if (flexitem_packed.has_z_element) { if (old_target == html_element) traversal_object->SetTarget(NULL); if (!traversal_object->GetTarget() && old_traverse_type != TRAVERSE_ONE_PASS) traversal_object->SetTraverseType(TRAVERSE_BACKGROUND); } if (traversal_object->EnterVerticalBox(parent_lprops, layout_props, this, traverse_info)) { if (flexitem_packed.has_stacking_context) { if (stacking_context.HasNegativeZChildren() && traversal_object->GetTraverseType() == TRAVERSE_BACKGROUND) traversal_object->FlushBackgrounds(layout_props, this); // Traverse stacking context children with negative z-index. stacking_context.Traverse(traversal_object, layout_props, this, FALSE, FALSE); } // Traverse children in normal flow if (flexitem_packed.has_z_element) if (traversal_object->GetTraverseType() == TRAVERSE_BACKGROUND) { content->Traverse(traversal_object, layout_props); traversal_object->FlushBackgrounds(layout_props, this); traversal_object->SetTraverseType(TRAVERSE_CONTENT); traversal_object->TraverseFloats(this, layout_props); } content->Traverse(traversal_object, layout_props); if (flexitem_packed.has_stacking_context) // Traverse stacking context children with zero or positive z-index. stacking_context.Traverse(traversal_object, layout_props, this, TRUE, FALSE); traversal_object->LeaveVerticalBox(layout_props, this, traverse_info); } else traversal_object->SetTraverseType(old_traverse_type); #ifdef CSS_TRANSFORMS if (transform_context) transform_context->PopTransforms(traversal_object, transforms_translation_state); #endif // CSS_TRANSFORMS if (flexitem_packed.has_z_element) if (old_target == html_element) { traversal_object->SetTarget(old_target); if (traversal_object->SwitchTarget(containing_element) == TraversalObject::SWITCH_TARGET_NEXT_IS_DESCENDANT) { OP_ASSERT(!GetLocalStackingContext()); traverse_descendant_target = TRUE; } } if (flexitem_packed.has_z_element) traversal_object->RestoreRootScrollAndTranslation(root_translation_state); traversal_object->Translate(-x, -y); if (traverse_descendant_target) /* This box was the target (whether it was entered or not is not interesting, though). The next target is a descendant. We can proceed (no need to return to the stacking context loop), but first we have to retraverse this box with the new target set - most importantly because we have to make sure that we enter it and that we do so in the right way. */ Traverse(traversal_object, parent_lprops); } } /** Get flex base size (main axis margin box size). */ LayoutCoord FlexItemBox::GetFlexBaseSize(LayoutCoord containing_block_size) { LayoutCoord item_size = preferred_main_size; if (item_size <= CONTENT_SIZE_SPECIAL || item_size < 0 && containing_block_size == CONTENT_SIZE_AUTO) { // Treat as auto. if (flexitem_packed.vertical) item_size = hypothetical_margin_height; else { LayoutCoord dummy; content->GetMinMaxWidth(dummy, dummy, item_size); item_size += margin_left + margin_right; } } else { if (item_size < 0) { // Resolve percentage. OP_ASSERT(item_size > CONTENT_SIZE_SPECIAL); OP_ASSERT(containing_block_size >= 0); item_size = PercentageToLayoutCoord(LayoutFixed(-item_size), containing_block_size); } // Convert to margin box. if (!flexitem_packed.border_box_sizing) item_size += main_border_padding; if (flexitem_packed.vertical) item_size += margin_top + margin_bottom; else item_size += margin_left + margin_right; } return item_size; } /** Calculate real coordinates (values for upcoming reflow). */ void FlexItemBox::CalculateVisualMarginPos(FlexContent* flexbox, LayoutCoord& x, LayoutCoord& y) const { if (!flexbox->GetPlaceholder()->GetReflowState()) { /* Not reflowing the flexbox (anymore). Then the stored X and Y coordinates are valid. */ x = this->x - margin_left - left; y = this->y - margin_top - top; return; } const HTMLayoutProperties& flex_props = *flexbox->GetPlaceholder()->GetCascade()->GetProps(); LayoutCoord margin_x; // item's margin left edge relative to content box of flexbox LayoutCoord margin_y; // item's margin top edge relative to content box of flexbox BOOL lines_reversed = flexbox->IsLineOrderReversed(); BOOL items_reversed = flexbox->IsItemOrderReversed(); if (flexbox->IsVertical()) { if (lines_reversed) margin_x = flexbox->GetContentWidth() - new_cross_margin_edge - new_cross_margin_size; else margin_x = new_cross_margin_edge; if (items_reversed) margin_y = flexbox->GetContentHeight() - new_main_margin_edge - new_main_margin_size; else margin_y = new_main_margin_edge; } else { if (items_reversed) margin_x = flexbox->GetContentWidth() - new_main_margin_edge - new_main_margin_size; else margin_x = new_main_margin_edge; if (lines_reversed) margin_y = flexbox->GetContentHeight() - new_cross_margin_edge - new_cross_margin_size; else margin_y = new_cross_margin_edge; } x = LayoutCoord(flex_props.border.left.width) + flex_props.padding_left + margin_x; y = LayoutCoord(flex_props.border.top.width) + flex_props.padding_top + margin_y; } /** Push new static Y position of margin box (for upcoming reflow) downwards. */ void FlexItemBox::MoveNewStaticMarginY(FlexContent* flexbox, LayoutCoord amount) { if (flexbox->IsVertical()) { if (flexbox->IsItemOrderReversed()) new_main_margin_edge -= amount; else new_main_margin_edge += amount; } else { if (flexbox->IsLineOrderReversed()) new_cross_margin_edge -= amount; else new_cross_margin_edge += amount; } } /** Constrain the specified main size to min/max-width/height and return that value. */ LayoutCoord FlexItemBox::GetConstrainedMainSize(LayoutCoord margin_box_size) const { LayoutCoord main_margin = flexitem_packed.vertical ? margin_top + margin_bottom : margin_left + margin_right; LayoutCoord new_size = margin_box_size - main_margin; if (!flexitem_packed.border_box_sizing) new_size -= main_border_padding; if (max_main_size >= 0) if (new_size > max_main_size) new_size = max_main_size; LayoutCoord min_size; if (min_main_size == CONTENT_SIZE_AUTO) { if (flexitem_packed.vertical) min_size = minimum_margin_height - main_margin; else { LayoutCoord dummy; content->GetMinMaxWidth(dummy, min_size, dummy); } if (!flexitem_packed.border_box_sizing) { min_size -= main_border_padding; if (min_size < 0) min_size = LayoutCoord(0); } } else min_size = min_main_size; if (new_size < min_size) new_size = min_size; if (!flexitem_packed.border_box_sizing) new_size += main_border_padding; new_size += main_margin; return new_size; } /** Constrain the specified cross size to min/max-height/width and return that value. */ LayoutCoord FlexItemBox::GetConstrainedCrossSize(LayoutCoord margin_box_size) const { LayoutCoord cross_margin = flexitem_packed.vertical ? margin_left + margin_right : margin_top + margin_bottom; LayoutCoord new_size = margin_box_size - cross_margin; if (!flexitem_packed.border_box_sizing) new_size -= cross_border_padding; if (max_cross_size >= 0) if (new_size > max_cross_size) new_size = max_cross_size; if (new_size < min_cross_size) new_size = min_cross_size; if (!flexitem_packed.border_box_sizing) new_size += cross_border_padding; new_size += cross_margin; return new_size; }
#pragma once #include <iberbar/Gui/Headers.h> #include <iberbar/Utility/ViewportState.h> #include <iberbar/Utility/Result.h> #include <memory_resource> namespace iberbar { struct UMouseEventData; struct UKeyboardEventData; class CBaseCommand; class CCommandQueue; namespace Renderer { class CRenderer; class CRenderCommand; class CRenderCallbackCommand; class CRenderGroupCommandManager; class CRenderGroupCommand; class CEffectMatrices; } namespace Gui { class CWidget; class CDialog; class __iberbarGuiApi__ CEngine final { public: CEngine( Renderer::CRenderer* pRenderer, CCommandQueue* pCommandQueue ); CEngine( Renderer::CRenderer* pRenderer, CCommandQueue* pCommandQueue, std::pmr::memory_resource* pMemoryRes ); ~CEngine(); public: std::pmr::memory_resource* GetMemoryPool() { return m_pMemoryRes; } CViewportState* GetViewportState() { return &m_ViewportState; } Renderer::CRenderer* GetRenderer() { return m_pRenderer; } public: CResult Initial(); void AddDialog( CDialog* pDialog ); CDialog* GetDialog( const char* strId ); void RemoveDialog( CDialog* pDialog ); void RequestFocus( CWidget* pWidget ); void ClearFocus( bool bSendEvent ); CWidget* GetFocus() { return m_pWidgetFocus; } void RequestTop( CDialog* pDialog ); void AddCommand( CBaseCommand* pCommand ); void Update( int64 nElapsedTimeMs, float nElapsedTimeSecond ); void Render(); void HandleMouse( const UMouseEventData* EventData ); void HandleKeyboard( const UKeyboardEventData* pEventData ); void SetCanvasResolution( const CSize2i& Size ); private: void OnRenderCallbackCommand(); private: Renderer::CRenderer* m_pRenderer; Renderer::CRenderGroupCommandManager* m_pRenderGroupCommandManager; Renderer::CRenderCallbackCommand* m_pRenderCommand_Callback; CCommandQueue* m_pCommandQueue; bool m_bMemoryResAuto; std::pmr::memory_resource* m_pMemoryRes; CWidget* m_pWidgetFocus; std::list<CDialog*> m_Dialogs; std::vector<Renderer::CRenderGroupCommand*> m_RenderGroupCommandList; CViewportState m_ViewportState; CSize2i m_CanvasResolution; Renderer::CEffectMatrices* m_pEffectMatrices; public: static CEngine* sGetInstance() { return sm_pInstance; } private: static CEngine* sm_pInstance; }; template < typename TElem > std::pmr::polymorphic_allocator<TElem> GetMemoryAllocator() { return std::pmr::polymorphic_allocator<TElem>( CEngine::sGetInstance()->GetMemoryPool() ); } #define iberbarGuiOverride_OperatorNewAndDelete_1( type ) \ public: \ void* operator new(size_t n) { return GetMemoryAllocator<type>().allocate( 1 ); } \ void operator delete(void* p) { GetMemoryAllocator<type>().deallocate( (type*)p, 1 ); } \ void* operator new[]( size_t n ) = delete; \ void operator delete[]( void* ) = delete; } }
#include <wx/combo.h> #ifndef __WXCOMBOBTN_H #define __WXCOMBOBTN_H /** контрол для выбора данных типа комбобокса, только с троеточием */ class wxComboBtn: public wxComboCtrl { public: wxComboBtn() : wxComboCtrl() { Init(); } wxComboBtn(wxWindow *parent, wxWindowID id = wxID_ANY, const wxString& value = wxEmptyString, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, long style = 0 | wxTE_PROCESS_ENTER, const wxValidator& validator = wxDefaultValidator, const wxString& name = wxComboBoxNameStr) : wxComboCtrl() { Init(); Create(parent,id,value, pos,size, // Style flag wxCC_STD_BUTTON makes the button // behave more like a standard push button. style | wxCC_STD_BUTTON, validator,name); // // Prepare custom button bitmap (just '...' text) wxMemoryDC dc; wxBitmap bmp(12,16); dc.SelectObject(bmp); // Draw transparent background wxColour magic(255,0,255); wxBrush magicBrush(magic); dc.SetBrush( magicBrush ); dc.SetPen( *wxTRANSPARENT_PEN ); dc.DrawRectangle(0,0,bmp.GetWidth(),bmp.GetHeight()); // Draw text wxString str = wxT("..."); int w,h; dc.GetTextExtent(str, &w, &h, 0, 0); dc.DrawText(str, (bmp.GetWidth()-w)/2, (bmp.GetHeight()-h)/2); dc.SelectObject( wxNullBitmap ); // Finalize transparency with a mask wxMask *mask = new wxMask( bmp, magic ); bmp.SetMask( mask ); SetButtonBitmaps(bmp,true); } virtual void OnButtonClick() { wxCommandEvent evt(wxEVT_COMMAND_BUTTON_CLICKED, this->GetId()); evt.SetEventObject(this); ProcessWindowEvent(evt); } // Implement empty DoSetPopupControl to prevent assertion failure. virtual void DoSetPopupControl(wxComboPopup* WXUNUSED(popup)) { } private: void Init() { // Initialize member variables here } }; #endif
#ifndef SENDRCV_H #define SENDRCV_H #include "synch.h" class sendRcv { private: Lock *mon_lock; Condition Sender[10]; Condition Recv[10]; int Buffer[10]; Semaphore mesg[10]; public: sendRcv(); ~sendRcv(); void Send(int port, int msg); void Receive(int port, int *msg); }; #endif
// // Created by fab on 25/11/2020. // #ifndef DUMBERENGINE_EDITOR_HPP #define DUMBERENGINE_EDITOR_HPP #include <vector> #include <glfw/glfw3.h> #include <iostream> #include "ISystem.hpp" #include "../utils/IDragNDrop.hpp" class Editor : public ISystem { private: std::vector<IDragNDrop*> callbackDragNDrop; public: static Editor* instance; public: void init() override; void update() override; std::vector<IDragNDrop*>& getDragNDropCallbacks() { return callbackDragNDrop;} static void onDroppedFile(GLFWwindow* window, int count, const char** paths) { for(auto callback : Editor::instance->getDragNDropCallbacks()) { for (int i = 0; i < count; i++) callback->OnFileDropped(paths[i]); } } void addDragNDropCallback(IDragNDrop* callback) { callbackDragNDrop.push_back(callback); } void removeDragNDropCallback(IDragNDrop* callback) { auto index = std::find(callbackDragNDrop.begin(), callbackDragNDrop.end(), callback); callbackDragNDrop.erase(index); } }; #endif //DUMBERENGINE_EDITOR_HPP
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main() { int n, input; vector<int> arr; cin >> n; for(int i=0; i<n; i++) { cin >> input; arr.push_back(input); } int tmp; for(int i=0; i<n; i++) { tmp = i; for(int j=i; j<n; j++) { if(arr[tmp] > arr[j]) tmp = j; } cout << arr[tmp] << endl;; swap(arr[i], arr[tmp]); } return 0; }
// Copyright (c) 2012-2017 The Cryptonote developers // Copyright (c) 2018-2023 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include "Transfers/BlockchainSynchronizer.h" #include "Transfers/TransfersSynchronizer.h" #include "INodeStubs.h" #include "TestBlockchainGenerator.h" #include "TransactionApiHelpers.h" #include "CryptoNoteCore/TransactionApi.h" #include <boost/scoped_array.hpp> #include <future> #include <algorithm> #include <Logging/ConsoleLogger.h> using namespace cn; class TransfersObserver : public ITransfersObserver { public: virtual void onTransactionUpdated(ITransfersSubscription* object, const Hash& transactionHash) override { std::lock_guard<std::mutex> lk(m_mutex); m_transfers.emplace_back(transactionHash); } std::vector<Hash> m_transfers; std::mutex m_mutex; }; class TransfersApi : public ::testing::Test, public IBlockchainSynchronizerObserver { public: TransfersApi() : m_currency(cn::CurrencyBuilder(m_logger).currency()), generator(m_currency), m_node(generator), m_sync(m_node, m_currency.genesisBlockHash()), m_transfersSync(m_currency, m_logger, m_sync, m_node) { } void addAccounts(size_t count) { while (count--) { m_accounts.push_back(generateAccountKeys()); } } void addPaymentAccounts(size_t count) { KeyPair p1; crypto::generate_keys(p1.publicKey, p1.secretKey); auto viewKeys = p1; while (count--) { crypto::generate_keys(p1.publicKey, p1.secretKey); m_accounts.push_back(accountKeysFromKeypairs(viewKeys, p1)); } } void addMinerAccount() { m_accounts.push_back(reinterpret_cast<const AccountKeys&>(generator.getMinerAccount())); } AccountSubscription createSubscription(size_t acc, uint64_t timestamp = 0) { const auto& keys = m_accounts[acc]; AccountSubscription sub; sub.keys = keys; sub.syncStart.timestamp = timestamp; sub.syncStart.height = 0; sub.transactionSpendableAge = 5; return sub; } void subscribeAccounts() { m_transferObservers.reset(new TransfersObserver[m_accounts.size()]); for (size_t i = 0; i < m_accounts.size(); ++i) { m_subscriptions.push_back(&m_transfersSync.addSubscription(createSubscription(i))); m_subscriptions.back()->addObserver(&m_transferObservers[i]); } } void startSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_sync.start(); syncCompletedFuture.get(); m_sync.removeObserver(this); } void refreshSync() { syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); m_sync.addObserver(this); m_sync.lastKnownBlockHeightUpdated(0); syncCompletedFuture.get(); m_sync.removeObserver(this); } void synchronizationCompleted(std::error_code result) override { decltype(syncCompleted) detachedPromise = std::move(syncCompleted); detachedPromise.set_value(result); } void generateMoneyForAccount(size_t idx) { generator.getBlockRewardForAddress( reinterpret_cast<const cn::AccountPublicAddress&>(m_accounts[idx].address)); } std::error_code submitTransaction(ITransactionReader& tx) { auto data = tx.getTransactionData(); Transaction outTx; cn::fromBinaryArray(outTx, data); std::promise<std::error_code> result; m_node.relayTransaction(outTx, [&result](std::error_code ec) { std::promise<std::error_code> detachedPromise = std::move(result); detachedPromise.set_value(ec); }); return result.get_future().get(); } protected: boost::scoped_array<TransfersObserver> m_transferObservers; std::vector<AccountKeys> m_accounts; std::vector<ITransfersSubscription*> m_subscriptions; logging::ConsoleLogger m_logger; cn::Currency m_currency; TestBlockchainGenerator generator; INodeTrivialRefreshStub m_node; BlockchainSynchronizer m_sync; TransfersSyncronizer m_transfersSync; std::promise<std::error_code> syncCompleted; std::future<std::error_code> syncCompletedFuture; }; TEST_F(TransfersApi, testSubscriptions) { addAccounts(1); m_transfersSync.addSubscription(createSubscription(0)); std::vector<AccountPublicAddress> subscriptions; m_transfersSync.getSubscriptions(subscriptions); const auto& addr = m_accounts[0].address; ASSERT_EQ(1, subscriptions.size()); ASSERT_EQ(addr, subscriptions[0]); ASSERT_TRUE(m_transfersSync.getSubscription(addr) != 0); ASSERT_TRUE(m_transfersSync.removeSubscription(addr)); subscriptions.clear(); m_transfersSync.getSubscriptions(subscriptions); ASSERT_EQ(0, subscriptions.size()); } TEST_F(TransfersApi, syncOneBlock) { addAccounts(2); subscribeAccounts(); generator.getBlockRewardForAddress(m_accounts[0].address); generator.generateEmptyBlocks(15); startSync(); auto& tc1 = m_transfersSync.getSubscription(m_accounts[0].address)->getContainer(); auto& tc2 = m_transfersSync.getSubscription(m_accounts[1].address)->getContainer(); ASSERT_NE(&tc1, &tc2); ASSERT_GT(tc1.balance(ITransfersContainer::IncludeAll), 0); ASSERT_GT(tc1.transfersCount(), 0); ASSERT_EQ(0, tc2.transfersCount()); } TEST_F(TransfersApi, syncMinerAcc) { addMinerAccount(); subscribeAccounts(); generator.generateEmptyBlocks(10); startSync(); ASSERT_NE(0, m_subscriptions[0]->getContainer().transfersCount()); } namespace { std::unique_ptr<ITransaction> createMoneyTransfer( uint64_t amount, uint64_t fee, const AccountKeys& senderKeys, const AccountPublicAddress& reciever, ITransfersContainer& tc) { std::vector<TransactionOutputInformation> transfers; tc.getOutputs(transfers, ITransfersContainer::IncludeAllUnlocked); auto tx = createTransaction(); std::vector<std::pair<transaction_types::InputKeyInfo, KeyPair>> inputs; uint64_t foundMoney = 0; for (const auto& t : transfers) { transaction_types::InputKeyInfo info; info.amount = t.amount; transaction_types::GlobalOutput globalOut; globalOut.outputIndex = t.globalOutputIndex; globalOut.targetKey = t.outputKey; info.outputs.push_back(globalOut); info.realOutput.outputInTransaction = t.outputInTransaction; info.realOutput.transactionIndex = 0; info.realOutput.transactionPublicKey = t.transactionPublicKey; KeyPair kp; tx->addInput(senderKeys, info, kp); inputs.push_back(std::make_pair(info, kp)); foundMoney += info.amount; if (foundMoney >= amount + fee) { break; } } // output to reciever tx->addOutput(amount, reciever); // change uint64_t change = foundMoney - amount - fee; if (change) { tx->addOutput(change, senderKeys.address); } for (size_t inputIdx = 0; inputIdx < inputs.size(); ++inputIdx) { tx->signInputKey(inputIdx, inputs[inputIdx].first, inputs[inputIdx].second); } return tx; } } TEST_F(TransfersApi, moveMoney) { addMinerAccount(); addAccounts(2); subscribeAccounts(); generator.generateEmptyBlocks(2 * m_currency.minedMoneyUnlockWindow()); // sendAmount is an even number uint64_t sendAmount = (get_outs_money_amount(generator.getBlockchain()[1].baseTransaction) / 4) * 2; auto fee = m_currency.minimumFee(); startSync(); auto& tc0 = m_subscriptions[0]->getContainer(); ASSERT_LE(sendAmount, tc0.balance(ITransfersContainer::IncludeAllUnlocked)); auto tx = createMoneyTransfer(sendAmount, fee, m_accounts[0], m_accounts[1].address, tc0); submitTransaction(*tx); refreshSync(); ASSERT_EQ(1, m_transferObservers[1].m_transfers.size()); ASSERT_EQ(tx->getTransactionHash(), m_transferObservers[1].m_transfers[0]); auto& tc1 = m_subscriptions[1]->getContainer(); ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAll)); ASSERT_EQ(0, tc1.balance(ITransfersContainer::IncludeAllUnlocked)); generator.generateEmptyBlocks(m_currency.minedMoneyUnlockWindow()); // unlock money refreshSync(); ASSERT_EQ(sendAmount, tc1.balance(ITransfersContainer::IncludeAllUnlocked)); auto tx2 = createMoneyTransfer(sendAmount / 2, fee, m_accounts[1], m_accounts[2].address, tc1); submitTransaction(*tx2); refreshSync(); ASSERT_EQ(2, m_transferObservers[1].m_transfers.size()); ASSERT_EQ(tx2->getTransactionHash(), m_transferObservers[1].m_transfers.back()); ASSERT_EQ(sendAmount / 2 - fee, m_subscriptions[1]->getContainer().balance(ITransfersContainer::IncludeAll)); ASSERT_EQ(sendAmount / 2, m_subscriptions[2]->getContainer().balance(ITransfersContainer::IncludeAll)); } struct lessOutKey { bool operator()(const TransactionOutputInformation& t1, const TransactionOutputInformation& t2) { return std::hash<PublicKey>()(t1.outputKey) < std::hash<PublicKey>()(t2.outputKey); } }; bool compareStates(TransfersSyncronizer& sync1, TransfersSyncronizer& sync2) { std::vector<AccountPublicAddress> subs; sync1.getSubscriptions(subs); for (const auto& s : subs) { auto& tc1 = sync1.getSubscription(s)->getContainer(); if (sync2.getSubscription(s) == nullptr) return false; auto& tc2 = sync2.getSubscription(s)->getContainer(); std::vector<TransactionOutputInformation> out1; std::vector<TransactionOutputInformation> out2; tc1.getOutputs(out1); tc2.getOutputs(out2); std::sort(out1.begin(), out1.end(), lessOutKey()); std::sort(out2.begin(), out2.end(), lessOutKey()); if (out1 != out2) return false; } return true; } TEST_F(TransfersApi, state) { addMinerAccount(); subscribeAccounts(); generator.generateEmptyBlocks(20); startSync(); m_sync.stop(); std::stringstream memstm; m_transfersSync.save(memstm); m_sync.start(); BlockchainSynchronizer bsync2(m_node, m_currency.genesisBlockHash()); TransfersSyncronizer sync2(m_currency, m_logger, bsync2, m_node); for (size_t i = 0; i < m_accounts.size(); ++i) { sync2.addSubscription(createSubscription(i)); } sync2.load(memstm); // compare transfers ASSERT_TRUE(compareStates(m_transfersSync, sync2)); // generate more blocks generator.generateEmptyBlocks(10); refreshSync(); syncCompleted = std::promise<std::error_code>(); syncCompletedFuture = syncCompleted.get_future(); bsync2.addObserver(this); bsync2.start(); syncCompletedFuture.get(); bsync2.removeObserver(this); // check again ASSERT_TRUE(compareStates(m_transfersSync, sync2)); } TEST_F(TransfersApi, sameTrackingKey) { size_t offset = 2; // miner account + ordinary account size_t paymentAddresses = 1000; size_t payments = 10; addMinerAccount(); addAccounts(1); addPaymentAccounts(paymentAddresses); subscribeAccounts(); for (size_t i = 0; i < payments; ++i) { generateMoneyForAccount(i + offset); } startSync(); for (size_t i = 0; i < payments; ++i) { auto sub = m_subscriptions[offset + i]; EXPECT_NE(0, sub->getContainer().balance(ITransfersContainer::IncludeAll)); } }
#include "SimFastTiming/FastTimingCommon/interface/SimpleElectronicsSimInMIPs.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" using namespace ftl; SimpleElectronicsSimInMIPs::SimpleElectronicsSimInMIPs(const edm::ParameterSet& pset) : debug_(pset.getUntrackedParameter<bool>("debug", false)), adcNbits_(pset.getParameter<uint32_t>("adcNbits")), tdcNbits_(pset.getParameter<uint32_t>("tdcNbits")), adcSaturation_MIP_(pset.getParameter<double>("adcSaturation_MIP")), adcLSB_MIP_(adcSaturation_MIP_ / std::pow(2., adcNbits_)), adcThreshold_MIP_(pset.getParameter<double>("adcThreshold_MIP")), toaLSB_ns_(pset.getParameter<double>("toaLSB_ns")) {} void SimpleElectronicsSimInMIPs::run(const ftl::FTLSimHitDataAccumulator& input, FTLDigiCollection& output) const { FTLSimHitData chargeColl, toa; for (FTLSimHitDataAccumulator::const_iterator it = input.begin(); it != input.end(); it++) { chargeColl.fill(0.f); toa.fill(0.f); for (size_t i = 0; i < it->second.hit_info[0].size(); i++) { //time of arrival float finalToA = (it->second).hit_info[1][i]; while (finalToA < 0.f) finalToA += 25.f; while (finalToA > 25.f) finalToA -= 25.f; toa[i] = finalToA; // collected charge (in this case in MIPs) chargeColl[i] = (it->second).hit_info[0][i]; } //run the shaper to create a new data frame FTLDataFrame rawDataFrame(it->first); runTrivialShaper(rawDataFrame, chargeColl, toa); updateOutput(output, rawDataFrame); } } void SimpleElectronicsSimInMIPs::runTrivialShaper(FTLDataFrame& dataFrame, const ftl::FTLSimHitData& chargeColl, const ftl::FTLSimHitData& toa) const { bool debug = debug_; #ifdef EDM_ML_DEBUG for (int it = 0; it < (int)(chargeColl.size()); it++) debug |= (chargeColl[it] > adcThreshold_fC_); #endif if (debug) edm::LogVerbatim("FTLSimpleElectronicsSimInMIPs") << "[runTrivialShaper]" << std::endl; //set new ADCs for (int it = 0; it < (int)(chargeColl.size()); it++) { //brute force saturation, maybe could to better with an exponential like saturation const uint32_t adc = std::floor(std::min(chargeColl[it], adcSaturation_MIP_) / adcLSB_MIP_); const uint32_t tdc_time = std::floor(toa[it] / toaLSB_ns_); FTLSample newSample; newSample.set(chargeColl[it] > adcThreshold_MIP_, false, tdc_time, adc); dataFrame.setSample(it, newSample); if (debug) edm::LogVerbatim("FTLSimpleElectronicsSimInMIPs") << adc << " (" << chargeColl[it] << "/" << adcLSB_MIP_ << ") "; } if (debug) { std::ostringstream msg; dataFrame.print(msg); edm::LogVerbatim("FTLSimpleElectronicsSimInMIPs") << msg.str() << std::endl; } } void SimpleElectronicsSimInMIPs::updateOutput(FTLDigiCollection& coll, const FTLDataFrame& rawDataFrame) const { int itIdx(9); if (rawDataFrame.size() <= itIdx + 2) return; FTLDataFrame dataFrame(rawDataFrame.id()); dataFrame.resize(5); bool putInEvent(false); for (int it = 0; it < 5; ++it) { dataFrame.setSample(it, rawDataFrame[itIdx - 2 + it]); if (it == 2) putInEvent = rawDataFrame[itIdx - 2 + it].threshold(); } if (putInEvent) { coll.push_back(dataFrame); } }
//知识点:贪心 /* 将输入数列进行排序 可以发现: 1.若此时最大的,最小的两数之和<=w 那么将这两个数组成一对,一定是较优的 2.若此时最大,最小的两数之和>w 那么不再有数,能与最大的数组成一组 则将最大的数单独作为一组, 一定是较优的. 按照上述法则, 使用首尾两指针模拟即可 */ #include<cstdio> #include<algorithm> #include<ctype.h> const int MARX = 3e4+10; //============================================================= int w,n,ans , p[MARX]; //============================================================= inline int read() { int fl=1,w=0;char ch=getchar(); while(!isdigit(ch) && ch!='-') ch=getchar(); if(ch=='-') fl=-1; while(isdigit(ch)){w=w*10+ch-'0',ch=getchar();} return fl*w; } //============================================================= signed main() { w=read(),n=read(); for(int i=1;i<=n;i++) p[i]=read(); std::sort(p+1,p+n+1);//排序 for(int l=1,r=n;l<=r;) { if(p[l]+p[r]<=w) l++,r--,ans++;//两个组成一组 else r--,ans++;//将最大的单独组成一组 } printf("%d",ans); }
#include "rsa.h" #include <iostream> int main() { RSA rsa; std::cout << "¹«Ô¿£º"<<rsa.GetPkey() << std::endl; rsa.EncryptionFile("test.txt", "test.ecrept.txt"); rsa.DecryptFile("test.ecrept.txt", "test.decrept.txt"); return 0; }
#ifndef wali_KEY_SET_SOURCE_GUARD #define wali_KEY_SET_SOURCE_GUARD 1 /*! * @author Amanda Burton */ #include "wali/Common.hpp" #include "wali/KeySource.hpp" #include "wali/KeyContainer.hpp" #include <set> namespace wali { class KeySetSource : public wali::KeySource { public: KeySetSource( std::set<Key> kys ); virtual ~KeySetSource(); virtual bool equal( KeySource* rhs ); virtual size_t hash() const; virtual std::ostream& print( std::ostream& o ) const; // TODO: probably shouldn't be virtual virtual std::set<Key> get_key_set() const; protected: std::set<Key> kys; }; } #endif
#ifndef SERVER_H #define SERVER_H #define _WINSOCK_DEPRECATED_NO_WARNINGS #include <WinSock2.h> #include <iostream> #include <string> #include <pthread.h> #include <fstream> #include <list> #include <utility> #include <stdlib.h> #define NOMBRE_OCTET 2048 typedef struct connectedClient{ int ID; char* pseudo; SOCKET socket; }connectedClient; struct data; void* threadAcceptClient(void* p_data); void* threadSendMessage(void* p_data); void* threadReceiveMessage(void* p_data); /*! \class Server * *La classe gerant les connexions et les echanges de donnees avec les clients */ class Server { public: /*! * \brief Constructeur de la classe * * * */ Server(); Server(std::string pseudo, u_short port, u_short portMusic); int start(); /*! * \brief Methode permettant de recevoir les messages. * *Methode sous forme de boucle qui verifie qu'un client n'a pas envoye de message, et permet donc la reception de celui-ci en cas d'envoie de *la part d'un client * */ void receiveMessage(); /*! * \brief Methode permettant d'accepter des client * *Methode sous forme de boucle qui verifie constament que de nouveaux client ne tentent pas de se connecter * */ int acceptClient(); /*! * \brief Methode pour envoyer de la musique * *Methode permettant l'envoie d'une musique * * */ int sendMusic(); /*! * \brief Methode pour envoyer de la musique * *Methode permettant l'envoie d'une musique * * */ void sendMessage(); /*! * \brief Methode pour changer le port * *Methode permettant de changer le port utiliser pour envoyer et recevoir des messages * *\param port Nouveau port. * */ void setPort(u_short port); /*! * \brief Methode pour changer dle port musique * *Methode permettant de changer le port utiliser pour transfere la musique * *\param port Nouveau port. * */ void setMusicPort(u_short port); /*! * \brief Methode pour changer le pseudo * *Methode permettant de changer le pseudo du serveur * *\param pseudo Nouveau Pseudo qui va remplacer l'ancien. * */ void setPseudo(std::string pseudo); int getError(); u_short getPort(); u_short getPortMusic(); char* getBufer(); private: SOCKET *m_sockServer;/*!< Socket principale du serveur*/ SOCKET *m_sockMusic;/*!< Socket permettant d'envoyer de la musique*/ SOCKADDR_IN m_sin; SOCKADDR_IN m_sinMusic; SOCKADDR_IN m_cSin; connectedClient m_lastClient;/*!< Donnees du dernier client s'etant connecte*/ std::string *m_pseudo;/*!< Pseudo de l'utilisateur du serveur*/ std::string *m_message;/*!< Message saisi et envoye par le serveur*/ u_short *m_port;/*!< Port principal qu'ecoute le serveur*/ u_short *m_portMusic;/*!< Port permettant d'envoyer de la musique*/ char *m_buffer;/*!< Buffer contenant les messages recus*/ char *m_bufferMusic;/*!< Buffer contenant les donnees du ficier musique a envoyer*/ int *m_error;/*!< Variable contenant la derniere erreur rencontree*/ int *m_resultat;/*!< Variable contenant le resultat de la derniere action*/ std::list<connectedClient> listeClient;/*!< List des client conectes*/ }; typedef struct data{ Server server; pthread_mutex_t mutex; }data; #endif
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <string.h> using namespace std; #define MAXLEN 50 struct Data{ char key[10]; char value[10]; int id; }; struct QueueType{ Data node[MAXLEN+1]; int front; int tail; }; void QInit(QueueType &QT){ QT.front = 0; QT.tail = 0; } int QIsEmpty(QueueType &QT){ if(QT.front == QT.tail) return 1; else return 0; } int QIsFull(QueueType &QT){ if(MAXLEN == (QT.tail-QT.front)) return 1; else return 0; } void QPush(QueueType &QT, Data node){ if(MAXLEN == (QT.tail-QT.front)){ cout<<"Queue is Full, Push Failed."<<endl; return; } QT.node[QT.tail++] = node; return; } int QPop(QueueType &QT, Data &node){ if(QT.front == QT.tail){ cout<<"Queue is Empty, Pop Failed."<<endl; return 0; } node = QT.node[QT.front++]; return 1; } void QShow(QueueType &QT){ if(QT.front == QT.tail){ cout<<"Empty Queue."<<endl; return; } cout<<"============ </> Show Queue ============="<<endl; int index; for(index = QT.front; index < QT.tail; index++) cout<<QT.node[index].key<<" "<<QT.node[index].value<<" "<<QT.node[index].id<<endl; cout<<"============ Show Queue </> ============="<<endl; return; } void QTClear(QueueType &QT){ QT.front = 0; QT.tail = 0; return; } void QueueTest(){ QueueType queue; QInit(queue); Data node; strcpy(node.key, "name"); strcpy(node.value, "localhost"); node.id = 0; QPush(queue, node); strcpy(node.key, "port"); strcpy(node.value, "8080"); node.id = 1; QPush(queue, node); strcpy(node.key, "user"); strcpy(node.value, "admin"); node.id = 2; QPush(queue, node); QShow(queue); Data popnode; QPop(queue, popnode); QPop(queue, popnode); QShow(queue); } int main(int args, char** argv){ QueueTest(); return 1; }
#include <memory> #include <vector> #include "gmock/gmock.h" #include "explicit_transversals.h" #include "orbits.h" #include "perm.h" #include "perm_set.h" #include "schreier_tree.h" #include "test_main.cc" using cgtl::ExplicitTransversals; using cgtl::Orbit; using cgtl::Perm; using cgtl::PermSet; using cgtl::SchreierTree; using testing::UnorderedElementsAreArray; template <typename T> class SchreierStructureTest : public testing::Test {}; using SchreierStructureTypes = ::testing::Types<ExplicitTransversals, SchreierTree>; TYPED_TEST_CASE(SchreierStructureTest, SchreierStructureTypes); TYPED_TEST(SchreierStructureTest, CanConstructSchreierStructures) { unsigned n = 8; PermSet const generators { Perm(n, {{1, 2, 3}}), Perm(n, {{1, 3}}), Perm(n, {{4, 6, 5}}), Perm(n, {{5, 6}, {7, 8}}) }; std::vector<unsigned> expected_orbits[] = { {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, {4, 5, 6}, {4, 5, 6}, {4, 5, 6}, {7, 8}, {7, 8} }; PermSet expected_transversals[] = { { Perm(n), Perm(n, {{1, 2, 3}}), Perm(n, {{1, 3}}) }, { Perm(n, {{1, 3, 2}}), Perm(n), Perm(n, {{1, 2, 3}}) }, { Perm(n, {{1, 2, 3}}), Perm(n, {{1, 3, 2}}), Perm(n) }, { Perm(n), Perm(n, {{4, 5, 6}}), Perm(n, {{4, 6, 5}}) }, { Perm(n, {{4, 6, 5}}), Perm(n), Perm(n, {{5, 6}, {7, 8}}) }, { Perm(n, {{4, 5, 6}}), Perm(n, {{4, 6, 5}}), Perm(n) }, { Perm(n), Perm(n, {{5, 6}, {7, 8}}) }, { Perm(n, {{5, 6}, {7, 8}}), Perm(n) } }; for (unsigned i = 0u; i < n; ++i) { auto schreier_structure(std::make_shared<TypeParam>(n, i + 1u, generators)); Orbit::generate(i + 1u, generators, schreier_structure); EXPECT_EQ(i + 1u, schreier_structure->root()) << "Root correct"; EXPECT_THAT(expected_orbits[i], UnorderedElementsAreArray(schreier_structure->nodes())) << "Node (orbit) correct " << "(root is " << i + 1u << ")."; for (unsigned x = 1u; x < n; ++x) { auto it(std::find(expected_orbits[i].begin(), expected_orbits[i].end(), x)); bool contained = it != expected_orbits[i].end(); EXPECT_EQ(contained, schreier_structure->contains(x)) << "Can identify contained elements " << "(root is " << i + 1u << ", element is " << x << ")."; } auto labels(schreier_structure->labels()); std::vector<Perm> labels_vect(labels.begin(), labels.end()); std::vector<Perm> gen_vect(generators.begin(), generators.end()); EXPECT_THAT(labels_vect, UnorderedElementsAreArray(gen_vect)) << "Edge labels correct " << "(root is " << i + 1u << ")."; for (unsigned j = 0u; j < expected_orbits[i].size(); ++j) { unsigned origin = expected_orbits[i][j]; EXPECT_EQ(expected_transversals[i][j], schreier_structure->transversal(origin)) << "Transversal correct " << "(root is " << i + 1u << ", origin is " << origin << ")."; } } }
// // Created by biega on 22.03.2018. // #ifndef TANKSMAPGENERATOR_MAPMODIFICATOR_H #define TANKSMAPGENERATOR_MAPMODIFICATOR_H #include "map.h" class MapModificator { public: Map* generateMap(int level, int size); //generates symbol map Map* modify(int x, int y, char a, Map* m); //modifyies a symbol of coordinates (x,y) to the symbol a Map* freeMemory(Map* m); //free memory allocated for object map }; #endif //TANKSMAPGENERATOR_MAPMODIFICATOR_H
#pragma once class MonsterAction; //モンスターアクションのローディングを担っている class MonsterActionManeger:public GameObject { public: //モンスターに技を加えるときに使うローダー //id: 技のID //target: 対象のモンスター static MonsterAction* LoadAction(int id,int target,...); /*enum en_action { en_Chase, en_Atack, en_Leave, en_Fire, };*/ private: };
/* -*- 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. * */ #ifndef OP_SEPARATOR_H #define OP_SEPARATOR_H #include "modules/widgets/OpWidget.h" class OpSeparator : public OpWidget { public: static OP_STATUS Construct(OpSeparator** obj) { *obj = OP_NEW(OpSeparator, ()); return *obj ? OpStatus::OK : OpStatus::ERR_NO_MEMORY; } OpSeparator() { GetBorderSkin()->SetImage ( "Horizontal Separator" ); SetSkinned ( TRUE ); } virtual Type GetType() { return WIDGET_TYPE_SEPARATOR; } }; #endif // OP_SEPARATOR_H
#include <string> #include <iostream> using namespace std; #include "City.h" City::City() { } City::City(string name) { this->name = name; } City::City(string origin, string name, string departure, string arrival, string cost) { this->origin = origin; this->name = name; this->departure = Time(departure); this->arrival = Time(arrival); this->cost = stoi(cost.substr(1, cost.length())); }
/* -*- Mode: c++; tab-width: 4; 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. * * @author Patricia Aas (psmaas) */ #include "core/pch.h" #include "modules/util/OpHashTable.h" #include "platforms/viewix/FileHandlerManager.h" #include "platforms/viewix/src/HandlerElement.h" #include "platforms/viewix/src/FileHandlerStore.h" #include "platforms/viewix/src/FileHandlerManagerUtilities.h" #include "platforms/viewix/src/nodes/ApplicationNode.h" #include "platforms/viewix/src/nodes/MimeTypeNode.h" #include "platforms/viewix/src/input_files/DefaultListFile.h" #include "platforms/viewix/src/input_files/DesktopFile.h" #include "platforms/viewix/src/input_files/GlobsFile.h" #include "platforms/viewix/src/input_files/MimeInfoCacheFile.h" #include "platforms/viewix/src/input_files/ProfilercFile.h" #include "platforms/viewix/src/input_files/GnomeVFSFile.h" /*********************************************************************************** ** FileHandlerStore - Constructor ** ** ** ** ***********************************************************************************/ FileHandlerStore::FileHandlerStore() { m_mime_table.SetHashFunctions(&m_hash_function); m_globs_table.SetHashFunctions(&m_hash_function); m_default_table.SetHashFunctions(&m_hash_function); m_application_table.SetHashFunctions(&m_hash_function); } /*********************************************************************************** ** FileHandlerStore - Destructor ** ** ** ** ***********************************************************************************/ FileHandlerStore::~FileHandlerStore() { EmptyStore(); } /*********************************************************************************** ** EmptyStore ** ** ** ** ***********************************************************************************/ void FileHandlerStore::EmptyStore() { OP_STATUS ret_val; // Empty out the application table: OpHashIterator* it = GetApplicationTable().GetIterator(); ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { uni_char * key = (uni_char *)it->GetKey(); ApplicationNode * node = (ApplicationNode *)it->GetData(); OP_DELETEA(key); OP_DELETE(node); ret_val = it->Next(); } OP_DELETE(it); // Empty out the globs table: it = GetGlobsTable().GetIterator(); ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { uni_char * key = (uni_char *)it->GetKey(); GlobNode * node = (GlobNode *)it->GetData(); OP_DELETEA(key); OP_DELETE(node); ret_val = it->Next(); } OP_DELETE(it); // Empty out the default table: it = GetDefaultTable().GetIterator(); ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { uni_char * key = (uni_char *)it->GetKey(); OP_DELETEA(key); // node was deleted when emptying application table. ret_val = it->Next(); } OP_DELETE(it); m_mime_table.RemoveAll(); m_globs_table.RemoveAll(); m_default_table.RemoveAll(); m_application_table.RemoveAll(); m_nodelist.DeleteAll(); m_nodelist.Clear(); m_complex_globs.DeleteAll(); m_complex_globs.Clear(); OP_ASSERT(GetNumberOfMimeTypes() == 0); } /*********************************************************************************** ** GetGlobsTable ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::InitGlobsTable(OpVector<OpString>& files) { // Initialize them: for(UINT32 i = 0; i < files.GetCount(); i++) { GlobsFile globs_file; globs_file.Parse(*files.Get(i)); } return OpStatus::OK; } /*********************************************************************************** ** GetDefaultTable ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::InitDefaultTable(OpVector<OpString>& profilerc_files, OpVector<OpString>& files) { UINT32 i = 0; for(i = 0; i < profilerc_files.GetCount(); i++) { ProfilercFile profilerc_file; profilerc_file.Parse(*profilerc_files.Get(i)); } for(i = 0; i < files.GetCount(); i++) { DefaultListFile default_file; default_file.Parse(*files.Get(i)); } return OpStatus::OK; } /*********************************************************************************** ** GetMimeTable ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::InitMimeTable(OpVector<OpString>& files, OpVector<OpString>& gnome_files) { UINT32 i = 0; for(i = 0; i < files.GetCount(); i++) { MimeInfoCacheFile mime_info_file; mime_info_file.Parse(*files.Get(i)); } for(i = 0; i < gnome_files.GetCount(); i++) { GnomeVFSFile gnome_file; gnome_file.Parse(*gnome_files.Get(i)); } return OpStatus::OK; } /*********************************************************************************** ** GetMimeTypeNode ** ** Gets a mimenode and returns a pointer to it. ** ** @return pointer to mimenode (or 0 if it doesn't exist) ** ** NOTE: ***********************************************************************************/ MimeTypeNode* FileHandlerStore::GetMimeTypeNode(const OpStringC & mime_type) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // mime_type has to be set OP_ASSERT(mime_type.HasContent()); if (mime_type.HasContent()) { void *node = 0; // Look up mimetype in mime table - Reuse node if possible: m_mime_table.GetData((void *) mime_type.CStr(), &node); return (MimeTypeNode*) node; } return 0; } /*********************************************************************************** ** MakeMimeTypeNode ** ** Makes a mimenode (if it doesn't already exist) and returns a pointer to it. ** ** @return pointer to created mimenode (or 0 if OOM) ** ** NOTE: ***********************************************************************************/ MimeTypeNode* FileHandlerStore::MakeMimeTypeNode(const OpStringC & mime_type) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // mime_type has to be set OP_ASSERT(mime_type.HasContent()); if(mime_type.IsEmpty()) return 0; //----------------------------------------------------- MimeTypeNode* node = GetMimeTypeNode(mime_type); if(!node) { node = OP_NEW(MimeTypeNode, (mime_type)); m_nodelist.Add(node); if(node) { const uni_char * key = node->GetMimeTypes().Get(0)->CStr(); m_mime_table.Add((void *) key, (void *) node); } } return node; } /*********************************************************************************** ** LinkMimeTypeNode ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::LinkMimeTypeNode(const OpStringC & mime_type, MimeTypeNode* node, BOOL subclass_type) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // mime_type has to be set OP_ASSERT(mime_type.HasContent()); if(mime_type.IsEmpty()) return OpStatus::ERR; // node has to be set OP_ASSERT(node); if(!node) return OpStatus::ERR; //----------------------------------------------------- //Make sure the mimetype is not already linked : MimeTypeNode* existing_node = GetMimeTypeNode(mime_type); if(!existing_node) { OpString * mime_type_str = 0; if(subclass_type) mime_type_str = node->AddSubclassType(mime_type); else mime_type_str = node->AddMimeType(mime_type); if(!mime_type_str) return OpStatus::ERR_NO_MEMORY; m_mime_table.Add((void *) mime_type_str->CStr(), (void *) node); } return OpStatus::OK; } /*********************************************************************************** ** MergeMimeNodes ** ** Merges node_1 into node_2 ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::MergeMimeNodes(MimeTypeNode* node_1, MimeTypeNode* node_2) { if(!node_1 || !node_2) return OpStatus::OK; if(node_1 == node_2) return OpStatus::OK; unsigned int i = 0; // Remove referrences to node_1 for(i = 0; i < node_1->GetMimeTypes().GetCount(); i++) { // Get the mimetype : OpString * mime_type_1 = node_1->GetMimeTypes().Get(i); // Remove the mapping: void * tmp_node = 0; OpStatus::Ignore(m_mime_table.Remove(mime_type_1->CStr(), &tmp_node)); OP_ASSERT((MimeTypeNode*)tmp_node == node_1); } // Make sure node_1 is deleted even if we are not successful in the merging m_nodelist.RemoveByItem(node_1); OpAutoPtr<MimeTypeNode> anchor(node_1); // Merge the mimetypes and map the mime types to node_2 instead for(i = 0; i < node_1->GetMimeTypes().GetCount(); i++) { // Get the mimetype : OpString * mime_type_1 = node_1->GetMimeTypes().Get(i); // Add the new mapping: OpString * mime_type_2 = node_2->AddMimeType(mime_type_1->CStr()); if(!mime_type_2) return OpStatus::ERR_NO_MEMORY; OP_ASSERT(m_mime_table.Contains((void *) mime_type_2->CStr()) == FALSE); RETURN_IF_ERROR(m_mime_table.Add((void *) mime_type_2->CStr(), (void *) node_2)); } // Merge the default if(node_1->GetDefaultApp()) node_2->SetDefault(node_1->GetDefaultApp()); // Merge the applications OpHashIterator* it = node_1->m_applications->GetIterator(); OP_STATUS status = it->First(); while (OpStatus::IsSuccess(status)) { ApplicationNode * app = (ApplicationNode*) it->GetData(); status = node_2->AddApplication(app); if(OpStatus::IsError(status)) break; else status = it->Next(); } OP_DELETE(it); return status; } /*********************************************************************************** ** GetGlobNode ** ** Gets a globnode and returns a pointer to it. ** ** @return pointer to globnode (or 0 if it doesn't exist) ** ** NOTE: ***********************************************************************************/ GlobNode* FileHandlerStore::GetGlobNode(const OpStringC & glob) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // glob has to be set OP_ASSERT(glob.HasContent()); if (glob.HasContent()) { void* node = 0; //Look up mimetype in mime table - Reuse node if possible: m_globs_table.GetData((void *) glob.CStr(), &node); return (GlobNode*) node; } return 0; } /*********************************************************************************** ** MakeGlobNode ** ** Makes a globnode (if it doesn't already exist) and returns a pointer to it. ** ** @return pointer to created globnode (or 0 if OOM) ** ** NOTE: ***********************************************************************************/ GlobNode* FileHandlerStore::MakeGlobNode(const OpStringC & glob, const OpStringC & mime_type, GlobType type) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- // mime_type has to be set OP_ASSERT(mime_type.HasContent()); if(mime_type.IsEmpty()) return 0; // glob has to be set OP_ASSERT(glob.HasContent()); if(glob.IsEmpty()) return 0; //----------------------------------------------------- GlobNode* node = GetGlobNode(glob); if(!node) { node = OP_NEW(GlobNode, (glob, mime_type, GLOB_TYPE_SIMPLE)); if(node) { m_globs_table.Add((void *) node->GetKey(), (void *) node); } } return node; } /*********************************************************************************** ** MakeApplicationNode ** ** Makes a application node and returns a pointer to it. ** ** @return pointer to created application node (or 0 if element is 0) ***********************************************************************************/ ApplicationNode* FileHandlerStore::MakeApplicationNode(HandlerElement* element) { if(!element) return 0; return MakeApplicationNode(0, 0, element->handler, 0, FALSE); } /*********************************************************************************** ** MakeApplicationNode ** ** Makes a application node and returns a pointer to it. ** ** @return pointer to created application node (or 0 if OOM or if both desktop_file_name ** and command are 0) ** ** NOTE: desktop_file_name, path, command and icon can all be 0, but either command ** or desktop_file_name have to be set. ***********************************************************************************/ ApplicationNode* FileHandlerStore::MakeApplicationNode(const OpStringC & desktop_file_name, const OpStringC & path, const OpStringC & comm, const OpStringC & icon, BOOL do_guessing) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Either desktop_file_name or command has to be set OP_ASSERT(desktop_file_name.HasContent() || comm.HasContent()); if(desktop_file_name.IsEmpty() && comm.IsEmpty()) return 0; //----------------------------------------------------- ApplicationNode* node = 0; OpString command; OpString desktop_filename; OpString desktop_path; command.Set(comm); desktop_filename.Set(desktop_file_name); desktop_path.Set(path); command.Strip(); desktop_filename.Strip(); desktop_path.Strip(); if (do_guessing && desktop_filename.IsEmpty() && command.HasContent()) FindDesktopFile(command, desktop_filename, desktop_path); // Look up application in application table - Reuse node if possible: void *lookup_node = 0; if (desktop_filename.HasContent()) m_application_table.GetData(desktop_filename.CStr(), &lookup_node); else if (command.HasContent()) m_application_table.GetData(command.CStr(), &lookup_node); else return NULL; // It did not have neither desktop_filename or command so just bail node = (ApplicationNode*) lookup_node; if (!node) //If no node was present make a new one and insert it into the table { node = OP_NEW(ApplicationNode, (desktop_filename, desktop_path, command, icon)); if(node) m_application_table.Add(node->GetKey(), node); } return node; } /*********************************************************************************** ** FindDesktopFile ** ** ** ** ***********************************************************************************/ OP_STATUS FileHandlerStore::FindDesktopFile(const OpStringC & command, OpString & desktop_filename, OpString & desktop_path) { OpAutoVector<OpString> words; FileHandlerManagerUtilities::SplitString(words, command, ' '); if(words.GetCount()) { OpString command_name; command_name.AppendFormat(UNI_L("%s.desktop"), words.Get(0)->CStr()); OpAutoVector<OpString> files; FileHandlerManager::GetManager()->FindDesktopFile(command_name, files); if(files.GetCount()) { OpString * fullpath = files.Get(0); OpString path; FileHandlerManagerUtilities::GetPath(*fullpath, path); OpString filename; FileHandlerManagerUtilities::StripPath(filename, *fullpath); desktop_filename.Set(filename.CStr()); desktop_path.Set(path.CStr()); } } return OpStatus::OK; } /*********************************************************************************** ** InsertIntoApplicationList ** ** Attempts to reuse an application node (or will attempt to create one) for the ** handler. If one is found/created, it will be added to the nodes applications ** list. ** ** @param node - head of a MimeTypeNode list ** @param desktop_file - name of desktop file for this application ** @param path - path to desktop file for this application ** ** NOTE: desktop_file, path and command can all be 0, but either command ** or desktop_file have to be set for MakeApplicationNode to succeed. ***********************************************************************************/ ApplicationNode * FileHandlerStore::InsertIntoApplicationList(MimeTypeNode* node, const OpStringC & desktop_file, const OpStringC & path, const OpStringC & command, BOOL default_app) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Mime-type node cannot be null OP_ASSERT(node); if(!node) return 0; //----------------------------------------------------- ApplicationNode * app = 0; app = MakeApplicationNode(desktop_file, path, command, 0); //OOM return InsertIntoApplicationList(node, app, default_app); } /*********************************************************************************** ** InsertIntoApplicationList ** ** Inserts the application into the mime nodes application list or makes it default ***********************************************************************************/ ApplicationNode * FileHandlerStore::InsertIntoApplicationList(MimeTypeNode* node, ApplicationNode * app, BOOL default_app) { //----------------------------------------------------- // Parameter checking: //----------------------------------------------------- //Mime-type node cannot be null OP_ASSERT(node); if(!node) return 0; OP_ASSERT(app); if(!app) return 0; //Application could not be created (OOM or error) //----------------------------------------------------- if(default_app) node->SetDefault(app); else node->AddApplication(app); return app; } /*********************************************************************************** ** PrintDefaultTable ** ** Prints the default table supplied using printf. ** ** @param the default table to be printed ** ** ***********************************************************************************/ void FileHandlerStore::PrintDefaultTable() { OpHashIterator* it = m_default_table.GetIterator(); printf("_____________________________________________________________________ \n"); printf("___________________________ DEFAULT TABLE ___________________________ \n"); printf("_____________________________________________________________________ \n"); INT32 i = 0; OP_STATUS ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { i++; uni_char * key = (uni_char *) it->GetKey(); OpString8 tmp; tmp.Set(key); printf("%d.\tKey : %s\n", i, tmp.CStr()); MimeTypeNode* node = (MimeTypeNode* ) it->GetData(); if(node) { ApplicationNode * app = node->GetDefaultApp(); if(app) { OpString8 tmp2; tmp.Set(app->GetDesktopFileName().CStr()); tmp2.Set(app->GetPath().CStr()); //OOM printf("\tValue : %s \t %s \n", tmp.CStr(), tmp2.CStr()); } } ret_val = it->Next(); } printf("_____________________________________________________________________ \n"); } /*********************************************************************************** ** PrintMimeTable ** ** Prints the mime table supplied using printf. ** ** @param the mime table to be printed ** ** ***********************************************************************************/ void FileHandlerStore::PrintMimeTable() { OpHashIterator* it = m_mime_table.GetIterator(); printf("_____________________________________________________________________ \n"); printf("___________________________ MIME TABLE ______________________________ \n"); printf("_____________________________________________________________________ \n"); INT32 i = 0; OP_STATUS ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { i++; uni_char * key = (uni_char *) it->GetKey(); OpString8 tmp; tmp.Set(key); printf("%d.\tKey : %s\n", i, tmp.CStr()); MimeTypeNode* node = (MimeTypeNode* ) it->GetData(); if(node) { ApplicationNode * app = 0; OpHashIterator* it2 = node->m_applications->GetIterator(); OP_STATUS ret_val2 = it2->First(); while (OpStatus::IsSuccess(ret_val2)) { app = (ApplicationNode*) it2->GetData(); if(app) { OpString8 tmp2; tmp.Set(app->GetDesktopFileName().CStr()); tmp2.Set(app->GetCommand().CStr()); //OOM printf("\tValue : %s \t %s \n", tmp.CStr(), tmp2.CStr()); } ret_val2 = it2->Next(); } } ret_val = it->Next(); } printf("_____________________________________________________________________ \n"); } /*********************************************************************************** ** PrintGlobsTable ** ** Prints the globs table supplied using printf. ** ** @param the globs table to be printed ** ** ***********************************************************************************/ void FileHandlerStore::PrintGlobsTable() { OpHashIterator* it = m_globs_table.GetIterator(); printf("_____________________________________________________________________ \n"); printf("___________________________ GLOBS TABLE _____________________________ \n"); printf("_____________________________________________________________________ \n"); INT32 i = 0; OP_STATUS ret_val = it->First(); while (OpStatus::IsSuccess(ret_val)) { i++; OpString8 tmp; OpString8 tmp2; uni_char * key = (uni_char *) it->GetKey(); tmp.Set(key); printf("%d.\tKey : %s\n", i, tmp.CStr()); GlobNode* node = (GlobNode* ) it->GetData(); if(node) { tmp.Set(node->GetGlob().CStr()); tmp2.Set(node->GetMimeType().CStr()); printf("\tValue : %s \t %s \n", tmp.CStr(), tmp2.CStr()); } ret_val = it->Next(); } printf("_____________________________________________________________________ \n"); } /*********************************************************************************** ** GetGlobNode ** ** ** ** ***********************************************************************************/ GlobNode * FileHandlerStore::GetGlobNode(const OpStringC & filename, BOOL strip_path) { OP_ASSERT(filename.HasContent()); // _GUESS_ based on extenstion : //Remove the path if strip_path is set : OpString file_name; if(strip_path) { FileHandlerManagerUtilities::StripPath(file_name, filename); } else { file_name.Set(filename.CStr()); } // Literal: GlobNode * node = GetGlobNode(file_name.CStr()); // Simple: if (!node) { OpAutoVector<OpString> globs; FileHandlerManagerUtilities::MakeGlobs(file_name, globs); for(UINT32 i = 0; i < globs.GetCount(); i++) { node = GetGlobNode(globs.Get(i)->CStr()); if(node) //Found break; } } // Complex: if(!node) { //TODO: Test for complex in vector } return node; }
#include "Phong.h" Phong::Phong() { ambientBRDF = new Lambertian; diffuseBRDF = new Lambertian; specularBRDF = new GlossySpecular; } Phong::~Phong() { delete ambientBRDF; delete diffuseBRDF; delete specularBRDF; } BRDF* Phong::getAmbientBRDF() { return ambientBRDF; } BRDF* Phong::getDiffuseBRDF() { return diffuseBRDF; } BRDF* Phong::getSpecularBRDF() { return specularBRDF; }
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; const int pri[44] = {2,3,5,7,13,17,19,31,6l,89,107,127,521,607,1279,2203,2281, 3217,4253,4423,9689,9941,11213,19937,21701,23209,44497,86243, 110503,132049,216091,756839,859433,1257787,1398269,2976221, 3021377,6972593,13466917,20996011,24036583,25964951,30402457, 32582657}; int main() { int p; while (scanf("%d",&p) != EOF) { bool ans = false; for (int i = 0;i < 44; i++) if (p == pri[i]) { ans = true; break; } if (ans) printf("YES\n"); else printf("NO\n"); } return 0; }
// Created on: 1994-11-03 // Created by: Marie Jose MARTZ // Copyright (c) 1994-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESToBRep_Actor_HeaderFile #define _IGESToBRep_Actor_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <Standard_Integer.hxx> #include <Transfer_ActorOfTransientProcess.hxx> #include <Message_ProgressRange.hxx> class Interface_InterfaceModel; class Standard_Transient; class Transfer_Binder; class Transfer_TransientProcess; class IGESToBRep_Actor; DEFINE_STANDARD_HANDLE(IGESToBRep_Actor, Transfer_ActorOfTransientProcess) //! This class performs the transfer of an Entity from //! IGESToBRep //! //! I.E. for each type of Entity, it invokes the appropriate Tool //! then returns the Binder which contains the Result class IGESToBRep_Actor : public Transfer_ActorOfTransientProcess { public: Standard_EXPORT IGESToBRep_Actor(); Standard_EXPORT void SetModel (const Handle(Interface_InterfaceModel)& model); //! ---Purpose By default continuity = 0 //! if continuity = 1 : try C1 //! if continuity = 2 : try C2 Standard_EXPORT void SetContinuity (const Standard_Integer continuity = 0); //! Return "thecontinuity" Standard_EXPORT Standard_Integer GetContinuity() const; Standard_EXPORT virtual Standard_Boolean Recognize (const Handle(Standard_Transient)& start) Standard_OVERRIDE; Standard_EXPORT virtual Handle(Transfer_Binder) Transfer (const Handle(Standard_Transient)& start, const Handle(Transfer_TransientProcess)& TP, const Message_ProgressRange& theProgress = Message_ProgressRange()) Standard_OVERRIDE; //! Returns the tolerance which was actually used, either from //! the file or from statics Standard_EXPORT Standard_Real UsedTolerance() const; DEFINE_STANDARD_RTTIEXT(IGESToBRep_Actor,Transfer_ActorOfTransientProcess) protected: private: Handle(Interface_InterfaceModel) themodel; Standard_Integer thecontinuity; Standard_Real theeps; }; #endif // _IGESToBRep_Actor_HeaderFile
#include "Util.h" #include <ctime> #include "User.h" #include "Pisica.h" #include "Caine.h" #include "Iepure.h" #include "testoasa.h" #include "papagal.h" #include "iguana.h" #include "corb.h" #include "caracatita.h" #include "peste.h" #include "porumbel.h" #include "sarpe.h" #include "foca.h" void pause(int dur) { int temp = time(NULL) + dur; while(temp > time(NULL)); } void Load_Accounts(std::string name, std::string pass, DataBase *X, std::string date) { User *newUser = new User(name, pass, X, date); }
/* * SpewFiltering.hpp * * Created on: Apr 2, 2015 * Author: tomh */ #ifndef SPEWFILTERING_HPP_ #define SPEWFILTERING_HPP_ #include <string> //#include "boost/filesystem.hpp" namespace SpewFilteringSpace { const size_t SUCCESS = 0; const size_t ERROR_IN_COMMAND_LINE = 1; const size_t ERROR_UNHANDLED_EXCPTN = 2; const size_t HELP_SUCCESSFUL = 3; const size_t ERROR_FILE_WAS_NOT_FOUND = 4; const size_t ERROR_OUTPUT_FILE_PATH_NOT_FOUND = 5; class SpewFiltering { public: SpewFiltering() {}; virtual ~SpewFiltering() {}; typedef enum { PRODUCE_EVERY_FILE, APPLY_ALL_FILTERS, ONLY_PHONE_FILTER, ONLY_ACTION_SCRIPT_FILTER, ONLY_HANDSFREE_FILTER, ONLY_MAP_FILTER, ONLY_MTP_FILTER, NO_FILTER } SPEW_FILTER; typedef struct { std::string sInputFile; //boost::filesystem::path pthInput; std::string sOutputFile; //boost::filesystem::path output; SPEW_FILTER sfFilterToApply; } SpewFilteringParams; virtual int ConfigureFilteringParams( int & argc, char ** & argv, SpewFilteringParams & sfp ); bool ProduceFilteredSpewFiles( SpewFilteringParams & sfp ); bool ApplySpewFiltering( SpewFilteringParams & sfp ); private: std::string SpewFiltering::TrimWhiteSpace(const std::string & str, const std::string & whitespace = " \t"); }; } #endif /* SPEWFILTERING_HPP_ */
#include "server.h" #include<iostream> Server::Server() { } Server::~Server() { } void Server::Start() { std::cout << "(-TCP-) t or u (-UDP-)" << std::endl; std::cin >> mode; std::cout << "Set server port: "; std::cin >> port; std::cout << "Set max number of players: "; std::cin >> playersString; maxPlayers = std::stoi(playersString); connectedPlayers = 0; currentClientId = 0; if (mode == 'u') { Usocket.bind(port); do { sf::IpAddress rIp; unsigned short port; Usocket.receive(buffer, sizeof(buffer), received, rIp, port); if (received > 0) { computerID[port] = rIp; std::cout << "Received connection from Ip: " << rIp << " Running Port: " << port << " With clientName: " << buffer << std::endl; ServerClient* client = new ServerClient(); client->clientIp = rIp; client->clientPort = port; client->clientName = buffer; client->clientId = currentClientId; clients.push_back(client); currentClientId++; connectedPlayers++; } } while(connectedPlayers != maxPlayers); } if (mode == 't') { listener.listen(port); listener.accept(Tsocket); Tsocket.send(text.c_str(), text.length() + 1); Tsocket.receive(buffer, sizeof(buffer), received); std::cout << buffer << std::endl; tcpStatus = 's'; } } void Server::Run() { isRunning = true; std::cout << "Starting loop " << isRunning << std::endl; sf::Clock dtClock; float dt; while(isRunning) { dt = dtClock.getElapsedTime().asSeconds(); if (mode == 'u') { if (dt >= 2) { printf("\033c"); std::cout << "\x1B[2J\x1B[H"; dt = dtClock.restart().asSeconds(); std::string message = "stop server"; for(auto &c : clients) { StringToData(c, message); SendUDPPacket(c); ReceiveUDPPacket(c); } } } if (mode == 't') { if (tcpStatus == 's') { std::getline(std::cin, text); Tsocket.send(text.c_str(), text.length() + 1); tcpStatus = 'r'; } else if (tcpStatus == 'r') { Tsocket.receive(buffer, sizeof(buffer), received); if (received > 0) { std::cout << "Received: " << buffer << std::endl; tcpStatus = 's'; } } } } } void Server::StringToData(ServerClient* c, std::string message) { strncpy(c->serverData, message.c_str(), sizeof(c->serverData)); c->serverData[sizeof(c->serverData)-1] = '\0'; } void Server::SendUDPPacket(ServerClient* client) { if(Usocket.send(client->serverData, sizeof(client->serverData), client->clientIp, client->clientPort) == sf::Socket::Done) { std::cout << "succesfully send all data: " << client->serverData << std::endl; } } void Server::SendUDPPacketToAll(char data[50]) { for(auto &client : clients) { if(Usocket.send(data, 50, client->clientIp, client->clientPort) == sf::Socket::Done) { std::cout << "succesfully send all data to client with id: " << client->clientId << std::endl; } } } void Server::ReceiveUDPPacket(ServerClient* client) { std::size_t received; if(Usocket.receive(client->clientData, sizeof(client->clientData), received , client->clientIp, client->clientPort) == sf::Socket::Done) { if (received > 0) { //client->clientData = buffer; std::cout << "Received: " << client->clientData << std::endl; } } } /* void Server::SendTCPPacket(sf::Packet _packet) { Tsocket.send(_packet); _packet.clear(); } void Server::ReceiveTCPPacket(sf::Packet _packet) { Tsocket.receive(_packet); } */
class Solution { public: int minDistance(string word1, string word2) { int len1=word1.length(),len2=word2.length(); //dp[index1][index2]:前index1个word1字符转换成前index2个word2字符需要的最少步数 vector<vector<int>> dp(len1+1,vector<int>(len2+1)); for(int index1=0;index1<=len1;index1++){ for(int index2=0;index2<=len2;index2++){ if(index1 == 0) //从无到有显然要经历index2步插入操作 dp[index1][index2] = index2; else if(index2 == 0) //从有到无显然要经历index1步删除操作 dp[index1][index2] = index1; //三种操作方式 //1.word1删除末尾字符 dp[index1-1][index2]+1 //2.word1在末尾插入字符 dp[index1][index2-1]+1 //3.word1替换末尾字符(如果末尾字符本来就相等,就不用换了) dp[index1-1][index2-1]+(word1[index1-1]!=word2[index2-1] else dp[index1][index2] = min(min(dp[index1-1][index2]+1,dp[index1][index2-1]+1),dp[index1-1][index2-1]+(word1[index1-1]!=word2[index2-1])); //cout << dp[index1][index2] << " "; } //cout << endl; } return dp[len1][len2]; } };
/** * @file * @brief Reading from a PE module that is loaded within a remote process. */ #pragma once #include <windows.h> #include "pe_hdrs_helper.h" #include "pe_virtual_to_raw.h" #include "exports_mapper.h" #include "pe_dumper.h" namespace peconv { bool fetch_region_info(HANDLE processHandle, BYTE* start_addr, MEMORY_BASIC_INFORMATION &page_info); /** Fetch size of the memory region starting from the given address. */ size_t fetch_region_size(HANDLE processHandle, BYTE* start_addr); /** Fetch the allocation base of the memory region with the supplied start address. \param processHandle : handle of the process where the region of interest belongs \param start_addr : the address inside the region of interest \return the allocation base address of the memory region, or 0 if not found */ ULONGLONG fetch_alloc_base(HANDLE processHandle, BYTE* start_addr); /** Wrapper over ReadProcessMemory. Requires a handle with privilege PROCESS_VM_READ. If reading full buffer_size was not possible, it will keep trying to read smaller chunk, decreasing requested size by step_size in each iteration. Returns how many bytes were successfuly read. It is a workaround for errors such as FAULTY_HARDWARE_CORRUPTED_PAGE. */ size_t read_remote_memory(HANDLE processHandle, BYTE *start_addr, OUT BYTE* buffer, const size_t buffer_size, const SIZE_T step_size = 0x100); /** Reads the full memory area of a given size within a given process, skipping inaccessible pages. Requires a handle with privilege PROCESS_QUERY_INFORMATION. step_size is passed to the underlying read_remote_memory. */ size_t read_remote_area(HANDLE processHandle, BYTE *start_addr, OUT BYTE* buffer, const size_t buffer_size, const SIZE_T step_size = 0x100); /** Reads a PE header of the remote module within the given process. Requires a valid output buffer to be supplied (buffer). */ bool read_remote_pe_header(HANDLE processHandle, BYTE *moduleBase, OUT BYTE* buffer, const size_t bufferSize); /** Reads a PE section with a given number (sectionNum) from the remote module within the given process. The buffer of appropriate size is automatically allocated. After use, it should be freed by the function free_unaligned. The size of the buffer is writen into sectionSize. \return a buffer containing a copy of the section. */ peconv::UNALIGNED_BUF get_remote_pe_section(HANDLE processHandle, BYTE *moduleBase, const size_t sectionNum, OUT size_t &sectionSize); /** Reads PE file from the remote process into the supplied buffer. It expects the module base and size to be given. */ size_t read_remote_pe(const HANDLE processHandle, BYTE *moduleBase, const size_t moduleSize, OUT BYTE* buffer, const size_t bufferSize); /** Dumps PE from the remote process into a file. It expects the module base and size to be given. \param outputFilePath : the path where the dump will be saved \param processHandle : the handle to the remote process \param moduleBase : the base address of the module that needs to be dumped \param dump_mode : specifies in which format the PE should be dumped. If the mode was set to PE_DUMP_AUTO, it autodetects mode and returns the detected one. \param exportsMap : optional. If exportsMap is supplied, it will try to recover destroyed import table of the PE, basing on the supplied map of exported functions. */ bool dump_remote_pe( IN const char *outputFilePath, IN const HANDLE processHandle, IN BYTE *moduleBase, IN OUT t_pe_dump_mode &dump_mode, IN OPTIONAL peconv::ExportsMapper* exportsMap = nullptr ); /** Retrieve the Image Size saved in the header of the remote PE. \param processHandle : process from where we are reading \param start_addr : a base address of the PE within the given process */ DWORD get_remote_image_size(IN const HANDLE processHandle, IN BYTE *start_addr); }; //namespace peconv
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef BEAST_UTILITY_ENABLEIF_H_INCLUDED #define BEAST_UTILITY_ENABLEIF_H_INCLUDED #include "../type_traits/IntegralConstant.h" namespace beast { template <bool Enable, class T = void> struct EnableIfBool : TrueType { typedef T type; }; template <class T> struct EnableIfBool <false, T> : FalseType { }; template <class Cond, class T = void> struct EnableIf : public EnableIfBool <Cond::value, T> { }; template <bool Enable, class T = void> struct DisableIfBool : FalseType { typedef T type; }; template <class T> struct DisableIfBool <true, T> { }; template <class Cond, class T = void> struct DisableIf : public DisableIfBool <Cond::value, T> { }; } #endif
#pragma once #include "SFML\Graphics.hpp" #include <iostream> #include "SFML\Audio.hpp" #define MAX_NUMBER_OF_ITEMS 1 class rules { public: rules(); rules(float width, float height); ~rules(); void printRules(); void draw(sf::RenderWindow &window); void MoveUp(); void MoveDown(); int GetPressedItem() { return selectedItemIndex; } private: int selectedItemIndex; sf::Font font; sf::Text menu[MAX_NUMBER_OF_ITEMS]; };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** ** Yngve Pettersen ** */ #include "core/pch.h" //#include "url_man.h" #include "modules/url/url2.h" #include "modules/formats/argsplit.h" #include "modules/formats/hdsplit.h" #include "modules/mime/mimedec2.h" #include "modules/upload/upload.h" //#include "url_cs.h" //#include "mime_cs.h" #include "modules/mime/mimetnef.h" #include "modules/mime/smimefun.h" #include "modules/mime/mime_enum.h" #include "modules/hardcore/mem/mem_man.h" #include "modules/olddebug/tstdump.h" #ifdef M2_SUPPORT #include "modules/prefs/prefsmanager/collections/pc_m2.h" #endif #include "modules/util/handy.h" #ifdef _MIME_SUPPORT_ /** * mimespec.cpp * * This file is used to determine MIME content types, and whether * or not they are to be handled by special classes * * The types must be represented in the MIME_ContentTypeID enumerated * value defined in mimedec.h * * Add the necessary specific types in mimecontent_keyword table below, * and any non-specific types in mimecontent_keyword1. * * Add the required id's to the MIME_Decoder::SpecialHandling to * trigger special handling * * Allocation of the appropriate class objects must then be added in the * case selection in the CreateSubElement functions */ #include "modules/url/tools/arrays.h" #define CONST_KEYWORD_ARRAY(name) PREFIX_CONST_ARRAY(static, KeywordIndex, name, mime) #define CONST_KEYWORD_ENTRY(x,y) CONST_DOUBLE_ENTRY(keyword, x, index, y) #define CONST_KEYWORD_END(name) CONST_END(name) /** * Add specific content types to be specially handled here * **** Note: Alphabetiacally Sorted **** */ CONST_KEYWORD_ARRAY(mimecontent_keyword) CONST_KEYWORD_ENTRY((char*) NULL,MIME_Other) CONST_KEYWORD_ENTRY("application/mime", MIME_Mime) CONST_KEYWORD_ENTRY("application/ms-tnef", MIME_MS_TNEF_data) CONST_KEYWORD_ENTRY("application/octet-stream", MIME_Binary) #ifdef _SUPPORT_OPENPGP_ CONST_KEYWORD_ENTRY("application/pgp", MIME_PGP_File) CONST_KEYWORD_ENTRY("application/pgp-encrypted", MIME_PGP_Encrypted) CONST_KEYWORD_ENTRY("application/pgp-signature", MIME_PGP_Signed) #endif #ifdef _SUPPORT_SMIME_ CONST_KEYWORD_ENTRY("application/pkcs7-mime", MIME_SMIME_pkcs7) #endif #ifdef WBMULTIPART_MIXED_SUPPORT CONST_KEYWORD_ENTRY("application/vnd.wap.multipart.mixed", MIME_Multipart_Binary) CONST_KEYWORD_ENTRY("application/vnd.wap.multipart.related", MIME_Multipart_Binary) #endif #ifdef WBXML_SUPPORT CONST_KEYWORD_ENTRY("application/vnd.wap.wbxml", MIME_XML_text) CONST_KEYWORD_ENTRY("application/vnd.wap.wmlc", MIME_XML_text) #endif CONST_KEYWORD_ENTRY("application/vnd.wap.xhtml+xml", MIME_XML_text) #ifdef _SUPPORT_SMIME_ CONST_KEYWORD_ENTRY("application/x-pkcs7-signature", MIME_SMIME_pkcs7) #endif CONST_KEYWORD_ENTRY("application/x-shockwave-flash", MIME_Flash_plugin) CONST_KEYWORD_ENTRY("application/xhtml+xml", MIME_XML_text) CONST_KEYWORD_ENTRY("application/xml",MIME_XML_text) CONST_KEYWORD_ENTRY("image/bmp", MIME_BMP_image) CONST_KEYWORD_ENTRY("image/gif", MIME_GIF_image) CONST_KEYWORD_ENTRY("image/jpeg", MIME_JPEG_image) CONST_KEYWORD_ENTRY("image/png", MIME_PNG_image) #if defined(SVG_SUPPORT) CONST_KEYWORD_ENTRY("image/svg+xml", MIME_SVG_image) #endif #ifdef WBMP_SUPPORT CONST_KEYWORD_ENTRY("image/vnd.wap.wbmp", MIME_BMP_image) #endif CONST_KEYWORD_ENTRY("image/x-windows-bmp", MIME_BMP_image) CONST_KEYWORD_ENTRY("message/external-body", MIME_ExternalBody) CONST_KEYWORD_ENTRY("multipart/alternative" ,MIME_Alternative) #if defined(_SUPPORT_SMIME_) || defined(_SUPPORT_OPENPGP_) CONST_KEYWORD_ENTRY("multipart/encrypted", MIME_Multipart_Encrypted) #endif CONST_KEYWORD_ENTRY("multipart/related", MIME_Multipart_Related) #if defined(_SUPPORT_SMIME_) || defined(_SUPPORT_OPENPGP_) CONST_KEYWORD_ENTRY("multipart/signed", MIME_Multipart_Signed) #endif CONST_KEYWORD_ENTRY("text", MIME_Plain_text) CONST_KEYWORD_ENTRY("text/calendar", MIME_calendar_text) CONST_KEYWORD_ENTRY("text/css", MIME_CSS_text) CONST_KEYWORD_ENTRY("text/html",MIME_HTML_text) CONST_KEYWORD_ENTRY("text/javascript",MIME_Javascript_text) CONST_KEYWORD_ENTRY("text/plain", MIME_Plain_text) CONST_KEYWORD_ENTRY("text/vnd.wap.wml",MIME_XML_text) CONST_KEYWORD_ENTRY("text/wml",MIME_XML_text) CONST_KEYWORD_ENTRY("text/xml",MIME_XML_text) CONST_KEYWORD_END(mimecontent_keyword) /** * Add non-specific content types to be specially handled here * **** Note: Alphabetiacally Sorted **** */ CONST_KEYWORD_ARRAY(mimecontent_keyword1) CONST_KEYWORD_ENTRY((char*) NULL,MIME_Other) CONST_KEYWORD_ENTRY("multipart/", MIME_MultiPart) CONST_KEYWORD_ENTRY("text/", MIME_Text) CONST_KEYWORD_ENTRY("audio/", MIME_audio) CONST_KEYWORD_ENTRY("video/", MIME_video) CONST_KEYWORD_ENTRY("image/", MIME_image) CONST_KEYWORD_ENTRY("message/", MIME_Message) CONST_KEYWORD_END(mimecontent_keyword1) MIME_ContentTypeID MIME_Decoder::FindContentTypeId(const char *type_string) { MIME_ContentTypeID type_id; type_id = (MIME_ContentTypeID) CheckKeywordsIndex(type_string,g_mimecontent_keyword, (int)CONST_ARRAY_SIZE(mime, mimecontent_keyword)); if(type_id == MIME_Other) { type_id = (MIME_ContentTypeID) CheckStartsWithKeywordIndex(type_string,g_mimecontent_keyword1, (int)CONST_ARRAY_SIZE(mime, mimecontent_keyword1)); } return type_id; } void MIME_MultipartBase::CreateNewBodyPartWithNewHeaderL(const OpStringC8 &p_content_type, const OpStringC &p_filename, const OpStringC8 &p_content_encoding) { ANCHORD(Header_List, temp_header_list); if(p_filename.HasContent()) { temp_header_list.AddParameterL("Content-Disposition", "attachment"); temp_header_list.AddRFC2231ParameterL("Content-Disposition","filename",p_filename, NULL); } CreateNewBodyPartWithNewHeaderL(temp_header_list, p_content_type, p_content_encoding); } void MIME_MultipartBase::CreateNewBodyPartWithNewHeaderL(const OpStringC8 &p_content_type, const OpStringC8 &p_filename, const OpStringC8 &p_content_encoding) { ANCHORD(Header_List, temp_header_list); if(p_filename.HasContent()) { temp_header_list.AddParameterL("Content-Disposition", "attachment"); temp_header_list.AddParameterL("Content-Disposition","filename",p_filename); } CreateNewBodyPartWithNewHeaderL(temp_header_list, p_content_type, p_content_encoding); } void MIME_MultipartBase::CreateNewBodyPartWithNewHeaderL(/*upload*/ Header_List &headers, const OpStringC8 &p_content_type, const OpStringC8 &p_content_encoding) { if(p_content_type.HasContent()) headers.AddParameterL("Content-Type", p_content_type); if(p_content_encoding.HasContent()) headers.AddParameterL("Content-Transfer-Encoding", p_content_encoding); ANCHORD(OpString8, tempheader); tempheader.ReserveL(headers.CalculateLength()+30); // A little extra, just in case char *hdr_pos = headers.OutputHeaders(tempheader.DataPtr()); if(!hdr_pos) LEAVE(OpStatus::ERR_NULL_POINTER); *hdr_pos = '\0'; CreateNewBodyPartL((unsigned char *) tempheader.CStr(), tempheader.Length()); } void MIME_MultipartBase::CreateNewBodyPartL(HeaderList &hdrs) { FinishSubElementL(); OP_MEMORY_VAR MIME_ContentTypeID id = MIME_Plain_text; // if no MIME type, assume it is text HeaderEntry *hdr = hdrs.GetHeaderByID(HTTP_Header_Content_Type); if(hdr) { ParameterList *parameters = hdr->GetParametersL(PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES ); if(parameters && parameters->First()) { Parameters *ctyp = parameters->First(); id = FindContentTypeId(ctyp->Name()); } } TRAPD(op_err, current_element = CreateNewBodyPartL(id, hdrs, base_url_type)); if(OpStatus::IsError(op_err)) { current_element = NULL; g_memory_manager->RaiseCondition(op_err); RaiseDecodeWarning(); return; } if(current_element) { current_element->Into(&sub_elements); ++*number_of_parts_counter; } else g_memory_manager->RaiseCondition(OpStatus::ERR_NO_MEMORY); } MIME_Decoder *MIME_MultipartBase::CreateNewBodyPartL(MIME_ContentTypeID id, HeaderList &hdrs, URLType url_type) { return MIME_Decoder::CreateDecoderL(this, id, hdrs, url_type, base_url #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , GetContextID() #endif ); } MIME_Decoder *MIME_Decoder::CreateDecoderL(const MIME_Decoder *parent, MIME_ContentTypeID id, HeaderList &hdrs, URLType url_type, URL_Rep* url #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , URL_CONTEXT_ID ctx_id #endif ) { BOOL attachment_flag = FALSE; if(parent) { HeaderEntry *header = hdrs.GetHeaderByID(HTTP_Header_Content_Disposition); if(header) { ParameterList *parameters = header->GetParametersL((PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES | PARAM_HAS_RFC2231_VALUES), KeywordIndex_HTTP_General_Parameters); attachment_flag = (parameters && !parameters->Empty() && parameters->First()->GetNameID() != HTTP_General_Tag_Inline); } if (parent->nesting_depth >= 16) { id = MIME_ignored_body; } } OpStackAutoPtr<MIME_Decoder> decoder(NULL); #if defined(_SUPPORT_SMIME_) || defined(_SUPPORT_OPENPGP_) retry_id:; #endif switch(id) { /** * NOTE: Add Allocation for Content Types that require special handling here * NOTE: For classes: ALWAYS execute SetHeaders() after construction of MIME_Decoder * NEVER use the headerlist construction (virtual function calls are not yet initialized !! */ case MIME_MS_TNEF_data: decoder.reset(OP_NEW_L(MS_TNEF_Decoder, (hdrs, url_type))); break; #ifdef _SUPPORT_SMIME_ case MIME_SMIME_pkcs7: case MIME_SMIME_Signed: decoder.reset(OP_NEW_L(SMIME_Decoder, (hdrs, url_type))); if(decoder.get() == NULL) { id = MIME_Text; goto retry_id; } break; #endif #ifdef _SUPPORT_OPENPGP_ case MIME_PGP_File: case MIME_PGP_Signed: case MIME_PGP_Encrypted: case MIME_PGP_Keys: decoder.reset((MIME_Decoder *)CreatePGPDecoderL(id, hdrs, url_type)); if(decoder.get() == NULL) { id = MIME_Text; goto retry_id; } break; #endif #if defined(_SUPPORT_SMIME_) || defined(_SUPPORT_OPENPGP_) case MIME_Multipart_Signed: case MIME_Multipart_Encrypted: decoder.reset(CreateSecureMultipartDecoderL(id, hdrs, url_type)); break; #endif #ifdef WBMULTIPART_MIXED_SUPPORT case MIME_Multipart_Binary: decoder.reset(OP_NEW_L(MIME_Multipart_Decoder, (hdrs, url_type, TRUE))); break; #endif case MIME_Alternative: decoder.reset(OP_NEW_L(MIME_Multipart_Alternative_Decoder, (hdrs, url_type))); break; case MIME_MultiPart: decoder.reset(OP_NEW_L(MIME_Multipart_Decoder, (hdrs, url_type))); break; case MIME_Multipart_Related: decoder.reset(OP_NEW_L(MIME_Multipart_Related_Decoder, (hdrs, url_type))); break; case MIME_Mime: case MIME_Message: decoder.reset(OP_NEW_L(MIME_Mime_Payload, (hdrs, url_type))); break; case MIME_HTML_text: case MIME_XML_text: decoder.reset(OP_NEW_L(MIME_Formatted_Payload, (hdrs, url_type))); break; case MIME_ExternalBody: decoder.reset(OP_NEW_L(MIME_External_Payload, (hdrs, url_type))); break; case MIME_ignored_body: decoder.reset(OP_NEW_L(MIME_IgnoredBody, (hdrs, url_type))); break; case MIME_Plain_text: case MIME_Text: { if(!attachment_flag) { decoder.reset(OP_NEW_L(MIME_Unprocessed_Text, (hdrs, url_type))); break; } // Fall through to MIME_Text } case MIME_CSS_text: case MIME_Javascript_text: case MIME_GIF_image: case MIME_JPEG_image: case MIME_PNG_image: case MIME_BMP_image: case MIME_SVG_image: case MIME_Flash_plugin: #if defined(M2_SUPPORT) if(!attachment_flag || (id==MIME_GIF_image || id==MIME_JPEG_image || id==MIME_PNG_image || id==MIME_BMP_image || id == MIME_SVG_image) #if defined(NEED_URL_MIME_DECODE_LISTENERS) || g_pcm2->GetIntegerPref(PrefsCollectionM2::ShowAttachmentsInline) #endif // NEED_URL_MIME_DECODE_LISTENERS ) #endif { decoder.reset(OP_NEW_L(MIME_Displayable_Payload, (hdrs, url_type))); break; } // Use payload decoder instead (as attachment); case MIME_image: case MIME_calendar_text: default: // MIME_CSS_text might be probably also handled here decoder.reset(CreateNewMIME_PayloadDecoderL(NULL, hdrs, url_type)); break; } if(parent) decoder->InheritAttributes(parent); #ifdef URL_SEPARATE_MIME_URL_NAMESPACE if(parent && !ctx_id) ctx_id = parent->GetContextID(); decoder->SetContextID(ctx_id); #endif decoder->SetBaseURL(url); decoder->ConstructL(); return decoder.release(); } MIME_Decoder *MIME_Decoder::CreateDecoderL(const MIME_Decoder *parent, const unsigned char *src, unsigned long src_len, URLType url_type, URL_Rep* url #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , URL_CONTEXT_ID ctx_id #endif ) { HeaderList headers(KeywordIndex_HTTP_MIME); ANCHOR(HeaderList, headers); ANCHORD(OpString8, header_string); header_string.SetL((const char *) src, src_len); headers.SetValueL(header_string.CStr(), 0); MIME_ContentTypeID id = MIME_Other; HeaderEntry *hdr = headers.GetHeaderByID(HTTP_Header_Content_Type); if(hdr) { ParameterList *parameters = hdr->GetParametersL(PARAM_SEP_SEMICOLON| PARAM_ONLY_SEP | PARAM_STRIP_ARG_QUOTES ); if(parameters && parameters->First()) { Parameters *ctyp = parameters->First(); id = FindContentTypeId(ctyp->Name()); } else id = MIME_Plain_text; } else id = MIME_Plain_text; return CreateDecoderL(parent, id, headers, url_type, url #ifdef URL_SEPARATE_MIME_URL_NAMESPACE , ctx_id #endif ); } MIME_Decoder *MIME_Decoder::CreateNewMIME_PayloadDecoderL(const MIME_Decoder *parent, HeaderList &hdr, URLType url_type) { MIME_Decoder *decoder = OP_NEW_L(MIME_Payload, (hdr, url_type)); // Safe, nothing leaves after this call if(parent) decoder->InheritAttributes(parent); return decoder; } void MIME_MultipartBase::CreateNewMIME_PayloadBodyPartL(HeaderList &hdrs) { TRAPD(op_err, current_element = CreateNewMIME_PayloadDecoderL(this, hdrs, base_url_type)); if(OpStatus::IsError(op_err)) { current_element = NULL; g_memory_manager->RaiseCondition(op_err); RaiseDecodeWarning(); LEAVE(op_err); } OP_ASSERT(current_element); current_element->Into(&sub_elements); ++*number_of_parts_counter; } // Do not add special handling void MIME_MultipartBase::CreateNewBodyPartL(const unsigned char *src, unsigned long src_len) { HeaderList headers(KeywordIndex_HTTP_MIME); ANCHOR(HeaderList, headers); ANCHORD(OpString8, header_string); header_string.SetL((const char *) src, src_len); headers.SetValueL(header_string.CStr(), 0); CreateNewBodyPartL(headers); } #endif
#include<stdio.h> #define limit 1000000 int gcd(int a,int b){int tmp; if(a<b){tmp=a;a=b;b=tmp;} while(b){tmp=a%b;a=b;b=tmp;}return a; } int main(){ unsigned long long n_max=0,d_max=1,n,d; for(d=2;d<=limit;d++){if(d%7){goto label;}continue;label:; n=(3*d)/7; if(n*d_max>n_max*d){d_max=d;n_max=n;} } printf("%llu/%llu\n",n_max/gcd(n_max,d_max),d_max/gcd(n_max,d_max)); return 0; }
#include "bricks/core/string.h" #include "bricks/core/exception.h" #include <stdarg.h> #include <stdio.h> namespace Bricks { const String String::Empty; static size_t UTF8GetCharacterSize(String::Character character) { if (!character) return 2; if (character <= 0x7F) return 1; else if (character <= 0x7FF) return 2; else if (character <= 0xFFFF) return 3; return 4; } static int UTF8EncodeCharacter(u8* data, String::Character character) { #define UTF8_ENCODE_CHAR(length) UTF8_ENCODE_CHAR_##length(length) #define UTF8_ENCODE_CHAR_HEADER_0 0x00 #define UTF8_ENCODE_CHAR_HEADER_2 0xC0 #define UTF8_ENCODE_CHAR_HEADER_3 0xE0 #define UTF8_ENCODE_CHAR_HEADER_4 0xF0 #define UTF8_ENCODE_CHAR_MASK_0 0x7F #define UTF8_ENCODE_CHAR_MASK_2 0x1F #define UTF8_ENCODE_CHAR_MASK_3 0x0F #define UTF8_ENCODE_CHAR_MASK_4 0x07 #define UTF8_ENCODE_CHAR_0(length) data[0] = UTF8_ENCODE_CHAR_HEADER_##length | (character & UTF8_ENCODE_CHAR_MASK_##length) #define UTF8_ENCODE_CHAR_1(index) data[index] = (character & 0x3F); character >>= 6 #define UTF8_ENCODE_CHAR_2(length) UTF8_ENCODE_CHAR_1(1); UTF8_ENCODE_CHAR_0(length) #define UTF8_ENCODE_CHAR_3(length) UTF8_ENCODE_CHAR_1(2); UTF8_ENCODE_CHAR_2(length) #define UTF8_ENCODE_CHAR_4(length) UTF8_ENCODE_CHAR_1(3); UTF8_ENCODE_CHAR_3(length) switch (UTF8GetCharacterSize(character)) { case 1: UTF8_ENCODE_CHAR(0); return 1; case 2: UTF8_ENCODE_CHAR(2); return 2; case 3: UTF8_ENCODE_CHAR(3); return 3; case 4: UTF8_ENCODE_CHAR(4); return 4; default: return 0; } } static size_t UTF8GetCharacterSize(const u8* data) { if (!(*data & 0x80)) return 1; switch (*data & 0xF0) { case UTF8_ENCODE_CHAR_HEADER_4: return 4; case UTF8_ENCODE_CHAR_HEADER_3: return 3; default: return 2; } } static String::Character UTF8DecodeCharacter(const u8* data) { #define UTF8_DECODE_CHAR(length) UTF8_DECODE_CHAR_##length(length) #define UTF8_DECODE_CHAR_HEADER_1 0x7F #define UTF8_DECODE_CHAR_HEADER_2 0x1F #define UTF8_DECODE_CHAR_HEADER_3 0x0F #define UTF8_DECODE_CHAR_HEADER_4 0x07 #define UTF8_DECODE_CHAR_0(length) (((String::Character)data[0] & UTF8_DECODE_CHAR_HEADER_##length) << ((length - 1) * 6)) #define UTF8_DECODE_CHAR_1(length, index) (((String::Character)data[index] & 0x3F) << ((length - index - 1) * 6)) #define UTF8_DECODE_CHAR_2(length) (UTF8_DECODE_CHAR_0(length) | UTF8_DECODE_CHAR_1(length, 1)) #define UTF8_DECODE_CHAR_3(length) (UTF8_DECODE_CHAR_2(length) | UTF8_DECODE_CHAR_1(length, 2)) #define UTF8_DECODE_CHAR_4(length) (UTF8_DECODE_CHAR_3(length) | UTF8_DECODE_CHAR_1(length, 3)) switch (UTF8GetCharacterSize(data)) { case 4: return UTF8_DECODE_CHAR(4); case 3: return UTF8_DECODE_CHAR(3); case 2: return UTF8_DECODE_CHAR(2); default: return UTF8_DECODE_CHAR_0(1); } } static size_t UTF8GetStringLength(const char* data) { size_t count = 0; while (*data) { if (!(*data & 0x80)) { do { count++; data++; } while (*data && !(*data & 0x80)); if (!*data) break; } switch (*data & 0xF0) { case UTF8_ENCODE_CHAR_HEADER_4: data++; case UTF8_ENCODE_CHAR_HEADER_3: data++; default: data += 2; count++; break; } } return count; } static size_t UTF8GetStringOffset(const char* data, int index) { const char* origData = data; while (index > 0 && *data) { if (!(*data & 0x80)) { do { index--; data++; } while (index > 0 && *data && !(*data & 0x80)); if (!index || !*data) break; } switch (*data & 0xF0) { case UTF8_ENCODE_CHAR_HEADER_4: data++; case UTF8_ENCODE_CHAR_HEADER_3: data++; default: data += 2; index--; break; } } return data - origData; } void String::Construct(size_t len) { buffer = autonew Data(len + 1); buffer->SetValue(len, 0); dataLength = 0; } void String::Construct(const char* string, size_t len) { if (len == npos) len = string ? strlen(string) : 0; Construct(len); strncpy((char*)buffer->GetData(), string, len); } String::String() : dataLength(0) { Construct(0); } String::String(const String& string) : buffer(string.GetBuffer()), dataLength(string.dataLength) { } String::String(const String& string, size_t off, size_t len) : dataLength(0) { size_t offset = UTF8GetStringOffset(string.CString(), off); size_t length = len == npos ? string.GetSize() - offset : UTF8GetStringOffset(string.CString() + offset, len); Construct(string.CString() + offset, length); dataLength = len == npos ? 0 : len; } String::String(const char* string, size_t len) { size_t length = len == npos ? strlen(string) : UTF8GetStringOffset(string, len); Construct(string, length); dataLength = len == npos ? 0 : len; } String::String(char character, size_t repeat) { Construct(repeat); memset(buffer->GetData(), character, repeat); } String::String(String::Character character, size_t repeat) { size_t size = UTF8GetCharacterSize(character); Construct(repeat * size); for (size_t i = 0; i < repeat; i++) UTF8EncodeCharacter((u8*)buffer->GetData() + i * size, character); } String::~String() { } String String::GetDebugString() const { return Format("\"%s\" [%d]", CString(), GetReferenceCount()); } String& String::operator=(const String& string) { buffer = string.buffer; dataLength = string.dataLength; return *this; } String& String::operator=(const char* string) { Construct(string, npos); return *this; } String String::operator+(const String& string) const { String out; out.Construct(CString(), GetSize() + string.GetSize()); memcpy((char*)out.GetBuffer()->GetData() + GetSize(), string.GetBuffer()->GetData(), string.GetSize()); return out; } String& String::operator+=(const String& string) { AutoPointer<Data> newbuffer = autonew Data(GetSize() + string.GetSize() + 1); memcpy((char*)newbuffer->GetData(), buffer->GetData(), GetSize()); memcpy((char*)newbuffer->GetData() + GetSize(), string.GetBuffer()->GetData(), string.GetBuffer()->GetSize()); buffer = newbuffer; return *this; } String::Character String::GetCharacter(size_t index) const { size_t offset = UTF8GetStringOffset(CString(), index); return UTF8DecodeCharacter((const u8*)CString() + offset); } void String::SetCharacter(size_t index, String::Character character) { size_t offset = UTF8GetStringOffset(CString(), index); size_t sourceSize = UTF8GetCharacterSize((const u8*)buffer->GetData() + offset); size_t destSize = UTF8GetCharacterSize(character); if (sourceSize > destSize) { memmove((u8*)buffer->GetData() + offset + destSize, (const u8*)buffer->GetData() + offset + sourceSize, buffer->GetSize() - offset - sourceSize); TruncateSize(GetSize() - (sourceSize - destSize)); } else if (destSize > sourceSize) { AutoPointer<Data> newbuffer = autonew Data(buffer->GetSize() + destSize - sourceSize); memcpy(newbuffer->GetData(), buffer->GetData(), offset); memcpy((u8*)newbuffer->GetData() + offset + destSize, (const u8*)buffer->GetData() + offset + sourceSize, buffer->GetSize() - offset - sourceSize); buffer = newbuffer; } UTF8EncodeCharacter((u8*)buffer->GetData() + offset, character); } bool String::operator==(const String& rhs) const { return GetSize() == rhs.GetSize() && !memcmp(CString(), rhs.CString(), GetSize()); } size_t String::GetLength() const { return dataLength ?: (dataLength = UTF8GetStringLength(CString())); } int String::Compare(const String& string) const { return Compare(0, string.CString()); } int String::Compare(const String& string, size_t len) const { return Compare(0, string.CString(), len); } int String::Compare(size_t off1, const String& string, size_t off2, size_t len) const { return Compare(off1, string.CString() + off2, len); } int String::Compare(const char* string) const { return Compare(0, string); } int String::Compare(const char* string, size_t len) const { return Compare(0, string, len); } int String::Compare(size_t off1, const char* string, size_t len) const { return strncmp(CString() + off1, string, len); } int String::Compare(size_t off1, const char* string) const { return strcmp(CString() + off1, string); } void String::Truncate(size_t len) { size_t length = UTF8GetStringOffset(CString(), len); buffer->SetSize(length + 1); buffer->SetValue(length, 0); } void String::TruncateSize(size_t len) { buffer->SetSize(len + 1); buffer->SetValue(len, 0); } String String::Substring(size_t off, size_t len) const { return String(CString() + (off == npos ? 0 : UTF8GetStringOffset(CString(), off)), len); } size_t String::FirstIndexOf(String::Character chr, size_t off) const { const u8* charData = (const u8*)CString() + UTF8GetStringOffset(CString(), off); size_t index = off; while (*charData) { if (UTF8DecodeCharacter(charData) == chr) return index; charData += UTF8GetCharacterSize(charData); index++; } return npos; } size_t String::LastIndexOf(String::Character chr, size_t off) const { const u8* charData = (const u8*)CString() + UTF8GetStringOffset(CString(), off); size_t index = off; size_t lastIndex = npos; while (*charData) { if (UTF8DecodeCharacter(charData) == chr) lastIndex = index; charData += UTF8GetCharacterSize(charData); index++; } return lastIndex; } size_t String::FirstIndexOf(const String& string, size_t off) const { size_t count = string.GetLength(); size_t firstindex = GetLength(); for (size_t i = 0; i < count; i++) { size_t index = FirstIndexOf(string[i], off); if (index != npos && index < firstindex) firstindex = index; } return firstindex == GetLength() ? npos : firstindex; } size_t String::LastIndexOf(const String& string, size_t off) const { size_t count = string.GetLength(); size_t firstindex = 0; bool found = false; for (size_t i = 0; i < count; i++) { size_t index = LastIndexOf(string[i], off); if (index != npos && index > firstindex) { firstindex = index; found = true; } } return found ? firstindex : npos; } String String::FormatVariadic(const String& format, va_list args) { #ifdef _GNU_SOURCE char* temp = NULL; if (vasprintf(&temp, format.CString(), args) < 0) BRICKS_FEATURE_THROW(OutOfMemoryException()); String ret(temp); free(temp); #else va_list argsCount; va_copy(argsCount, args); char dummy[1]; int size = vsnprintf(dummy, 0, format.CString(), argsCount); va_end(argsCount); if (size < 0) BRICKS_FEATURE_THROW(NotSupportedException()); char temp[size + 1]; vsnprintf(temp, size + 1, format.CString(), args); temp[size] = '\0'; String ret(temp); #endif return ret; } String String::Format(const String& format, ...) { va_list args; va_start(args, format); String ret = FormatVariadic(format, args); va_end(args); return ret; } int String::ScanVariadic(const String& format, va_list args) { return vsscanf(CString(), format.CString(), args); } int String::Scan(const String& format, ...) { va_list args; va_start(args, format); int ret = ScanVariadic(format, args); va_end(args); return ret; } }
// // Light.h // Odin.MacOSX // // Created by Daniel on 17/10/15. // Copyright (c) 2015 DG. All rights reserved. // #ifndef Odin_MacOSX_Light_h #define Odin_MacOSX_Light_h #include <string> #include "Vector3.h" #include "Vector4.h" #include "NumericTypes.h" #include "Shader.h" namespace odin { namespace render { class Light { public: std::string name; math::vec4 color; virtual void setLightUniforms(const resource::Shader& shader, I32 index) const = 0; }; class DirectionalLight : public Light { public: math::vec3 direction; virtual void setLightUniforms(const resource::Shader& shader, I32 index) const; }; class PointLight : public Light { public: math::vec3 position; F32 constant; F32 linear; F32 quadratic; virtual void setLightUniforms(const resource::Shader& shader, I32 index) const; }; class SpotLight : public Light { public: math::vec3 position; math::vec3 direction; F32 cutOff; F32 outerCutOff; virtual void setLightUniforms(const resource::Shader& shader, I32 index) const; }; } } #endif
// // CCarrierListenerCAPI.h // SwitchServer // // Created by Joel Liang on 2018/8/26. // #ifndef CCarrierListenerCAPI_h #define CCarrierListenerCAPI_h #ifdef __cplusplus #include "elatypes.h" class CCarrierListener; extern "C" { #else typedef struct CCarrierListener CCarrierListener; #endif typedef _ELASTOS ECode (*fnCarrierListenerOnIdle)( /* [in] */ const void *pSwiftObj); typedef _ELASTOS ECode (*fnCarrierListenerOnConnectionChanged)( /* [in] */ const void *pSwiftObj, /* [in] */ _ELASTOS Boolean online); typedef _ELASTOS ECode (*fnCarrierListenerOnReady)( /* [in] */ const void *pSwiftObj); typedef _ELASTOS ECode (*fnCarrierListenerOnFriendRequest)( /* [in] */ const void *pSwiftObj, /* [in] */ const char* uid, /* [in] */ const char* hello); typedef _ELASTOS ECode (*fnCarrierListenerOnFriendConnectionChanged)( /* [in] */ const void *pSwiftObj, /* [in] */ const char* uid, /* [in] */ _ELASTOS Boolean online); typedef _ELASTOS ECode (*fnCarrierListenerOnPortForwardingRequest)( /* [in] */ const void *pSwiftObj, /* [in] */ const char* uid, /* [in] */ const char* servicePort, /* [out] */ _ELASTOS Boolean *accept); typedef _ELASTOS ECode (*fnCarrierListenerOnPortForwardingResult)( /* [in] */ const void *pSwiftObj, /* [in] */ const char* uid, /* [in] */ const char* localPort, /* [in] */ const char* remotePort, /* [in] */ _ELASTOS ECode code); typedef _ELASTOS ECode (*fnCarrierListenerOnMessageReceived)( /* [in] */ const void *pSwiftObj, /* [in] */ const char* uid, /* [in] */ const unsigned char* message, /* [in] */ const unsigned int msgSize); CCarrierListener *createCarrierListener(const void *pSwiftObj); void registerCarrierListenerOnIdle( CCarrierListener *pObj, fnCarrierListenerOnIdle OnIdle); void registerCarrierListenerOnConnectionChanged( CCarrierListener *pObj, fnCarrierListenerOnConnectionChanged OnConnectionChanged); void registerCarrierListenerOnReady( CCarrierListener *pObj, fnCarrierListenerOnReady OnReady); void registerCarrierListenerOnFriendRequest( CCarrierListener *pObj, fnCarrierListenerOnFriendRequest OnFriendRequest); void registerCarrierListenerOnFriendConnectionChanged( CCarrierListener *pObj, fnCarrierListenerOnFriendConnectionChanged OnFriendConnectionChanged); void registerCarrierListenerOnPortForwardingRequest( CCarrierListener *pObj, fnCarrierListenerOnPortForwardingRequest OnPortForwardingRequest); void registerCarrierListenerOnPortForwardingResult( CCarrierListener *pObj, fnCarrierListenerOnPortForwardingResult OnPortForwardingResult); void registerCarrierListenerOnMessageReceived( CCarrierListener *pObj, fnCarrierListenerOnMessageReceived OnMessageReceived); #ifdef __cplusplus } /* extern "C" */ #endif #endif /* CCarrierListenerCAPI_h */
#include <SPI.h> #include <SdFat.h> SdFat SD; const int chipSelect = 4; void setup() { Serial.begin(9600); Serial.print("--Formula SAE-E UFPB 2016--"); Serial.println("SIS v1.0"); sdsetup(); } void loop() { sdsetup(); gpsdata(); } void sdsetup(){ Serial.print("\nInicializando SD Card..."); pinMode(10, OUTPUT); if (!SD.begin(chipSelect)) { Serial.println("Erro!"); Serial.end(); } else Serial.println("Conectado!"); } void gpsdata() { String dados = ""; dados += (random(0, 7)); //latitude dados += (","); dados += (random(15, 30)); //longitude dados += (","); dados += (random(0, 5)); //altitude dados += (","); dados += (random(30, 50)); //velocidade Serial.println(dados); File dataFile = SD.open("testegrava.txt", FILE_WRITE); if (dataFile) { dataFile.println(dados); dataFile.close(); } delay(300); }
#ifndef MEMORY_RTL_H #define MEMORY_RTL_H #include "simple_mem_if.h" class MEMORY_RTL : public sc_module { public: // inputs sc_in< sc_logic > Clk; sc_in< sc_logic > Ren, Wen; sc_in< sc_uint<32> > Addr; sc_in< sc_uint<32> > DataIn; // outputs sc_out< sc_uint<32> > DataOut; sc_out< sc_logic > Ack; unsigned int* memData; SC_HAS_PROCESS(MEMORY_RTL); MEMORY_RTL(sc_module_name name, unsigned int memData[]) : sc_module(name) { this->memData = memData; SC_METHOD(rtl); sensitive << Clk.pos() << Ren << Wen << Addr; } void rtl(); // memory behaviors }; #endif // MEMORY_RTL_H
#ifndef FAST_DENSEALKS_H #define FAST_DENSEALKS_H #include <igraph.h> #include <stdio.h> #include <iostream> #include <assert.h> #include <set> #include <vector> #include "mystr.h" #include "read_data.h" #include "expected_degree.h" #include "graph_partition.h" #include "print_graph.h" #include "Fast-DensestSubgraph.h" #include <algorithm> #include <iterator> #include <string> #include <sstream> int max_dense_kv_subg(const Mysubgraph *origal_graph, const std::vector< std::vector<int> > *subg_vvec, const int in_gsize ,Mysubgraph *res, std::vector< std::vector<int> > *out_subg_vvec_kv = NULL) { if (origal_graph == NULL || subg_vvec == NULL || res == NULL) { return 1; } long int no_node = igraph_vcount(origal_graph->graph); long int no_edge = igraph_ecount(origal_graph->graph); igraph_vector_t remain_vertices; igraph_vector_bool_t vertices_flag; std::vector< std::vector<int> > subg_vvec_kv; igraph_vector_t rm_vertices; igraph_vector_t expected_edges; Mysubgraph subg; Mysubgraph subg_max_density; igraph_real_t max_density = -1; igraph_real_t directed = origal_graph->graph->directed; init_mysubgraph(&subg, directed); init_mysubgraph(&subg_max_density, directed); init_mysubgraph(res, directed); igraph_vector_init(&remain_vertices, 0); igraph_vector_bool_init(&vertices_flag, no_node); // 填充到k个节点 for (int subg_th = 0; subg_th < subg_vvec->size(); subg_th++) { std::vector<int> subg_kv((*subg_vvec)[subg_th].begin(), (*subg_vvec)[subg_th].end()); int vsize = (*subg_vvec)[subg_th].size(); igraph_vector_bool_null(&vertices_flag); for each (int vid in subg_kv) { if (vid >= no_node) { printf("invalid id\n"); break; } VECTOR(vertices_flag)[vid] = 1; } igraph_vector_resize(&remain_vertices, 0); for (int i = 0; i < no_node; i++) { if (VECTOR(vertices_flag)[i] == 0) { igraph_vector_push_back(&remain_vertices, i); } } igraph_vector_shuffle(&remain_vertices); // printf("in_gsize : %d vsize : %d\n", in_gsize, vsize); for (int i = 0; i < in_gsize - vsize; i++) { int vid = (int)VECTOR(remain_vertices)[i]; subg_kv.push_back(vid); } subg_vvec_kv.push_back(subg_kv); subg_kv.clear(); } for each (std::vector<int> vvec in subg_vvec_kv) { printf("vsize :%d\n", vvec.size()); } printf("-----------------------\n"); // 获取期望密度最大的k稠密子图 igraph_real_t density; igraph_vector_init(&rm_vertices, 0); igraph_vector_init(&expected_edges, 0); for (int subg_th = 0; subg_th < subg_vvec_kv.size(); subg_th++) { igraph_vector_resize(&rm_vertices, 0); igraph_vector_resize(&expected_edges, 0); igraph_vector_resize(&remain_vertices, 0); for each (int vid in subg_vvec_kv[subg_th]) { igraph_vector_push_back(&remain_vertices, vid); } vertices_rm(no_node, remain_vertices, &rm_vertices); subgraph_removeVetices2(origal_graph, &rm_vertices, &subg); igraph_edges_expected(subg.graph, &expected_edges); graph_expected_density(subg.graph, &density, igraph_vss_all(), IGRAPH_OUT, IGRAPH_NO_LOOPS, &expected_edges); printf("vsize : %d density : %f\n", igraph_vcount(subg.graph), density); if (density > max_density) { max_density = density; mysubgraph_copy(&subg_max_density, &subg); } mysubgraph_empty(&subg, directed); // igraph_vector_resize(subg.invmap, 0); // igraph_vector_resize(subg.map_pre, 0); // igraph_vector_resize(subg.map_next, 0); // igraph_empty(subg.graph, 0, directed); } printf("-----------------------\n"); // 原稠密子图密度 igraph_vector_init(&rm_vertices, 0); igraph_vector_init(&expected_edges, 0); for (int subg_th = 0; subg_th < (*subg_vvec).size(); subg_th++) { igraph_vector_resize(&rm_vertices, 0); igraph_vector_resize(&expected_edges, 0); igraph_vector_resize(&remain_vertices, 0); for each (int vid in (*subg_vvec)[subg_th]) { igraph_vector_push_back(&remain_vertices, vid); } printf("reamin_vertices : %d \n", igraph_vector_size(&remain_vertices)); vertices_rm(no_node, remain_vertices, &rm_vertices); printf("rm_vertices : %d \n", igraph_vector_size(&rm_vertices)); subgraph_removeVetices2(origal_graph, &rm_vertices, &subg); igraph_edges_expected(subg.graph, &expected_edges); graph_expected_density(subg.graph, &density, igraph_vss_all(), IGRAPH_OUT, IGRAPH_NO_LOOPS, &expected_edges); printf("vsize : %d density : %f\n", igraph_vcount(subg.graph), density); mysubgraph_empty(&subg, directed); } mysubgraph_copy(res, &subg_max_density); // 返回节点列表 if (out_subg_vvec_kv != NULL) { out_subg_vvec_kv->clear(); for each (std::vector<int> vvec_kv in subg_vvec_kv) { std::vector<int> tmp(vvec_kv.begin(), vvec_kv.end()); out_subg_vvec_kv->push_back(vvec_kv); } } // 释放内存 for (int subg_th = 0; subg_th < subg_vvec_kv.size(); subg_th++) { std::vector<int> vecint_empty(0); subg_vvec_kv[subg_th].swap(vecint_empty); } subg_vvec_kv.clear(); igraph_vector_destroy(&rm_vertices); igraph_vector_destroy(&expected_edges); igraph_vector_destroy(&remain_vertices); igraph_vector_bool_destroy(&vertices_flag); destroy_mysubgraph(&subg_max_density); destroy_mysubgraph(&subg); return 0; } // subg_density暂时还没返回值 int Fast_DenseALKS(const igraph_t *input_graph, const int in_gsize, Mysubgraph *res, igraph_real_t *subg_density) { // 存放稠密子图节点 std::vector< std::vector<int> > subg_vvec(0); // 存放k稠密子图节点 std::vector< std::vector<int> > subg_vec_kv(0); std::vector<int> cur_m(0); std::vector<int> empty_vec(0); // 原图 Mysubgraph origal_graph; Mysubgraph pre_subg; Mysubgraph cur_subg; Mysubgraph cur_density_subg; igraph_vector_t origal_keepv; igraph_vector_t cur_keepv; igraph_vector_t cur_density_vertices; igraph_vector_t rm_vertices; if (input_graph == NULL) { printf("input graph is null in Fast_DenseALKS\n"); return 1; } init_mysubgraph(input_graph, &origal_graph); igraph_bool_t directed = origal_graph.graph->directed; init_mysubgraph(&pre_subg, directed); init_mysubgraph(&cur_subg, directed); init_mysubgraph(&cur_density_subg, directed); init_mysubgraph(res, directed); mysubgraph_copy(&pre_subg, &origal_graph); int times = 1; subg_vvec.push_back(std::vector<int>(0)); while (subg_vvec[times - 1].size() < in_gsize) { std::vector<int> pre_m = subg_vvec[times - 1]; printf("-----------------times : %d vsize : %d \n", times, pre_m.size()); igraph_vector_init(&rm_vertices, 0); for each (int vid in pre_m) { igraph_vector_push_back(&rm_vertices, vid); } // printf("times : %d rmvsize : %d \n", times, igraph_vector_size(&rm_vertices)); subgraph_removeVetices2(&origal_graph, &rm_vertices, &cur_subg); printf("times : %d curkeepvsize : %d \n", times, igraph_vcount(cur_subg.graph)); // printf("times : %d prekeepvsize : %d \n", times, igraph_vcount(pre_subg.graph)); // 获取子图映射父图的节点编号 igraph_vector_init(&origal_keepv, 0); for (int i = 0; i < igraph_vector_size(cur_subg.invmap); i++) { igraph_vector_push_back(&origal_keepv, VECTOR(*(cur_subg.invmap))[i]); //printf("%d ", (int)VECTOR(*(cur_subg.invmap))[i]); } //printf("\n"); //printf("cur_size : %d\n", igraph_vector_size(cur_subg.invmap)); // 将原图的节点编号映射到子图的节点编号 igraph_vector_init(&cur_keepv, 0); for (int i = 0; i < igraph_vector_size(&origal_keepv); i++) { long origal_vid = VECTOR(origal_keepv)[i]; long pre_subg_vid = VECTOR(*(pre_subg.map_next))[origal_vid] - 1; if (pre_subg_vid >= 0) { igraph_vector_push_back(&cur_keepv, pre_subg_vid); } else { printf("1 : invalid vertices id %d\n", pre_subg_vid); } } igraph_real_t cur_density; igraph_vector_init(&cur_density_vertices, 0); //fast_densestSubgraph2(&pre_subg, &cur_keepv, &cur_density_subg, &cur_density, &cur_density_vertices); fast_densestSubgraph2(&pre_subg, &cur_keepv, &cur_density_subg, &cur_density, &cur_density_vertices); // printf("---------------------------\n"); // for (int i = 0; i < igraph_vector_size(pre_subg.invmap); i++) // { // printf("%d ", (int)VECTOR(*(pre_subg.invmap))[i]); // } // printf("\n"); // printf("---------\n"); // igraph_vector_print(&cur_keepv); // printf("---------------------------\n"); printf("cur_density : %f\n", cur_density); printf("times : %d hsize : %d hkeepvsize : %d\n", times, igraph_vcount(cur_density_subg.graph), igraph_vector_size(&cur_density_vertices)); // 将这次的稠密子图节点集合与上次的图节点集合并 std::set<int> cur_m_set(pre_m.begin(), pre_m.end()); for (int i = 0; i < igraph_vector_size(&cur_density_vertices); i++) { int vid = VECTOR(cur_density_vertices)[i]; int origal_vid = VECTOR(*(cur_density_subg.invmap))[vid]; if (origal_vid >= 0) { cur_m_set.insert(origal_vid); //printf("%d ", origal_vid); } else { printf("2 : invalid vertices id\n"); } } //printf("\n"); printf("cur_vsize : %d\n\n", cur_m_set.size()); for each (int vid in cur_m_set) { cur_m.push_back(vid); } if (cur_m.size() > in_gsize) { break; } subg_vvec.push_back(cur_m); cur_m.clear(); times++; mysubgraph_swap(&cur_subg, &pre_subg); mysubgraph_empty(&cur_subg, directed); // igraph_empty(cur_subg.graph, 0, directed); // igraph_vector_resize(cur_subg.invmap, 0); // igraph_vector_resize(cur_subg.map_next, 0); // igraph_vector_resize(cur_subg.map_pre, 0); } // fast_densestSubgraph(&sub_graph, &subgi, &density); // // vector<int> subg_vpre = subg_vec[times - 1]; // vector<int> subg_vcur(0); // vector<int> subg_next(0); // for (int i = 0; i < igraph_vector_size(subgi.invmap); i++) // { // subg_vcur.push_back((int)VECTOR(*(subgi.invmap))[i]); // } // vecint_union(subg_vpre, subg_vcur, &subg_next); // subg_vec.push_back(subg_next); max_dense_kv_subg(&origal_graph, &subg_vvec, in_gsize, res, &subg_vec_kv); print_each_graph(&origal_graph, &subg_vvec, "result\\original_dense_", "gml"); print_each_graph(&origal_graph, &subg_vec_kv, "result\\dense_", "gml"); igraph_vector_destroy(&cur_keepv); destroy_mysubgraph(&origal_graph); destroy_mysubgraph(&pre_subg); destroy_mysubgraph(&cur_subg); return 0; } // subg_density暂时还没返回值 int Fast_DenseALKS2(const igraph_t *input_graph, const int in_gsize, Mysubgraph *res, igraph_real_t *subg_density) { // 存放稠密子图节点 std::vector< std::vector<int> > subg_vvec(0); // 存放k稠密子图节点 std::vector< std::vector<int> > subg_vec_kv(0); std::vector<int> cur_m(0); std::vector<int> empty_vec(0); // 原图 Mysubgraph origal_graph; // Mysubgraph pre_subg; Mysubgraph cur_subg; Mysubgraph cur_density_subg; // igraph_vector_t origal_keepv; // igraph_vector_t cur_keepv; // igraph_vector_t cur_density_vertices; igraph_vector_t rm_vertices; if (input_graph == NULL) { printf("input graph is null in Fast_DenseALKS\n"); return 1; } init_mysubgraph(input_graph, &origal_graph); igraph_bool_t directed = origal_graph.graph->directed; // init_mysubgraph(&pre_subg, directed); init_mysubgraph(&cur_subg, directed); init_mysubgraph(&cur_density_subg, directed); init_mysubgraph(res, directed); // mysubgraph_copy(&pre_subg, &origal_graph); int times = 0; subg_vvec.push_back(std::vector<int>(0)); while (subg_vvec[times].size() < in_gsize) { std::vector<int> pre_m = subg_vvec[times]; printf("times : %d vsize : %d \n", times, pre_m.size()); igraph_vector_init(&rm_vertices, 0); for each (int vid in pre_m) { igraph_vector_push_back(&rm_vertices, vid); } // printf("times : %d rmvsize : %d \n", times, igraph_vector_size(&rm_vertices)); subgraph_removeVetices2(&origal_graph, &rm_vertices, &cur_subg); // printf("times : %d curkeepvsize : %d \n", times, igraph_vcount(cur_subg.graph)); igraph_real_t cur_density; //igraph_vector_init(&cur_density_vertices, 0); //fast_densestSubgraph2(&pre_subg, &cur_keepv, &cur_density_subg, &cur_density, &cur_density_vertices); fast_densestSubgraph(&cur_subg, &cur_density_subg, &cur_density); //printf("times : %d hsize : %d hkeepvsize : %d\n", times, //igraph_vcount(cur_density_subg.graph), igraph_vector_size(&cur_density_vertices)); // 将这次的稠密子图节点集合与上次的图节点集合并 std::set<int> cur_m_set(pre_m.begin(), pre_m.end()); //cur_m_set.clear(); // for each (int var in pre_m) // { // cur_m_set.insert(var); // } printf("times : %d vsize : %d \n", times, cur_m_set.size()); for (int i = 0; i < igraph_vector_size(cur_density_subg.invmap); i++) { int origal_vid = VECTOR(*(cur_density_subg.invmap))[i]; if (origal_vid >= 0) { cur_m_set.insert(origal_vid); if (times == 0) { printf("%d ", origal_vid); } } else { printf("2 : invalid vertices id\n"); } } if (times == 0) { printf("\n"); } printf("times : %d vsize : %d \n\n", times, cur_m_set.size()); for each (int vid in cur_m_set) { cur_m.push_back(vid); } if (cur_m.size() > in_gsize) { break; } subg_vvec.push_back(cur_m); cur_m.clear(); times++; mysubgraph_empty(&cur_subg, directed); //mysubgraph_swap(&cur_subg, &pre_subg); // igraph_empty(cur_subg.graph, 0, directed); // igraph_vector_resize(cur_subg.invmap, 0); // igraph_vector_resize(cur_subg.map_next, 0); // igraph_vector_resize(cur_subg.map_pre, 0); mysubgraph_empty(&cur_density_subg, directed); // igraph_empty(cur_density_subg.graph, 0, directed); // igraph_vector_resize(cur_density_subg.invmap, 0); // igraph_vector_resize(cur_density_subg.map_next, 0); // igraph_vector_resize(cur_density_subg.map_pre, 0); } for each (std::vector<int> var in subg_vvec) { printf("msize : %d\n", var.size()); } dense_vertivce(&origal_graph, &subg_vvec, in_gsize, res); // igraph_vector_destroy(&cur_keepv); destroy_mysubgraph(&origal_graph); // destroy_mysubgraph(&pre_subg); destroy_mysubgraph(&cur_subg); return 0; } #endif // !FAST_DENSEALKS_H
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <folly/futures/Future.h> #include <folly/io/async/test/MockAsyncTransport.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/io/async/AsyncTransport.h> #include <quic/api/test/Mocks.h> #include <quic/client/QuicClientAsyncTransport.h> #include <quic/client/QuicClientTransport.h> #include <quic/common/QuicAsyncUDPSocketWrapper.h> #include <quic/common/test/TestClientUtils.h> #include <quic/common/test/TestUtils.h> #include <quic/fizz/client/handshake/FizzClientHandshake.h> #include <quic/fizz/client/handshake/FizzClientQuicHandshakeContext.h> #include <quic/server/QuicServer.h> #include <quic/server/QuicServerTransport.h> #include <quic/server/async_tran/QuicAsyncTransportServer.h> #include <quic/server/async_tran/QuicServerAsyncTransport.h> #include <quic/server/test/Mocks.h> using namespace testing; namespace quic::test { class QuicAsyncTransportServerTest : public Test { public: void SetUp() override { folly::ssl::init(); createServer(); createClient(); } void createServer() { EXPECT_CALL(serverReadCB_, isBufferMovable_()) .WillRepeatedly(Return(false)); EXPECT_CALL(serverReadCB_, getReadBuffer(_, _)) .WillRepeatedly(Invoke([&](void** buf, size_t* len) { *buf = serverBuf_.data(); *len = serverBuf_.size(); })); EXPECT_CALL(serverReadCB_, readDataAvailable_(_)) .WillOnce(Invoke([&](auto len) { auto echoData = folly::IOBuf::wrapBuffer(serverBuf_.data(), len); echoData->appendChain(folly::IOBuf::copyBuffer(" ding dong")); serverAsyncWrapper_->writeChain(&serverWriteCB_, std::move(echoData)); serverAsyncWrapper_->shutdownWrite(); })); EXPECT_CALL(serverReadCB_, readEOF_()).WillOnce(Return()); EXPECT_CALL(serverWriteCB_, writeSuccess_()).WillOnce(Return()); server_ = std::make_shared<QuicAsyncTransportServer>([this](auto sock) { sock->setReadCB(&serverReadCB_); serverAsyncWrapper_ = std::move(sock); }); server_->setFizzContext(test::createServerCtx()); folly::SocketAddress addr("::1", 0); server_->start(addr, 1); serverAddr_ = server_->quicServer().getAddress(); } void createClient() { clientEvbThread_ = std::thread([&]() { clientEvb_.loopForever(); }); EXPECT_CALL(clientReadCB_, isBufferMovable_()) .WillRepeatedly(Return(false)); EXPECT_CALL(clientReadCB_, getReadBuffer(_, _)) .WillRepeatedly(Invoke([&](void** buf, size_t* len) { *buf = clientBuf_.data(); *len = clientBuf_.size(); })); EXPECT_CALL(clientReadCB_, readDataAvailable_(_)) .WillOnce(Invoke([&](auto len) { clientReadPromise_.setValue( std::string(reinterpret_cast<char*>(clientBuf_.data()), len)); })); EXPECT_CALL(clientReadCB_, readEOF_()).WillOnce(Return()); EXPECT_CALL(clientWriteCB_, writeSuccess_()).WillOnce(Return()); clientEvb_.runInEventBaseThreadAndWait([&]() { auto sock = std::make_unique<QuicAsyncUDPSocketType>(&clientEvb_); auto fizzClientContext = FizzClientQuicHandshakeContext::Builder() .setCertificateVerifier(test::createTestCertificateVerifier()) .build(); client_ = std::make_shared<QuicClientTransport>( &clientEvb_, std::move(sock), std::move(fizzClientContext)); client_->setHostname("echo.com"); client_->addNewPeerAddress(serverAddr_); clientAsyncWrapper_.reset(new QuicClientAsyncTransport(client_)); clientAsyncWrapper_->setReadCB(&clientReadCB_); }); } void TearDown() override { server_->shutdown(); server_ = nullptr; clientEvb_.runInEventBaseThreadAndWait([&] { clientAsyncWrapper_ = nullptr; client_ = nullptr; }); clientEvb_.terminateLoopSoon(); clientEvbThread_.join(); } protected: std::shared_ptr<QuicAsyncTransportServer> server_; folly::SocketAddress serverAddr_; folly::AsyncTransport::UniquePtr serverAsyncWrapper_; folly::test::MockWriteCallback serverWriteCB_; folly::test::MockReadCallback serverReadCB_; std::array<uint8_t, 1024> serverBuf_; std::shared_ptr<QuicClientTransport> client_; folly::EventBase clientEvb_; std::thread clientEvbThread_; QuicClientAsyncTransport::UniquePtr clientAsyncWrapper_; folly::test::MockWriteCallback clientWriteCB_; folly::test::MockReadCallback clientReadCB_; std::array<uint8_t, 1024> clientBuf_; folly::Promise<std::string> clientReadPromise_; }; TEST_F(QuicAsyncTransportServerTest, ReadWrite) { auto [promise, future] = folly::makePromiseContract<std::string>(); clientReadPromise_ = std::move(promise); std::string msg = "jaja"; clientEvb_.runInEventBaseThreadAndWait([&] { clientAsyncWrapper_->write(&clientWriteCB_, msg.data(), msg.size()); clientAsyncWrapper_->shutdownWrite(); }); std::string clientReadString = std::move(future).get(1s); EXPECT_EQ(clientReadString, "jaja ding dong"); } } // namespace quic::test
#include<stdio.h> int main() { int a[5] = {1,2,3,4,5}; int *p = &a[0]; int i; for (i = 0; i < 5; i ++) { printf("a[%d]=%d\n", i, a[i]); } for (i = 0; i < 5; i ++) { printf("*(a+%d)=%d\n", i, *(a+i)); } for (i = 0; i < 5; i ++) { printf("p[%d]=%d\n", i, p[i]); } for (i = 0, p = a; p < 5 + a; i ++, p ++) { printf("*(p+%d)=%d\n", i, *(p)); } }
#include <iostream> #include <vector> #include <algorithm> using namespace std; /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ #define int long long int #define ld long double #define F first #define S second #define P pair<int,int> #define pb push_back #define endl '\n' /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ //method-I; // const int N = 1e5 + 5; // vector <int> Graph[N]; // vector <int> ans; // vector <int> indeg; // int n, m; // typedef vector <int> vi; // void kahn(int no) { // queue <int> q; // for (int i = 1; i <= n; i++) { // if (indeg[i] == 0)//starting node; // q.push(i); // } // while (!q.empty()) { // int temp = q.front(); // q.pop(); // ans.pb(temp);//adding to topo-sort array i.e. ans; // for (auto to : Graph[temp]) { // indeg[to]--; // if (indeg[to] == 0) // q.push(to); // } // } // } // void solve() { // ans.clear(); // indeg = vi(N, 0); // cin >> n >> m; // while (m--) { // int u, v; cin >> u >> v; // Graph[u].pb(v); // //Graph[v].pb(u); // indeg[v]++; // } // kahn(n); // if (ans.size() == n) { // for (auto x : ans) // cout << x << " "; // cout << endl; // } // else // cout << "IMPOSSIBLE" << endl; // return ; // } //method-II; const int N = 1e5 + 5; vector <int> Graph[N]; vector <int> vis, act; vector <int> ans; int n, m; typedef vector <int> vi; void dfs(int src, int par) { vis[src] = 1; act[src] = 1; for (auto to : Graph[src]) { if (act[to]) { cout << "IMPOSSIBLE" << endl; exit(0); } else if (!vis[to]) dfs(to, src); } ans.pb(src); act[src] = 0; } void topological_sort() { for (int i = 1; i <= n; i++) { if (!vis[i]) dfs(i, -1); } } void solve() { ans.clear(); vis = vi(N, 0); act = vi(N, 0); cin >> n >> m; while (m--) { int u, v; cin >> u >> v; Graph[u].pb(v); //Graph[v].pb(u); } topological_sort(); reverse(ans.begin(), ans.end()); for (auto x : ans) cout << x << " "; cout << endl; return ; } int32_t main() { /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ ios_base:: sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif /* → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → → */ //int t;cin>>t;while(t--) solve(); return 0; }
// ---------------------------------------------------------------------------- // nexus | LiquidArgonProperties.cc // // This class collects the relevant physical properties of liquid xenon. // // The NEXT Collaboration // ---------------------------------------------------------------------------- #include "LiquidArgonProperties.h" // #include <G4AnalyticalPolSolver.hh> #include <G4MaterialPropertiesTable.hh> #include "CLHEP/Units/SystemOfUnits.h" #include "CLHEP/Units/PhysicalConstants.h" // #include <stdexcept> // #include <cassert> using CLHEP::h_Planck; using CLHEP::c_light; using namespace CLHEP; LiquidArgonProperties::LiquidArgonProperties() { } LiquidArgonProperties::~LiquidArgonProperties() { } G4double LiquidArgonProperties::RefractiveIndex(G4double energy) { // Formula for the refractive index taken from // https://arxiv.org/pdf/2002.09346.pdf G4double a0 = 0.335; G4double aUV = 0.099; G4double aIR = 0.008; G4double lambdaUV = 106.6 * nm; G4double lambdaIR = 908.3 * nm; G4double wavelength = h_Planck * c_light / energy; G4double x = a0 + aUV * pow (wavelength, 2) / (pow (wavelength, 2) - pow (lambdaUV, 2)) + aIR * pow (wavelength, 2) / (pow (wavelength, 2) - pow (lambdaIR, 2)); G4double rindex_element = sqrt (1 + 3 * x / (3 - x)); return rindex_element; } G4double LiquidArgonProperties::Scintillation(G4double energy) { // Gaussian centered at 128 with a FWHM of 10 // values taken from the LBL page // https://lar.bnl.gov/properties/ G4double Wavelength_peak = 128.*nm; G4double Wavelength_FWHM = 10.*nm; G4double Wavelength_sigma = Wavelength_FWHM/2.35; G4double Energy_peak = (h_Planck*c_light/Wavelength_peak); G4double Energy_sigma = (h_Planck*c_light*Wavelength_sigma/pow(Wavelength_peak,2)); G4double intensity = exp(-pow(Energy_peak/eV-energy/eV,2)/(2*pow(Energy_sigma/eV, 2)))/(Energy_sigma/eV*sqrt(pi*2.)); return intensity; } void LiquidArgonProperties::Scintillation (std::vector<G4double>& energy, std::vector<G4double>& intensity) { for (unsigned i=0; i<energy.size(); i++) intensity.push_back(Scintillation(energy[i])); }
group "url URI-test"; // -*- Mode: C++; tab-width: 4; -*- require init; include "core/pch.h"; include "modules/url/url2.h"; include "modules/url/url_man.h"; include "modules/encodings/utility/charsetnames.h"; // Extracted from draft-fielding-uri-rfc2396bis-05 // Base URI = http://a/b/c/d;p?q // URL, expected URL, expected URL without username/pasword, url_type, servername, path, username, password, fragment table url_samples ( const char *, const char *, const char *, URLType, const char *, const char *, const char *, const char *, const char *, const char *, const char *) { // 5.4.1 Normal Examples { "g:h", "g:h", NULL, URL_UNKNOWN, NULL, "h", NULL, NULL, NULL, "h", NULL }, { "g", "http://a/b/c/g", NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, NULL, "/b/c/g", NULL }, { "./g", "http://a/b/c/g", NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, NULL, "/b/c/g", NULL }, { "g/", "http://a/b/c/g/", NULL, URL_HTTP, "a", "/b/c/g/", NULL, NULL, NULL, "/b/c/g/", NULL }, { "/g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL }, { "//g", "http://g/" , NULL, URL_HTTP, "g", "/", NULL, NULL, NULL, "/", NULL}, { "?y", "http://a/b/c/d;p?y", NULL, URL_HTTP, "a", "/b/c/d;p?y", NULL, NULL, NULL, "/b/c/d;p", "?y" }, { "g?y", "http://a/b/c/g?y", NULL, URL_HTTP, "a", "/b/c/g?y", NULL, NULL, NULL, "/b/c/g", "?y" }, { "#s", "http://a/b/c/d;p?q#s", NULL, URL_HTTP, "a", "/b/c/d;p?q", NULL, NULL, "s", "/b/c/d;p", "?q"}, { "g#s", "http://a/b/c/g#s", NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, "s", "/b/c/g", NULL }, { "g?y#s", "http://a/b/c/g?y#s", NULL, URL_HTTP, "a", "/b/c/g?y", NULL, NULL, "s", "/b/c/g", "?y"}, { ";x", "http://a/b/c/;x", NULL, URL_HTTP, "a", "/b/c/;x", NULL, NULL, NULL, "/b/c/;x", NULL}, { "g;x", "http://a/b/c/g;x", NULL, URL_HTTP, "a", "/b/c/g;x", NULL, NULL, NULL, "/b/c/g;x", NULL}, { "g;x?y#s", "http://a/b/c/g;x?y#s", NULL, URL_HTTP, "a", "/b/c/g;x?y", NULL, NULL, "s", "/b/c/g;x", "?y"}, { "", "http://a/b/c/d;p?q", NULL, URL_HTTP, "a", "/b/c/d;p?q", NULL, NULL, NULL, "/b/c/d;p", "?q"}, { ".", "http://a/b/c/", NULL, URL_HTTP, "a", "/b/c/", NULL, NULL, NULL, "/b/c/", NULL }, { "./", "http://a/b/c/", NULL, URL_HTTP, "a", "/b/c/", NULL, NULL, NULL, "/b/c/", NULL }, { "..", "http://a/b/", NULL, URL_HTTP, "a", "/b/", NULL, NULL, NULL, "/b/", NULL }, { "../", "http://a/b/", NULL, URL_HTTP, "a", "/b/", NULL, NULL, NULL, "/b/", NULL }, { "../g", "http://a/b/g", NULL, URL_HTTP, "a", "/b/g", NULL, NULL, NULL, "/b/g", NULL }, { "../..", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "../../", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "../../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL }, // 5.4.2 Abnormal Examples { "../../../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "../../../../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "/./g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "/../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "g.", "http://a/b/c/g.", NULL, URL_HTTP, "a", "/b/c/g.", NULL, NULL, NULL, "/b/c/g.", NULL}, { ".g", "http://a/b/c/.g", NULL, URL_HTTP, "a", "/b/c/.g", NULL, NULL, NULL, "/b/c/.g", NULL}, { "g..", "http://a/b/c/g..", NULL, URL_HTTP, "a", "/b/c/g..", NULL, NULL, NULL, "/b/c/g..", NULL}, { "..g", "http://a/b/c/..g", NULL, URL_HTTP, "a", "/b/c/..g", NULL, NULL, NULL, "/b/c/..g", NULL}, { "./../g", "http://a/b/g", NULL, URL_HTTP, "a", "/b/g", NULL, NULL, NULL, "/b/g", NULL}, { "./g/.", "http://a/b/c/g/", NULL, URL_HTTP, "a", "/b/c/g/", NULL, NULL, NULL, "/b/c/g/", NULL}, { "g/./h", "http://a/b/c/g/h", NULL, URL_HTTP, "a", "/b/c/g/h", NULL, NULL, NULL, "/b/c/g/h", NULL}, { "g/../h", "http://a/b/c/h", NULL, URL_HTTP, "a", "/b/c/h", NULL, NULL, NULL, "/b/c/h", NULL}, { "g;x=1/./y", "http://a/b/c/g;x=1/y", NULL, URL_HTTP, "a", "/b/c/g;x=1/y", NULL, NULL, NULL, "/b/c/g;x=1/y", NULL}, { "g;x=1/../y", "http://a/b/c/y", NULL, URL_HTTP, "a", "/b/c/y", NULL, NULL, NULL, "/b/c/y", NULL}, { "g?y/./x", "http://a/b/c/g?y/./x", NULL, URL_HTTP, "a", "/b/c/g?y/./x", NULL, NULL, NULL, "/b/c/g", "?y/./x"}, { "g?y/../x", "http://a/b/c/g?y/../x",NULL, URL_HTTP, "a", "/b/c/g?y/../x",NULL, NULL, NULL, "/b/c/g", "?y/../x"}, { "g#s/./x", "http://a/b/c/g#s/./x", NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, "s/./x", "/b/c/g", NULL}, { "g#s/../x", "http://a/b/c/g#s/../x",NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, "s/../x", "/b/c/g", NULL}, { "http:g", "http://a/b/c/g", NULL, URL_HTTP, "a", "/b/c/g", NULL, NULL, NULL, "/b/c/g", NULL}, // for backward compatibility // Extra tests { "./g/.?y", "http://a/b/c/g/?y", NULL, URL_HTTP, "a", "/b/c/g/?y", NULL, NULL, NULL, "/b/c/g/", "?y"}, { "./g/./", "http://a/b/c/g/", NULL, URL_HTTP, "a", "/b/c/g/", NULL, NULL, NULL, "/b/c/g/", NULL}, { "./g/./?y", "http://a/b/c/g/?y", NULL, URL_HTTP, "a", "/b/c/g/?y", NULL, NULL, NULL, "/b/c/g/", "?y"}, { "/g/.?y", "http://a/g/?y", NULL, URL_HTTP, "a", "/g/?y", NULL, NULL, NULL, "/g/", "?y"}, { "/g/./", "http://a/g/", NULL, URL_HTTP, "a", "/g/", NULL, NULL, NULL, "/g/", NULL}, { "/g/./?y", "http://a/g/?y", NULL, URL_HTTP, "a", "/g/?y", NULL, NULL, NULL, "/g/", "?y"}, { "http://f/g/h?q2", "http://f/g/h?q2", NULL, URL_HTTP, "f", "/g/h?q2", NULL, NULL, NULL, "/g/h", "?q2"}, { "https://f/g/h?q2", "https://f/g/h?q2", NULL, URL_HTTPS, "f", "/g/h?q2", NULL, NULL, NULL, "/g/h", "?q2"}, { "ftp://f/g/h?q2", "ftp://f/g/h?q2", NULL, URL_FTP, "f", "/g/h?q2", NULL, NULL, NULL, "/g/h", "?q2"}, { "http://f:81/g/h?q2", "http://f:81/g/h?q2",NULL, URL_HTTP, "f", "/g/h?q2", NULL, NULL, NULL, "/g/h", "?q2"}, { "https://f:82/g/h?q2","https://f:82/g/h?q2",NULL, URL_HTTPS, "f", "/g/h?q2", NULL, NULL, NULL, "/g/h", "?q2"}, { "http://u:p@f/g/h?q2","http://u:p@f/g/h?q2", "http://f/g/h?q2", URL_HTTP, "f", "/g/h?q2", "u", "p", NULL, "/g/h", "?q2"}, { "http://f/?q1", "http://f/?q1", NULL, URL_HTTP, "f", "/?q1", NULL, NULL, NULL, "/", "?q1"}, { "http://f?q2", "http://f/?q2", NULL, URL_HTTP, "f", "/?q2", NULL, NULL, NULL, "/", "?q2"}, { "../", "http://a/b/", NULL, URL_HTTP, "a", "/b/", NULL, NULL, NULL, "/b/", NULL }, { "..", "http://a/b/", NULL, URL_HTTP, "a", "/b/", NULL, NULL, NULL, "/b/", NULL }, { "../../", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "../..", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "../.", "http://a/b/", NULL, URL_HTTP, "a", "/b/", NULL, NULL, NULL, "/b/", NULL }, { "../../.", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "%2e/g/.?y", "http://a/b/c/g/?y", NULL, URL_HTTP, "a", "/b/c/g/?y", NULL, NULL, NULL, "/b/c/g/", "?y"}, { "%2e/g%2f%2e?y", "http://a/b/c/g/?y",NULL, URL_HTTP, "a", "/b/c/g/?y", NULL, NULL, NULL, "/b/c/g/", "?y"}, { "../../%2e%2e/../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "../..%2f%2e%2e%2f../g", "http://a/g", NULL, URL_HTTP, "a", "/g", NULL, NULL, NULL, "/g", NULL}, { "..%2f%2e%2e", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "..%2f%2e%2e%2f", "http://a/", NULL, URL_HTTP, "a", "/", NULL, NULL, NULL, "/", NULL }, { "http://f/g%2fh?q2", "http://f/g%2fh?q2",NULL, URL_HTTP, "f", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "http://10.20.30.40/g%2fh?q2", "http://10.20.30.40/g%2fh?q2", NULL, URL_HTTP, "10.20.30.40", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "http://0x0a.0x14.0x1e.0x28/g%2fh?q2", "http://10.20.30.40/g%2fh?q2", NULL, URL_HTTP, "10.20.30.40", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "http://xa.x14.x1e.28/g%2fh?q2", "http://xa.x14.x1e.28/g%2fh?q2", NULL, URL_HTTP, "xa.x14.x1e.28", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "http://0x0a.ccc.0x1e.0x28/g%2fh?q2", "http://0x0a.ccc.0x1e.0x28/g%2fh?q2", NULL, URL_HTTP, "0x0a.ccc.0x1e.0x28", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, /*{ "http://012.024.036.048/g%2fh?q2", "http://10.20.30.40/g%2fh?q2", NULL, URL_HTTP, "10.20.30.40", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, */ { "http://169090600/g%2fh?q2", "http://10.20.30.40/g%2fh?q2", NULL, URL_HTTP, "10.20.30.40", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "widget://169090600/g%2fh?q2", "widget://169090600/g%2fh?q2", NULL, URL_WIDGET, "169090600", "/g%2fh?q2", NULL, NULL, NULL, "/g%2fh", "?q2"}, { "javascript:test()", "javascript:test()", NULL, URL_JAVASCRIPT, NULL, "test()", NULL, NULL, NULL, "test()", NULL}. { "javascript:x==y?false:true", "javascript:x==y?false:true", NULL, URL_JAVASCRIPT, NULL, "x==y?false:true", NULL, NULL, NULL, "x==y?false:true", NULL}. { "opera:blank", "opera:blank", NULL, URL_OPERA, NULL, "blank", NULL, NULL, NULL, "blank", NULL}, { "about:blank", "about:blank", NULL, URL_OPERA, NULL, "blank", NULL, NULL, NULL, "blank", NULL}, { "about:about", "opera:about", NULL, URL_OPERA, NULL, "about", NULL, NULL, NULL, "about", NULL}, { "about:cache", "opera:cache", NULL, URL_OPERA, NULL, "cache", NULL, NULL, NULL, "cache", NULL}, { "opera:cache", "opera:cache", NULL, URL_OPERA, NULL, "cache", NULL, NULL, NULL, "cache", NULL}, { "opera:historysearch", "opera:historysearch",NULL,URL_OPERA, NULL, "historysearch",NULL, NULL, NULL, "historysearch",NULL}, { "opera:historysearch?q=opera&p=25&s=2", "opera:historysearch?q=opera&p=25&s=2", NULL, URL_OPERA, NULL, "historysearch?q=opera&p=25&s=2", NULL, NULL, NULL, "historysearch","?q=opera&p=25&s=2"}, { "data:text/plain;charset=iso-8859-7,%be%fg%be", "data:text/plain;charset=iso-8859-7,%be%fg%be", NULL, URL_DATA, NULL, "text/plain;charset=iso-8859-7,%be%fg%be", NULL, NULL, NULL, "text/plain;charset=iso-8859-7,%be%fg%be", NULL}, { "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz" "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp" "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl" "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis" "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH" "hhx4dbgYKAAA7", "data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz" "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp" "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl" "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis" "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH" "hhx4dbgYKAAA7", NULL, URL_DATA, NULL, "image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz" "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp" "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl" "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis" "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH" "hhx4dbgYKAAA7", NULL, NULL, NULL, "image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw" "AAAC8IyPqcvt3wCcDkiLc7C0qwyGHhSWpjQu5yqmCYsapyuvUUlvONmOZtfzgFz" "ByTB10QgxOR0TqBQejhRNzOfkVJ+5YiUqrXF5Y5lKh/DeuNcP5yLWGsEbtLiOSp" "a/TPg7JpJHxyendzWTBfX0cxOnKPjgBzi4diinWGdkF8kjdfnycQZXZeYGejmJl" "ZeGl9i2icVqaNVailT6F5iJ90m6mvuTS4OK05M0vDk0Q4XUtwvKOzrcd3iq9uis" "F81M1OIcR7lEewwcLp7tuNNkM3uNna3F2JQFo97Vriy/Xl4/f1cf5VWzXyym7PH" "hhx4dbgYKAAA7", NULL}, /* note: only tests scheme identification, and not content type nor well-formedness of data: URI */ { "data:text/plain;missing-comma", "data:text/plain;missing-comma", NULL, URL_DATA, NULL, "text/plain;missing-comma", NULL, NULL, NULL, "text/plain;missing-comma", NULL}, { "data:text/plain;,with-comma", "data:text/plain;,with-comma", NULL, URL_DATA, NULL, "text/plain;,with-comma", NULL, NULL, NULL, "text/plain;,with-comma", NULL}, } subtest CheckScheme(const uni_char *uni_scheme, const char *scheme, const char *scheme_upper, URLType scheme_id, URLType used_scheme_id,unsigned short def_port, BOOL have_server) { verify(uni_scheme); verify(scheme); verify(scheme_upper); verify(op_stricmp(scheme, scheme_upper) == 0); verify(uni_strcmp(uni_scheme, scheme) == 0); const protocol_selentry* entry = urlManager->LookUpUrlScheme(scheme, TRUE); verify(entry); verify(entry->protocolname); verify(entry->uni_protocolname); verify(op_strcmp(entry->protocolname, scheme) == 0); verify(uni_strcmp(entry->uni_protocolname, uni_scheme) == 0); verify(entry->real_urltype == scheme_id); verify(entry->used_urltype == used_scheme_id); verify(entry->default_port == def_port); verify(entry->have_servername == have_server); const protocol_selentry* entry2 = urlManager->LookUpUrlScheme(scheme_upper, FALSE); verify(entry2 == entry); const protocol_selentry* entry1 = urlManager->GetUrlScheme(uni_scheme, FALSE); verify(entry1 == entry); const protocol_selentry* entry4 = urlManager->LookUpUrlScheme(scheme_id); verify(entry4 == entry); } table scheme_sample (const uni_char *, const char *, const char *, URLType, URLType, unsigned short, BOOL) { {UNI_L("http"), "http", "HtTP", URL_HTTP, URL_HTTP, 80, TRUE}, {UNI_L("https"), "https", "HtTPS", URL_HTTPS, URL_HTTPS, 443, TRUE}, {UNI_L("ftp"), "ftp", "FTp", URL_FTP, URL_FTP, 21, TRUE}, {UNI_L("about"), "about", "aBoUt", URL_ABOUT, URL_OPERA, 0, FALSE}, } test("URL schemes") { iterate(uni_scheme, scheme, scheme_upper, scheme_id, used_scheme_id, def_port, have_server) from scheme_sample { verify(CheckScheme(uni_scheme, scheme, scheme_upper, scheme_id, used_scheme_id, def_port, have_server)); } // Create an example scheme const protocol_selentry* entry = urlManager->GetUrlScheme(UNI_L("example_scheme"), TRUE); verify(entry != NULL); verify(op_strcmp(entry->protocolname, "example_scheme") == 0); verify(uni_strcmp(entry->uni_protocolname, UNI_L("example_scheme")) == 0); verify(entry->real_urltype > URL_NULL_TYPE); verify(entry->used_urltype == entry->real_urltype); verify(entry->default_port == 0); verify(entry->have_servername == FALSE); verify(CheckScheme(UNI_L("example_scheme"), "example_scheme", "example_scheme", entry->real_urltype, entry->real_urltype, 0, FALSE)); } test("URL resolving test") { URL base_url = g_url_api->GetURL("http://a/b/c/d;p?q"); OpString8 url_string; verify_success(base_url.GetAttribute(URL::KName_With_Fragment_Username_Password_Escaped_NOT_FOR_UI, url_string)); verify_string(url_string, "http://a/b/c/d;p?q"); iterate(input_url, output_url, output_url_notpass, url_type, servername, pathandquery, username, password, fragment, path, query) from url_samples { { URL result_url = g_url_api->GetURL(base_url, input_url); url_string.Empty(); verify_success(result_url.GetAttribute(URL::KName_With_Fragment_Username_Password_Escaped_NOT_FOR_UI, url_string)); verify_string(url_string, output_url); url_string.Empty(); verify_success(result_url.GetAttribute(URL::KName_With_Fragment_Escaped, url_string)); verify_string(url_string, output_url_notpass ? output_url_notpass : output_url); verify_string(result_url.GetAttribute(URL::KPath), path); OpString8 pathquery; TRAPD(op_err, result_url.GetAttribute(URL::KPathAndQuery_L, pathquery)); verify_success(op_err); verify_string(pathquery, pathandquery); OpStringC8 query_attr(result_url.GetAttribute(URL::KQuery)); if (query == NULL) verify(query_attr.IsEmpty()); else verify_string(query_attr, query); if(url_type == URL_UNKNOWN) { // UNKNOWN URL types are using a dynamically generated type ID, not possible to predict. verify((URLType) result_url.GetAttribute(URL::KType) > url_type); } else { verify((URLType) result_url.GetAttribute(URL::KType) == url_type); } OpStringC8 server_name_attr(result_url.GetAttribute(URL::KHostName)); if (servername == NULL) verify(server_name_attr.IsEmpty()); else verify_string(server_name_attr, servername); OpStringC8 user_name_attr(result_url.GetAttribute(URL::KUserName)); if (username == NULL) verify(user_name_attr.IsEmpty()); else verify_string(result_url.GetAttribute(URL::KUserName), username); OpStringC8 password_attr(result_url.GetAttribute(URL::KPassWord)); if (password == NULL) verify(password_attr.IsEmpty()); else verify_string(password_attr, password); OpStringC8 fragment_name_attr(result_url.GetAttribute(URL::KFragment_Name)); if (fragment == NULL) verify(fragment_name_attr.IsEmpty()); else verify_string(result_url.GetAttribute(URL::KFragment_Name), fragment); } } // Check unique iterate(input_url, output_url, output_url_notpass, url_type, servername, pathandquery, username, password, fragment, path, query) from url_samples { { URL result_url = g_url_api->GetURL(base_url, input_url, TRUE); url_string.Empty(); verify_success(result_url.GetAttribute(URL::KName_With_Fragment_Username_Password_Escaped_NOT_FOR_UI, url_string)); verify_string(url_string, output_url); verify(result_url.GetAttribute(URL::KUnique)); url_string.Empty(); verify_success(result_url.GetAttribute(URL::KName_With_Fragment_Escaped, url_string)); verify_string(url_string, output_url_notpass ? output_url_notpass : output_url ); verify_string(result_url.GetAttribute(URL::KPath), path); OpString8 pathquery; TRAPD(op_err, result_url.GetAttribute(URL::KPathAndQuery_L, pathquery)); verify_success(op_err); verify_string(pathquery, pathandquery); OpStringC8 query_attr(result_url.GetAttribute(URL::KQuery)); if (query == NULL) verify(query_attr.IsEmpty()); else verify_string(query_attr, query); if(url_type == URL_UNKNOWN) { // UNKNOWN URL types are using a dynamically generated type ID, not possible to predict. verify((URLType) result_url.GetAttribute(URL::KType) > url_type); } else { verify((URLType) result_url.GetAttribute(URL::KType) == url_type); } OpStringC8 server_name_attr(result_url.GetAttribute(URL::KHostName)); if (servername == NULL) verify(server_name_attr.IsEmpty()); else verify_string(server_name_attr, servername); OpStringC8 user_name_attr(result_url.GetAttribute(URL::KUserName)); if (username == NULL) verify(user_name_attr.IsEmpty()); else verify_string(result_url.GetAttribute(URL::KUserName), username); OpStringC8 password_attr(result_url.GetAttribute(URL::KPassWord)); if (password == NULL) verify(password_attr.IsEmpty()); else verify_string(password_attr, password); OpStringC8 fragment_name_attr(result_url.GetAttribute(URL::KFragment_Name)); if (fragment == NULL) verify(fragment_name_attr.IsEmpty()); else verify_string(result_url.GetAttribute(URL::KFragment_Name), fragment); } } } subtest CheckUrlWithCharset(const char *p_url, const char *charset, const uni_char *result) { verify(p_url); verify(charset); verify(result); URL url = g_url_api->GetURL(p_url); verify(url.IsValid()); unsigned short charset_id = g_charsetManager->GetCharsetIDL(charset); verify(charset_id != 0); OpString test_result; verify(OpStatus::IsSuccess(url.GetAttribute(URL::KUniName, charset_id, test_result))); verify(test_result.HasContent()); verify(test_result.Compare(result) == 0); } subtest CheckUniUrlWithCharset(const uni_char *p_url, const char *charset, const uni_char *result) { verify(p_url); verify(charset); verify(result); URL url = g_url_api->GetURL(p_url); verify(url.IsValid()); unsigned short charset_id = g_charsetManager->GetCharsetIDL(charset); verify(charset_id != 0); OpString test_result; verify(OpStatus::IsSuccess(url.GetAttribute(URL::KUniName, charset_id, test_result))); verify(test_result.HasContent()); verify(test_result.Compare(result) == 0); } test("URL charset selection") { verify(CheckUrlWithCharset("http://www.example.com/test/something", "iso-8859-1", UNI_L("http://www.example.com/test/something"))); verify(CheckUrlWithCharset("http://www.example.com/test%e5/something", "iso-8859-1", UNI_L("http://www.example.com/test\x00e5/something"))); verify(CheckUrlWithCharset("http://www.example.com/test%e5/something?%e5else", "iso-8859-1", UNI_L("http://www.example.com/test\x00e5/something?%e5else"))); verify(CheckUniUrlWithCharset(UNI_L("http://\x00e6\x00f8\x00e5.example.com/test/something"), "iso-8859-1", UNI_L("http://\x00e6\x00f8\x00e5.example.com/test/something"))); verify(CheckUniUrlWithCharset(UNI_L("http://\x00e6\x00f8\x00e5.example.com/test%e5/something"), "iso-8859-1", UNI_L("http://\x00e6\x00f8\x00e5.example.com/test\x00e5/something"))); verify(CheckUniUrlWithCharset(UNI_L("http://\x00e6\x00f8\x00e5.example.com/test%e5/something?%e5else"), "iso-8859-1", UNI_L("http://\x00e6\x00f8\x00e5.example.com/test\x00e5/something?%e5else"))); } test("Illegal URL does not get parsed but stays the same") { URL url = g_url_api->GetURL("http://%%.com"); OpString uni_url; url.GetAttributeL(URL::KUniName, uni_url); verify(!uni_url.Compare(UNI_L("http://%%.com"))); OpString8 char_url; url.GetAttributeL(URL::KName, char_url); verify(!char_url.Compare("http://%%.com")); } table url_escape_samples ( const uni_char *, const char *, const char *) { { UNI_L("http://www.example.com/\x30d0"), "http://www.example.com/%E3%83%90", "http://www.example.com/\xE3\x83\x90" }, // CORE-26953 { UNI_L("http://www.example.com/\x202E"), "http://www.example.com/%E2%80%AE", "http://www.example.com/%E2%80%AE" }, // Testing ExceptUnsafeHigh { UNI_L("http://www.x.com/a b%63?%64"), "http://www.x.com/a%20b%63?%64", "http://www.x.com/a%20bc?%64" }, // Testing StopAfterQuery { UNI_L("http://www.x.com/?f\"`o<o>\\bar"), "http://www.x.com/?f%22%60o%3Co%3E\\bar", "http://www.x.com/?f%22%60o%3Co%3E\\bar"}, // Testing query escape. } test("URL escaping/unescaping") { iterate(input_url16, escaped_url8, unescaped_url8) from url_escape_samples { URL url = urlManager->GetURL(input_url16); OpString8 url_string8; verify(OpStatus::IsSuccess(url.GetAttribute(URL::KName_Username_Password_Escaped_NOT_FOR_UI, url_string8))); verify(url_string8.Compare(escaped_url8) == 0); verify(OpStatus::IsSuccess(url.GetAttribute(URL::KName_Username_Password_NOT_FOR_UI, url_string8))); verify(url_string8.Compare(unescaped_url8) == 0); OpString url_string16; verify(OpStatus::IsSuccess(url.GetAttribute(URL::KUniName_Username_Password_NOT_FOR_UI, url_string16))); url_string8.SetUTF8FromUTF16(url_string16); verify(url_string8.Compare(unescaped_url8) == 0); } }
#pragma once #include "Template.hh" #include "Typedefs.hh" #include <memory> #include <vector> namespace HotaSim { using CCC::SPtrVec; class Biom : public TemplateObject<Biom> { public: Biom(const BiomTemplate& _tmpl); SPtrVec<Ability> getAbilities() const noexcept; private: SPtrVec<Ability> abilities; }; }
// exception.cc // Entry point into the Nachos kernel from user programs. // There are two kinds of things that can cause control to // transfer back to here from user code: // // syscall -- The user code explicitly requests to call a procedure // in the Nachos kernel. Right now, the only function we support is // "Halt". // // exceptions -- The user code does something that the CPU can't handle. // For instance, accessing memory that doesn't exist, arithmetic errors, // etc. // // Interrupts (which can also cause control to transfer from user // code into the Nachos kernel) are handled elsewhere. // // For now, this only handles the Halt() system call. // Everything else core dumps. // // Copyright (c) 1992-1993 The Regents of the University of California. // All rights reserved. See copyright.h for copyright notice and limitation // of liability and disclaimer of warranty provisions. #include "copyright.h" #include "system.h" #include "syscall.h" #define FILE_NAME_SIZE 128 //---------------------------------------------------------------------- // ExceptionHandler // Entry point into the Nachos kernel. Called when a user program // is executing, and either does a syscall, or generates an addressing // or arithmetic exception. // // For system calls, the following is the calling convention: // // system call code -- r2 // arg1 -- r4 // arg2 -- r5 // arg3 -- r6 // arg4 -- r7 // // The result of the system call, if any, must be put back into r2. // // And don't forget to increment the pc before returning. (Or else you'll // loop making the same system call forever! // // "which" is the kind of exception. The list of possible exceptions // are in machine.h. //---------------------------------------------------------------------- extern void PageFaultHandler(int); void myFork(int); void myYield(); SpaceId myExec(char *); int myJoin(int); void myExit(int); void myCreate(char *); OpenFileId myOpen(char *); int myRead(int, int, OpenFileId); void myWrite(int, int, OpenFileId); void myClose(OpenFileId); char* CloneString(char *old){ char * newString = new char[FILE_NAME_SIZE]; for (int i = 0; i < FILE_NAME_SIZE; i++) { newString[i] = old[i]; if (old[i] == NULL) break; } return newString; } void incrRegs(){ int pc = machine->ReadRegister(PCReg); machine->WriteRegister(PrevPCReg, pc); pc = machine->ReadRegister(NextPCReg); machine->WriteRegister(PCReg, pc); machine->WriteRegister(NextPCReg, pc + 4); } void ExceptionHandler(ExceptionType which) { int type = machine->ReadRegister(2); char* fileName = new char[128]; int pid; if(which == SyscallException) { switch(type) { case SC_Halt: { DEBUG('a', "Shutdown, initiated by user program.\n"); interrupt->Halt(); break; } case SC_Fork: { myFork(machine->ReadRegister(4)); //machine->WriteRegister(2, ); break; } case SC_Yield: { myYield(); break; } case SC_Exec: { //printf("in myexec\n"); int position = 0; int arg = machine->ReadRegister(4); int value; while (value != NULL) { machine->ReadMem(arg, 1, &value); fileName[position] = (char) value; position++; arg++; } pid = myExec(fileName); //printf("pid returned from myExec: %d\n", pid); machine->WriteRegister(2, pid); break; } case SC_Join: { int arg = machine->ReadRegister(4); pid = myJoin(arg); machine->WriteRegister(2, pid); break; } case SC_Exit: { int arg = machine->ReadRegister(4); myExit(arg); break; } case SC_Create: { int position = 0; int arg = machine->ReadRegister(4); int value; while(value != NULL){ machine->ReadMem(arg, 1, &value); fileName[position] = (char) value; position++; arg++; } myCreate(fileName); break; } case SC_Open: { int position = 0; int arg = machine->ReadRegister(4); int value; while(value != NULL){ machine->ReadMem(arg, 1, &value); fileName[position] = (char) value; position++; arg++; } //printf("before open: %s\n", fileName); OpenFileId index = myOpen(fileName); if(index == -1) printf("Unable to open file\n"); machine->WriteRegister(2, index); break; } case SC_Read: { int arg1 = machine->ReadRegister(4); int arg2 = machine->ReadRegister(5); int arg3 = machine->ReadRegister(6); int tmp = myRead(arg1, arg2, arg3); machine->WriteRegister(2, tmp); break; } case SC_Write: { int arg1 = machine->ReadRegister(4); int arg2 = machine->ReadRegister(5); int arg3 = machine->ReadRegister(6); myWrite(arg1, arg2, arg3); break; } case SC_Close: { int arg1 = machine->ReadRegister(4); myClose(arg1); break; } } currentThread->space->CleanupSysCall(); incrRegs(); }else if(which == PageFaultException) { //printf("**PageFaultException in exception.cc\n"); PageFaultHandler(machine->ReadRegister(BadVAddrReg)); } else { printf("Unexpected user mode exception %d %d\n", which, type); ASSERT(FALSE); } } ///////////////////////////////// // PageFaultExceptionHandler //////////////////////////////// extern void PageFaultHandler(int vaddr) { int page = vaddr / PageSize; DEBUG('q',"Page fault at page %d\n",page); #ifdef VM vm->Swap(page, currentThread->space->pcb->pid); #endif } ///////////////////////////////// // Dummy function used by myFork ///////////////////////////////// void myForkHelper(int funcAddr) { //@@@ ADDED currentThread->space->InitRegisters(); currentThread->space->RestoreState(); // load page table register machine->WriteRegister(PCReg, funcAddr); machine->WriteRegister(NextPCReg, funcAddr + 4); //@@@ return address added //machine->WriteRegister(RetAddrReg, funcAddr+8); machine->Run(); // jump to the user progam ASSERT(FALSE); // machine->Run never returns; } ///////////////////////////////// // Fork system call ///////////////////////////////// void myFork(int funcAddr){ printf("System Call: %d invoked Fork\n", currentThread->space->pcb->pid); int currPid = currentThread->space->pcb->pid; AddrSpace *space = currentThread->space->Duplicate(); if(space==NULL){ printf("Process %d Fork: start at address 0x%X with %d pages memory failed\n", currentThread->space->pcb->pid,funcAddr,space->getNumPages()); return; } PCB *pcb = new PCB(); Thread* thread = new Thread("new forked thread."); pcb->thread = thread; pcb->pid = procManager->getPID(); ASSERT(pcb->pid!=-1); pcb->parentPid = currentThread->space->pcb->pid; space->pcb = pcb; thread->space = space; procManager->insertProcess(pcb, pcb->pid); //@@@ save state needed? space->SaveState(); printf("Process %d Fork %d: start at address 0x%X with %d pages memory\n",currPid,pcb->pid,funcAddr,space->getNumPages()); thread->Fork(myForkHelper, funcAddr); currentThread->Yield(); } // Yield system call void myYield(){ printf("System Call: %d invoked Yield\n", currentThread->space->pcb->pid); currentThread->Yield(); } ///////////////////////////////// // Helper func to create new process in register. ///////////////////////////////// void newProc(int arg){ /*printf("***exec stuf\n"); printf("currentThread: %p\n", currentThread); printf("currentThread->space: %p\n", currentThread->space); printf("currentThread->space->pcb: %p\n", currentThread->space->pcb); printf("currentThread->space->pcb->pid: %i\n", currentThread->space->pcb->pid);*/ currentThread->space->InitRegisters(); currentThread->space->SaveState(); currentThread->space->RestoreState(); //printf("before run\n"); machine->Run(); } ///////////////////////////////// // Exec system call ///////////////////////////////// SpaceId myExec(char *file){ printf("System Call: %d invoked Exec\n", currentThread->space->pcb->pid); printf("Exec Program: %d loading %s\n", currentThread->space->pcb->pid, file); int spaceID; OpenFile *executable = fileSystem->Open(file); if(executable == NULL){ printf("Exec Program: %d loading %s failed\n", currentThread->space->pcb->pid, file); return -1; } AddrSpace *space; space = new AddrSpace(executable); PCB* pcb = new PCB(); pcb->pid = procManager->getPID(); Thread *t = new Thread("Forked process"); pcb->pid = procManager->getPID(); spaceID = pcb->pid; ASSERT(pcb->pid!=-1); /* printf("currentThread: %p\n", currentThread); printf("currentThread->space: %p\n", currentThread->space); printf("currentThread->space->pcb: %p\n", currentThread->space->pcb); printf("currentThread->space->pcb->pid: %i\n", currentThread->space->pcb->pid); */ pcb->parentPid = currentThread->space->pcb->pid; pcb->thread = t; space->pcb = pcb; t->space = space; procManager->insertProcess(pcb, pcb->pid); delete executable; t->Fork(newProc, NULL); currentThread->Yield(); return spaceID; } ///////////////////////////////// // Join system call ///////////////////////////////// int myJoin(int arg){ printf("System Call: %d invoked Join\n", currentThread->space->pcb->pid); currentThread->space->pcb->status = BLOCKED; if(procManager->getStatus(arg) < 0) return procManager->getStatus(arg); procManager->join(arg); currentThread->space->pcb->status = RUNNING; return procManager->getStatus(arg); } ///////////////////////////////// // Exit system call ///////////////////////////////// void myExit(int status){ printf("System Call: %d invoked Exit\n", currentThread->space->pcb->pid); printf("Process %d exists with %d\n", currentThread->space->pcb->pid,status); int pid = currentThread->space->pcb->pid; procManager->Broadcast(pid); delete currentThread->space; currentThread->space = NULL; procManager->clearPID(pid); currentThread->Finish(); } ///////////////////////////////// // Create system call ///////////////////////////////// void myCreate(char *fileName){ printf("System Call: %d invoked Create\n", currentThread->space->pcb->pid); bool fileCreationWorked = fileSystem->Create(fileName, 0); ASSERT(fileCreationWorked); } ///////////////////////////////// // Open system call ///////////////////////////////// OpenFileId myOpen(char *name){ printf("System Call: %d invoked Open\n", currentThread->space->pcb->pid); int index = 0; SysOpenFile *sFile = openFileManager->Get(name, index); //printf("open sys call\n"); //@@@ /*for(int i = 2; i < MAX_FILES; i++){ //printf("opening at %i\n", i); //checking to see if file already open if(openFilesArray[i] != NULL && strcmp(openFilesArray[i]->fileName, name)==0){ //printf("opened2 at %i\n", i); sFile = openFilesArray[i]; index = i; } }*/ if (sFile == NULL) { //printf("open3 at\n"); OpenFile *oFile = fileSystem->Open(name); sFile = new SysOpenFile(name, oFile, -1); index = openFileManager->Add(sFile); //printf("open4 at\n"); /* if (oFile == NULL) { // Here if file is unable to be opened //printf("ofile is %p\n", oFile); return -1; } //printf("open5 at\n"); */ /*SysOpenFile *sysFile = new SysOpenFile(); sysFile->file = oFile; sysFile->numUsersAccess = 1; sysFile->fileName = CloneString(name); //printf("open6 at\n"); //char* tmp[strlen(name)]; //strcpy(tmp, name); //printf("open7 at %s\n", sysFile->fileName); for(int i = 2; i < MAX_FILES; i++){ //printf("openingAGAIN at %i\n", i); if(openFilesArray[i] == NULL){ //Opened file placed at [i] //printf("openFilesArray[i]: %p\n", openFilesArray[i]); openFilesArray[i] = sysFile; index = i; break; } }*/ } else{ sFile->numUsersAccess++; } //printf("open8 at\n"); UserOpenFile *uFile = new UserOpenFile(); uFile->indexPosition = index; uFile->offset = 0; uFile->fileName = CloneString(name); //printf("open9 at: %s\n", uFile->fileName); OpenFileId oFileId = currentThread->space->pcb->Add(uFile); //printf("open10 at: %i\n", oFileId); return oFileId; } ///////////////////////////////// // Read system call ///////////////////////////////// int myRead(int bufferAddress, int size, OpenFileId id){ printf("System Call: %d invoked Read\n", currentThread->space->pcb->pid); char *buffer = new char[size + 1]; int sizeCopy = size; if (id == ConsoleInput) { int count = 0; while (count < size) { buffer[count]=getchar(); count++; } } else { UserOpenFile* userFile = currentThread->space->pcb->getFile(id); if(userFile == NULL){ return -1; // error } SysOpenFile *sFile; if(openFileManager->Get(userFile->indexPosition)->fileID == id) sFile = openFileManager->Get(userFile->indexPosition); else return -1; if(sFile == NULL) { return -1; //error } //new fileManager = openFilesArray /*if(openFilesArray[userFile->indexPosition] != NULL) sFile = openFilesArray[userFile->indexPosition];*/ //printf("reading sFile->file: %d\n", sFile->file); //printf("reading offset: %d\n",userFile->offset); //printf("reading buffer: %p\n",buffer); //printf("reading size: %d\n",size); sFile->lock->Acquire(); sizeCopy = sFile->file->ReadAt(buffer,size,userFile->offset); sFile->lock->Release(); //printf("reading is now here\n"); userFile->offset+=sizeCopy; //@@@ need buffer[sizeCopy] = '/0' ???? } //---------Need a read write func---------- //int ReadWrite(int virAddr, OpenFile *file, int size, int fileAddr, int type) //ReadWrite(bufferAddress, userFilesArray[id]->file, sizeCopy, ) ReadWrite(bufferAddress,buffer,sizeCopy,USER_READ); //----------------------------------------- delete[] buffer; return sizeCopy; } ///////////////////////////////// // Write system call ///////////////////////////////// void myWrite(int bufferAddress, int size, OpenFileId id){ printf("System Call: %d invoked Write\n", currentThread->space->pcb->pid); char* buffer = new char[size+1]; ReadWrite(bufferAddress,buffer,size,USER_WRITE); if (id == ConsoleOutput) { buffer[size]=0; printf("%s",buffer); } else { buffer = new char[size]; int writeSize = ReadWrite(bufferAddress,buffer,size,USER_WRITE); UserOpenFile* uFile = currentThread->space->pcb->getFile(id); if(uFile == NULL) return; SysOpenFile *sFile; if(openFileManager->Get(uFile->indexPosition)->fileID == id) sFile = openFileManager->Get(uFile->indexPosition); else return; /*if(openFilesArray[uFile->indexPosition] != NULL) sFile = openFilesArray[uFile->indexPosition];*/ if(sFile == NULL){ return; //error } int bytes = sFile->file->WriteAt(buffer,size,uFile->offset); uFile->offset+=bytes; } delete[] buffer; } ///////////////////////////////// // Close system call ///////////////////////////////// void myClose(OpenFileId id){ printf("System Call: %d invoked Close\n", currentThread->space->pcb->pid); UserOpenFile* userFile = currentThread->space->pcb->getFile(id); if(userFile == NULL){ return ; } //int tmpIndex = userFile->indexPosition; SysOpenFile *sFile; if(openFileManager->Get(userFile->indexPosition)->fileID == id) sFile = openFileManager->Get(userFile->indexPosition); else return; if(sFile == NULL){ return; } /*if(openFilesArray[userFile->indexPosition] != NULL) sFile = openFilesArray[tmpIndex];*/ //sFile->closeOne(); currentThread->space->pcb->Remove(userFile); //delete openFilesArray[tmpIndex]; //openFilesArray[tmpIndex] = NULL; }
/* Question: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order. Example: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1]. */ /* Approach: - Traverse through the vector in nested for loops hence taking a two pair each time - store the indices if the sum is equal to target. */ class Solution { public: vector<int> twoSum(vector<int> &nums, int target) { vector<int> sum; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++) { if (nums[i] + nums[j] == target) { sum.push_back(i); sum.push_back(j); } } } return sum; } };
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2005 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. */ #ifndef MODULES_DOCHAND_DOCHAND_MODULE_H #define MODULES_DOCHAND_DOCHAND_MODULE_H #include "modules/hardcore/opera/module.h" class WindowManager; class OperaURL_Generator; /** * Class which limits the amount of fraud checks being done after a request fails. * * This is to stop DOS-ing the site check server once it comes up again because all * clients try to hammer it simultaniously. Hence if a request fails we will not try * another attempt until the time FRAUD_CHECK_MINIMUM_GRACE_PERIOD has expired, and with * exponential fall off for each successive failed attempt until the grace period is * FRAUD_CHECK_MAXIMUM_GRACE_PERIOD. * * See bug CORE-18851 */ class FraudCheckRequestThrottler { public: FraudCheckRequestThrottler() : m_last_failed_request(0.0), m_grace_period(0) {} void RequestFailed(); void RequestSucceeded() { m_grace_period = 0; } // Reset grace period /// Should making a fraud check be allowed now, or are we still in the grace period from a previous failed check BOOL AllowRequestNow(); private: double m_last_failed_request; // GetRuntimeMS() time of the last failed request or 0.0 if nothing has ever failed unsigned m_grace_period; // seconds from one failed request until we can try a new request }; class DochandModule : public OperaModule { public: DochandModule(); void InitL(const OperaInitInfo& info); void Destroy(); WindowManager* window_manager; #ifdef TRUST_RATING FraudCheckRequestThrottler fraud_request_throttler; #endif // TRUST_RATING #ifdef WEBSERVER_SUPPORT OperaURL_Generator* unitewarningpage_generator; #endif // WEBSERVER_SUPPORT }; #define g_windowManager g_opera->dochand_module.window_manager #define windowManager g_windowManager #ifdef TRUST_RATING # define g_fraud_check_request_throttler g_opera->dochand_module.fraud_request_throttler #endif // TRUST_RATING #define DOCHAND_MODULE_REQUIRED #endif // !MODULES_DOCHAND_DOCHAND_MODULE_H
// // main.cpp // Tarea1Ejercicio2 // // Created by Daniel on 26/08/14. // Copyright (c) 2014 Gotomo. All rights reserved. // #include <iostream> #define N 6 void imprimir(int **a); bool resolver(int **a, int x, int y); int main(int argc, const char * argv[]) { /*construir laberinto * 1 casilla disponible * 0 casilla prohibida * 2 camino correcto * 3 camino erroneo */ int** matriz = new int*[N]; for(int i = 0; i < N; i++){ matriz[i] = new int[N]; for(int j = 0; j<N; j++){ matriz[i][j] = 0; } } matriz[0][0] = 1; matriz[0][1] = 1; matriz[1][1] = 1; matriz[1][2] = 1; matriz[1][3] = 1; matriz[1][4] = 1; matriz[2][4] = 1; matriz[3][4] = 1; matriz[4][4] = 1; matriz[5][4] = 1; matriz[5][5] = 1; matriz[2][1] = 1; matriz[3][1] = 1; matriz[3][2] = 1; matriz[4][1] = 1; /*fin construccion laberinto*/ imprimir(matriz); std::cout<<std::endl; std::cout<<std::endl; if(resolver(matriz, 0,0)){ imprimir(matriz); } else{ std::cout<<"Impossible"; } return 0; } void imprimir(int **a){ std::cout<<std::endl; for(int i = 0; i<N; i++){ for(int j = 0; j < N; j++){ std::cout<<a[i][j]<<" "; } std::cout<<std::endl; } } bool resolver(int **a, int x, int y){ if((x == N-1) &&(y == N-1)) { a[x][y] = 2; std::cout<<"Completado"; return true; } else if((x+1< N)&&(a[x+1][y] == 1)){ std::cout<<"Abajo, "; a[x][y] = 2; return resolver(a, x+1, y); } else if((y+1< N)&&(a[x][y+1] == 1)){ std::cout<<"Derecha, "; a[x][y] = 2; return resolver(a, x, y+1); } else if((x-1 >= 0)&&(a[x-1][y] == 1)){ std::cout<<"Arriba, "; a[x][y] = 2; return resolver(a, x -1, y); } else if((y-1 >= 0)&&(a[x][y-1] == 1)){ std::cout<<"Izquierda, "; a[x][y] = 2; return resolver(a, x, y-1); } //regresar else if((x+1< N)&&(a[x+1][y] == 2)){ std::cout<<"regresar Abajo, "; a[x][y] = 3; return resolver(a, x +1, y); } else if((y+1< N)&&(a[x][y+1] == 2)){ std::cout<<"regresar Derecha, "; a[x][y] = 3; return resolver(a, x, y+1); } else if((x-1>= 0)&&(a[x-1][y] == 2)){ std::cout<<"regresar Arriba, "; a[x][y] = 3; return resolver(a, x-1, y); } else if((y-1 >= 0)&&(a[x][y-1] == 2)){ std::cout<<"regresar Izquierda, "; a[x][y] = 3; return resolver(a, x, y-1); } else{ std::cout<<"x = "<<x<<", y = "<<y<<", break"<<std::endl; return false; } }
#include "config.h" #include <iostream> #include <QDomDocument> namespace httpserver { QString configFileLocation = "config.xml"; std::map<QString, ConfigValue> Config::s_configDeclarations = { std::make_pair("port", ConfigValue::Port), std::make_pair("not_found_page_location", ConfigValue::NotFoundPageLocation), std::make_pair("server_root", ConfigValue::ServerRoot), }; ////////////////////////////////////////////////////////////////////////////// Config::Config() { } ////////////////////////////////////////////////////////////////////////////// bool Config::load() { QFile configFile(configFileLocation); QDomDocument document; if (!configFile.open(QIODevice::ReadOnly) || !document.setContent(&configFile)) return false; auto root = document.documentElement(); auto childNodes = root.childNodes(); for (int i = 0, sz = childNodes.count(); i < sz; i++) { const auto& configNode = childNodes.at(i).toElement(); QString name = configNode.attribute("name"); QString value = configNode.attribute("value"); auto configDeclaration = s_configDeclarations.find(name); if (configDeclaration == s_configDeclarations.end()) return false; ConfigValue configType = configDeclaration->second; switch (configType) { case ConfigValue::Port: { int port; if (!parseInt(value, port)) return false; m_port = port; } break; case ConfigValue::NotFoundPageLocation: m_notFoundPageLocation = value; break; case ConfigValue::ServerRoot: m_rootLocation = value; break; } } return true; } ////////////////////////////////////////////////////////////////////////////// bool Config::parseInt(const QString& textValue, int& value) const { bool isOk; value = textValue.toInt(&isOk); return isOk; } ////////////////////////////////////////////////////////////////////////////// }
#pragma once class CPong { public: void start(); };
/*============================================================================= /*----------------------------------------------------------------------------- /* [JSONHelper.h] RapidJSONヘルパークラス /* Author:Kousuke,Ohno. /*----------------------------------------------------------------------------- /* 説明:JSON操作ヘルパークラス =============================================================================*/ #ifndef JSON_HELPER_H_ #define JSON_HELPER_H_ /*--- インクルードファイル ---*/ #include "../StdAfx.h" /*--- 構造体定義 ---*/ /*--- クラスの前方宣言 ---*/ /*------------------------------------- /* RapidJSONヘルパークラス -------------------------------------*/ class JSONHelper { private: JSONHelper(void); public: ~JSONHelper(void); //サンプル関数 static void RapidJSONSampler(void); //////////////////////////////////////////////////////////////////////////////////// /*==================== JSONオブジェクトのプロパティGet関数群 ====================*/ //////////////////////////////////////////////////////////////////////////////////// // GetInt()は,成功した場合に true を返します. // 1番目のパラメータには、JSONオブジェクトを入力。 // 2番目のパラメータには、オブジェクト内のプロパティ名を入力。 // 3番目のパラメータにオブジェクト内のプロパティから取得する値が出力されます。 // さらに、プロパティが見つからなかった場合、戻り値を変更しないことが保証されています。 static bool GetInt(const rapidjson::Value& inObject, const char* inPropertyName, int& outInt); // GetFloat()は,成功した場合に true を返します. // 1番目のパラメータには、JSONオブジェクトを入力。 // 2番目のパラメータには、オブジェクト内のプロパティ名を入力。 // 3番目のパラメータにオブジェクト内のプロパティから取得する値が出力されます。 // さらに、プロパティが見つからなかった場合、戻り値を変更しないことが保証されています。 static bool GetFloat(const rapidjson::Value& inObject, const char* inPropertyName, float& outFloat); // GetDouble()は,成功した場合に true を返します. // 1番目のパラメータには、JSONオブジェクトを入力。 // 2番目のパラメータには、オブジェクト内のプロパティ名を入力。 // 3番目のパラメータにオブジェクト内のプロパティから取得する値が出力されます。 // さらに、プロパティが見つからなかった場合、戻り値を変更しないことが保証されています。 static bool GetDouble(const rapidjson::Value& inObject, const char* inPropertyName, double& outDouble); // GetString()は,成功した場合に true を返します. // 1番目のパラメータには、JSONオブジェクトを入力。 // 2番目のパラメータには、オブジェクト内のプロパティ名を入力。 // 3番目のパラメータにオブジェクト内のプロパティから取得する値が出力されます。 // さらに、プロパティが見つからなかった場合、戻り値を変更しないことが保証されています。 static bool GetString(const rapidjson::Value& inObject, const char* inPropertyName, std::string& outStr); // GetBool()は,成功した場合に true を返します. // 1番目のパラメータには、JSONオブジェクトを入力。 // 2番目のパラメータには、オブジェクト内のプロパティ名を入力。 // 3番目のパラメータにオブジェクト内のプロパティから取得する値が出力されます。 // さらに、プロパティが見つからなかった場合、戻り値を変更しないことが保証されています。 static bool GetBool(const rapidjson::Value& inObject, const char* inPropertyName, bool& outBool); //////////////////////////////////////////////////////////////////////////////////// /*==================== JSONオブジェクトのプロパティSet関数群 ====================*/ //////////////////////////////////////////////////////////////////////////////////// // AddInt()は,JSONのDocumentに、int型のデータメンバを追加します。 // 1番目のパラメータには、JSONのDocumentを入力。 // 2番目のパラメータには、JSONオブジェクトを入力。 // 3番目のパラメータには、プロパティ名を命名して入力。 // 4番目のパラメータには、命名したプロパティが含むint型の"値"を入力。 // さらに、入力した値がint型でなかった場合、警告を発行します。 static void AddInt(rapidjson::Document::AllocatorType& alloc , rapidjson::Value& inObject , const char* inPropertyName , int value); // AddFloat()は,JSONのDocumentに、float型のデータメンバを追加します。 // 1番目のパラメータには、JSONのDocumentを入力。 // 2番目のパラメータには、JSONオブジェクトを入力。 // 3番目のパラメータには、プロパティ名を命名して入力。 // 4番目のパラメータには、命名したプロパティが含むfloat型の"値"を入力。 // さらに、入力した値がfloat型でなかった場合、警告を発行します。 static void AddFloat(rapidjson::Document::AllocatorType& alloc , rapidjson::Value& inObject , const char* inPropertyName , float value); // AddDouble()は,JSONのDocumentに、float型のデータメンバを追加します。 // 1番目のパラメータには、JSONのDocumentを入力。 // 2番目のパラメータには、JSONオブジェクトを入力。 // 3番目のパラメータには、プロパティ名を命名して入力。 // 4番目のパラメータには、命名したプロパティが含むdouble型の"値"を入力。 // さらに、入力した値がdouble型でなかった場合、警告を発行します。 static void AddDouble(rapidjson::Document::AllocatorType& alloc , rapidjson::Value& inObject , const char* inPropertyName , double value); // AddString()は,JSONのDocumentに、string型のデータメンバを追加します。 // 1番目のパラメータには、JSONのDocumentを入力。 // 2番目のパラメータには、JSONオブジェクトを入力。 // 3番目のパラメータには、プロパティ名を命名して入力。 // 4番目のパラメータには、命名したプロパティが含むstring型の"値"を入力。 // さらに、入力した値がstring型でなかった場合、警告を発行します。 static void AddString(rapidjson::Document::AllocatorType& alloc , rapidjson::Value& inObject , const char* inPropertyName , const std::string& value); // AddBool()は,JSONのDocumentに、bool型のデータメンバを追加します。 // 1番目のパラメータには、JSONのDocumentを入力。 // 2番目のパラメータには、JSONオブジェクトを入力。 // 3番目のパラメータには、プロパティ名を命名して入力。 // 4番目のパラメータには、命名したプロパティが含むbool型の"値"を入力。 // さらに、入力した値がbool型でなかった場合、警告を発行します。 static void AddBool(rapidjson::Document::AllocatorType& alloc , rapidjson::Value& inObject , const char* inPropertyName , bool value); }; #endif //JSON_HELPER_H_ /*============================================================================= /* End of File =============================================================================*/
#include "stdafx.h" #include "Dict.h" using namespace Dictionary; Instance Dictionary::Create(const char name[DICTNAMEMAXSIZE], int size) { if (strlen(name) > DICTNAMEMAXSIZE) throw THROW01; if (size > DICTMAXSIZE) throw THROW02; Instance *dict = new Instance; dict->dictionary = new Entry[size]; dict->size = strlen(name); strcpy_s(dict->name, name); dict->maxsize = size; return *dict; } void Dictionary::AddEntry(Instance& inst, Entry ed) { if (ed.id > inst.maxsize) throw THROW03; if (inst.dictionary[ed.id - 1].id == ed.id) throw THROW04; inst.dictionary[ed.id - 1] = ed; } void Dictionary::DelEntry(Instance & inst, int id) { bool chckd = false; for (int i = 0; i < inst.maxsize; ++i) { if (inst.dictionary[i].id == id) { chckd = true; break; } } if (!chckd) { throw THROW06; } Entry *tempDict = new Entry[inst.maxsize--]; for (int i = 0, j = 0; j < inst.maxsize; ++i, ++j) { if (j == id) { i--; continue; } tempDict[i] = inst.dictionary[j]; } delete inst.dictionary; inst.maxsize = inst.maxsize--; inst.dictionary = new Entry[inst.maxsize]; for (int i = 0; i < inst.maxsize; ++i) { inst.dictionary[i] = tempDict[i]; } delete tempDict; } void Dictionary::UpdEntry(Instance& inst, int id, Entry new_ed) { if (inst.dictionary[id - 1].id == id) throw THROW08; if (id > inst.maxsize) throw THROW07; inst.dictionary[id - 1] = new_ed; } Entry Dictionary::GetEntr(Instance inst, int id) { if (id > inst.maxsize) throw THROW05; Entry entVal = inst.dictionary[id - 1]; return entVal; } void Dictionary::Print(Instance d) { std::cout << "---------------------------" << std::endl; std::cout << "Название словаря: " << d.name << std::endl; std::cout << "Элементы словаря: " << std::endl; for (int i = 0; i < d.maxsize; ++i) { std::cout << "Id: " << d.dictionary[i].id << " Название: " << d.dictionary[i].name << std::endl; } std::cout << "---------------------------" << std::endl; } void Dictionary::Delete(Instance& d) { delete d.dictionary; std::cout << "COMPLETE" << std::endl; }
#include"Sort3.h" void Swap(float& a,float& b) { float temp; temp=a; a=b; b=temp; } void Sort3(float& x,float& y,float& z) { if(x>y) Swap(x,y); else ; if(y>z) Swap(y,z); else ; if(x>y) Swap(x,y); else ; }
/** * @file AudioMachine.cpp * @brief Header file for Engine::AudioMachine * * @author Gemuele (Gem) Aludino * @date 09 Dec 2019 */ /** * Copyright © 2019 Gemuele Aludino * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH * THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "AudioMachine.h" #include <TaskerPerf/perftimer.h> #include <QThread> #include <QTimer> using Engine::AudioDevice; using Engine::AudioMachine; /** * @brief AudioMachine::AudioMachine */ AudioMachine::AudioMachine() : audioDevice(nullptr), qAudioInput(nullptr) { QAudioFormat format; // Set up the desired format, for example: format.setSampleRate(8000); format.setChannelCount(1); format.setSampleSize(8); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::UnSignedInt); // destinationFile.setFileName("/tmp/test.raw"); // destinationFile.open( QIODevice::WriteOnly | QIODevice::Truncate ); audioDevice = new AudioDevice(format); audioDevice->open(QIODevice::WriteOnly); // assign audio device here QAudioDeviceInfo info = QAudioDeviceInfo::defaultInputDevice(); QList<QAudioDeviceInfo> devices = QAudioDeviceInfo::availableDevices(QAudio::Mode::AudioInput); qDebug()<<"Available Devices:"; for(QAudioDeviceInfo i: devices) { qDebug()<<"device info:"<<i.isNull(); } if (!info.isFormatSupported(format)) { qDebug( "Default format not supported, trying to use the nearest."); format = info.nearestFormat(format); } qAudioInput = new QAudioInput(format, this); // connect(audio, SIGNAL(stateChanged(QAudio::State)), this, SLOT(handleStateChanged(QAudio::State))); // QTimer::singleShot(3000, this, SLOT(stopRecording())); // qDebug()<<"calling start on destinationFile "; // qDebug()<<"audiomachine thread:"<<QThread::currentThreadId(); // show device name on console qDebug()<<info.deviceName(); qAudioInput->start(audioDevice); qAudioInput->setVolume(0.0); audioDevice->setMinAmplitude(audioDevice->getDeviceLevel()); qAudioInput->setVolume(1.0); } /** * @brief AudioMachine::~AudioMachine */ AudioMachine::~AudioMachine() { delete qAudioInput; delete audioDevice; } /** * @brief AudioMachine::getAudioDevice * @return */ AudioDevice *&AudioMachine::getAudioDevice() { return audioDevice; } /** * @brief AudioMachine::getQAudioInput * @return */ QAudioInput *&AudioMachine::getQAudioInput() { return qAudioInput; } /** * @brief AudioMachine::handleStateChanged * @param newState */ void AudioMachine::handleStateChanged(QAudio::State newState) { switch (newState) { case QAudio::StoppedState: if (qAudioInput->error() != QAudio::NoError) { // Error handling } else { // Finished recording qDebug("stopped state"); } break; case QAudio::ActiveState: // Started recording - read from IO device qDebug("active state"); default: // ... other cases as appropriate break; } } /** * @brief AudioMachine::stopRecording */ void AudioMachine::stopRecording() { qAudioInput->stop(); audioDevice->close(); delete qAudioInput; qAudioInput = nullptr; delete audioDevice; audioDevice = nullptr; }
/* * Copyright (c) 2011 Pierre-Etienne Bougué <pe.bougue(a)gmail.com> * Copyright (c) 2011 Florian Colin <florian.colin28(a)gmail.com> * Copyright (c) 2011 Kamal Fadlaoui <kamal.fadlaoui(a)gmail.com> * Copyright (c) 2011 Quentin Lequy <quentin.lequy(a)gmail.com> * Copyright (c) 2011 Guillaume Pinot <guillaume.pinot(a)tremplin-utc.net> * Copyright (c) 2011 Cédric Royer <cedroyer(a)gmail.com> * Copyright (c) 2011 Guillaume Turri <guillaume.turri(a)gmail.com> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #ifndef STRATEGYGENERATION_HH #define STRATEGYGENERATION_HH #include <list> #include <boost/program_options.hpp> #include <boost/shared_ptr.hpp> using namespace std; using namespace boost; using namespace boost::program_options; class ContextBO; class StrategyGeneration { public: virtual ~StrategyGeneration() = 0; /** * Methode de generation d'instance. * @param arg_p Les arguments fournis au binaire (via la ligne de commande) * afin de permettre a chaque classe concrete de solliciter ces propres arguments * @return la liste des instances generees, sous forme d'une liste de ContextBO * Il suffit ensuite de fournir ces ContextBO a un writer pour generer les fichiers souhaites * (Les perfs n'etant pas cruciales sur ce binaire, on en se prive pas d'utiliser des smart pointers) */ virtual list<shared_ptr<ContextBO> > generate(const variables_map& arg_p) = 0; }; #endif
#include "stdafx.h" #include "MusicFade.h" #include "Fade.h" void MusicFade::OnDestroy() { if (m_Music != nullptr) m_Music->Stop(); } void MusicFade::init(Sound * music,float vol,float speed) { m_Music = music; m_vol = vol; if (speed < 0) { m_speed = FindGO<Fade>("fade")->GetSpeed(); } else m_speed = speed; } void MusicFade::Update() { if (m_Music == nullptr) { DeleteGO(this); return; } else { m_Music->SetVolume(m_vol); } m_vol -= m_speed * IGameTime().GetFrameDeltaTime(); if (m_vol <= 0) { m_Music->Stop(); DeleteGO(this); m_vol = 0; } }
#include <iostream> #include <vector> using namespace std; int main(){ vector<int> measurements = vector<int>(); int num; int numIncreased = 0; int x1, x2; while(cin >> num){ measurements.push_back(num); } for(auto it = measurements.begin(); it < measurements.end(); it++){ if(it + 3 >= measurements.end()){ break; } x1 = it[0] + it[1] + it[2]; x2 = it[1] + it[2] + it[3]; if(x1 < x2){ numIncreased++; } } cout << numIncreased; return 0; }
#ifndef EMPLOYEE_H #define EMPLOYEE_H using namespace std; //#include "headers.h" #include <string> #include <iostream> #include <unistd.h> class Employee { private: string name_; string surname_; string office_; string salary_; public: Employee(){} void setName(string str){name_ = str;} void setSurname(string str){surname_ = str;} void setOffice(string str); void setSalary(string str){salary_ = str;} string getName(){return name_;} string getSurname(){return surname_;} string getOffice(){return office_;} string getSalary(){return salary_;} virtual void getInfo(){} virtual void getSumSalary(){} }; #endif // EMPLOYEE_H
#include "trainer.h" trainer::trainer() { }
#include<stdio.h> int main(int argc, char const *argv[]) { int a[20]; int i; for(i=0;i<=19;i++) scanf("%c",&a[i]); for(i=19;i>=0;i--) printf("%c",a[i]); return 0; }
#ifndef SHADER_H #define SHADER_H #include <string> #include <stb_image.h> #include <glad/glad.h> class VertexArrayObject { public: GLuint id; void init(); // Select this VAO for subsequent draw calls void bind(); void free(); }; class VertexBufferObject { public: GLuint id; int attrib_num; void init(); // Updates the VBO with a 1D array M void update(const GLfloat *M, int size, int attr_num); void update(const GLint *M, int size, int attr_num); // Select this VBO for subsequent draw calls void bind(); void free(); }; class ElementBufferObject { public: GLuint id; ElementBufferObject(); // Updates the EBO with a 1D array M void update(const GLuint *M, int mRows, int mCols); // Select this EBO for subsequent draw calls void bind(); void free(); }; // This class wraps an OpenGL program composed of two shaders class Program { public: GLuint vertex_shader; GLuint fragment_shader; GLuint geometry_shader; GLuint program_shader; Program(); // Create a new shader from the specified source strings bool init(const std::string &fragment_data_name); void attach(GLenum type, std::string &shader_string); // Select this shader for subsequent draw calls void bind(); // Release all OpenGL objects void free(); // Return the OpenGL handle of a named shader attribute (-1 if it does not exist) GLint attrib(const std::string &name) const; // Return the OpenGL handle of a uniform attribute (-1 if it does not exist) GLint uniform(const std::string &name) const; // Bind a per-vertex array attribute GLint bindVertexAttribArray(const std::string &name, VertexBufferObject& VBO) const; GLuint create_shader_helper(GLint type, const std::string &shader_string); }; class Texture { public: GLuint id; int width; int height; int channels; Texture() { glGenTextures(1, &id); } ~Texture() { glDeleteTextures(1, &id); } void load(GLenum active_texture, const std::string filename); }; // From: https://blog.nobel-joergensen.com/2013/01/29/debugging-opengl-using-glgeterror/ void _check_gl_error(const char *file, int line); /// /// Usage /// [... some opengl calls] /// glCheckError(); /// #define check_gl_error() _check_gl_error(__FILE__,__LINE__) #endif
#include "FogShader.h" FogShader::FogShader() { } FogShader::FogShader(std::shared_ptr<Graphics> graphics) { m_Graphics = graphics; } FogShader::~FogShader() { } bool FogShader::Initialize(HWND hwnd) { if (!InitializeShader(hwnd, "FogVertex.cso", "FogPixel.cso")); return true; } bool FogShader::Render(int vertexCount, int instanceCount, DirectX::SimpleMath::Matrix worldMatrix, DirectX::SimpleMath::Matrix viewMatrix, DirectX::SimpleMath::Matrix projectionMatrix, ID3D11ShaderResourceView * texture, DirectX::SimpleMath::Vector3 lightDirection, DirectX::SimpleMath::Vector4 diffuseColor, DirectX::SimpleMath::Vector4 ambientColor, float fogStart, float fogEnd) { if (!SetShaderParameters(vertexCount, instanceCount, worldMatrix, viewMatrix, projectionMatrix, texture, lightDirection, diffuseColor, ambientColor, fogStart, fogEnd)) { return false; } RenderShader(vertexCount, instanceCount); return true; } bool FogShader::InitializeShader(HWND hwnd, std::string vertexShaderFile, std::string pixelShaderFile) { HRESULT result; Microsoft::WRL::ComPtr<ID3D10Blob> errorMessage; D3D11_INPUT_ELEMENT_DESC polygonLayout[4]; unsigned int numElements; // Initialize the pointers this function will use to null. errorMessage.Reset(); auto vertexShader = std::make_unique<ShaderFileType>(); auto pixelShader = std::make_unique<ShaderFileType>(); if (!GetShaderFile(vertexShaderFile, vertexShader.get())) { return false; } auto device = m_Graphics->getRenderer()->getDevice(); result = device->CreateVertexShader(vertexShader->data, vertexShader->length, NULL, m_vertexShader.ReleaseAndGetAddressOf()); if (FAILED(result)) { return false; } if (!GetShaderFile(pixelShaderFile, pixelShader.get())) { return false; } result = device->CreatePixelShader(pixelShader->data, pixelShader->length, NULL, m_pixelShader.ReleaseAndGetAddressOf()); if (FAILED(result)) { return false; } polygonLayout[0].SemanticName = "POSITION"; polygonLayout[0].SemanticIndex = 0; polygonLayout[0].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[0].InputSlot = 0; polygonLayout[0].AlignedByteOffset = 0; polygonLayout[0].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[0].InstanceDataStepRate = 0; polygonLayout[1].SemanticName = "TEXCOORD"; polygonLayout[1].SemanticIndex = 0; polygonLayout[1].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[1].InputSlot = 0; polygonLayout[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[1].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[1].InstanceDataStepRate = 0; polygonLayout[2].SemanticName = "TEXCOORD"; polygonLayout[2].SemanticIndex = 1; polygonLayout[2].Format = DXGI_FORMAT_R32G32_FLOAT; polygonLayout[2].InputSlot = 1; polygonLayout[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[2].InputSlotClass = D3D11_INPUT_PER_INSTANCE_DATA; polygonLayout[2].InstanceDataStepRate = 1; polygonLayout[3].SemanticName = "NORMAL"; polygonLayout[3].SemanticIndex = 0; polygonLayout[3].Format = DXGI_FORMAT_R32G32B32_FLOAT; polygonLayout[3].InputSlot = 0; polygonLayout[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT; polygonLayout[3].InputSlotClass = D3D11_INPUT_PER_VERTEX_DATA; polygonLayout[3].InstanceDataStepRate = 0; numElements = sizeof(polygonLayout) / sizeof(polygonLayout[0]); // Create the vertex input layout. result = device->CreateInputLayout(polygonLayout, numElements, vertexShader->data, vertexShader->length, m_layout.ReleaseAndGetAddressOf()); if (FAILED(result)) { return false; } if (!CreateBuffers()) { return false; } if (!CreateSamplerState()) { return false; } delete vertexShader->data; delete pixelShader->data; return true; } bool FogShader::CreateBuffers() { if (!CreateMatrixBuffer()) { return false; } if (!CreateLightBuffer()) { return false; } if (!CreateFogBuffer()) { return false; } return true; } bool FogShader::CreateFogBuffer() { HRESULT result; D3D11_BUFFER_DESC fogBufferDesc; // Setup the description of the dynamic fog constant buffer that is in the vertex shader. fogBufferDesc.Usage = D3D11_USAGE_DYNAMIC; fogBufferDesc.ByteWidth = sizeof(FogBufferType); fogBufferDesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; fogBufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; fogBufferDesc.MiscFlags = 0; fogBufferDesc.StructureByteStride = 0; result = m_Graphics->getRenderer()->getDevice()->CreateBuffer(&fogBufferDesc, NULL, m_fogBuffer.ReleaseAndGetAddressOf()); if (FAILED(result)) { return false; } return true; } bool FogShader::SetShaderParameters(int vertexCount, int instanceCount, DirectX::SimpleMath::Matrix worldMatrix, DirectX::SimpleMath::Matrix viewMatrix, DirectX::SimpleMath::Matrix projectionMatrix, ID3D11ShaderResourceView * texture, DirectX::SimpleMath::Vector3 lightDirection, DirectX::SimpleMath::Vector4 diffuseColor, DirectX::SimpleMath::Vector4 ambientColor, float fogStart, float fogEnd) { HRESULT result; D3D11_MAPPED_SUBRESOURCE mappedResource; MatrixBufferType* dataPtr; LightBufferType* dataPtr2; FogBufferType* dataPtr3; unsigned int bufferNumber; // Transpose the matrices to prepare them for the shader. worldMatrix = worldMatrix.Transpose(); viewMatrix = viewMatrix.Transpose(); projectionMatrix = projectionMatrix.Transpose(); auto deviceContext = m_Graphics->getRenderer()->getContext(); //////////////////////////////////////////////////////// // //////////////////////////////////////////////////////// // Lock the constant buffer so it can be written to. result = deviceContext->Map(m_matrixBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr = (MatrixBufferType*)mappedResource.pData; // Copy the matrices into the constant buffer. dataPtr->world = worldMatrix; dataPtr->view = viewMatrix; dataPtr->projection = projectionMatrix; // Unlock the constant buffer. deviceContext->Unmap(m_matrixBuffer.Get(), 0); // Set the position of the constant buffer in the vertex shader. bufferNumber = 0; // Finanly set the constant buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, m_matrixBuffer.GetAddressOf()); // Set shader texture resource in the pixel shader deviceContext->PSSetShaderResources(0, 1, &texture); //////////////////////////////////////////////////////// // //////////////////////////////////////////////////////// // Lock the light constant buffer so it can be written to. result = deviceContext->Map(m_lightBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr2 = (LightBufferType*)mappedResource.pData; // Copy the lighting variables into the constant buffer. dataPtr2->ambientColor = ambientColor; dataPtr2->diffuseColor = diffuseColor; dataPtr2->lightDirection = lightDirection; dataPtr2->padding = 0.0f; // Unlock the constant buffer. deviceContext->Unmap(m_lightBuffer.Get(), 0); // Set the position of the light constant buffer in the pixel shader. bufferNumber = 0; // Finally set the light constant buffer in the pixel shader with the updated values. deviceContext->PSSetConstantBuffers(bufferNumber, 1, m_lightBuffer.GetAddressOf()); //////////////////////////////////////////////////////// // //////////////////////////////////////////////////////// // Lock the fog constant buffer so it can be written to. result = deviceContext->Map(m_fogBuffer.Get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource); if (FAILED(result)) { return false; } // Get a pointer to the data in the constant buffer. dataPtr3 = (FogBufferType*)mappedResource.pData; // Copy the fog information into the fog constant buffer. dataPtr3->fogStart = fogStart; dataPtr3->fogEnd = fogEnd; // Unlock the constant buffer. deviceContext->Unmap(m_fogBuffer.Get(), 0); // Set the position of the fog constant buffer in the vertex shader. bufferNumber = 1; // Now set the fog buffer in the vertex shader with the updated values. deviceContext->VSSetConstantBuffers(bufferNumber, 1, m_fogBuffer.GetAddressOf()); return true; }
#include<cstdio> #include<cstring> #include<map> #include<vector> #include<queue> using namespace std; typedef map<int,int>::iterator IT; struct TRIE{ int pre,dep; int end; map<int,int> next; TRIE() { end=0; dep=0; next.clear(); } }; vector<TRIE> trie; int n,m; void input() { char ch; int x,tmp; scanf("%d\n",&n); trie.resize(2); trie[1].end=false; trie[1].dep=0; for(int i=0;i<n;++i) { x=1; for(ch=getchar();ch=='\0' || ch=='\n' || ch=='\r';ch=getchar()) ; do{ //printf("%c",ch); int v=ch<0?ch+256:ch; if(trie[x].next.count(v)) x=trie[x].next[v]; else { tmp=trie.size(); trie.push_back(TRIE()); trie[x].next[v]=tmp; trie[tmp].dep=trie[x].dep+1; x=tmp; } ch=getchar(); }while(ch!='\0' && ch!='\n' && ch!='\r'); //printf("\n"); trie[x].end=1; } } int find_pre(int pre_id,int i) { while(pre_id!=1) { if(trie[pre_id].next.count(i)) break; pre_id=trie[pre_id].pre; } if(trie[pre_id].next.count(i)) pre_id=trie[pre_id].next[i]; return pre_id; } void trie_pre_cal() { int pre_id; queue<int> que; trie[1].pre=1; IT it; for(it=trie[1].next.begin();it!=trie[1].next.end();++it) { trie[it->second].pre=1; que.push(it->second); } while(!que.empty()) { int x=que.front(); que.pop(); if(trie[x].end) continue; for(it=trie[x].next.begin();it!=trie[x].next.end();++it) { que.push(it->second); pre_id=find_pre(trie[x].pre,it->first); trie[it->second].pre=pre_id; if(!trie[it->second].end && trie[pre_id].end) trie[it->second].end=2; } } } void solve() { char ch; scanf("%d",&m); int line=-1,pos=-1; for(int i=0;i<m;++i) { int x=1; int cnt=0; for(ch=getchar();ch=='\0' || ch=='\n' || ch=='\r';ch=getchar()) ; do{ cnt++; if(line==-1){ int v=ch<0?ch+256:ch; if(trie[x].next.count(v)) x=trie[x].next[v]; else x=find_pre(trie[x].pre,v); if(trie[x].end){ line=i; if(trie[x].end==1) pos=cnt-trie[x].dep; else { for(x=trie[x].pre;trie[x].end!=1;x=trie[x].pre) ; pos=cnt-trie[x].dep; } } } ch=getchar(); }while(ch!='\0' && ch!='\n' && ch!='\r'); } if(line==-1) printf("Passed\n"); else printf("%d %d\n",line+1,pos+1); } int main() { freopen("u1269.in","r",stdin); input(); trie_pre_cal(); solve(); return 0; }
// Created on: 2016-11-14 // Created by: Irina KRYLOVA // Copyright (c) 2016 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 _StepVisual_CameraModelD3MultiClippingUnion_HeaderFile #define _StepVisual_CameraModelD3MultiClippingUnion_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <StepGeom_GeometricRepresentationItem.hxx> class StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect; class TCollection_HAsciiString; DEFINE_STANDARD_HANDLE(StepVisual_CameraModelD3MultiClippingUnion, StepGeom_GeometricRepresentationItem) class StepVisual_CameraModelD3MultiClippingUnion : public StepGeom_GeometricRepresentationItem { public: //! Returns a StepVisual_CameraModelD3MultiClippingUnion Standard_EXPORT StepVisual_CameraModelD3MultiClippingUnion(); Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& theName, const Handle(StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect)& theShapeClipping); void SetShapeClipping(const Handle(StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect)& theShapeClipping) { myShapeClipping = theShapeClipping; } const Handle(StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect) ShapeClipping() { return myShapeClipping; } DEFINE_STANDARD_RTTIEXT(StepVisual_CameraModelD3MultiClippingUnion, StepGeom_GeometricRepresentationItem) private: Handle(StepVisual_HArray1OfCameraModelD3MultiClippingUnionSelect) myShapeClipping; }; #endif // _StepVisual_CameraModelD3MultiClippingUnion_HeaderFile
#include "game.h" #include "..\\engine\scene.h" #include "..\\engine\text_component.h" bool Game::Startup() { bool success = engine_->Startup(); score_event_handle_ = engine_->GetSystem<EntityEventDispatcher>() ->Subscribe("score", std::bind(&Game::OnScore, this, std::placeholders::_1)); monch_handle_ = engine_->GetSystem<EntityEventDispatcher>() ->Subscribe("food_devoured", std::bind(&Game::OnMonch, this)); state_machine_ = new StateMachine<Game>(this); { State title_state; title_state.Enter = std::bind(&Game::TitleState_Enter, this); title_state.Update = std::bind(&Game::TitleState_Update, this); title_state.Exit = std::bind(&Game::TitleState_Exit, this); state_machine_->AddState("title", title_state); } { State start_state; start_state.Enter = std::bind(&Game::StartState_Enter, this); start_state.Update = std::bind(&Game::StartState_Update, this); state_machine_->AddState("start", start_state); } state_machine_->SetState("title"); return success; } void Game::Shutdown() { engine_->GetSystem<EntityEventDispatcher>()->Unsubscribe("score", score_event_handle_); engine_->GetSystem<EntityEventDispatcher>()->Unsubscribe("food_devoured", monch_handle_); engine_->Shutdown(); delete engine_; delete state_machine_; } void Game::Update() { engine_->Update(); quit_ = engine_->Quit(); state_machine_->Update(); } void Game::TitleState_Enter() { engine_->LoadScene("scenes/astro_blasters_title.json"); } void Game::TitleState_Update() { if (engine_->GetSystem<InputSystem>()->GetKey(SDL_SCANCODE_SPACE)) { state_machine_->SetState("start"); } } void Game::TitleState_Exit() { engine_->DestroyScene(); } void Game::StartState_Enter() { engine_->LoadScene("scenes/picnic.json"); } void Game::StartState_Update() { if (engine_->GetScene()->GetEntitiesWithTag("ant").size() == 0) { SpawnAntWave(g_random_int(6, 13)); SpawnCookieCrumb(); } } bool Game::OnMonch() { //if (--lives_ == 0) { // state_machine_->SetState("game_over"); //} lives_--; Entity* entity = engine_->GetScene()->GetEntityWithName("lives"); std::string lives = std::to_string(lives_); lives += " Lives Left"; entity->GetComponent<TextComponent>()->SetText(lives.c_str()); return true; } bool Game::OnScore(const Event<Entity>& event) { score_ += event.data[0].as_int; Entity* entity = engine_->GetScene()->GetEntityWithName("score"); std::string score = std::to_string(score_); entity->GetComponent<TextComponent>()->SetText(score.c_str()); return true; } void Game::SpawnAntWave(int ant_count) { for (int i = 0; i < ant_count; i++) { Entity* entity = engine_->GetScene()->GetObjectFactory()->Create<Entity>("red_ant"); bool left = static_cast<bool>(g_random_int(1)); bool top = static_cast<bool>(g_random_int(1)); float x; float y; if (left) { x = g_random(200); } else { x = g_random(600, 800); } if (top) { y = g_random(150); } else { y = g_random(450, 600); } entity->GetTransform().translation = vector2(x, y); engine_->GetScene()->Add(entity); } } void Game::SpawnCookieCrumb() { Entity* crumb = engine_->GetScene()->GetObjectFactory()->Create<Entity>("crumb"); crumb->GetTransform().translation = vector2(g_random(250, 350), g_random(200, 400)); engine_->GetScene()->Add(crumb); }
#include "treeface/gl/Errors.h" #include "treeface/gl/ImageRef.h" #include "treeface/gl/Texture.h" #include "treeface/graphics/Image.h" #include "treeface/graphics/ImageManager.h" #include "treeface/misc/Errors.h" #include "treeface/misc/PropertyValidator.h" #include "treeface/misc/StringCast.h" #include <treecore/DynamicObject.h> #include <treecore/Logger.h> #include <treecore/HashSet.h> #include <treecore/NamedValueSet.h> #include <treecore/String.h> #include <treecore/StringRef.h> #include <treecore/Variant.h> using namespace treecore; namespace treeface { const GLenum TEXTURE_UNITS[32] = { GL_TEXTURE0, GL_TEXTURE1, GL_TEXTURE2, GL_TEXTURE3, GL_TEXTURE4, GL_TEXTURE5, GL_TEXTURE6, GL_TEXTURE7, GL_TEXTURE8, GL_TEXTURE9, GL_TEXTURE10, GL_TEXTURE11, GL_TEXTURE12, GL_TEXTURE13, GL_TEXTURE14, GL_TEXTURE15, GL_TEXTURE16, GL_TEXTURE17, GL_TEXTURE18, GL_TEXTURE19, GL_TEXTURE20, GL_TEXTURE21, GL_TEXTURE22, GL_TEXTURE23, GL_TEXTURE24, GL_TEXTURE25, GL_TEXTURE26, GL_TEXTURE27, GL_TEXTURE28, GL_TEXTURE29, GL_TEXTURE30, GL_TEXTURE31, }; inline GLuint _gen_texture_() { GLuint result = 0; glGenTextures( 1, &result ); if (result == 0) die( "failed to generate texture" ); return result; } inline void _gl_tex_image_( GLenum target, GLint level, TextureCompatibleImageRef img ) { glTexImage2D( target, level, img.internal_format, img.width, img.height, 0, img.format, img.type, img.data ); } inline void _gl_tex_image_( GLenum target, GLint level, TextureCompatibleImageArrayRef img ) { glTexImage3D( target, level, img.internal_format, img.width, img.height, img.num_frame, 0, img.format, img.type, img.data ); } inline void _gl_tex_image_( GLenum target, GLint level, TextureCompatibleVoxelBlockRef img ) { glTexImage3D( target, level, img.internal_format, img.width, img.height, img.depth, 0, img.format, img.type, img.data ); } inline void _check_error_unbind_( GLTextureType type, const String& msg ) { GLenum err = glGetError(); if (err != GL_NO_ERROR) { glBindTexture( type, 0 ); switch (err) { case GL_INVALID_ENUM: throw GLInvalidEnum( "invalid enum while " + msg ); case GL_INVALID_VALUE: throw GLInvalidValue( "invalid value while " + msg ); case GL_INVALID_OPERATION: throw GLInvalidOperation( "invalid operation while " + msg ); default: throw std::runtime_error( "" ); } } } Texture::Texture( TextureCompatibleImageRef image, treecore::uint32 num_gen_mipmap ) : m_type( TFGL_TEXTURE_2D ) , m_texture( _gen_texture_() ) { glBindTexture( m_type, m_texture ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); _gl_tex_image_( m_type, 0, image ); _check_error_unbind_( m_type, "assigning 2D texture image" ); if (num_gen_mipmap) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating 2D texture mipmaps" ); } glBindTexture( m_type, 0 ); } Texture::Texture( GLsizei width, GLsizei height, GLsizei levels, GLInternalImageFormat internal_fmt ) : m_texture( _gen_texture_() ) , m_type( TFGL_TEXTURE_2D ) , m_immutable( true ) { glBindTexture( m_type, m_texture ); glTexStorage2D( m_type, levels, internal_fmt, width, height ); _check_error_unbind_( m_type, "creating immutable 2D texture" ); glBindTexture( m_type, 0 ); } Texture::Texture( treecore::ArrayRef<TextureCompatibleImageRef> images ) : m_texture( _gen_texture_() ) , m_type( TFGL_TEXTURE_2D ) { glBindTexture( m_type, m_texture ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, images.size() - 1 ); for (int level = 0; level < images.size(); level++) { _gl_tex_image_( m_type, level, images[level] ); _check_error_unbind_( m_type, "assigning 2D texture data for mipmap level " + String( level ) ); } glBindTexture( m_type, 0 ); } Texture::Texture( TextureCompatibleImageArrayRef images, uint32 num_gen_mipmap ) : m_texture( _gen_texture_() ) , m_type( TFGL_TEXTURE_2D_ARRAY ) { glBindTexture( m_type, m_texture ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); _gl_tex_image_( m_type, 0, images ); _check_error_unbind_( m_type, "assigning 2D texture array image data" ); if (num_gen_mipmap > 0) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating 2D texture array mipmaps" ); } glBindTexture( m_type, 0 ); } Texture::Texture( TextureCompatibleImageRef img_x_plus, TextureCompatibleImageRef img_x_minus, TextureCompatibleImageRef img_y_plus, TextureCompatibleImageRef img_y_minus, TextureCompatibleImageRef img_z_plus, TextureCompatibleImageRef img_z_minus, treecore::uint32 num_gen_mipmap ) : m_texture( _gen_texture_() ) , m_type( TFGL_TEXTURE_CUBE ) { glBindTexture( m_type, m_texture ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, img_x_plus ); _check_error_unbind_( m_type, "assigning 2D cube texture x+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, img_x_minus ); _check_error_unbind_( m_type, "assigning 2D cube texture x- image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, img_y_plus ); _check_error_unbind_( m_type, "assigning 2D cube texture y+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, img_y_minus ); _check_error_unbind_( m_type, "assigning 2D cube texture y- image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, img_z_plus ); _check_error_unbind_( m_type, "assigning 2D cube texture z+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, img_z_minus ); _check_error_unbind_( m_type, "assigning 2D cube texture z- image data" ); if (num_gen_mipmap > 0) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating 2D texture array mipmaps" ); } glBindTexture( m_type, 0 ); } Texture::Texture( TextureCompatibleVoxelBlockRef voxel, uint32 num_gen_mipmap ) : m_texture( _gen_texture_() ) , m_type( TFGL_TEXTURE_3D ) { glBindTexture( m_type, m_texture ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); _gl_tex_image_( m_type, 0, voxel ); _check_error_unbind_( m_type, "assigning 3D texture image data" ); if (num_gen_mipmap > 0) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating 3D texture mipmaps" ); } glBindTexture( m_type, 0 ); } #define KEY_NAME "name" #define KEY_IMG "image" #define KEY_MAG_LINEAR "mag_filter_linear" #define KEY_MIN_LINEAR "min_filter_linear" #define KEY_MIPMAP "mipmap" #define KEY_MIPMAP_LINEAR "mipmap_filter_linear" #define KEY_SLICES "slices" #define KEY_TYPE "type" #define KEY_WRAP_S "wrap_s" #define KEY_WRAP_T "wrap_t" #define KEY_POL_SOLO "solo_policy" #define KEY_POL_DUAL "dual_policy" #define KEY_POL_INT "int_policy" Result _validate_keys_( NamedValueSet& kv ) { static PropertyValidator* validator = nullptr; if (!validator) { validator = new PropertyValidator(); validator->add_item( KEY_IMG, PropertyValidator::ITEM_SCALAR | PropertyValidator::ITEM_ARRAY, true ); validator->add_item( KEY_MAG_LINEAR, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_MIN_LINEAR, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_MIPMAP, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_MIPMAP_LINEAR, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_SLICES, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_TYPE, PropertyValidator::ITEM_SCALAR, true ); validator->add_item( KEY_WRAP_S, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_WRAP_T, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_POL_SOLO, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_POL_DUAL, PropertyValidator::ITEM_SCALAR, false ); validator->add_item( KEY_POL_INT, PropertyValidator::ITEM_SCALAR, false ); } return validator->validate( kv ); } Texture::Texture( const treecore::var& tex_node ) : m_texture( _gen_texture_() ) { if ( !tex_node.isObject() ) throw std::runtime_error( "texture node is not KV" ); NamedValueSet& tex_kv = tex_node.getDynamicObject()->getProperties(); { Result re = _validate_keys_( tex_kv ); if (!re) throw ConfigParseError( re.getErrorMessage() ); } // // create OpenGL texture object // if ( !fromString( tex_kv[KEY_TYPE], m_type ) ) throw ConfigParseError( "failed to parse type from " + tex_kv[KEY_TYPE].toString() ); glBindTexture( m_type, m_texture ); // // load properties // bool mag_linear = false; if ( tex_kv.contains( KEY_MAG_LINEAR ) ) mag_linear = bool(tex_kv[KEY_MAG_LINEAR]); if (mag_linear) set_mag_filter( TFGL_TEXTURE_LINEAR ); else set_mag_filter( TFGL_TEXTURE_NEAREST ); if ( tex_kv.contains( KEY_WRAP_S ) ) { GLTextureWrap wrap_s; if ( !fromString( tex_kv[KEY_WRAP_S], wrap_s ) ) throw ConfigParseError( "failed to parse texture S wrap from " + tex_kv[KEY_WRAP_S].toString() ); set_wrap_s( wrap_s ); } if ( tex_kv.contains( KEY_WRAP_T ) ) { GLTextureWrap wrap_t; if ( !fromString( tex_kv[KEY_WRAP_T], wrap_t ) ) throw ConfigParseError( "failed to parse texture T wrap from " + tex_kv[KEY_WRAP_T].toString() ); set_wrap_t( wrap_t ); } TextureImageSoloChannelPolicy pol_solo = TEXTURE_IMAGE_SOLO_AS_LUMINANCE; TextureImageDualChannelPolicy pol_dual = TEXTURE_IMAGE_DUAL_AS_LUMINANCE_ALPHA; TextureImageIntDataPolicy pol_int = TEXTURE_IMAGE_INT_TO_FLOAT; if ( tex_kv.contains( KEY_POL_SOLO ) && !fromString( tex_kv[KEY_POL_SOLO], pol_solo ) ) throw ConfigParseError( "failed to parse solo policy from " + tex_kv[KEY_POL_SOLO].toString() ); if ( tex_kv.contains( KEY_POL_DUAL ) && !fromString( tex_kv[KEY_POL_DUAL], pol_dual ) ) throw ConfigParseError( "failed to parse dual policy from " + tex_kv[KEY_POL_DUAL].toString() ); if ( tex_kv.contains( KEY_POL_INT ) && !fromString( tex_kv[KEY_POL_INT], pol_int ) ) throw ConfigParseError( "failed to parse dual policy from " + tex_kv[KEY_POL_INT].toString() ); // // load image // uint32 num_gen_mipmap = 3; // multiple texture for mipmapped 2D texture or cube map texture if ( tex_kv[KEY_IMG].isArray() ) { Array<var>* image_name_nodes = tex_kv[KEY_IMG].getArray(); // load images specified for each mipmap if (m_type == TFGL_TEXTURE_2D) { num_gen_mipmap = image_name_nodes->size() - 1; glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); for (int level = 0; level < image_name_nodes->size(); level++) { String img_name = (*image_name_nodes)[level].toString(); Image* img = ImageManager::getInstance()->get_image( img_name ); _gl_tex_image_( m_type, level, img->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D texture data for mipmap level " + String( level ) ); } } // load six images for cube map else if (m_type == TFGL_TEXTURE_CUBE) { // parse mipmap level if ( tex_kv.contains( KEY_MIPMAP ) && !fromString( tex_kv[KEY_MIPMAP], num_gen_mipmap ) ) throw ConfigParseError( "failed to parse mipmap level from " + tex_kv[KEY_MIPMAP].toString() ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); // load images if (image_name_nodes->size() != 6) throw ConfigParseError( "invalid number of image for 2D cube map texture: " + String( image_name_nodes->size() ) ); Image* img_xp = ImageManager::getInstance()->get_image( (*image_name_nodes)[0].toString() ); Image* img_xn = ImageManager::getInstance()->get_image( (*image_name_nodes)[1].toString() ); Image* img_yp = ImageManager::getInstance()->get_image( (*image_name_nodes)[2].toString() ); Image* img_yn = ImageManager::getInstance()->get_image( (*image_name_nodes)[3].toString() ); Image* img_zp = ImageManager::getInstance()->get_image( (*image_name_nodes)[4].toString() ); Image* img_zn = ImageManager::getInstance()->get_image( (*image_name_nodes)[5].toString() ); // set texture image _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, img_xp->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture x+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, img_xn->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture x- image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, img_yp->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture y+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, img_yn->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture y- image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, img_zp->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture z+ image data" ); _gl_tex_image_( GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, img_zn->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D cube texture z- image data" ); // generate mipmap if (num_gen_mipmap > 0) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating 2D cube texture mipmaps" ); } } else { throw ConfigParseError( "texture type is " + tex_kv[KEY_TYPE].toString() + ", but data is 2D images which assume mipmapped texture 2D " ); } } // single image for 2D, 2D array or 3D texture else { // parse mipmap level if ( tex_kv.contains( KEY_MIPMAP ) && !fromString( tex_kv[KEY_MIPMAP], num_gen_mipmap ) ) throw ConfigParseError( "failed to parse mipmap level from " + tex_kv[KEY_MIPMAP].toString() ); glTexParameteri( m_type, GL_TEXTURE_BASE_LEVEL, 0 ); glTexParameteri( m_type, GL_TEXTURE_MAX_LEVEL, num_gen_mipmap ); // get image data Image* img = ImageManager::getInstance()->get_image( tex_kv[KEY_IMG].toString() ); // set texture image if (m_type == TFGL_TEXTURE_2D) { _gl_tex_image_( m_type, 0, img->get_texture_compatible_2d( pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D texture image data" ); } else if (m_type == TFGL_TEXTURE_2D_ARRAY || m_type == TFGL_TEXTURE_3D) { // get number of slices for 2D array or 3D texture GLsizei slices = 0; if ( !tex_kv.contains( KEY_SLICES ) ) throw ConfigParseError( "2D array or 3D texture don't have property " KEY_SLICES ); if ( !fromString( tex_kv[KEY_SLICES], slices ) ) throw ConfigParseError( "failed to parse slice number from " + tex_kv[KEY_SLICES].toString() ); _gl_tex_image_( m_type, 0, img->get_texture_compatible_3d( slices, pol_solo, pol_dual, pol_int ) ); _check_error_unbind_( m_type, "assigning 2D array or 3D texture image data" ); } // generate mipmap if (num_gen_mipmap > 0) { glGenerateMipmap( m_type ); _check_error_unbind_( m_type, "generating texture mipmaps" ); } } // set filter params bool min_linear = true; if ( tex_kv.contains( KEY_MIN_LINEAR ) ) min_linear = bool(tex_kv[KEY_MIN_LINEAR]); GLTextureFilter min_filter; if (num_gen_mipmap > 0) { bool mipmap_linear = true; if ( tex_kv.contains( KEY_MIPMAP_LINEAR ) ) mipmap_linear = bool(tex_kv[KEY_MIPMAP_LINEAR]); if (min_linear) { if (mipmap_linear) min_filter = TFGL_TEXTURE_LINEAR_MIPMAP_LINEAR; else min_filter = TFGL_TEXTURE_LINEAR_MIPMAP_NEAREST; } else { if (mipmap_linear) min_filter = TFGL_TEXTURE_NEAREST_MIPMAP_LINEAR; else min_filter = TFGL_TEXTURE_NEAREST_MIPMAP_NEAREST; } } else { if (min_linear) min_filter = TFGL_TEXTURE_LINEAR; else min_filter = TFGL_TEXTURE_NEAREST; } set_min_filter( min_filter ); glBindTexture( m_type, 0 ); } Texture::~Texture() { if (m_texture) glDeleteTextures( 1, &m_texture ); } GLuint Texture::get_current_bound_texture( GLTextureType type ) noexcept { GLenum pname = -1; GLint result = -1; switch (type) { case TFGL_TEXTURE_2D: pname = GL_TEXTURE_BINDING_2D; break; case TFGL_TEXTURE_2D_ARRAY: pname = GL_TEXTURE_BINDING_2D_ARRAY; break; case TFGL_TEXTURE_CUBE: pname = GL_TEXTURE_BINDING_CUBE_MAP; break; case TFGL_TEXTURE_3D: pname = GL_TEXTURE_BINDING_3D; break; default: abort(); } glGetIntegerv( pname, &result ); return GLuint( result ); } } // namespace treeface
#include <string> #include "Direction.hpp" #include "Board.hpp" #include <iterator> #include <map> #include <bits/stdc++.h> using namespace std; namespace ariel { /* * Initializes the minimum row and minimum column * to be what is given in the question, * if this is the first time something is added to the board. */ void Board::initializesFirstTime (unsigned int row, unsigned int column) { if(isFirstTime) { min_row=row; min_col=column; isFirstTime=false; } } /* *Function that updates the maximum and minimum row number, *the maximum and minimum column number, *according to the values given and previous data of the table. */ void Board::update_min_max_raw_col(unsigned int row, unsigned int column) { //row min-max update if(row>max_row) { max_row=row; } else if(row<min_row) { min_row=row; } //column min-max update if(column>max_col) { max_col=column; } if(column<min_col) { min_col=column; } } /* *Post horizantal messege on the board */ void Board::postHorizontal(unsigned int row, unsigned int column, string const & message) { int str_len=message.length(); initializesFirstTime (row,column); update_min_max_raw_col(row,column); for(size_t i=0;i<str_len;i++) { //max column update if(column>max_col) { max_col=column; } board_map[row][column]=message.at(i); column++; } } /* *Post vertical messege on the board */ void Board::postVertical(unsigned int row, unsigned int column, string const & message) { int str_len=message.length(); initializesFirstTime (row,column); update_min_max_raw_col(row,column); for(size_t i=0;i<str_len;i++) { //max row update if(row>max_row) { max_row=row; } board_map[row][column]=message.at(i); row++; } } /* *Post messege on the board */ void Board::post(unsigned int row, unsigned int column, Direction direction, string const & message) { //empty meesege if (message.length()<0) { return; } switch (direction) { case Direction::Horizontal: postHorizontal(row, column, message); break; case Direction::Vertical: postVertical(row, column, message); break; } } /* *A function that receives a row and a column *and returns the corresponding character on the board. */ char Board:: charInLoc(unsigned int row,unsigned int column) { map<unsigned int,map<unsigned int,char>>::iterator itr_rows; map<unsigned int,char>::iterator itr_columns; char char_in_loc=EMPTY_CHAR; itr_rows=board_map.find(row); //if the row exist in the map if(itr_rows!=board_map.end()) { itr_columns=(itr_rows->second).find(column); //if the column exist in the map if(itr_columns!=(itr_rows->second).end()) { char_in_loc=itr_columns->second; } } return char_in_loc; } /* *Read horizontal messege from the board */ string Board::readHorizontal(unsigned int row, unsigned int column, unsigned int length) { string ans; for (size_t i = 0; i < length; i++) { ans+=charInLoc(row,column+i); } return ans; } /* *Read vertical messege from the board */ string Board::readVertical(unsigned int row, unsigned int column, unsigned int length) { string ans; for (size_t i = 0; i < length; i++) { ans+=charInLoc(row+i,column); } return ans; } /* *Read horizontal messege from the board */ string Board::read(unsigned int row, unsigned int column, Direction direction, unsigned int length) { switch (direction) { case Direction::Horizontal: return(readHorizontal(row, column, length)); case Direction::Vertical: return(readVertical(row, column, length)); } } /* *A function that displays the board to the screen */ void Board::show() { cout<<"start column: "<<min_col<<" "<<endl<<endl; for(size_t row=min_row;row<=max_row;row++) { //print row number cout<<row<<": "; cout<<read( row, min_col, Direction::Horizontal,max_col-min_col+1); cout<<endl; } } };
// Created on: 1996-02-26 // Created by: Philippe MANGIN // 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 _FairCurve_MinimalVariation_HeaderFile #define _FairCurve_MinimalVariation_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <FairCurve_Batten.hxx> #include <FairCurve_AnalysisCode.hxx> #include <Standard_OStream.hxx> class gp_Pnt2d; class gp_Vec2d; //! Computes a 2D curve using an algorithm which //! minimizes tension, sagging, and jerk energy. As in //! FairCurve_Batten, two reference points are used. //! Unlike that class, FairCurve_MinimalVariation //! requires curvature settings at the first and second //! reference points. These are defined by the rays of //! curvature desired at each point. class FairCurve_MinimalVariation : public FairCurve_Batten { public: DEFINE_STANDARD_ALLOC //! Constructs the two contact points P1 and P2 and the geometrical //! characteristics of the batten (elastic beam) //! These include the real number values for height of //! deformation Height, slope value Slope, and kind of //! energy PhysicalRatio. The kinds of energy include: //! - Jerk (0) //! - Sagging (1). //! Note that the default setting for Physical Ration is in FairCurve_Batten //! Other parameters are initialized as follow : //! - FreeSliding = False //! - ConstraintOrder1 = 1 //! - ConstraintOrder2 = 1 //! - Angle1 = 0 //! - Angle2 = 0 //! - Curvature1 = 0 //! - Curvature2 = 0 //! - SlidingFactor = 1 //! Warning //! If PhysicalRatio equals 1, you cannot impose constraints on curvature. //! Exceptions //! NegativeValue if Height is less than or equal to 0. //! NullValue if the distance between P1 and P2 is less //! than or equal to the tolerance value for distance in //! Precision::Confusion: P1.IsEqual(P2, //! Precision::Confusion()). The function //! gp_Pnt2d::IsEqual tests to see if this is the case. //! Definition of the geometricals constraints Standard_EXPORT FairCurve_MinimalVariation(const gp_Pnt2d& P1, const gp_Pnt2d& P2, const Standard_Real Heigth, const Standard_Real Slope = 0, const Standard_Real PhysicalRatio = 0); //! Allows you to set a new constraint on curvature at the first point. void SetCurvature1 (const Standard_Real Curvature); //! Allows you to set a new constraint on curvature at the second point. void SetCurvature2 (const Standard_Real Curvature); //! Allows you to set the physical ratio Ratio. //! The kinds of energy which you can specify include: //! 0 is only "Jerk" Energy //! 1 is only "Sagging" Energy like batten //! Warning: if Ratio is 1 it is impossible to impose curvature constraints. //! Raises DomainError if Ratio < 0 or Ratio > 1 void SetPhysicalRatio (const Standard_Real Ratio); //! Computes the curve with respect to the constraints, //! NbIterations and Tolerance. The tolerance setting //! allows you to control the precision of computation, and //! the maximum number of iterations allows you to set a limit on computation time. Standard_EXPORT virtual Standard_Boolean Compute (FairCurve_AnalysisCode& ACode, const Standard_Integer NbIterations = 50, const Standard_Real Tolerance = 1.0e-3) Standard_OVERRIDE; //! Returns the first established curvature. Standard_Real GetCurvature1() const; //! Returns the second established curvature. Standard_Real GetCurvature2() const; //! Returns the physical ratio, or kind of energy. Standard_Real GetPhysicalRatio() const; //! Prints on the stream o information on the current state //! of the object. //! Is used to redefine the operator <<. Standard_EXPORT virtual void Dump (Standard_OStream& o) const Standard_OVERRIDE; protected: private: //! compute the curve with respect of the delta-constraints. Standard_EXPORT Standard_Boolean Compute (const gp_Vec2d& DeltaP1, const gp_Vec2d& DeltaP2, const Standard_Real DeltaAngle1, const Standard_Real DeltaAngle2, const Standard_Real DeltaCurvature1, const Standard_Real DeltaCurvature2, FairCurve_AnalysisCode& ACode, const Standard_Integer NbIterations, const Standard_Real Tolerance); Standard_Real OldCurvature1; Standard_Real OldCurvature2; Standard_Real OldPhysicalRatio; Standard_Real NewCurvature1; Standard_Real NewCurvature2; Standard_Real NewPhysicalRatio; }; #include <FairCurve_MinimalVariation.lxx> #endif // _FairCurve_MinimalVariation_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2012 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #ifndef OPNETWORKINTERFACE_H #define OPNETWORKINTERFACE_H #ifdef PI_NETWORK_INTERFACE_MANAGER class OpSocketAddress; /** @short Network interface status. */ enum OpNetworkInterfaceStatus { /** @short The network link (connection) is down. * * This means that the interface may not be used to reach remote hosts. */ NETWORK_LINK_DOWN, /** @short The network link (connection) is up. * * This means that the interface may be used to reach remote hosts. */ NETWORK_LINK_UP }; /** @short Network interface. */ class OpNetworkInterface { public: virtual ~OpNetworkInterface() { } /** @short Get the address associated with this network interface. * * To determine the type of address (localhost/loopback, private, public), * GetNetType() may be called on the object returned. * * @param[out] address Set to the local address associated with this * interface. May set to an empty address if the network link is down (so * that address->IsHostValid() would return FALSE, if called). The port * number part of the OpSocketAddress is not relevant. * * @return OK or ERR_NO_MEMORY. */ virtual OP_STATUS GetAddress(OpSocketAddress* address) = 0; /** @short Get the current status of this network interface. * * @return Whether the network link is up or not. */ virtual OpNetworkInterfaceStatus GetStatus() = 0; #ifdef PI_NETWORK_INTERFACE_INSPECTION /** @short Enum for different network connection types * */ enum NetworkType { UNKNOWN, //< any connection of a type not specified by this enum or impossible to detect the type. ETHERNET, //< wired ethernet connection WIFI, //< WiFi connection CELLULAR_RADIO, //< any cellular telphony connection. To get more info of what is the actual connection type (gsm, cdma etc) @see OpTelephonyNetworkInfo IRDA, //< infrared connection BLUETOOTH, //< bluetooth connection DIRECT_PC_LINK //< (e.g. ActiveSync) }; /** @short Type of physical connection used by this interface. */ virtual NetworkType GetNetworkType() = 0; /** @short Gets system identifier of the interface. eg "eth0" * * @param[out] id Set to the name of the interface. MUST not be NULL. * @return * - OK * - ERR_NOT_SUPPORTED - if the platform doesn't support this method * - ERR_NO_MEMORY - if OOM occured * - ERR - any other error. */ virtual OP_STATUS GetId(OpString* id) = 0; /** @short Gets the APN of the network interface. * * This method will succeed only for network types which support APN(CELLULAR_RADIO). * * @param[out] apn Set to the name of the interface. MUST not be NULL. * @return * - OK * - ERR_NO_SUCH_RESOURCE - if the interface doesn't have APN * - ERR_NOT_SUPPORTED - if the platform doesn't support this method * - ERR_NO_MEMORY - if OOM occured * - ERR - any other error. */ virtual OP_STATUS GetAPN(OpString* apn) = 0; /** @short Gets the SSID of used by the network interface. * * This method will succeed only for network types which support SSID(WIFI). * * @param[out] ssid Set to the name of the interface. MUST not be NULL. * @return * - OK * - ERR_NO_SUCH_RESOURCE - if the interface doesn't have SSID * - ERR_NOT_SUPPORTED - if the platform doesn't support this method * - ERR_NO_MEMORY - if OOM occured * - ERR - any other error. */ virtual OP_STATUS GetSSID(OpString* ssid) = 0; #endif //PI_NETWORK_INTERFACE_INSPECTION }; /** @short Network interface manager. * * It is implemented on the platform side. Methods are called from core. * * This class is typically used as a singleton object. * * This class owns OpNetworkInterface instances, and maintains a list of * them. When a network interface is added or removed on the system, this will * be reflected in the list, and the listener (if set) will be notified. The * listener will also be notified when something about an interface changes * (such as address change, or link going up or down). * * The list of OpNetworkInterface instances must not change while the * OpNetworkInterfaceManager is locked. The interfaces themselves (their state, * address, etc.) are allowed to change while the manager is locked, as long as * the list remains the same. It is locked by calling BeginEnumeration(), and * unlocked again with EndEnumeration(). */ class OpNetworkInterfaceManager { public: /** @short Create a new OpNetworkInterfaceManager object. * * @param[out] new_object Set to the new OpNetworkInterfaceManager object * created. The caller must ignore this value unless OpStatus::OK is * returned. * @param listener Listener for network interface changes. May be * NULL. Only interface additions and removals that take place after the * OpNetworkInterfaceManager has been created shall be reported via the * listener (i.e. don't report interfaces that already exist) * * @return ERR_NO_MEMORY on OOM, OK otherwise. */ static OP_STATUS Create(OpNetworkInterfaceManager** new_object, class OpNetworkInterfaceListener* listener); /** @short Destructor. * * The manager will be automatically unlocked here, and all the * OpNetworkInterface objects associated with this * OpNetworkInterfaceManager will be deleted, but that will not trigger * calls listener-OnInterfaceRemoved() in this case. */ virtual ~OpNetworkInterfaceManager() { } /** @short Change the listener for this network interface manager. * * @param listener New listener to set. NULL is allowed. */ virtual void SetListener(OpNetworkInterfaceListener* listener) = 0; /** @short Begin network interface enumeration. Lock the manager. * * While the manager is locked, the method GetNextInterface() may be * called, to list each interface. The first call to GetNextInterface() * will return the first interface, the second call will return the second * interface, and so on, until NULL is returned when there are no more * interfaces in the list. While the manager is locked, the list of * interfaces may not change. An interface's state is allowed to change, * though. * * The manager may be unlocked again by calling EndEnumeration(). * * Calling BeginEnumeration() when the manager is already locked will fail * with OpStatus::ERR. * * @return OK, ERR or ERR_NO_MEMORY. Any other value than OK means that * locking failed (so that calling GetNextInterface() will return NULL). */ virtual OP_STATUS BeginEnumeration() = 0; /** @short End network interface enumeration. Unlock the manager. * * Unlocks the manager after a previous call to BeginEnumeration(). * * Calling EndEnumeration() when the manager is not locked has is allowed, * but has no effect. */ virtual void EndEnumeration() = 0; /** @short Get the next interface in the list. * * May only be called while the manager is locked. See * BeginEnumeration(). The first call to GetNextInterface() after a * successful call to BeginEnumeration() will return the first interface in * the list, the second call will return the second interface in the list, * and so on, until NULL is returned when there are no more interfaces in * the list. * * @return The next network interface in the list, or NULL if there are no * more interfaces in the list. NULL is also returned if the manager is not * locked. */ virtual OpNetworkInterface* GetNextInterface() = 0; }; /** @short Listener for network interface related changes. * * Implemented in core. Methods are called from the platform side. */ class OpNetworkInterfaceListener { public: virtual ~OpNetworkInterfaceListener() { } /** @short A new network interface was added. * * The implementation of this method may want to call methods on the * OpNetworkInterface to get the current status and address. That may be * done synchronously from this method. * * @param nic The new interface that was added. The object is owned * by the platform side. Core may use the object until the * OpNetworkInterfaceManager is deleted, or OnInterfaceRemoved() is called * on this interface, whichever comes first. */ virtual void OnInterfaceAdded(OpNetworkInterface* nic) = 0; /** @short A network interface was removed. * * @param nic The interface that was removed. This object is about to * be deleted. Core must not use it during or after this call. */ virtual void OnInterfaceRemoved(OpNetworkInterface* nic) = 0; /** @short The status and/or address of a network interface changed. * * The implementation of this method should call methods on the * OpNetworkInterface to see what changed. That may be done synchronously * from this method. * * @param nic The interface whose status changed. */ virtual void OnInterfaceChanged(OpNetworkInterface* nic) = 0; }; #endif // PI_NETWORK_INTERFACE_MANAGER #endif // OPNETWORKINTERFACE_H
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- ** ** Copyright (C) 1995-2002 Opera Software AS. All rights reserved. ** ** This file is part of the Opera web browser. It may not be distributed ** under any circumstances. ** */ #ifndef DOM_TEXT_H #define DOM_TEXT_H #include "modules/dom/src/domcore/chardata.h" class DOM_EnvironmentImpl; class DOM_Text : public DOM_CharacterData { protected: friend class DOM_EnvironmentImpl; DOM_Text(DOM_NodeType type = TEXT_NODE); public: static OP_STATUS Make(DOM_Text *&text, DOM_Node *reference, const uni_char *contents); virtual ES_GetState GetName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual ES_PutState PutName(OpAtom property_name, ES_Value *value, ES_Runtime *origining_runtime); virtual BOOL IsA(int type) { return type == DOM_TYPE_TEXT || DOM_CharacterData::IsA(type); } OP_STATUS IsWhitespace(BOOL &is_whitespace); ES_GetState GetWholeText(ES_Value *value); DOM_DECLARE_FUNCTION(splitText); DOM_DECLARE_FUNCTION(replaceWholeText); enum { FUNCTIONS_BASIC = 1, FUNCTIONS_replaceWholeText, FUNCTIONS_ARRAY_SIZE }; }; #endif // DOM_TEXT_H
#define ButtonPin1 2 #define ButtonPin2 3 #define LedPin 13 #include <Arduino.h> int pin_reading1 = 0; int pin_reading2 = 0; int a = 0; void setup() { pinMode(ButtonPin1,INPUT_PULLUP); pinMode(ButtonPin2,INPUT_PULLUP); pinMode(LedPin,OUTPUT); } void loop() { pin_reading1 = digitalRead(ButtonPin1); pin_reading2 = digitalRead(ButtonPin2); if(pin_reading1 == LOW) { if(a<1) { a = a+1; } } if(pin_reading2 == LOW) { if(a>0) { a = a-1; } } if(a>0) { digitalWrite(LedPin,HIGH); } if(a<1) { digitalWrite(LedPin,LOW); } else { digitalWrite(LedPin,LOW); } }
#include "stdafx.h" #include "UIAnimationTabLayout.h" namespace UiLib{ CAnimationTabLayoutUI::CAnimationTabLayoutUI() : m_bIsRunning(false), m_bIsVerticalDirection(false), m_nPositiveDirection( 1 ) { m_AnimatID = 1001; m_iOldXOffset = 0; m_iOldYOffset = 0; m_nStep = 0; CControlUI::OnInit += MakeDelegate(this,&CAnimationTabLayoutUI::OnInit); } LPCTSTR CAnimationTabLayoutUI::GetClass() const { return _T("AnimationTabLayoutUI"); } LPVOID CAnimationTabLayoutUI::GetInterface(LPCTSTR pstrName) { if( _tcscmp(pstrName, _T("AnimationTabLayoutUI")) == 0 ) return static_cast<CAnimationTabLayoutUI*>(this); return CTabLayoutUI::GetInterface(pstrName); } bool CAnimationTabLayoutUI::SelectItem( int iIndex ) { if( iIndex < 0 || iIndex >= m_items.GetSize() ) return false; if( iIndex == m_iCurSel ) return true; if( iIndex > m_iCurSel ) m_nPositiveDirection = -1; if( iIndex < m_iCurSel ) m_nPositiveDirection = 1; m_iOldXOffset = 0; m_iOldYOffset = 0; if(m_bIsVerticalDirection) m_iOldYOffset = (m_rcItem.bottom-m_rcItem.top)*m_nPositiveDirection; else m_iOldXOffset = (m_rcItem.right-m_rcItem.left)*m_nPositiveDirection; m_rcCurPos = m_rcOldPos; m_iOldSel = m_iCurSel; m_iCurSel = iIndex; StopAnimation( m_AnimatID); StartAnimation( TAB_ANIMATION_ELLAPSE, TAB_ANIMATION_FRAME_COUNT, m_AnimatID); if( m_pManager != NULL ) { m_pManager->SetNextTabControl(); m_pManager->SendNotify(this, _T("tabselect"), m_iCurSel, m_iOldSel); } return true; } void CAnimationTabLayoutUI::AnimationSwitch() { if( !m_bIsVerticalDirection ) m_nStep = ( m_rcItem.right - m_rcItem.left ) * m_nPositiveDirection / GetTotalFram(m_AnimatID); else m_nStep = ( m_rcItem.bottom - m_rcItem.top ) * m_nPositiveDirection / GetTotalFram(m_AnimatID); if(!m_bIsRunning) { if( !m_bIsVerticalDirection ) { m_rcCurPos.top = m_rcItem.top; m_rcCurPos.bottom = m_rcItem.bottom; m_rcCurPos.left = m_rcItem.left - ( m_rcItem.right - m_rcItem.left ) * m_nPositiveDirection; m_rcCurPos.right = m_rcItem.right - ( m_rcItem.right - m_rcItem.left ) * m_nPositiveDirection; } else { m_rcCurPos.left = m_rcItem.left; m_rcCurPos.right = m_rcItem.right; m_rcCurPos.top = m_rcItem.top - ( m_rcItem.bottom - m_rcItem.top ) * m_nPositiveDirection; m_rcCurPos.bottom = m_rcItem.bottom - ( m_rcItem.bottom - m_rcItem.top ) * m_nPositiveDirection; } } } bool CAnimationTabLayoutUI::OnInit(void *param) { SetOwner(this); return true; } void CAnimationTabLayoutUI::DoEvent(TEventUI& event) { if( event.Type == UIEVENT_TIMER ) OnTimer( event.wParam ); __super::DoEvent( event ); } void CAnimationTabLayoutUI::OnTimer( int nTimerID ) { OnAnimationElapse( nTimerID ); } void CAnimationTabLayoutUI::OnAnimationStep(INT nTotalFrame, INT nCurFrame, INT nAnimationID) { int iStepLen = 0; if( !m_bIsVerticalDirection ) { if( nCurFrame <= nTotalFrame) { m_rcCurPos.left = m_rcCurPos.left + m_nStep; m_rcCurPos.right = m_rcCurPos.right +m_nStep; } else m_rcCurPos = m_rcItem; } else { if(nCurFrame <= nTotalFrame) { m_rcCurPos.top = m_rcCurPos.top + m_nStep; m_rcCurPos.bottom = m_rcCurPos.bottom +m_nStep; } else { m_rcCurPos = m_rcItem; } } CControlUI* pCur = static_cast<CControlUI *>(m_items[m_iCurSel]); if(pCur) pCur->SetPos(m_rcCurPos); CControlUI* pOld = static_cast<CControlUI *>(m_items[m_iOldSel]); RECT tmp = {m_rcCurPos.left+m_iOldXOffset,m_rcCurPos.top+m_iOldYOffset,m_rcCurPos.right+m_iOldXOffset,m_rcCurPos.bottom+m_iOldYOffset}; m_rcOldPos = tmp; if(pOld) pOld->SetPos(m_rcOldPos); } void CAnimationTabLayoutUI::OnAnimationStart(INT nAnimationID, BOOL bFirstLoop) { m_pManager->SendNotify(this,_T("animationstart")); AnimationSwitch(); GetItemAt(m_iCurSel)->SetVisible(true); GetItemAt(m_iCurSel)->SetFocus(); m_bIsRunning = true; } void CAnimationTabLayoutUI::OnAnimationStop(INT nAnimationID) { m_pManager->SendNotify(this,_T("animationend")); for( int it = 0; it < m_items.GetSize(); it++ ) { if(it != m_iCurSel) GetItemAt(it)->SetVisible(false); } m_bIsRunning = false; } void CAnimationTabLayoutUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) { if( _tcscmp(pstrName, _T("animation_direction")) == 0 && _tcscmp( pstrValue, _T("vertical")) == 0 ) m_bIsVerticalDirection = true; // pstrValue = "vertical" or "horizontal" if( _tcscmp(pstrName, _T("selectedid")) == 0 ) CTabLayoutUI::SelectItem(_ttoi(pstrValue)); if(_tcscmp(pstrName, _T("AnimatID")) == 0) m_AnimatID = _ttoi(pstrValue); return CTabLayoutUI::SetAttribute(pstrName, pstrValue); } void CAnimationTabLayoutUI::SetAnimationDirection(bool bVertical) { m_bIsVerticalDirection = bVertical; } }
#include<iostream> #include<stdio.h> #include<bits/stdc++.h> #include<algorithm> #include<cmath> #include<string> #include<cstring> #include<vector> #include<map> #include<queue> #include<set> #include<list> #include<unordered_map> #include<unordered_set> #define ll long long #define MAX 100000003 #define MAX_RLEN 50 #define ll long long #define pb push_back #define pii pair<ll,ll> #define N 200005 #define PI 3.1415926535 using namespace std; bool arr[MAX]={false}; void prime() { for(ll i=2;i<=MAX;i++) { arr[i]=true; } for(ll i=2;i*i<=MAX;i++) if(arr[i]==true) for(ll j=i*i;j<=MAX;j=j+i) arr[j]=false; } int main() { prime(); ll n,i=0,k=0; cin>>n; while(1) { if(k==n) { cout<<i-1<<endl; break; } if(arr[i]==1) k++; i++; } }
/* * BinConvert.h * * Created on: 8 Jul 2015 * Author: Jack */ #ifndef BINCONVERT_H_ #define BINCONVERT_H_ #include <vector> #include <cmath> #include <iostream> class BinConverter { private: int bits; int dpIndex; public: BinConverter(int bits, int dpIndex = 0); std::vector<bool> decToBin(int dec); std::vector<bool> decToBin(float dec); int binToDecInt(std::vector<bool> bin); float binToDecFloat(std::vector<bool> bin); }; void printBinString(std::vector<bool> bin); #endif /* BINCONVERT_H_ */
#include <iostream> #include <string> using namespace std; int GetUserInput() { cout << "Enter a number: "; int a; cin >> a; return a; } int main() { int A = GetUserInput(); if (A % 3 == 0) { cout << "Fizz"; } if (A % 5 == 0) cout << "Buzz"; } if (A % 3 > 0) { if (A % 5 > 0) { cout << A; } return 0; }
#ifndef _SUB1_H_ #define _SUB1_H_ #include "Sup1.h" class Sub1 : public Sup1 { public: void func(); }; #endif //_SUB1_H_
#include <iostream> #include <string> #include <vector> #include <cstring> #include "Creature.h" #include "../rapidxml/rapidxml.hpp" #include "../rapidxml/rapidxml_utils.hpp" #include "../rapidxml/rapidxml_print.hpp" using namespace std; using namespace rapidxml; Creature::Creature(xml_node<> * creatureTag){ xml_node<> * creatureElement = NULL; for(creatureElement = creatureTag->first_node(); creatureElement; creatureElement = creatureElement->next_sibling()){ if(strcmp(creatureElement->name(),"name") == 0){ name = creatureElement->value(); } if(strcmp(creatureElement->name(),"status") == 0){ status = creatureElement->value(); } if(strcmp(creatureElement->name(),"description") == 0){ description = creatureElement->value(); } if(strcmp(creatureElement->name(),"vulnerability") == 0){ vulnerability.push_back(creatureElement->value()); } if(strcmp(creatureElement->name(),"attack") == 0){ xml_node<> * attackElement = NULL; for(attackElement = creatureElement->first_node(); attackElement; attackElement = attackElement->next_sibling()){ if(strcmp(creatureElement->name(),"condition") == 0){ xml_node<> * conditionElement = NULL; Condition condition; for(conditionElement = attackElement->first_node(); conditionElement; conditionElement = conditionElement->next_sibling()){ if(strcmp(creatureElement->name(),"object") == 0){ condition.object = conditionElement->value(); } if(strcmp(creatureElement->name(),"status") == 0){ condition.status = conditionElement->value(); } } attack.condition = condition; } if(strcmp(creatureElement->name(),"print") == 0){ attack.print = attackElement->value(); } if(strcmp(creatureElement->name(),"action") == 0){ attack.action.push_back(attackElement->value()); } } } if(strcmp(creatureElement->name(),"trigger") == 0){ Trigger newTrigger = Trigger(creatureElement); trigger.push_back(newTrigger); } } } void Creature::setVulnerability(string vulnerability){ (this->vulnerability).push_back(vulnerability); } vector<string> Creature::getVulnerability(){ return vulnerability; } void Creature::setAttackList(Condition, string, vector<string>){ } Attack Creature::getAttackList(){ }
// Motor Y es el de los leds // Motor X es el del enfoque del portamuestras (eje z del portamuestras) #define Y_DIR_PIN 61 // poner n�mero del pin de direcci�n #define Y_STEP_PIN 60 // poner n�mero de pin de conexi�n al motor #define Y_ENABLE_PIN 56 // poner n�mero de pin de poner en marcha #define FIN_CARRERA_1 3 // poner n�mero de pin de final de carrera 1 #define FIN_CARRERA_2 2 // poner n�mero de pin de final de carrera 2 #define FIN_CARRERA_3 14 // poner n�mero de pin de final de carrera 3 #define X_DIR_PIN 55 // poner n�mero del pin de direcci�n #define X_STEP_PIN 54 // poner n�mero de pin de conexi�n al motor #define X_ENABLE_PIN 38 // poner n�mero de pin de poner en marcha #define TRIGGER_FILTRO_LINEAL 16 // poner n�mero de pin con el que leer el disparo de cada movimiento del filtro lineal #define TRIGGER_CAMARA 17// poner n�mero de pin en que lanzamos un disparo TTL para accionar la c�mara int stepDelay = 100; // tiempo de parada para controlar la velocidad boolean pos_1 = false; boolean pos_2 = false; boolean pos_3 = false; boolean pos_final = false; boolean primer_arranque = true; boolean primera_conexion = true; int final_carrera_1 = 1; int final_carrera_2 = 1; int final_carrera_3 = 1; int cont_led = 0; int cont_filtro = 0; int trigger = 0; int cont = 0; void setup() { // Marcar los pines como salida pinMode(Y_STEP_PIN, OUTPUT); pinMode(Y_DIR_PIN, OUTPUT); pinMode(Y_ENABLE_PIN, OUTPUT); digitalWrite(Y_ENABLE_PIN, LOW); pinMode(FIN_CARRERA_1, INPUT_PULLUP); pinMode(FIN_CARRERA_2, INPUT_PULLUP); pinMode(FIN_CARRERA_3, INPUT_PULLUP); pinMode(X_STEP_PIN, OUTPUT); pinMode(X_DIR_PIN, OUTPUT); pinMode(X_ENABLE_PIN, OUTPUT); digitalWrite(X_ENABLE_PIN, LOW); pinMode(TRIGGER_FILTRO_LINEAL, INPUT); pinMode(TRIGGER_CAMARA, OUTPUT); Serial.begin(115200); } void loop() { if (primera_conexion == true) // cuando encendemos el puerto serie mandamos la comprobacion de que es nuestro programa el que busca { delayMicroseconds(500); Serial.print("a"); // codigo ascii 97 primera_conexion = false; } if ((primer_arranque == true) && (primera_conexion == false)) // cuando encendemos el programa nos vamos a la posicion del final de carrera n�1 { posicion_1(); primer_arranque = false; pos_final = true; } if ((primer_arranque == false) && (primera_conexion == false)) { leer_serial(); que_hacer(); cont_led = 0; cont_filtro = 0; if (pos_final == true) { Serial.print("1"); pos_final = false; } } } //------------------------------------------------------------------------------------------------------------------------------- void que_hacer() // lee del puerto serie y decide que hacer segun la información que recibe { switch (cont_led) { case 1: posicion_3(); comprobar_salto(); pos_final = true; break; case 2: posicion_2(); comprobar_salto(); pos_final = true; break; case 3: posicion_2(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; case 4: posicion_1(); comprobar_salto(); pos_final = true; break; case 5: posicion_1(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; case 6: posicion_1(); comprobar_salto(); posicion_2(); comprobar_salto(); pos_final = true; break; case 7: posicion_1(); comprobar_salto(); posicion_2(); comprobar_salto(); posicion_3(); comprobar_salto(); pos_final = true; break; case 8: mover_enfoque(); break; case 9: autofocus(); break; } } //--------------------------------------------------------------------------------------------------------------------------------- // Funciones para el control de la parte de los cubos de las leds void comprobar_salto() // comprobamos si ha habido alg�n salto del filtro lineal y lo contabilizamos { int contador = 0; while (contador < cont_filtro) { trigger = digitalRead(TRIGGER_FILTRO_LINEAL); if (trigger == 1) { contador++; delay(250); } } } void leer_serial() { while (Serial.available()>0) { cont_led = Serial.parseInt(); cont_filtro = Serial.parseInt(); if (Serial.read() == '\n') { return; } } } void posicion_1() { final_carrera_1 = digitalRead(FIN_CARRERA_1); while ((final_carrera_1 == 1) && (pos_1 == false)) // vamos a ir hasta la posicion del led 1 { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_1 = digitalRead(FIN_CARRERA_1); } final_carrera_1 = digitalRead(FIN_CARRERA_1); if (final_carrera_1 == 0) { pos_1 = true; pos_2 = false; pos_3 = false; } } void posicion_2() { final_carrera_2 = digitalRead(FIN_CARRERA_2); while ((final_carrera_2 == 1) && (pos_2 == false) && (pos_1 == true)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } while ((final_carrera_2 == 1) && (pos_2 == false) && (pos_3 == true)) { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } if ((final_carrera_2 == 0) && (pos_3 == true)) { for (int x=0; x<3200; x++) { digitalWrite(Y_DIR_PIN, HIGH); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); } delay(100); final_carrera_2 = digitalRead(FIN_CARRERA_2); while ((final_carrera_2 == 1) && (pos_2 == false)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_2 = digitalRead(FIN_CARRERA_2); } } final_carrera_2 = digitalRead(FIN_CARRERA_2); if (final_carrera_2 == 0) { pos_1 = false; pos_3 = false; pos_2 = true; } } void posicion_3() { final_carrera_3 = digitalRead(FIN_CARRERA_3); while ((final_carrera_3 == 1) && (pos_3 == false)) { digitalWrite(Y_DIR_PIN, LOW); digitalWrite(Y_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(Y_STEP_PIN, HIGH); delayMicroseconds(stepDelay); final_carrera_3 = digitalRead(FIN_CARRERA_3); } final_carrera_3 = digitalRead(FIN_CARRERA_3); if (final_carrera_3 == 0) { pos_1 = false; pos_2 = false; pos_3 = true; } } //--------------------------------------------------------------------------------------------------------------------------------- // funciones para el control del micrometro void autofocus() { //// para las poleas de 20 Y 20 dientes: 400 es una vuelta completa del micrometro y 1 vueltas del motor. trabajando a pasos completos, 16 micropasos por paso. // // for (int x=0; x< 200; x++) // { // mover_enfoque_continuo_abajo(16); // } // delay(1000); // for (int x = 0; x< 400; x++) // { // mover_enfoque_continuo_arriba(16); // // enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n // digitalWrite(TRIGGER_CAMARA, HIGH); // delay(100); // digitalWrite(TRIGGER_CAMARA, LOW); // delay(900); // } // for (int x = 0; x< 200; x++) // { // mover_enfoque_continuo_abajo(16); // } // // volvemos a la posici�n inicial // delay(1000); // //----------------------------------------------------------------------------------------------------------------------------------------------------------------------- // para las poleas de 20 Y 20 dientes: 800 es una vuelta completa del micrometro y 2 vueltas del motor. trabajando a pasos completos, 8 micropasos por paso. //for (int x=0; x< 800; x++) //{ //mover_enfoque_continuo_abajo(8); //} //delay(1000); //for (int x = 0; x< 1600; x++) //{ //mover_enfoque_continuo_arriba(8); //// enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n //digitalWrite(TRIGGER_CAMARA, HIGH); //delay(100); //digitalWrite(TRIGGER_CAMARA, LOW); //delay(900); //} //for (int x = 0; x< 800; x++) //{ //mover_enfoque_continuo_abajo(8); //} //// volvemos a la posici�n inicial //delay(1000); //----------------------------------------------------------------------------------------------------------------------------------------------------------------------- //para las poleas de 44 Y 32 dientes: 550 es una vuelta completa del micrometro y 1,375 vueltas del motor. trabajando a pasos completos, 16 micropasos por paso. for (int x=0; x< 550; x++) // bajamos una vuelta desde el centro ( el centro se posiciona a mano actualmente) { mover_enfoque_continuo_abajo(16); } delay(1000); for (int x = 0; x< 1100; x++) // subimos la vuelta que hemos bajado y { mover_enfoque_continuo_arriba(16); // enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n digitalWrite(TRIGGER_CAMARA, HIGH); delay(100); digitalWrite(TRIGGER_CAMARA, LOW); delay(900); } for (int x = 0; x< 550; x++) { mover_enfoque_continuo_abajo(16); } // volvemos a la posici�n inicial delay(1000); //----------------------------------------------------------------------------------------------------------------------------------------------------------------------- // para las poleas de 44 Y 32 dientes: 1100 es una vuelta completa del micrometro y 2,75 vueltas del motor trabajando a 1/2 pasos, 8 micropasos por paso //for (int x=0; x< 1100; x++) // bajamos una vuelta desde el centro ( el centro se posiciona a mano actualmente) //{ //mover_enfoque_continuo_abajo(8); //} //delay(1000); //for (int x = 0; x< 2200; x++) // subimos la vuelta que hemos bajado y //{ //mover_enfoque_continuo_arriba(8); //// enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n //digitalWrite(TRIGGER_CAMARA, HIGH); //delay(100); //digitalWrite(TRIGGER_CAMARA, LOW); //delay(900); //} //for (int x = 0; x< 1100; x++) //{ //mover_enfoque_continuo_abajo(8); //} // //// volvemos a la posici�n inicial //delay(1000); //----------------------------------------------------------------------------------------------------------------------------------------------------------------------- // para las poleas de 44 Y 20 dientes: , 880 es una vuelta completa del micrometro y 2,2 vueltas del motor trabajando a paso completo, 16 micropasos por paso //for (int x=0; x< 880; x++) // bajamos una vuelta desde el centro ( el centro se posiciona a mano actualmente) //{ //mover_enfoque_continuo_abajo(16); //} //delay(1000); //for (int x = 0; x< 1760; x++) // subimos la vuelta que hemos bajado y //{ //mover_enfoque_continuo_arriba(16); //// enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n //digitalWrite(TRIGGER_CAMARA, HIGH); //delay(100); //digitalWrite(TRIGGER_CAMARA, LOW); //delay(900); //} //for (int x = 0; x< 880; x++) //{ //mover_enfoque_continuo_abajo(16); //} // //// volvemos a la posici�n inicial //delay(1000); //----------------------------------------------------------------------------------------------------------------------------------------------------------------------- // para las poleas de 44 Y 20 dientes: , 1760 es una vuelta completa del micrometro y 4,4 vueltas del motor. trabajando a 1/2 pasos, 8 micropasos por paso //for (int x=0; x< 1760; x++) // bajamos una vuelta desde el centro ( el centro se posiciona a mano actualmente) //{ //mover_enfoque_continuo_abajo(8); //} //delay(1000); //for (int x = 0; x< 3520; x++) // subimos la vuelta que hemos bajado y //{ //mover_enfoque_continuo_arriba(8); //// enviamos un disparo a la camara para que tome el dato y esperamos el tiempo que tarda en tomarla hay que preguntar a Iv�n //digitalWrite(TRIGGER_CAMARA, HIGH); //delay(100); //digitalWrite(TRIGGER_CAMARA, LOW); //delay(900); //} //for (int x = 0; x< 1760; x++) //{ //mover_enfoque_continuo_abajo(8); //} // //// volvemos a la posici�n inicial //delay(1000); Serial.print("1"); } void mover_enfoque_continuo_arriba(int pasos) { //el motor tiene 400 pasos por vuelta y el driver est� cnfigurado a 1/16 o 6400 micrpaos por vuelta. //Si ponemos los micropasos a 8 estamos trabajando al equivalente a 1/2 pasos 800 pasos por vuelta //int pasos = 8; //Si ponemos los micropasos a 16 estamos trabajando al equivalente a full steep 400 pasos por vuelta //int pasos = 16; boolean dir = LOW; while (pasos > 0) { digitalWrite(X_DIR_PIN, dir); digitalWrite(X_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(X_STEP_PIN, HIGH); delayMicroseconds(stepDelay); pasos--; } } void mover_enfoque_continuo_abajo(int pasos) { //el motor tiene 400 pasos por vuelta y el driver est� cnfigurado a 1/16 o 6400 micrpaos por vuelta. //Si ponemos los micropasos a 8 estamos trabajando al equivalente a 1/2 pasos 800 pasos por vuelta //int pasos = 8; //Si ponemos los micropasos a 16 estamos trabajando al equivalente a full steep 400 pasos por vuelta //int pasos = 16; boolean dir = HIGH; while (pasos > 0) { digitalWrite(X_DIR_PIN, dir); digitalWrite(X_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(X_STEP_PIN, HIGH); delayMicroseconds(stepDelay); pasos--; } } void mover_enfoque() { int pasos = 0; boolean dir= HIGH; switch (cont_filtro) { case 1: //mover_enfoque_continuo_abajo(80); // 5 pasos 4,5º mover_enfoque_continuo_abajo(32); //pasos = 32; // 2.5 um por pulsación //dir = HIGH; break; case 2: //mover_enfoque_continuo_abajo(160); // 10 pasos 9º mover_enfoque_continuo_abajo(128); //pasos = 128; // 10um por pulsación //dir = HIGH; break; case 3: //mover_enfoque_continuo_arriba(80); // 5 pasos 4,5º mover_enfoque_continuo_arriba(32); //pasos = 32; // 2.5 um por pulsación //dir = LOW; break; case 4: //mover_enfoque_continuo_arriba(160); // 10 pasos 9º mover_enfoque_continuo_arriba(128); //pasos = 128; // 10um por pulsación //dir = LOW; break; } while (pasos > 0) { digitalWrite(X_DIR_PIN, dir); digitalWrite(X_STEP_PIN, LOW); delayMicroseconds(stepDelay); digitalWrite(X_STEP_PIN, HIGH); delayMicroseconds(stepDelay); pasos--; } Serial.print("1"); }
#include "Arr.h" std::size_t n; //int** arr = new int*[n]; //std::vector < std::vector < int> > arr; /* void reserve(std::size_t n) { int* arr = new int[n]; } void arrtemp(std::size_t n, int i) { arr[i] = new int[n]; // добавляем новую строку } void inputelement(int i, int j, int a) { arr[i][j] = a; } void rend(int i, int j) { arr[i][j] = rand() % 10 + 1; } System::String ^ convertarr(int i, int j) { System::String ^ s = System::Convert::ToString(arr[i][j]); return s; } */
/** * @file NetworkFlow.cpp * CS 225: Data Structures */ #include <vector> #include <algorithm> #include <set> #include <climits> #include "graph.h" #include "edge.h" #include "NetworkFlow.h" using std::vector; int min(int a, int b) { if (a<b) return a; else return b; } NetworkFlow::NetworkFlow(Graph & startingGraph, Vertex source, Vertex sink) : g_(startingGraph), residual_(Graph(true,true)), flow_(Graph(true,true)), source_(source), sink_(sink) { // YOUR CODE HERE vector<Vertex> vertices_ = g_.getVertices(); vector<Edge> edges_ = g_.getEdges(); if (vertices_.empty()){ return; } for (auto it : vertices_){ residual_.insertVertex(it); flow_.insertVertex(it); } for (auto it : edges_){ residual_.insertEdge(it.source, it.dest); residual_.setEdgeWeight(it.source, it.dest, it.getWeight()); residual_.insertEdge(it.dest, it.source); residual_.setEdgeWeight(it.dest, it.source, 0); flow_.insertEdge(it.source, it.dest); flow_.setEdgeWeight(it.source, it.dest, 0); } /* vector<Vertex> path; findAugmentingPath(source_, sink_, path); if (path.empty()){ return; } // flow capacity int cap = pathCapacity(path); // if there is a path, get the edge weights and update the flow and residual graph for (int unsigned long i = 0; i < path.size() - 2; i++){ // update flow_ int fWeight = flow_.getEdgeWeight(path[i], path[i+1]); flow_.setEdgeWeight(path[i], path[i+1], fWeight+cap); // update residual_ int rWeight = residual_.getEdgeWeight(path[i], path[i+1]); int oppositeWeight = residual_.getEdgeWeight(path[i+1], path[i]); // get original graph edge weight int weightLimit = g_.getEdgeWeight(path[i], path[i+1]); if (weightLimit == Graph::InvalidWeight){ weightLimit = g_.getEdgeWeight(path[i+1], path[i]); } // check if new edge weight surpasses the limit if (rWeight - cap >= 0){ residual_.setEdgeWeight(path[i], path[i+1], rWeight - cap); } else { residual_.setEdgeWeight(path[i], path[i+1], 0); } if (oppositeWeight + cap <= weightLimit){ residual_.setEdgeWeight(path[i+1], path[i], oppositeWeight + cap); } else { residual_.setEdgeWeight(path[i+1], path[i], weightLimit); } } */ } /** * findAugmentingPath - use DFS to find a path in the residual graph with leftover capacity. * This version is the helper function. * * @@params: source -- The starting (current) vertex * @@params: sink -- The destination vertex * @@params: path -- The vertices in the path * @@params: visited -- A set of vertices we have visited */ bool NetworkFlow::findAugmentingPath(Vertex source, Vertex sink, std::vector<Vertex> &path, std::set<Vertex> &visited) { if (visited.count(source) != 0) return false; visited.insert(source); if (source == sink) { return true; } vector<Vertex> adjs = residual_.getAdjacent(source); for(auto it = adjs.begin(); it != adjs.end(); it++) { if (visited.count(*it) == 0 && residual_.getEdgeWeight(source,*it) > 0) { path.push_back(*it); if (findAugmentingPath(*it,sink,path,visited)) return true; else { path.pop_back(); } } } return false; } /** * findAugmentingPath - use DFS to find a path in the residual graph with leftover capacity. * This version is the main function. It initializes a set to keep track of visited vertices. * * @@params: source -- The starting (current) vertex * @@params: sink -- The destination vertex * @@params: path -- The vertices in the path */ bool NetworkFlow::findAugmentingPath(Vertex source, Vertex sink, std::vector<Vertex> &path) { std::set<Vertex> visited; path.clear(); path.push_back(source); return findAugmentingPath(source,sink,path,visited); } /** * pathCapacity - Determine the capacity of a path in the residual graph. * * @@params: path -- The vertices in the path */ int NetworkFlow::pathCapacity(const std::vector<Vertex> & path) const { // YOUR CODE HERE if (path.size() <= 1){ return 0; } int limit = INT_MAX; for (unsigned long i = 0; i < path.size() - 1; i++){ int currWeight = residual_.getEdgeWeight(path[i], path[i+1]); if (currWeight < limit){ limit = currWeight; } } return limit; } /** * calculuateFlow - Determine the capacity of a path in the residual graph. * Sets the member function `maxFlow_` to be the flow, and updates the * residual graph and flow graph according to the algorithm. * * @@outputs: The network flow graph. */ const Graph & NetworkFlow::calculateFlow() { // YOUR CODE HERE vector<Vertex> vertices = g_.getVertices(); vector<Vertex> path; // if path is empty /* if (path.empty()){ return ; }*/ bool opposite = false; int max = 0; while (findAugmentingPath(source_, sink_, path)){ // get pathCap int pathCap = pathCapacity(path); max += pathCap; for (unsigned long i = 0; i < path.size() - 1; i++){ int currWeight = flow_.getEdgeWeight(path[i], path[i+1]); // if its the opposite way if (currWeight == Graph::InvalidWeight){ currWeight = flow_.getEdgeWeight(path[i+1], path[i]); opposite = true; } if (opposite){ flow_.setEdgeWeight(path[i+1], path[i], currWeight - pathCap); } else { flow_.setEdgeWeight(path[i], path[i+1], currWeight + pathCap); } // residual_ int forward = residual_.getEdgeWeight(path[i], path[i+1]); residual_.setEdgeWeight(path[i], path[i+1], forward - pathCap); int backward = residual_.getEdgeWeight(path[i+1], path[i]); residual_.setEdgeWeight(path[i+1], path[i], backward + pathCap); } } maxFlow_ = max; return flow_; } int NetworkFlow::getMaxFlow() const { return maxFlow_; } const Graph & NetworkFlow::getGraph() const { return g_; } const Graph & NetworkFlow::getFlowGraph() const { return flow_; } const Graph & NetworkFlow::getResidualGraph() const { return residual_; }
#ifndef JSKEYS_HH #define JSKEYS_HH namespace NC { namespace DateKeys { constexpr const char* year = "year"; constexpr const char* month = "month"; constexpr const char* day = "day"; constexpr const char* hours = "hours"; constexpr const char* minutes = "minutes"; constexpr const char* seconds = "seconds"; constexpr const char* fractionalSeconds = "fractionalSeconds"; } // namespace DateKeys namespace ArgumentKeys { constexpr const char* bindings = "bindings"; constexpr const char* query = "query"; constexpr const char* batch_size = "batchSize"; constexpr const char* timeout = "timeout"; } // namespace ArgumentKeys } // namespace NC #endif /* JSKEYS_HH */
#pragma once #include "helpers.hpp" #include <climits> #include <vector> #include <iostream> // SCANNER DEFINITION // You can freely add member fields and functions to this class. class Scanner { int line; //int semicolonCount = 0; int value; int current_token_length; bool very_end_newline; std::vector<Token> tokens; public: // You really need to implement these four methods for the scanner to work. std::string total_input; Token nextToken(); void eatToken(Token); int lineNumber(); int getNumberValue(); Scanner(); }; // PARSER DEFINITION // You can freely add member fields and functions to this class. class Parser { Scanner scanner; std::vector<long> return_value; int result; bool evaluate; bool need_to_go_back; void start(); // You will need to define the recursive descent functions you're going to use here. // void expression(); // void term(); // void factor(); long E(); long E_prime(long value); long F(); public: void parse(); Parser(bool); };
s#include<string> #include<iostream> #include<vector> using namespace std; class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* hair = new ListNode(0); hair->next = head; ListNode* pre = hair; while (head) { ListNode* tail = pre; // 查看剩余部分长度是否大于等于 k for (int i = 0; i < k; ++i) { tail = tail->next; if (!tail) { return hair->next; } } ListNode* nex = tail->next; // 这里是 C++17 的写法,也可以写成 // pair<ListNode*, ListNode*> result = myReverse(head, tail); // head = result.first; // tail = result.second; tie(head, tail) = myReverse(head, tail); // 把子链表重新接回原链表 pre->next = head; tail->next = nex; pre = tail; head = tail->next; } return hair->next; } // 翻转一个子链表,并且返回新的头与尾 pair<ListNode*, ListNode*> myReverse(ListNode* head, ListNode* tail) { ListNode* pre = nullptr; ListNode* now = head; while(now!=nullptr){ ListNode* next = now->next; now->next=pre; pre = now; now = next; } return {tail, head}; } };
// // Created by Noam pnueli on 2/11/17. // #ifndef PHYSICSENGINE_PHYSICS_H #define PHYSICSENGINE_PHYSICS_H #include "renderer.h" #include "constraints.h" #define RUN_TIME 500 #define GRAVITY 9.807 #define TIME_INTERVAL 0.01 class Physics { private: std::vector<Object*> stage; Renderer* renderer; public: Physics(std::vector<Object*> stage) : stage(stage), renderer(new Renderer(stage)) { for(Object* obj : stage) { obj->add_force(vector2d(0, obj->get_mass() * GRAVITY)); } } ~Physics() { for(Object* obj : stage) delete(obj); delete(renderer); } void add_object(Object* object) { stage.push_back(object); } void run() { double start_point = 0; double last = 0; while(start_point < RUN_TIME) { clock_t now = clock(); start_point += now / CLOCKS_PER_SEC; for(Object* obj : stage) { obj->calculate(TIME_INTERVAL); } calculate_collisions(); renderer->render(); } } // TODO: use a more efficient algorithm - O(n^2) for now :( void calculate_collisions() { for(int i = 0; i < stage.size(); i++) { for(int k = 0; k < stage.size(); k++) { if(i != k) { collide(stage[i], stage[k]); } } } } void collide(Object* obj1, Object* obj2) { Manifold m = collision_overlap(obj1->get_collider(), obj2->get_collider()); if(m.penetration_depth != -1) { // Resolve collision vector2d relative_vel = obj2->get_velocity() - obj1->get_velocity(); double vel_along_norm = relative_vel * m.normal; if(vel_along_norm > 0) return; double e = std::min(obj1->get_restitution(), obj2->get_restitution()); double j = -(1 + e) * vel_along_norm; j /= (obj1->get_inverse_mass()) + (obj2->get_inverse_mass()); vector2d impulse = m.normal * j; vector2d tmp = impulse * (obj1->get_inverse_mass()); tmp = tmp * 10000; // Temporary monkey patch tmp = (obj1->get_velocity() - tmp); obj1->set_velocity(tmp); tmp = impulse * (obj2->get_inverse_mass()); tmp = tmp * 10000; tmp = (obj2->get_velocity() + tmp); obj2->set_velocity(tmp); } } }; #endif //PHYSICSENGINE_PHYSICS_H
/* -*- 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. ** */ #ifndef DOM_DOMXSLT_H #define DOM_DOMXSLT_H #ifdef DOM_XSLT_SUPPORT #include "modules/dom/src/domobj.h" #include "modules/xmlutils/xmltypes.h" #include "modules/xmlutils/xmlnames.h" #include "modules/util/simset.h" #include "modules/xslt/xslt.h" class DOM_XSLTParseCallback; class DOM_XSLTTransformCallback; class DOM_XSLTTransform_State; class XMLSerializer; class DOM_XSLTProcessor : public DOM_Object, public Link { protected: DOM_XSLTProcessor(); ~DOM_XSLTProcessor(); XSLT_StylesheetParser *stylesheetparser; XSLT_Stylesheet *stylesheet; XMLVersion version; BOOL is_disabled; friend class DOM_XSLTParseCallback; DOM_XSLTParseCallback *parse_callback; friend class DOM_XSLTTransformCallback; DOM_XSLTTransformCallback *transform_callback; friend class DOM_XSLTTransform_State; DOM_XSLTTransform_State *transform_state; XMLSerializer *serializer; class ParameterValue { public: XMLExpandedName name; ES_Value value; ParameterValue *next; } *parameter_values; OP_STATUS SetParameters(DOM_XSLTTransform_State *state, XSLT_Stylesheet::Input &input); void RemoveParameter(const XMLExpandedName &name); void ClearParameters(); public: static OP_STATUS Make(DOM_XSLTProcessor *&processor, DOM_EnvironmentImpl *environment); virtual BOOL IsA(int type) { return type == DOM_TYPE_XSLTPROCESSOR || DOM_Object::IsA(type); } virtual void GCTrace(); void Cleanup(); DOM_DECLARE_FUNCTION(importStylesheet); DOM_DECLARE_FUNCTION(getParameter); DOM_DECLARE_FUNCTION(setParameter); DOM_DECLARE_FUNCTION(removeParameter); DOM_DECLARE_FUNCTION(clearParameters); DOM_DECLARE_FUNCTION(reset); enum { FUNCTIONS_ARRAY_SIZE = 7 }; DOM_DECLARE_FUNCTION_WITH_DATA(transform); enum { FUNCTIONS_WITH_DATA_ARRAY_SIZE = 3 }; }; class DOM_XSLTProcessor_Constructor : public DOM_BuiltInConstructor { public: DOM_XSLTProcessor_Constructor(); virtual int Construct(ES_Value* argv, int argc, ES_Value* return_value, ES_Runtime *origining_runtime); }; #endif // DOM_XSLT_SUPPORT #endif // DOM_DOMXSLT_H
//===-- DWARFDebugRangesList.cpp ------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "DWARFDebugRangeList.h" #include "llvm/Support/Format.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; void DWARFDebugRangeList::clear() { Offset = -1U; AddressSize = 0; Entries.clear(); } bool DWARFDebugRangeList::extract(DataExtractor data, uint32_t *offset_ptr) { clear(); if (!data.isValidOffset(*offset_ptr)) return false; AddressSize = data.getAddressSize(); if (AddressSize != 4 && AddressSize != 8) return false; Offset = *offset_ptr; while (true) { RangeListEntry entry; uint32_t prev_offset = *offset_ptr; entry.StartAddress = data.getAddress(offset_ptr); entry.EndAddress = data.getAddress(offset_ptr); // Check that both values were extracted correctly. if (*offset_ptr != prev_offset + 2 * AddressSize) { clear(); return false; } if (entry.isEndOfListEntry()) break; Entries.push_back(entry); } return true; } void DWARFDebugRangeList::dump(raw_ostream &OS) const { for (const RangeListEntry &RLE : Entries) { const char *format_str = (AddressSize == 4 ? "%08x %08" PRIx64 " %08" PRIx64 "\n" : "%08x %016" PRIx64 " %016" PRIx64 "\n"); OS << format(format_str, Offset, RLE.StartAddress, RLE.EndAddress); } OS << format("%08x <End of list>\n", Offset); } bool DWARFDebugRangeList::containsAddress(uint64_t BaseAddress, uint64_t Address) const { for (const RangeListEntry &RLE : Entries) { if (RLE.isBaseAddressSelectionEntry(AddressSize)) BaseAddress = RLE.EndAddress; else if (RLE.containsAddress(BaseAddress, Address)) return true; } return false; }
// // Created by manout on 17-7-6. // #include "all_include.h" #include <opencv2/opencv.hpp> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/imgproc.hpp> #define KERNEL_SIZE cv::Size(7, 7) void show_blur(cv::Mat& src, const string& name) { cv::Mat dst = src.clone(); cv::blur(src, dst, KERNEL_SIZE); cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, dst); while(cv::waitKey(100) not_eq 27); } void show_gaussian(cv::Mat& src , const string& name) { cv::Mat dst = src.clone(); cv::GaussianBlur(src, dst, KERNEL_SIZE,0); cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, dst); while(cv::waitKey(100) not_eq 27); } void show_median(cv::Mat& src, const string& name) { cv::Mat dst = src.clone(); cv::medianBlur(src, dst, 7); cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, dst); while(cv::waitKey(100) not_eq 27); } void show_bilateral(cv::Mat& src, const string& name) { cv::Mat dst = src.clone(); cv::bilateralFilter(src, dst, 7, 14, 3); cv::namedWindow(name, cv::WINDOW_AUTOSIZE); cv::imshow(name, dst); while(cv::waitKey(100) not_eq 27); } // 提取图像中笔记部分(也可以称为去掉水平线) cv::Mat extract_content(cv::Mat img) { assert(img.data); string window_name(R"-(result)-"); cv::Mat gray; //将图像转化为灰度图 if(img.channels() == 3) { cv::cvtColor(img, gray, CV_BGR2GRAY); } else { gray = img.clone(); } cv::Mat bw; // 经过测试,当 blockSize = 15 时效果最好,默认值结果过于纤细 cv::adaptiveThreshold(~gray, bw, 255, CV_ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 15, -2); cv::Mat vertical = bw.clone(); // 以下是提取水平线的内容 /* //对 gray 的 bitwise_not 采用自适应阀值化,块的大小为 15 * 15, 采用 CV_ADAPTIVE_THRESH_MEAN_C 表示在邻域内平均加权 // 然后参考点的取值为 加权平均后 + 2 (- (-2)) cv::adaptiveThreshold(~gray, img, 255, CV_ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 15, -2); cv::Mat horizontal = img.clone(); cv::Mat vertical = img.clone(); int horizontal_size = horizontal.cols / 30; // 创建一个提取水平线的结构化元素 cv::Mat horizontal_structure = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(horizontal_size, 1)); // 如果是在黑暗前景中提取明亮物体,那么应该先腐蚀在膨胀 // 如果是在明亮前景中提取黑色物体,那么应该先膨胀在腐蚀 cv::erode(horizontal, horizontal, horizontal_structure); cv::dilate(horizontal, horizontal, horizontal_structure); cv::namedWindow(window_name, cv::WINDOW_AUTOSIZE); cv::imshow(window_name, horizontal); while(cv::waitKey(100) not_eq 27); */ int vertical_size = vertical.rows / 30; cv::Mat vertical_structure = cv::getStructuringElement(cv::MORPH_RECT, cv::Size(1, vertical_size)); // 内核是竖直形状,细长的水平线会在腐蚀时被腐蚀掉 /* cv::erode(vertical, vertical, vertical_structure); cv::dilate(vertical, vertical, vertical_structure); */ // 先腐蚀在膨胀可以用开运算代替 cv::morphologyEx(vertical, vertical,cv::MORPH_OPEN ,vertical_structure ); // 接下来是平滑图像 // 将 vertical 逐位取反 cv::bitwise_not(vertical, vertical); cv::Mat edge; cv::adaptiveThreshold(vertical, edge, 255, CV_ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 3, -2); cv::Mat kernel = cv::Mat::ones(2, 2, CV_8UC1); cv::dilate(edge, edge, kernel); //cv::imshow(window_name, edge); //while(cv::waitKey(100) not_eq 27); cv::Mat smooth; vertical.copyTo(smooth); cv::blur(smooth, smooth, cv::Size(2, 2)); smooth.copyTo(vertical, edge); //cv::imshow(window_name, vertical); //while(cv::waitKey(100) not_eq 27); return vertical; } cv::Mat find_circle(cv::Mat img) { cv::Mat ret, ret_grey; std::vector<cv::Vec3f> circles; cv::cvtColor(img, ret_grey, CV_BGR2GRAY); cv::medianBlur(ret_grey, ret, 5); cv::HoughCircles(ret, circles, cv::HOUGH_GRADIENT, ret_grey.rows/16, 100, 30, 1, 30); for(size_t i = 0; i < circles.size(); ++i) { cv::Vec3i c = circles[i]; cv::circle(img, cv::Point(c[0], c[1]), c[2], cv::Scalar(0, 0, 255), 3, cv::LINE_AA); cv::circle(img, cv::Point(c[0], c[1]), 2, cv::Scalar(0, 255, 0), 3, cv::LINE_AA); } return ret; } // 生成直方图 void generateHist(const cv::Mat& src, cv::Mat& dst) { std::vector<cv::Mat> bgr_planes; cv::split(src, bgr_planes); // 直方图大小 int histSize = 256; float range[] = {0, 256}; const float* histRange = {range}; bool uniform = true, accumulate = false; cv::Mat b_plane, g_plane, r_plane; cv::calcHist(&bgr_planes[0], 1, 0, cv::Mat(), b_plane, 1, &histSize, &histRange, uniform, accumulate); cv::calcHist(&bgr_planes[1], 1, 0, cv::Mat(), g_plane, 1, &histSize, &histRange, uniform, accumulate); cv::calcHist(&bgr_planes[2], 1, 0, cv::Mat(), r_plane, 1, &histSize, &histRange, uniform, accumulate); int histWidth = 256 * 2, histHeight = 400; int binWidth = cvRound(static_cast<double>(histWidth) / histSize); cv::Mat histImage(histHeight, histWidth, CV_8UC3, cv::Scalar(0, 0, 0)); cv::normalize(b_plane, b_plane, 0, histImage.rows, cv::NORM_MINMAX, -1, cv::Mat()); cv::normalize(g_plane, g_plane, 0, histImage.rows, cv::NORM_MINMAX, -1, cv::Mat()); cv::normalize(r_plane, r_plane, 0, histImage.rows, cv::NORM_MINMAX, -1, cv::Mat()); for (int i = 1; i < histSize; ++i) { cv::line(histImage, cv::Point(binWidth * (i - 1), histHeight - cvRound(b_plane.at<float>(i - 1))), cv::Point(binWidth * i, histHeight - cvRound(b_plane.at<float>(i))), cv::Scalar(255, 0, 0), 2, 8, 0); cv::line(histImage, cv::Point(binWidth * (i - 1), histHeight - cvRound(g_plane.at<float>(i - 1))), cv::Point(binWidth * i, histHeight - cvRound(g_plane.at<float>(i))), cv::Scalar(0, 255, 0), 2, 8, 0); cv::line(histImage, cv::Point(binWidth * (i - 1), histHeight - cvRound(r_plane.at<float>(i - 1))), cv::Point(binWidth * i, histHeight - cvRound(r_plane.at<float>(i))), cv::Scalar(0, 0, 255), 2, 8, 0); } dst = histImage; }
#include <iostream> #include <array> #include <fstream> #include <string> #include <optional> #include <cmath> #include <iomanip> typedef std::array<std::array<double, 3>, 3> matrix; struct Args { std::string matrixFile1; std::string matrixFile2; }; std::optional<Args> ParseArgs(int argc, char* argv[]) { if (argc != 3) { std::cout << "Invalid arguments count\n"; std::cout << "Usage: Multimatrix.exe <matrix file1> <matrix file2>\n"; return std::nullopt; } Args args; args.matrixFile1 = argv[1]; args.matrixFile2 = argv[2]; return args; } matrix ReadMatrix(std::ifstream& file) { int outterStep = 0; std::string temp; matrix matrix = { 0 }; while (getline(file, temp)) { int innerStep = 0; std::string digit; for (int i = 0; i < temp.length(); i++) { if (temp[i] != ' ') { digit += temp[i]; continue; } matrix[outterStep][innerStep] = stoi(digit); innerStep++; digit = ""; } matrix[outterStep][innerStep] = stoi(digit); outterStep++; } return matrix; } std::optional<matrix> ReadMatrixFromFile(const std::string& fileName) { std::ifstream file(fileName); if (!file.is_open()) { std::cout << "Failed to open '" << &file << "' for reading\n"; return std::nullopt; } matrix matrix = ReadMatrix(file); return matrix; } void ShowMatrix(matrix matrix) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { std::cout << std::fixed << std::setprecision(3) << matrix[i][j]; if (j != 2) std::cout << " "; } if (i != 2) std::cout << std::endl; } } matrix MultiplyMatrix(const matrix& m1, const matrix& m2) { matrix resultMatrix; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { double result = 0; for (int k = 0; k < 3; k++) { result += m1[i][k] * m2[k][j]; } resultMatrix[i][j] = result; } } return resultMatrix; } int main(int argc, char* argv[]) { auto args = ParseArgs(argc, argv); if (!args) { return 1; } matrix resultMatrix; auto matrix1 = ReadMatrixFromFile(args->matrixFile1); auto matrix2 = ReadMatrixFromFile(args->matrixFile2); if (!matrix1 || !matrix2) { return 1; } resultMatrix = MultiplyMatrix(*matrix1, *matrix2); ShowMatrix(resultMatrix); return 0; }
#ifndef __GAME__ #define __GAME__ #include "..\EngineLib\RDFTEngine.h" #include <math.h> class Minigame { public: enum GAMESTATE { WAITING, RUNNING, WINNING }; private: Minigame::GAMESTATE GameState; unsigned char lmState; HWND hwnd; void Setup(HWND hwnd); int Level; int NumMoves; Ball * ball; Hole * hole; void WaitingThink(); void RunningThink(); void WinningThink(); void WaitingDraw(); void RunningDraw(); void WinningDraw(); public: Minigame(); void Think(); void Draw(); void NewMap(); void NewGame(); void IncMoves() { NumMoves++; } void SetState(GAMESTATE state) { GameState = state; } Ball * GetBall() { return ball; } void Resize(); }; Minigame * MG(); #endif
#include "form02.h" #include "ui_form02.h" Form02::Form02(QWidget *parent) : QWidget(parent), ui(new Ui::Form02) { ui->setupUi(this); setWindowFlag(Qt::WindowStaysOnTopHint); tabModel = new QStandardItemModel(0, 4, this); ui->tableView->setModel(tabModel); tabSelectionModel = new QItemSelectionModel(tabModel); ui->tableView->setSelectionModel(tabSelectionModel); ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows); setHeader(); tableAddData(); createAction(); } Form02::~Form02() { delete ui; } void Form02::setHeader() { tabModel->setHeaderData(0, Qt::Horizontal, "이름"); tabModel->setHeaderData(1, Qt::Horizontal, "국어"); tabModel->setHeaderData(2, Qt::Horizontal, "영어"); tabModel->setHeaderData(3, Qt::Horizontal, "수학"); } void Form02::tableAddData() { struct searchEntry dsEntry; list<SEARCH_ENTRY>::iterator ds = listSearchEntry.begin(); memset(&dsEntry, 0x00, sizeof(dsEntry)); strcpy(dsEntry.name, "홍길동"); dsEntry.kor = 90; dsEntry.eng = 80; dsEntry.math = 99; advance(ds, 0); listSearchEntry.insert(ds, dsEntry); tabModel->insertRows(0, 1, QModelIndex()); tabModel->setData(tabModel->index(0, 0, QModelIndex()), dsEntry.name); tabModel->setData(tabModel->index(0, 1, QModelIndex()), dsEntry.kor); tabModel->setData(tabModel->index(0, 2, QModelIndex()), dsEntry.eng); tabModel->setData(tabModel->index(0, 3, QModelIndex()), dsEntry.math); memset(&dsEntry, 0x00, sizeof(dsEntry)); strcpy(dsEntry.name, "이순신"); dsEntry.kor = 88; dsEntry.eng = 77; dsEntry.math = 89; //advance(ds, 1); listSearchEntry.insert(ds, dsEntry); tabModel->insertRows(1, 1, QModelIndex()); tabModel->setData(tabModel->index(1, 0, QModelIndex()), dsEntry.name); tabModel->setData(tabModel->index(1, 1, QModelIndex()), dsEntry.kor); tabModel->setData(tabModel->index(1, 2, QModelIndex()), dsEntry.eng); tabModel->setData(tabModel->index(1, 3, QModelIndex()), dsEntry.math); } void Form02::createAction() { connect(ui->tableView, SIGNAL(clicked(const QModelIndex&)), this, SLOT(slotTabClick(const QModelIndex))); } void Form02::slotTabClick(const QModelIndex &index) { struct searchEntry dsEntry; qDebug() << "Index Rows : " << index.row(); qDebug() << "Index Column : " << index.column(); list<SEARCH_ENTRY>::iterator ds = listSearchEntry.begin(); advance(ds, index.row()); dsEntry = *ds; if(index.column() == 0) { QMessageBox::information(this, "선택값", QString("선택한 값 : <font color='Blue'><strong>") + dsEntry.name + QString("</strong></font>")); } else if (index.column() == 1) { QMessageBox::information(this, "선택값", QString("선택한 값 : <font color='Blue'><strong>") + QString::number(dsEntry.kor) + QString("</strong></font>")); } else if (index.column() == 2) { QMessageBox::information(this, "선택값", QString("선택한 값 : <font color='Blue'><strong>") + QString::number(dsEntry.eng) + QString("</strong></font>")); } else if (index.column() == 3) { QMessageBox::information(this, "선택값", QString("선택한 값 : <font color='Blue'><strong>") + QString::number(dsEntry.math) + QString("</strong></font>")); } }
// Created on: 2006-10-28 // Created by: Alexander GRIGORIEV // Copyright (c) 2006-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 VrmlData_ErrorStatus_HeaderFile #define VrmlData_ErrorStatus_HeaderFile /** * Status of read/write or other operation. */ enum VrmlData_ErrorStatus { VrmlData_StatusOK = 0, VrmlData_EmptyData, VrmlData_UnrecoverableError, VrmlData_GeneralError, VrmlData_EndOfFile, VrmlData_NotVrmlFile, VrmlData_CannotOpenFile, VrmlData_VrmlFormatError, VrmlData_NumericInputError, VrmlData_IrrelevantNumber, VrmlData_BooleanInputError, VrmlData_StringInputError, VrmlData_NodeNameUnknown, VrmlData_NonPositiveSize, VrmlData_ReadUnknownNode, VrmlData_NonSupportedFeature, VrmlData_OutputStreamUndefined, VrmlData_NotImplemented }; #endif
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Copyright (C) 2017, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation 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. // //M*/ #include "../precomp.hpp" #include "layers_common.hpp" #include <float.h> #include <algorithm> namespace cv { namespace dnn { namespace { const std::string layerName = "NormalizeBBox"; } class NormalizeBBoxLayerImpl : public NormalizeBBoxLayer { float _eps; bool _across_spatial; bool _channel_shared; public: bool getParameterDict(const LayerParams &params, const std::string &parameterName, DictValue& result) { if (!params.has(parameterName)) { return false; } result = params.get(parameterName); return true; } template<typename T> T getParameter(const LayerParams &params, const std::string &parameterName, const size_t &idx=0, const bool required=true, const T& defaultValue=T()) { DictValue dictValue; bool success = getParameterDict(params, parameterName, dictValue); if(!success) { if(required) { std::string message = layerName; message += " layer parameter does not contain "; message += parameterName; message += " parameter."; CV_Error(Error::StsBadArg, message); } else { return defaultValue; } } return dictValue.get<T>(idx); } NormalizeBBoxLayerImpl(const LayerParams &params) { _eps = getParameter<float>(params, "eps", 0, false, 1e-10f); _across_spatial = getParameter<bool>(params, "across_spatial"); _channel_shared = getParameter<bool>(params, "channel_shared"); setParamsFrom(params); } void checkInputs(const std::vector<Mat*> &inputs) { CV_Assert(inputs.size() > 0); CV_Assert(inputs[0]->dims == 4 && inputs[0]->type() == CV_32F); for (size_t i = 1; i < inputs.size(); i++) { CV_Assert(inputs[i]->dims == 4 && inputs[i]->type() == CV_32F); CV_Assert(inputs[i]->size == inputs[0]->size); } CV_Assert(inputs[0]->dims > 2); } bool getMemoryShapes(const std::vector<MatShape> &inputs, const int requiredOutputs, std::vector<MatShape> &outputs, std::vector<MatShape> &internals) const { bool inplace = Layer::getMemoryShapes(inputs, requiredOutputs, outputs, internals); size_t channels = inputs[0][1]; size_t rows = inputs[0][2]; size_t cols = inputs[0][3]; size_t channelSize = rows * cols; internals.assign(1, shape(channels, channelSize)); internals.push_back(shape(channels, 1)); internals.push_back(shape(1, channelSize)); return inplace; } void forward(std::vector<Mat*> &inputs, std::vector<Mat> &outputs, std::vector<Mat> &internals) { CV_TRACE_FUNCTION(); CV_TRACE_ARG_VALUE(name, "name", name.c_str()); checkInputs(inputs); Mat& buffer = internals[0], sumChannelMultiplier = internals[1], sumSpatialMultiplier = internals[2]; sumChannelMultiplier.setTo(1.0); sumSpatialMultiplier.setTo(1.0); const Mat& inp0 = *inputs[0]; size_t num = inp0.size[0]; size_t channels = inp0.size[1]; size_t channelSize = inp0.size[2] * inp0.size[3]; Mat zeroBuffer(channels, channelSize, CV_32F, Scalar(0)); Mat absDiff; Mat scale = blobs[0]; for (size_t j = 0; j < inputs.size(); j++) { for (size_t n = 0; n < num; ++n) { Mat src = Mat(channels, channelSize, CV_32F, inputs[j]->ptr<float>(n)); Mat dst = Mat(channels, channelSize, CV_32F, outputs[j].ptr<float>(n)); buffer = src.mul(src); if (_across_spatial) { absdiff(buffer, zeroBuffer, absDiff); // add eps to avoid overflow double absSum = sum(absDiff)[0] + _eps; float norm = sqrt(absSum); dst = src / norm; } else { Mat norm(channelSize, 1, buffer.type()); // 1 x channelSize // (_channels x channelSize)T * _channels x 1 -> channelSize x 1 gemm(buffer, sumChannelMultiplier, 1, norm, 0, norm, GEMM_1_T); // compute norm pow(norm, 0.5f, norm); // scale the layer // _channels x 1 * (channelSize x 1)T -> _channels x channelSize gemm(sumChannelMultiplier, norm, 1, buffer, 0, buffer, GEMM_2_T); dst = src / buffer; } // scale the output if (_channel_shared) { // _scale: 1 x 1 dst *= scale.at<float>(0, 0); } else { // _scale: _channels x 1 // _channels x 1 * 1 x channelSize -> _channels x channelSize gemm(scale, sumSpatialMultiplier, 1, buffer, 0, buffer); dst = dst.mul(buffer); } } } } }; Ptr<NormalizeBBoxLayer> NormalizeBBoxLayer::create(const LayerParams &params) { return Ptr<NormalizeBBoxLayer>(new NormalizeBBoxLayerImpl(params)); } } }
// // utility.cpp // #include "utility.h" double util::C2F(double TC) { double TF = 9*TC/5 + 32; return TF; } double util::F2C(double TF) { double TC = 5*(TF-32)/9; return TC; }
#include <iostream> #include <fstream> #include <string> #include "ImageProc.h" using namespace std; ifstream image; string header, input; int width, height, max_val, choice; void print_filters() { cout << " 0 --- Gaussian Blur\n"; } int main() { // will only accept .ppm P3 format! cout << "Would you like to create some test .ppm files? y/n: "; cin >> input; if (input == "y") { int w, h; cout << "Enter the desired dimensions (in pixels)\nWidth: "; cin >> w; cout << "Height: "; cin >> h; create_tests(w, h); cout << "Test files grid.ppm, circle.ppm, & gradient.ppm created successfully.\n\n"; } cout << "Enter file name to open (please include .ppm extension): "; cin >> input; cout << "Opening " << input << "...\n"; image.open(input); if (!image) { cout << "File not found" << endl; exit(1); // terminate with error } cout << "File opened successfully.\n\nLoading file data into program...\n"; image >> header; // "P3" header, we know it's a P3 already tho image >> width; // get width in pixels image >> height; // get height in pixels image >> max_val; // get max value of pixels // allocate memory to store data: // will be stored in a single line, rather than two-dimensionally, and in blocks of 3 (for the R, G, & B values. // [RGB][RGB][RGB][RGB][RGB][RGB][RGB][RGB]... int* data = new int[width * height * 3]; // begin reading in pixel values now { int n = 0; while (image >> data[n++]) ; // do nothing in the loop, everything is handled in the conditional statement } image.close(); cout << "Completed.\n\n"; // all pixel values have been loaded into data[] cout << "Make a choice of filter:\n"; print_filters(); cout << "Choice: "; cin >> choice; switch (choice) { case 0: do { cout << "\nLevel of Gaussian blur (positive number): "; cin >> choice; } while (choice <= 0); cout << "\nOutput filename (please include .ppm extension): "; cin >> input; gaussian_blur(data, width, height, input, choice); break; default: cout << "Invalide choice\n"; } delete[] data; return 0; }