diff --git a/pool/shard006/C++/0083647_UIPathSelector.cpp b/pool/shard006/C++/0083647_UIPathSelector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5a357fdbbc67d10bba51d3fa64734431a32d396 --- /dev/null +++ b/pool/shard006/C++/0083647_UIPathSelector.cpp @@ -0,0 +1,74 @@ +/* +This file is part of AlgAudio. + +AlgAudio, Copyright (C) 2015 CeTA - Audiovisual Technology Center + +AlgAudio is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +AlgAudio 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with AlgAudio. If not, see . +*/ +#include "nfd.h" +#include "UI/UIPathSelector.hpp" +#include "UI/UIBox.hpp" +#include "UI/UITextEntry.hpp" +#include "UI/UIButton.hpp" + +namespace AlgAudio{ + +UIPathSelector::UIPathSelector(std::weak_ptr parent_window, std::string p) + : UIHBox(parent_window), path(p) +{ + +} + +std::shared_ptr UIPathSelector::Create(std::weak_ptr w, std::string text) +{ + std::shared_ptr res(new UIPathSelector(w,text)); + res->Init(); + return res; +} + +void UIPathSelector::Init() +{ + child_button = UIButton::Create(window,"..."); + child_entry = UITextEntry::Create(window,path); + Insert(child_entry, UIBox::PackMode::WIDE); + Insert(child_button, UIBox::PackMode::TIGHT); + + child_button->SetBorder(false); + child_button->SetCustomSize(Size2D(16,16)); + child_button->SetInnerMargin(0); + + subscriptions += child_button->on_clicked.Subscribe([this](){ + OpenDialog(); + }); + subscriptions += child_entry->on_edited.Subscribe([this](){ + path = child_entry->GetText(); + }); +} + +void UIPathSelector::OpenDialog(){ + nfdchar_t *outPath = nullptr; + nfdresult_t result = NFD_OpenDialog( NULL, (path=="") ? NULL : path.c_str() , &outPath ); + if(result == NFD_OKAY){ + path = outPath; + on_selected.Happen(path); + child_entry->SetText(path); + free(outPath); + } +} + +void UIPathSelector::SetName(std::string t){ + child_entry->SetDefaultText(t); +} + +} // namespace AlgAudio diff --git a/pool/shard006/C++/0083648_current.cpp b/pool/shard006/C++/0083648_current.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37b568222e416a3d8f8d433379069dc4c986e22b --- /dev/null +++ b/pool/shard006/C++/0083648_current.cpp @@ -0,0 +1,47 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * 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 "glk/alan3/current.h" + +namespace Glk { +namespace Alan3 { + +/* PUBLIC DATA */ +CurVars current; +bool gameStateChanged = FALSE; + +void CurVars::synchronize(Common::Serializer &s) { + s.syncAsSint32LE(syntax); + s.syncAsSint32LE(verb); + s.syncAsSint32LE(location); + s.syncAsSint32LE(actor); + s.syncAsSint32LE(instance); + s.syncAsSint32LE(tick); + s.syncAsSint32LE(score); + s.syncAsSint32LE(visits); + s.syncAsSint32LE(sourceLine); + s.syncAsSint32LE(sourceFile); + s.syncAsUint32LE(meta); +} + +} // End of namespace Alan3 +} // End of namespace Glk diff --git a/pool/shard006/C++/0083654_82A.cpp b/pool/shard006/C++/0083654_82A.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d8e99a9f49149e2145da8c365bd5e15e93c9fcd --- /dev/null +++ b/pool/shard006/C++/0083654_82A.cpp @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +int main() { + int n; + scanf("%d", &n); + int rd = 0; + while (pow(2, rd)*5 < n) { + n -= pow(2, rd)*5; + rd++; + } + //printf("n = %d, rd = %d\n", n, rd); + int take = pow(2, rd); + switch (n%take==0?(n/take)-1:n/take) { + case 0: + printf("Sheldon\n"); + break; + case 1: + printf("Leonard\n"); + break; + case 2: + printf("Penny\n"); + break; + case 3: + printf("Rajesh\n"); + break; + default: + printf("Howard\n"); + break; + } + return 0; +} diff --git a/pool/shard006/C++/0083657_main.cpp b/pool/shard006/C++/0083657_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..450e89db80b090356f89257cdb3e161a8ccba28a --- /dev/null +++ b/pool/shard006/C++/0083657_main.cpp @@ -0,0 +1,211 @@ +#include +#include +#include +#include +#include +#include + +#include "cat.h" + +float average(std::string s); +void readin(std::ifstream &in, std::vector &cats); +void print(std::ofstream &out, std::vector &cats); +void print_extraLines(std::ofstream &out, std::vector &cats); +void print_extraSpaces(std::ofstream &out, std::vector &cats); +void print_lineOrder(std::ofstream &out, const std::vector &cats); +void print_frontSpacing(std::ofstream &out, std::vector &cats); +void print_columnSpacing(std::ofstream &out, std::vector &cats); + +//======================================================================================================== + +int main(int argc, char* argv[]) +{ + //check command line arguments + if(argc != 3) + { + std::cerr << "Wrong number of command line arguments" << std::endl; + exit(1); + } + + //open input stream + std::ifstream in(argv[1]); + if(!in.good()) + { + std::cerr << "Error opening input file" << std::endl; + exit(1); + } + + //open output stream + std::ofstream out(argv[2]); + if(!out.good()) + { + std::cerr << "Error opening output file" << std::endl; + } + + std::vector cats; + + readin(in, cats); + + //call a print function + + //print(out, cats); + //print_extraLines(out, cats); + //print_extraSpaces(out, cats); + //print_lineOrder(out, cats); + //print_frontSpacing(out, cats); + print_columnSpacing(out, cats); + + return 0; +} + +//============================================================================================================ + +//extracts the lower and upper of the range in the string and averages them +float average(std::string s) +{ + //get lower value of the range + std::size_t dash = s.find('-'); + std::size_t start = 0; + std::string lowerValue = s.substr(start, dash); + + //get upper value of the range + start = dash+1; + std::string upperValue = s.substr(start); + + //convert strings to ints + int lower; + int upper; + std::istringstream(lowerValue) >> lower; + std::istringstream(upperValue) >> upper; + + return (float)(upper + lower) / 2; +} + +//read in from the input file +void readin(std::ifstream &in, std::vector &cats) +{ + std::string breed, lifeSpan, weight; + std::string interesting = ""; + std::string s; + std::string classifier; + std::string unit; + + in >> classifier; + + while(!in.eof()) + { + //take in the breed, life span as a string, weight as a string + in >> breed; + in >> classifier >> lifeSpan >> unit; + in >> classifier >> weight >> unit; + in >> classifier >> s; + + //take in the interesting fact about the cat breed + while(!in.eof() && s != "BREED:") + { + interesting += s + " "; + in >> s; + } + + //get the average from the range of values + float weightAverage = average(weight); + float lifeSpanAverage = average(lifeSpan); + + cats.push_back(Cat(breed, lifeSpanAverage, weightAverage, interesting)); + + interesting = ""; + } +} + +//--------------------------------------------------------------------------------------------------------------------------- +//functions to print + +//print the output as expected +void print(std::ofstream &out, std::vector &cats) +{ + std::sort(cats.begin(), cats.end(), sortCats); + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl; + } +} + +//print the output with extra newlines at the end of every line +void print_extraLines(std::ofstream &out, std::vector &cats) +{ + std::sort(cats.begin(), cats.end(), sortCats); + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << std::endl << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() + << std::endl << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() + << std::endl << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() + << std::endl << std::endl; + } +} + +//print the output with extra spaces at the end of every line +void print_extraSpaces(std::ofstream &out, std::vector &cats) +{ + std::sort(cats.begin(), cats.end(), sortCats); + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << " " << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() + << " " << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() + << " " << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() + << " " << std::endl; + } +} + +//print the output with the lines in the wrong order +void print_lineOrder(std::ofstream &out, const std::vector &cats) +{ + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl; + } +} + +//print the output with the spacing in front off (expected: 5 spaces) +void print_frontSpacing(std::ofstream &out, std::vector &cats) +{ + std::sort(cats.begin(), cats.end(), sortCats); + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl; + } +} + +//print the output with the column spacing off +//(expected: 1 space between 1st column and 2nd, 1st column the length of the longest attribute) +void print_columnSpacing(std::ofstream &out, std::vector &cats) +{ + std::sort(cats.begin(), cats.end(), sortCats); + std::string spacing = " "; + for(unsigned int i = 0; i < cats.size(); i++) + { + out << cats[i].getBreed() << std::endl; + out << spacing << "Average Lifespan: " << cats[i].getAverageLifeSpan() << std::endl; + out << spacing << "Average Weight: " << cats[i].getAverageSize() << std::endl; + out << spacing << "Intersting Fact: " << cats[i].getInterestingFact() << std::endl; + } +} \ No newline at end of file diff --git a/pool/shard006/C++/0083662_user_script_slave.cc b/pool/shard006/C++/0083662_user_script_slave.cc new file mode 100644 index 0000000000000000000000000000000000000000..afd065ff82d596bcc00566440feeb3cfb9ba0821 --- /dev/null +++ b/pool/shard006/C++/0083662_user_script_slave.cc @@ -0,0 +1,180 @@ +// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/renderer/user_script_slave.h" + +#include "app/resource_bundle.h" +#include "base/histogram.h" +#include "base/logging.h" +#include "base/perftimer.h" +#include "base/pickle.h" +#include "base/shared_memory.h" +#include "base/string_util.h" +#include "googleurl/src/gurl.h" +#include "webkit/api/public/WebScriptSource.h" +#include "webkit/glue/webframe.h" + +#include "grit/renderer_resources.h" + +using WebKit::WebScriptSource; +using WebKit::WebString; + +// These two strings are injected before and after the Greasemonkey API and +// user script to wrap it in an anonymous scope. +static const char kUserScriptHead[] = "(function (unsafeWindow) {\n"; +static const char kUserScriptTail[] = "\n})(window);"; + +// Creates a convenient reference to a content script's parent extension. +// TODO(mpcomplete): self.onConnect is deprecated. Remove it at 1.0. +// http://code.google.com/p/chromium/issues/detail?id=16356 +static const char kInitExtension[] = + "chrome.extension = new chrome.Extension('%s');" + "chrome.self.onConnect = chrome.extension.onConnect;"; + +UserScriptSlave::UserScriptSlave() + : shared_memory_(NULL), + script_deleter_(&scripts_), + user_script_start_line_(0) { + // TODO: Only windows supports resources and only windows supports user + // scrips, so only load the Greasemonkey API on windows. Fix this when + // better cross platofrm support is available. +#if defined(OS_WIN) + api_js_ = ResourceBundle::GetSharedInstance().GetRawDataResource( + IDR_GREASEMONKEY_API_JS); +#endif + + // Count the number of lines that will be injected before the user script. + StringPiece::size_type pos = 0; + while ((pos = api_js_.find('\n', pos)) != StringPiece::npos) { + user_script_start_line_++; + pos++; + } + + // NOTE: There is actually one extra line in the injected script because the + // function header includes a newline as well. But WebKit expects the + // numbering to be one-based, not zero-based, so actually *not* accounting for + // this extra line ends us up with the right offset. +} + +bool UserScriptSlave::UpdateScripts(base::SharedMemoryHandle shared_memory) { + scripts_.clear(); + + // Create the shared memory object (read only). + shared_memory_.reset(new base::SharedMemory(shared_memory, true)); + if (!shared_memory_.get()) + return false; + + // First get the size of the memory block. + if (!shared_memory_->Map(sizeof(Pickle::Header))) + return false; + Pickle::Header* pickle_header = + reinterpret_cast(shared_memory_->memory()); + + // Now map in the rest of the block. + int pickle_size = sizeof(Pickle::Header) + pickle_header->payload_size; + shared_memory_->Unmap(); + if (!shared_memory_->Map(pickle_size)) + return false; + + // Unpickle scripts. + void* iter = NULL; + size_t num_scripts = 0; + Pickle pickle(reinterpret_cast(shared_memory_->memory()), + pickle_size); + pickle.ReadSize(&iter, &num_scripts); + + scripts_.reserve(num_scripts); + for (size_t i = 0; i < num_scripts; ++i) { + scripts_.push_back(new UserScript()); + UserScript* script = scripts_.back(); + script->Unpickle(pickle, &iter); + + // Note that this is a pointer into shared memory. We don't own it. It gets + // cleared up when the last renderer or browser process drops their + // reference to the shared memory. + for (size_t j = 0; j < script->js_scripts().size(); ++j) { + const char* body = NULL; + int body_length = 0; + CHECK(pickle.ReadData(&iter, &body, &body_length)); + script->js_scripts()[j].set_external_content( + StringPiece(body, body_length)); + } + for (size_t j = 0; j < script->css_scripts().size(); ++j) { + const char* body = NULL; + int body_length = 0; + CHECK(pickle.ReadData(&iter, &body, &body_length)); + script->css_scripts()[j].set_external_content( + StringPiece(body, body_length)); + } + } + + return true; +} + +bool UserScriptSlave::InjectScripts(WebFrame* frame, + UserScript::RunLocation location) { + PerfTimer timer; + int num_matched = 0; + + for (size_t i = 0; i < scripts_.size(); ++i) { + std::vector sources; + UserScript* script = scripts_[i]; + if (!script->MatchesUrl(frame->GetURL())) + continue; // This frame doesn't match the script url pattern, skip it. + + ++num_matched; + // CSS files are always injected on document start before js scripts. + if (location == UserScript::DOCUMENT_START) { + for (size_t j = 0; j < script->css_scripts().size(); ++j) { + UserScript::File& file = script->css_scripts()[j]; + frame->InsertCSSStyles(file.GetContent().as_string()); + } + } + if (script->run_location() == location) { + for (size_t j = 0; j < script->js_scripts().size(); ++j) { + UserScript::File &file = script->js_scripts()[j]; + std::string content = file.GetContent().as_string(); + + // We add this dumb function wrapper for standalone user script to + // emulate what Greasemonkey does. + if (script->is_standalone()) { + content.insert(0, kUserScriptHead); + content += kUserScriptTail; + } + sources.push_back(WebScriptSource( + WebString::fromUTF8(content.c_str(), content.length()), + file.url())); + } + } + + if (!sources.empty()) { + if (script->is_standalone()) { + // For standalone scripts, we try to emulate the Greasemonkey API. + sources.insert(sources.begin(), + WebScriptSource(WebString::fromUTF8(api_js_.as_string()))); + } else { + // Setup chrome.self to contain an Extension object with the correct + // ID. + sources.insert(sources.begin(), + WebScriptSource(WebString::fromUTF8( + StringPrintf(kInitExtension, script->extension_id().c_str())))); + } + + frame->ExecuteScriptInNewContext(&sources.front(), sources.size()); + } + } + + // Log debug info. + if (location == UserScript::DOCUMENT_START) { + HISTOGRAM_COUNTS_100("UserScripts:DocStart:Count", num_matched); + HISTOGRAM_TIMES("UserScripts:DocStart:Time", timer.Elapsed()); + } else { + HISTOGRAM_COUNTS_100("UserScripts:DocEnd:Count", num_matched); + HISTOGRAM_TIMES("UserScripts:DocEnd:Time", timer.Elapsed()); + } + + LOG(INFO) << "Injected " << num_matched << " user scripts into " << + frame->GetURL().spec(); + return true; +} diff --git a/pool/shard006/C++/0083663_MPHasher.cpp b/pool/shard006/C++/0083663_MPHasher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2136e59a3d83b65276fa35d9401b71088ebd6011 --- /dev/null +++ b/pool/shard006/C++/0083663_MPHasher.cpp @@ -0,0 +1,78 @@ +#include "MPHasher.h" +#include "EventTypeName.h" +#include + +namespace mParticle { + __attribute__((no_sanitize("integer"))) + int Hasher::hashFromString(const string &stringToHash) { + if (stringToHash.empty()) { + return 0; + } + + string lowerCaseStringToHash = stringToHash; + transform(lowerCaseStringToHash.begin(), lowerCaseStringToHash.end(), lowerCaseStringToHash.begin(), ::tolower); + + int hash = 0; + for (auto &character : lowerCaseStringToHash) { + hash = ((hash << 5) - hash) + character; + } + + return hash; + } + + string Hasher::hashString(string stringToHash) { + if (stringToHash.empty()) { + return ""; + } + + auto hash = Hasher::hashFromString(stringToHash); + + auto hashString = to_string(hash); + return hashString; + } + + vector Hasher::hashedEventTypes(const vector &eventTypes) { + vector hashedTypes; + + if (eventTypes.empty()) { + return hashedTypes; + } + + for (auto &eventType : eventTypes) { + auto eventTypeString = to_string(eventType); + auto hashedEventType = Hasher::hashString(eventTypeString); + hashedTypes.push_back(hashedEventType); + } + + return hashedTypes; + } + + vector Hasher::hashedAllEventTypes() { + vector eventTypes(EventTypeName::count); + + int i = 0; + for_each(eventTypes.begin(), eventTypes.end(), [&i](int &eventType) {eventType = i++;}); + + vector hashes = Hasher::hashedEventTypes(eventTypes); + return hashes; + } + + string Hasher::hashEvent(string eventName, string eventType) { + eventName.append(eventType); + return Hasher::hashString(eventName); + } + + __attribute__((no_sanitize("integer"))) + int64_t Hasher::hashFNV1a(const char *bytes, int length) { + // FNV-1a hashing + int64_t rampHash = 0xcbf29ce484222325; + + int i = 0; + while (i < length) { + rampHash = (rampHash ^ bytes[i]) * 0x100000001B3; + i += 1; + } + + return rampHash; + } +} diff --git a/pool/shard006/C++/0083666_clientsideeffects_test.cpp b/pool/shard006/C++/0083666_clientsideeffects_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34ace22d7e97a940cb613fc841ada4f54144606e --- /dev/null +++ b/pool/shard006/C++/0083666_clientsideeffects_test.cpp @@ -0,0 +1,302 @@ +//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ======== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// Purpose: +// +// $Workfile: $ +// $NoKeywords: $ +//============================================================================= +#include "cbase.h" +#include "engine/IEngineSound.h" +#include "view.h" + +#include "fx_line.h" +#include "fx_discreetline.h" +#include "fx_quad.h" +#include "clientsideeffects.h" + +#include "SoundEmitterSystemBase.h" +#include "tier0/vprof.h" + +//FIXME: All these functions will be moved out to FX_Main.CPP or a individual folder + +/* +================================================== +FX_AddStaticLine +================================================== +*/ + +void FX_AddStaticLine( const Vector& start, const Vector& end, float scale, float life, const char *materialName, unsigned char flags ) +{ + CFXStaticLine *t = new CFXStaticLine( "StaticLine", start, end, scale, life, materialName, flags ); + assert( t ); + + //Throw it into the list + clienteffects->AddEffect( t ); +} + +/* +================================================== +FX_AddDiscreetLine +================================================== +*/ + +void FX_AddDiscreetLine( const Vector& start, const Vector& direction, float velocity, float length, float clipLength, float scale, float life, const char *shader ) +{ + CFXDiscreetLine *t = new CFXDiscreetLine( "Line", start, direction, velocity, length, clipLength, scale, life, shader ); + assert( t ); + + //Throw it into the list + clienteffects->AddEffect( t ); +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void FX_AddQuad( const FXQuadData_t &data ) +{ + CFXQuad *quad = new CFXQuad( data ); + + Assert( quad != NULL ); + + clienteffects->AddEffect( quad ); +} +//----------------------------------------------------------------------------- +// Purpose: Parameter heavy version +//----------------------------------------------------------------------------- +void FX_AddQuad( const Vector &origin, + const Vector &normal, + float startSize, + float endSize, + float sizeBias, + float startAlpha, + float endAlpha, + float alphaBias, + float yaw, + float deltaYaw, + const Vector &color, + float lifeTime, + const char *shader, + unsigned int flags ) +{ + FXQuadData_t data; + + //Setup the data + data.SetAlpha( startAlpha, endAlpha ); + data.SetScale( startSize, endSize ); + data.SetFlags( flags ); + data.SetMaterial( shader ); + data.SetNormal( normal ); + data.SetOrigin( origin ); + data.SetLifeTime( lifeTime ); + data.SetColor( color[0], color[1], color[2] ); + data.SetScaleBias( sizeBias ); + data.SetAlphaBias( alphaBias ); + data.SetYaw( yaw, deltaYaw ); + + //Output it + FX_AddQuad( data ); +} + +//----------------------------------------------------------------------------- +// Purpose: Creates a test effect +//----------------------------------------------------------------------------- +void CreateTestEffect( void ) +{ + //NOTENOTE: Add any test effects here + //FX_BulletPass( NULL, NULL ); +} + +/* +================================================== +UTIL_NearestPointOnLine +================================================== +*/ + +float UTIL_NearestPointOnLine( const Vector& start, const Vector& end, const Vector& target, Vector& out ) +{ + Vector lineDir, targetDir; + float dot; + + //Find the direction of the line + VectorSubtract( end, start, lineDir ); + VectorNormalize( lineDir ); + + //Find the direction of the target to the line's path + VectorSubtract( target, start, targetDir ); + + //Find the nearest point to the target on that line + dot = DotProduct( targetDir, lineDir ); + VectorScale( lineDir, dot, out ); + VectorAdd( start, out, out ); + + //Find the distance to the nearest point + VectorSubtract( out, target, targetDir ); + + return VectorLength( targetDir ); +} + +/* +================================================== +FX_PlayerTracer +================================================== +*/ + +#define TRACER_BASE_OFFSET 8 + +void FX_PlayerTracer( Vector& start, Vector& end ) +{ + VPROF_BUDGET( "FX_PlayerTracer", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); + Vector shotDir, dStart, dEnd; + float length; + + //Find the direction of the tracer + VectorSubtract( end, start, shotDir ); + length = VectorNormalize( shotDir ); + + //We don't want to draw them if they're too close to us + if ( length < 256 ) + return; + + //Randomly place the tracer along this line, with a random length + VectorMA( start, TRACER_BASE_OFFSET + random->RandomFloat( -24.0f, 64.0f ), shotDir, dStart ); + VectorMA( dStart, ( length * random->RandomFloat( 0.1f, 0.6f ) ), shotDir, dEnd ); + + //Create the line + CFXStaticLine *t; + const char *materialName; + + //materialName = ( random->RandomInt( 0, 1 ) ) ? "effects/tracer_middle" : "effects/tracer_middle2"; + materialName = "effects/spark"; + + t = new CFXStaticLine( "Tracer", dStart, dEnd, random->RandomFloat( 0.5f, 0.75f ), 0.01f, materialName, 0 ); + assert( t ); + + //Throw it into the list + clienteffects->AddEffect( t ); +} + +/* +================================================== +FX_Tracer +================================================== +*/ +// Tracer must be this close to be considered for hearing +#define TRACER_MAX_HEAR_DIST (6*12) +#define TRACER_SOUND_TIME_MIN 0.10f +#define TRACER_SOUND_TIME_MAX 0.10f + + +class CBulletWhizTimer : public CAutoGameSystem +{ +public: + void LevelInitPreEntity() + { + m_nextWhizTime = 0; + } + + float m_nextWhizTime; +}; + +// Client-side tracking for whiz noises +CBulletWhizTimer g_BulletWhiz; + +//----------------------------------------------------------------------------- +// Purpose: +// Input : &vecStart - +// &vecDir - +// iTracerType - +//----------------------------------------------------------------------------- +void FX_TracerSound( const Vector &start, const Vector &end, int iTracerType ) +{ + const char *pszSoundName = NULL; + + switch( iTracerType ) + { + case TRACER_TYPE_DEFAULT: + pszSoundName = "Bullets.DefaultNearmiss"; + break; + + case TRACER_TYPE_GUNSHIP: + pszSoundName = "Bullets.GunshipNearmiss"; + break; + + case TRACER_TYPE_STRIDER: + pszSoundName = "Bullets.StriderNearmiss"; + break; + + default: + return; + break; + } + + if( pszSoundName ) + { + //Get out shot direction and length + float totalDist; + Vector shotDir; + + VectorSubtract( end, start, shotDir ); + totalDist = VectorNormalize( shotDir ); + + float dt = g_BulletWhiz.m_nextWhizTime - gpGlobals->curtime; + + //If needed, make a bullet whiz noise + if ( dt <= 0 ) + { + Vector vNear, dStart, dEnd; + + //Find the nearest point to our view on the bullet's path + float vDist = UTIL_NearestPointOnLine( start, end, MainViewOrigin(), vNear ); + + //See if we should play a bullet whizz + if ( vDist <= TRACER_MAX_HEAR_DIST ) + { + CLocalPlayerFilter filter; + CSoundParameters params; + + if( C_BaseEntity::GetParametersForSound( pszSoundName, params ) ) + { + enginesound->EmitSound( filter, SOUND_FROM_WORLD, CHAN_STATIC, params.soundname, params.volume, SNDLVL_TO_ATTN(params.soundlevel), 0, params.pitch, &start, &shotDir, false); + } + + //Don't play another bullet whiz for this client until this time has run out + g_BulletWhiz.m_nextWhizTime = gpGlobals->curtime + random->RandomFloat( TRACER_SOUND_TIME_MIN, TRACER_SOUND_TIME_MAX ); + + } + } + } +} + + +void FX_Tracer( Vector& start, Vector& end, int velocity, bool makeWhiz ) +{ + VPROF_BUDGET( "FX_Tracer", VPROF_BUDGETGROUP_PARTICLE_RENDERING ); + //Don't make small tracers + float dist; + Vector dir; + + VectorSubtract( end, start, dir ); + dist = VectorNormalize( dir ); + + // Don't make short tracers. + if ( dist < 256 ) + { + return; + } + + float length = random->RandomFloat( 64.0f, 128.0f ); + float life = ( dist + length ) / velocity; //NOTENOTE: We want the tail to finish its run as well + + //Add it + FX_AddDiscreetLine( start, dir, velocity, length, dist, random->RandomFloat( 0.75f, 0.9f ), life, "effects/spark" ); + + if( makeWhiz ) + { + FX_TracerSound( start, end, TRACER_TYPE_DEFAULT ); + } +} diff --git a/pool/shard006/C++/0083671_test_context_provider_factory.cc b/pool/shard006/C++/0083671_test_context_provider_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8ac73bec144c3a57ba8cc976e53fdbb721d8620 --- /dev/null +++ b/pool/shard006/C++/0083671_test_context_provider_factory.cc @@ -0,0 +1,46 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "webkit/gpu/test_context_provider_factory.h" + +#include "base/logging.h" +#include "cc/output/context_provider.h" +#include "webkit/gpu/context_provider_in_process.h" + +namespace webkit { +namespace gpu { + +static TestContextProviderFactory* context_provider_instance = NULL; + +// static +TestContextProviderFactory* TestContextProviderFactory::GetInstance() { + if (!context_provider_instance) + context_provider_instance = new TestContextProviderFactory(); + return context_provider_instance; +} + +TestContextProviderFactory::TestContextProviderFactory() {} + +TestContextProviderFactory::~TestContextProviderFactory() {} + +scoped_refptr TestContextProviderFactory:: + OffscreenContextProviderForMainThread() { + if (!main_thread_ || main_thread_->DestroyedOnMainThread()) { + main_thread_ = ContextProviderInProcess::Create(); + if (main_thread_ && !main_thread_->BindToCurrentThread()) + main_thread_ = NULL; + } + return main_thread_; +} + +scoped_refptr TestContextProviderFactory:: + OffscreenContextProviderForCompositorThread() { + if (!compositor_thread_ || + compositor_thread_->DestroyedOnMainThread()) + compositor_thread_ = ContextProviderInProcess::Create(); + return compositor_thread_; +} + +} // namespace gpu +} // namespace webkit diff --git a/pool/shard006/C++/0083679_rtcp_format_remb_unittest.cc b/pool/shard006/C++/0083679_rtcp_format_remb_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..88463e4718f812db2ccfac743ea74f81a7feae93 --- /dev/null +++ b/pool/shard006/C++/0083679_rtcp_format_remb_unittest.cc @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "testing/gtest/include/gtest/gtest.h" + +#include "webrtc/common_types.h" +#include "webrtc/modules/remote_bitrate_estimator/include/bwe_defines.h" +#include "webrtc/modules/remote_bitrate_estimator/include/mock/mock_remote_bitrate_observer.h" +#include "webrtc/modules/rtp_rtcp/source/rtcp_receiver.h" +#include "webrtc/modules/rtp_rtcp/source/rtcp_sender.h" +#include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_impl.h" +#include "webrtc/modules/rtp_rtcp/source/rtp_utility.h" +#include "webrtc/typedefs.h" + +namespace { + +using namespace webrtc; + + +class TestTransport : public Transport { + public: + TestTransport(RTCPReceiver* rtcp_receiver) : + rtcp_receiver_(rtcp_receiver) { + } + + virtual int SendPacket(int /*channel*/, const void* /*data*/, int /*len*/) { + return -1; + } + virtual int SendRTCPPacket(int /*channel*/, + const void *packet, + int packetLength) { + RTCPUtility::RTCPParserV2 rtcpParser((uint8_t*)packet, + (int32_t)packetLength, + true); // Allow non-compound RTCP + + EXPECT_TRUE(rtcpParser.IsValid()); + RTCPHelp::RTCPPacketInformation rtcpPacketInformation; + EXPECT_EQ(0, rtcp_receiver_->IncomingRTCPPacket(rtcpPacketInformation, + &rtcpParser)); + + EXPECT_EQ((uint32_t)kRtcpRemb, + rtcpPacketInformation.rtcpPacketTypeFlags & kRtcpRemb); + EXPECT_EQ((uint32_t)1234, + rtcpPacketInformation.receiverEstimatedMaxBitrate); + return packetLength; + } + private: + RTCPReceiver* rtcp_receiver_; +}; + + +class RtcpFormatRembTest : public ::testing::Test { + protected: + static const uint32_t kRemoteBitrateEstimatorMinBitrateBps = 30000; + + RtcpFormatRembTest() + : over_use_detector_options_(), + system_clock_(Clock::GetRealTimeClock()), + receive_statistics_(ReceiveStatistics::Create(system_clock_)), + remote_bitrate_observer_(), + remote_bitrate_estimator_( + RemoteBitrateEstimatorFactory().Create( + &remote_bitrate_observer_, + system_clock_, + kMimdControl, + kRemoteBitrateEstimatorMinBitrateBps)) {} + virtual void SetUp(); + virtual void TearDown(); + + OverUseDetectorOptions over_use_detector_options_; + Clock* system_clock_; + ModuleRtpRtcpImpl* dummy_rtp_rtcp_impl_; + scoped_ptr receive_statistics_; + RTCPSender* rtcp_sender_; + RTCPReceiver* rtcp_receiver_; + TestTransport* test_transport_; + MockRemoteBitrateObserver remote_bitrate_observer_; + scoped_ptr remote_bitrate_estimator_; +}; + +void RtcpFormatRembTest::SetUp() { + RtpRtcp::Configuration configuration; + configuration.id = 0; + configuration.audio = false; + configuration.clock = system_clock_; + configuration.remote_bitrate_estimator = remote_bitrate_estimator_.get(); + dummy_rtp_rtcp_impl_ = new ModuleRtpRtcpImpl(configuration); + rtcp_sender_ = + new RTCPSender(0, false, system_clock_, receive_statistics_.get()); + rtcp_receiver_ = new RTCPReceiver(0, system_clock_, dummy_rtp_rtcp_impl_); + test_transport_ = new TestTransport(rtcp_receiver_); + + EXPECT_EQ(0, rtcp_sender_->Init()); + EXPECT_EQ(0, rtcp_sender_->RegisterSendTransport(test_transport_)); +} + +void RtcpFormatRembTest::TearDown() { + delete rtcp_sender_; + delete rtcp_receiver_; + delete dummy_rtp_rtcp_impl_; + delete test_transport_; +} + +TEST_F(RtcpFormatRembTest, TestBasicAPI) { + EXPECT_FALSE(rtcp_sender_->REMB()); + EXPECT_EQ(0, rtcp_sender_->SetREMBStatus(true)); + EXPECT_TRUE(rtcp_sender_->REMB()); + EXPECT_EQ(0, rtcp_sender_->SetREMBStatus(false)); + EXPECT_FALSE(rtcp_sender_->REMB()); + + EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 0, NULL)); +} + +TEST_F(RtcpFormatRembTest, TestNonCompund) { + uint32_t SSRC = 456789; + EXPECT_EQ(0, rtcp_sender_->SetRTCPStatus(kRtcpNonCompound)); + EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 1, &SSRC)); + RTCPSender::FeedbackState feedback_state(dummy_rtp_rtcp_impl_); + EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpRemb)); +} + +TEST_F(RtcpFormatRembTest, TestCompund) { + uint32_t SSRCs[2] = {456789, 98765}; + EXPECT_EQ(0, rtcp_sender_->SetRTCPStatus(kRtcpCompound)); + EXPECT_EQ(0, rtcp_sender_->SetREMBData(1234, 2, SSRCs)); + RTCPSender::FeedbackState feedback_state(dummy_rtp_rtcp_impl_); + EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpRemb)); +} +} // namespace diff --git a/pool/shard006/C++/0083681_viewbasis_funcs.cpp b/pool/shard006/C++/0083681_viewbasis_funcs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5f00cd3f4857d1ba73117423db3a75401597c26 --- /dev/null +++ b/pool/shard006/C++/0083681_viewbasis_funcs.cpp @@ -0,0 +1,112 @@ +/* + *** Qt GUI: View Basis dialog functions + *** src/gui/viewbasis_funcs.cpp + Copyright T. Youngs 2007-2015 + + This file is part of Aten. + + Aten is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Aten 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 Aten. If not, see . +*/ + +#include "main/aten.h" +#include "gui/viewbasis.h" +#include "gui/mainwindow.h" +#include "base/messenger.h" +#include "base/sysfunc.h" +#include "model/model.h" + +// Constructor +AtenViewBasis::AtenViewBasis(QWidget* parent, Qt::WindowFlags flags) : QDialog(parent,flags) +{ + // Private variables + target_ = NULL; + + ui.setupUi(this); +} + +void AtenViewBasis::showWindow(Model* m) +{ + // Clear old contents + ui.BasisTable->clear(); + ui.BasisTable->setColumnCount(10); + ui.BasisTable->setHorizontalHeaderLabels(QStringList() << "Atom" << "Shell" << "Type" << "Exponent" << "Coefficients" << " " << " " << " " << " " << " " ); + // Check model pointer + if (m == NULL) return; + // If no basis definition exists in the supplied model, try to look at the trajectory parent + target_ = m; + if ((target_->basisShells() == NULL) && (target_->parent() != NULL)) + { + target_ = target_->parent(); + Messenger::print("No basis definition found in trajectory frame - looking in parent model..."); + } + // Determine total row count + BasisShell *bas; + BasisPrimitive* prim; + int row = 0, shell, lastid = -1, n, ncartesians = 0; + Dnchar text; + for (bas = target_->basisShells(); bas != NULL; bas = bas->next) row += bas->nPrimitives(); + ui.BasisTable->setRowCount(row); + ui.BasisShellsLabel->setText(itoa(target_->nBasisShells())); + // Populate table + QTableWidgetItem *tabitem; + row = 0; + shell = 0; + for (bas = target_->basisShells(); bas != NULL; bas = bas->next) + { + ++shell; + ncartesians += BasisShell::nCartesianFunctions(bas->type()); + // Create atom id item? + if (lastid != bas->atomId()) + { + lastid = bas->atomId(); + tabitem = new QTableWidgetItem(); + text.sprintf("%i (%s)\n", lastid+1, m->atom(lastid) != NULL ? Elements().symbol(m->atom(lastid)) : "NULL"); + tabitem->setText(text.get()); + ui.BasisTable->setItem(row, AtenViewBasis::AtomIdColumn, tabitem); + } + // Add in shell data + tabitem = new QTableWidgetItem(); + tabitem->setText(itoa(shell)); + ui.BasisTable->setItem(row, AtenViewBasis::ShellColumn, tabitem); + tabitem = new QTableWidgetItem(); + tabitem->setText(BasisShell::basisShellType(bas->type())); + ui.BasisTable->setItem(row, AtenViewBasis::TypeColumn, tabitem); + + // Cycle over primitives + n = 0; + for (prim = bas->primitives(); prim != NULL; prim = prim->next) + { + tabitem = new QTableWidgetItem(); + tabitem->setText(ftoa(prim->exponent())); + ui.BasisTable->setItem(row, AtenViewBasis::ExponentColumn, tabitem); + for (n = 0; n < prim->nCoefficients(); ++n) + { + tabitem = new QTableWidgetItem(); + tabitem->setText(ftoa(prim->coefficient(n))); + ui.BasisTable->setItem(row, AtenViewBasis::CoefficientColumn+n, tabitem); + } + row++; + } + } + ui.BasisCartesiansLabel->setText(itoa(ncartesians)); + // Resize columns + for (n=0; nresizeColumnToContents(n); + show(); +} + +void AtenViewBasis::dialogFinished(int result) +{ + accept(); +} + diff --git a/pool/shard006/C++/0083683_osc_route_observer.cc b/pool/shard006/C++/0083683_osc_route_observer.cc new file mode 100644 index 0000000000000000000000000000000000000000..576b92d1bb507a09de9be7345a8affc87aaeea56 --- /dev/null +++ b/pool/shard006/C++/0083683_osc_route_observer.cc @@ -0,0 +1,107 @@ +/* + Copyright (C) 2009 Paul Davis + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + +*/ + +#include "boost/lambda/lambda.hpp" + +#include "ardour/route.h" +#include "ardour/audio_track.h" +#include "ardour/midi_track.h" + +#include "osc.h" +#include "osc_route_observer.h" + +#include "i18n.h" + +using namespace std; +using namespace sigc; +using namespace PBD; +using namespace ARDOUR; +using namespace boost; + +OSCRouteObserver::OSCRouteObserver (boost::shared_ptr r, lo_address a) + : _route (r) +{ + addr = lo_address_new (lo_address_get_hostname(a) , lo_address_get_port(a)); + + _route->PropertyChanged.connect (name_changed_connection, MISSING_INVALIDATOR, boost::bind (&OSCRouteObserver::name_changed, this, boost::lambda::_1), OSC::instance()); + + if (dynamic_pointer_cast(_route) || dynamic_pointer_cast(_route)) { + + boost::shared_ptr track = dynamic_pointer_cast(r); + boost::shared_ptr rec_controllable = dynamic_pointer_cast(track->rec_enable_control()); + + rec_controllable->Changed.connect (rec_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/rec"), track->rec_enable_control()), OSC::instance()); + } + + boost::shared_ptr mute_controllable = dynamic_pointer_cast(_route->mute_control()); + mute_controllable->Changed.connect (mute_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/mute"), _route->mute_control()), OSC::instance()); + + boost::shared_ptr solo_controllable = dynamic_pointer_cast(_route->solo_control()); + solo_controllable->Changed.connect (solo_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/solo"), _route->solo_control()), OSC::instance()); + + boost::shared_ptr gain_controllable = dynamic_pointer_cast(_route->gain_control()); + gain_controllable->Changed.connect (gain_changed_connection, MISSING_INVALIDATOR, bind (&OSCRouteObserver::send_change_message, this, X_("/route/gain"), _route->gain_control()), OSC::instance()); +} + +OSCRouteObserver::~OSCRouteObserver () +{ + name_changed_connection.disconnect(); + rec_changed_connection.disconnect(); + mute_changed_connection.disconnect(); + solo_changed_connection.disconnect(); + gain_changed_connection.disconnect(); + + lo_address_free (addr); +} + +void +OSCRouteObserver::name_changed (const PBD::PropertyChange& what_changed) +{ + if (!what_changed.contains (ARDOUR::Properties::name)) { + return; + } + + if (!_route) { + return; + } + + lo_message msg = lo_message_new (); + + lo_message_add_int32 (msg, _route->remote_control_id()); + lo_message_add_string (msg, _route->name().c_str()); + + lo_send_message (addr, "/route/name", msg); + lo_message_free (msg); +} + +void +OSCRouteObserver::send_change_message (string path, boost::shared_ptr controllable) +{ + lo_message msg = lo_message_new (); + + lo_message_add_int32 (msg, _route->remote_control_id()); + lo_message_add_float (msg, (float) controllable->get_value()); + + /* XXX thread issues */ + + //std::cerr << "ORC: send " << path << " = " << controllable->get_value() << std::endl; + + lo_send_message (addr, path.c_str(), msg); + lo_message_free (msg); +} diff --git a/pool/shard006/C++/0083689_mode_fbwa.cpp b/pool/shard006/C++/0083689_mode_fbwa.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35b97ebbe06e8063ebb72debd9b4f8d3b7ed6933 --- /dev/null +++ b/pool/shard006/C++/0083689_mode_fbwa.cpp @@ -0,0 +1,37 @@ +#include "mode.h" +#include "Plane.h" + +void ModeFBWA::update() +{ + // set nav_roll and nav_pitch using sticks + plane.nav_roll_cd = plane.channel_roll->norm_input() * plane.roll_limit_cd; + plane.update_load_factor(); + float pitch_input = plane.channel_pitch->norm_input(); + if (pitch_input > 0) { + plane.nav_pitch_cd = pitch_input * plane.aparm.pitch_limit_max_cd; + } else { + plane.nav_pitch_cd = -(pitch_input * plane.pitch_limit_min_cd); + } + plane.adjust_nav_pitch_throttle(); + plane.nav_pitch_cd = constrain_int32(plane.nav_pitch_cd, plane.pitch_limit_min_cd, plane.aparm.pitch_limit_max_cd.get()); + if (plane.fly_inverted()) { + plane.nav_pitch_cd = -plane.nav_pitch_cd; + } + if (plane.failsafe.rc_failsafe && plane.g.fs_action_short == FS_ACTION_SHORT_FBWA) { + // FBWA failsafe glide + plane.nav_roll_cd = 0; + plane.nav_pitch_cd = 0; + SRV_Channels::set_output_limit(SRV_Channel::k_throttle, SRV_Channel::Limit::MIN); + } + RC_Channel *chan = rc().find_channel_for_option(RC_Channel::AUX_FUNC::FBWA_TAILDRAGGER); + if (chan != nullptr) { + // check for the user enabling FBWA taildrag takeoff mode + bool tdrag_mode = chan->get_aux_switch_pos() == RC_Channel::AuxSwitchPos::HIGH; + if (tdrag_mode && !plane.auto_state.fbwa_tdrag_takeoff_mode) { + if (plane.auto_state.highest_airspeed < plane.g.takeoff_tdrag_speed1) { + plane.auto_state.fbwa_tdrag_takeoff_mode = true; + plane.gcs().send_text(MAV_SEVERITY_WARNING, "FBWA tdrag mode"); + } + } + } +} diff --git a/pool/shard006/C++/0083690_DigitalGlitchFilterJNI.cpp b/pool/shard006/C++/0083690_DigitalGlitchFilterJNI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1bd50d49341c1628009c3f390ebb97676e42152 --- /dev/null +++ b/pool/shard006/C++/0083690_DigitalGlitchFilterJNI.cpp @@ -0,0 +1,68 @@ +/*----------------------------------------------------------------------------*/ +/* Copyright (c) FIRST 2016. All Rights Reserved. */ +/* Open Source Software - may be modified and shared by FRC teams. The code */ +/* must be accompanied by the FIRST BSD license file in the root directory of */ +/* the project. */ +/*----------------------------------------------------------------------------*/ + +#include +#include "HAL/HAL.hpp" +#include "HALUtil.h" + +#include "edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI.h" + +/* + * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI + * Method: setFilterSelect + */ +JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterSelect + (JNIEnv* env, jclass, jlong port_pointer, jint filter_index) +{ + int32_t status = 0; + void* digital_port_pointer = reinterpret_cast(port_pointer); + + setFilterSelect(digital_port_pointer, filter_index, &status); + CheckStatus(env, status); +} + +/* + * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI + * Method: getFilterSelect + */ +JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterSelect + (JNIEnv *env, jclass, jlong port_pointer) +{ + int32_t status = 0; + void* digital_port_pointer = reinterpret_cast(port_pointer); + + jint result = getFilterSelect(digital_port_pointer, &status); + CheckStatus(env, status); + return result; +} + +/* + * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI + * Method: setFilterPeriod + */ +JNIEXPORT void JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_setFilterPeriod + (JNIEnv *env, jclass, jint filter_index, jint fpga_cycles) +{ + int32_t status = 0; + + setFilterPeriod(filter_index, fpga_cycles, &status); + CheckStatus(env, status); +} + +/* + * Class: edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI + * Method: getFilterPeriod + */ +JNIEXPORT jint JNICALL Java_edu_wpi_first_wpilibj_hal_DigitalGlitchFilterJNI_getFilterPeriod + (JNIEnv *env, jclass, jint filter_index) +{ + int32_t status = 0; + + jint result = getFilterPeriod(filter_index, &status); + CheckStatus(env, status); + return result; +} diff --git a/pool/shard006/C++/0083691_uncle.cpp b/pool/shard006/C++/0083691_uncle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e2517d85fe6376dcdfea01c48e7e4847b1658a9 --- /dev/null +++ b/pool/shard006/C++/0083691_uncle.cpp @@ -0,0 +1,417 @@ +/** + * @file uncle.cpp + * @brief Purpose: Contains uncle's methods. + * + * MIT License + * Copyright (c) 2017 MindScape + * + * https://github.com/TecProg2017-2/mindscape/blob/master/LICENSE.md + */ + +#include "uncle.hpp" +#include "platform.hpp" +#include "little_girl.hpp" +#include "log.hpp" +#include + +using namespace mindscape; + +/** + * @brief Initializes Uncle enemy. + * + * Constructor responsible to initialize Uncle in game. + * + * @param name Object's name. + * @param position X and Y axis positions. + * @param priority Rendering priority object. + */ + +Uncle::Uncle( + std::string name, + std::pair position, + int priority + ):Enemy( + name, + position, + priority, + 100 + ){ + /* Initialize all the characterists of the Uncle's boss. */ + initialize_state_map(); + initialize_hitboxes(); + initialize_animations(); + initialize_audio_effects(); +}; + +/** + * @brief Creates Uncle's animation. + * + * Creates an animation to Uncle enemy. + * + * @param path Path to the image which contains the sprite sheet. + * @param sprite_lines Number of the lines on the sprite sheet. + * @param sprite_colums Number of colums on the sprite sheet. + * @param duration Time duration of animation. + * @param direction Direction of animation. + * @return This method returns Uncle's animation. + */ + +engine::Animation* Uncle::create_animation( + std::string path, + int sprite_lines, + int sprite_columns, + double duration, + std::string direction) { + DEBUG("Creating animations."); + + engine::Game& game = engine::Game::get_instance(); /**< Game. + Gets an instance of a game just initializated. */ + + engine::Animation* animation = nullptr; /**< Animation. + Can represents all functions about uncle's animation. */ + + /* Initializes uncle's animation object. */ + animation = new engine::Animation( + game.get_renderer(), + path, + false, + std::make_pair(0, 0), + 1, + sprite_lines, + sprite_columns, + duration, + true, + direction + ); + + /* Sets values to init a initial position of animation on the screen.*/ + animation->set_values( + std::make_pair(320, 320), + std::make_pair(320, 320), + std::make_pair(0, 0) + ); + + DEBUG("Animations created."); + return animation; +} + +/** + * @brief Initialize Uncle's animations. + * + * Define Uncle's movement and attack animation. + * + * @return void. + */ + +void Uncle::initialize_animations() { + /* Starts debugger to accompany the method's development. */ + DEBUG("Initializing animations."); + + engine::Animation* idle_animation = nullptr; /**< Animation. + Animation that represents uncle's in a idle state.s */ + + /* Creates uncle's idle animation. */ + idle_animation = create_animation( + "../assets/images/sprites/enemies/uncle/uncle_idle.png", + 1, 4, 3.0, "LEFT" + ); + + /* Sets uncle's idle animation to define when its stopped. */ + idle_animation->set_values( + std::make_pair(665, 484), + std::make_pair(665, 484), + std::make_pair(0, 0) + ); + + add_animation("idle_animation",idle_animation); + + idle_animation->activate(); + set_actual_animation(idle_animation); + + engine::Animation* attacking_animation = nullptr; /**< Animation. + Animation that represents uncle's attacking. */ + + /* Creates uncle's attack animation. */ + attacking_animation = create_animation( + "../assets/images/sprites/enemies/uncle/uncle_attacking.png", + 1, 1, 3.0, "LEFT" + ); + + /* Sets uncle's attacking animation to define when its attacking. */ + attacking_animation->set_values( + std::make_pair(719, 523), + std::make_pair(719, 523), + std::make_pair(0, 0) + ); + + attacking_animation->in_loop = false; + + add_animation("attacking_animation",attacking_animation); + + /* Ends debugger that represents the end of the method. */ + DEBUG("Animations initializated."); +} + +/** + * @brief Initialize Uncle's hitboxes. + * + * Initializes Uncle instance hitboxes. + * + * @return void. + */ + +void Uncle::initialize_hitboxes() { + /* Starts debugger to accompany the method's development. */ + DEBUG("Initializing uncle's hitbox."); + + engine::Game& game = engine::Game::get_instance(); /**< Game. + Gets an instance of a game just initializated. */ + + engine::Hitbox* head_hitbox = nullptr; /**< Hitbox. + Initialize uncle's head hitbox. */ + + head_hitbox = new engine::Hitbox( + "head_hitbox", + this->get_position(), + std::make_pair(160, 380), + std::make_pair(180,20), + game.get_renderer() + ); + + /* Add hitbox component into the game object. */ + add_component(head_hitbox); + + /* Ends debugger that represents the end of the method. */ + DEBUG("Uncle's hitbox initialized"); +} + +/** + * @brief Initialize Uncle's state map. + * + * Initialize all possibles states for the Uncle. + * + * @return void. + */ + +void Uncle::initialize_state_map() { + /* Starts debugger to accompany the method's development. */ + DEBUG("Initializing uncle's state."); + states.set_state("ACTION_STATE","NORMAL"); + /* Ends debugger that represents the end of the method. */ + DEBUG("Uncle's state initialized."); +} + +/** + * @brief Initialize uncle's audio effects. + * + * Not implemented. + * + * @return void. + */ + +void Uncle::initialize_audio_effects() { +} + +/** + * @brief Register game events. + * + * Register an event to Uncle. + * + * @param game_event Triggering in-game events. + * @return void. + */ + +void Uncle::on_event(GameEvent game_event) { + std::string event_name = ""; /**< String. + Gets an event catched by the Uncle. */ + + /* Gets event related with the Uncle. */ + event_name = game_event.game_event_name; + + /* Check if the Uncle gets an event to move to the left direction. */ + if (event_name == "MOVE_LEFT" + && !engine::GameObject::on_limit_of_level) { + + /* The Uncle increments its actual position. */ + set_position_x(get_position_x() + 10); + } + /* Check if the Uncle gets an event to move to the right direction. */ + else if (event_name == "MOVE_RIGHT" + && !engine::GameObject::on_limit_of_level) { + + /* The Uncle decrements its actual position. */ + set_position_x(get_position_x() - 10); + } + else { + /* Event name is not found. */ + } +} + +/** + * @brief Notify if the object is in the range. + * + * Notify if there is an object in the Uncle's range. + * + * @param game_object The game object passed in notification, in this case, + * the girl. + * @return void. + */ + +void Uncle::notify(engine::Observable *game_object) { + LittleGirl* little_girl = nullptr; /**< LittleGirl. + Gets as observable that tells when little_girl is next. */ + + little_girl = dynamic_cast(game_object); + + /* Notify if little_girl exists, moving to her direction. */ + if (little_girl) { + /* The Uncle moves in direction of the girl. */ + attack(little_girl); + } + else { + /* The Uncle don't attack. */ + } +} + +/** + * @brief Event for the collision. + * + * Method called everytime when two game objects collides. + * + * @param other Other game object that collides. + * @param p_my_hitbox Hitbox that receives the collision. + * @param p_other_hitbox Hitbox that collided. + * @return void. + */ + +void Uncle::on_collision( + engine::GameObject* other, + engine::Hitbox* p_my_hitbox, + engine::Hitbox* p_other_hitbox) { + LittleGirl* little_girl = nullptr; /**< LittleGirl. + References to LittleGirl object. */ + little_girl = dynamic_cast(other); + + engine::Hitbox* my_hitbox = nullptr; /**< Hitbox. + References to Uncle's hitbox. */ + my_hitbox = dynamic_cast(p_my_hitbox); + + engine::Hitbox* other_hitbox = nullptr; /**< Hitbox. + References to girl's hitbox. */ + other_hitbox = dynamic_cast(p_other_hitbox); + + /* Check if the girl is attacking the Uncle. */ + if (little_girl + && little_girl->get_state("ACTION_STATE") == "ATTACKING" + && my_hitbox->get_name() == "head_hitbox" + && little_girl->get_actual_animation()->actual_column == 2 + && get_state("X_STATE") != little_girl->get_state("X_STATE")) { + + /* Check if the Uncle is under attack. */ + if(get_state("ACTION_STATE") == "ON_ATTACK") { + return; + } + else { + on_attack(other); + } + } + else { + /* The girl is not attacking the Uncle. */ + } +} + +/** + * @brief Define a basic attack. + * + * Method not implemented. + * + * @return void. + */ + +void Uncle::basic_attack(){ +} + +/** + * @brief Uncle's attack. + * + * This method define Uncle's state while is attacking, is on attack or + * while is dying. + * + * @param little_girl Object to be attacked. + * @return void. + */ + +void Uncle::attack(engine::GameObject* little_girl) { + DEBUG("The uncle is attacking."); + + std::string actual_action_state = ""; /**< String. + Gets the actual state of the uncle. */ + actual_action_state = get_state("ACTION_STATE"); + + if (actual_action_state == "DYING") { + INFO("The Uncle is dying."); + return; + } + else { + /* The Uncle stills alive. */ + } + + if (actual_action_state == "ON_ATTACK" + || actual_action_state == "ATTACKING") { + + if (get_actual_animation()->is_finished) { + states.set_state("ACTION_STATE","NORMAL"); + set_actual_animation(animations["idle_animation"]); + } + else { + return; + } + } + else { + /* The Uncle is in a idle state. */ + } +} + +/** + * @brief Define action when is on attack. + * + * Event called when Uncle is attacking. + * + * @param game_object Object to be attacked. + * @return void. + */ + +void Uncle::on_attack(engine::GameObject *game_object) { + states.set_state("ACTION_STATE","ON_ATTACK"); + + hit(game_object, 1); + if (is_alive()) { + set_actual_animation(animations["on_attack_animation"]); + //play_song("hit_me"); + } + else { + /* The Uncle is dead. */ + } +} + +/** + * @brief Death method. + * + * This method define an animation when Uncle is dead. + * + * @param game_object Uncle. + * @return void. + */ + +void Uncle::die(engine::GameObject *game_object) { + DEBUG("The uncle is dying."); + std::string actual_x_state = ""; /**< String. + Gets the actual state of the uncle. */ + actual_x_state = get_state("X_STATE"); + /* Sets a state that represents when uncle is dead. */ + states.set_state("ACTION_STATE", "DYING"); + /* Initiates the animation that show the uncle dying.*/ + set_actual_animation(animations["dying_animation"]); + //play_song("hit_me"); + DEBUG("The uncle died."); +} diff --git a/pool/shard006/C++/0083703_reportescuotas.cpp b/pool/shard006/C++/0083703_reportescuotas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a93e8a1eedb4ac395df4477a6b53149e1de6f275 --- /dev/null +++ b/pool/shard006/C++/0083703_reportescuotas.cpp @@ -0,0 +1,114 @@ +#include "reportescuotas.h" +#include "EReporte.h" +#include "mclientes.h" + +#include +#include +#include + + +/*! + * \brief ReportesCuotas::version + * \return + */ +double ReportesCuotas::version() const +{ return 0.1; } + +/*! + * \brief ReportesCuotas::nombre + * \return + */ +QString ReportesCuotas::nombre() const +{ return "ReportesCuotas"; } + +/*! + * \brief ReportesCuotas::inicializar + * \return + */ +bool ReportesCuotas::inicializar() +{ + ActResumenCuotasDeudaHistorica = new QAction( this ); + ActResumenCuotasDeudaHistorica->setText( "Deuda historica" ); + ActResumenCuotasDeudaHistorica->setStatusTip( "Muestra un resumen de los estados de todas las cuotas" ); + ActResumenCuotasDeudaHistorica->setIcon( QIcon( ":/imagenes/resumen_cuotas.png" ) ); + connect( ActResumenCuotasDeudaHistorica, SIGNAL( triggered() ), this, SLOT( resumenCuotasDeudaHistorica() ) ); + + ActResumenCuotasMes = new QAction( this ); + ActResumenCuotasMes->setText( "Deuda en mes" ); + ActResumenCuotasMes->setStatusTip( "Muestra el resumen de las cuotas del mes" ); + connect( ActResumenCuotasMes, SIGNAL( triggered() ), this, SLOT( resumenCuotasMes() ) ); + + ActResumenCuotasCliente = new QAction( this ); + ActResumenCuotasCliente->setText( "Deuda por cliente" ); + ActResumenCuotasCliente->setStatusTip( "Muestra las deudas de un cliente especifico" ); + connect( ActResumenCuotasCliente, SIGNAL( triggered() ), this, SLOT( resumenCuotasCliente() ) ); + + return true; +} + +/*! + * \brief ReportesCuotas::hacerMenu + * \param m + */ +void ReportesCuotas::hacerMenu( QMenu *m ) +{ + QMenu *menu = m->addMenu( "Cuotas" ); + menu->addAction( ActResumenCuotasDeudaHistorica ); + menu->addAction( ActResumenCuotasMes ); + menu->addAction( ActResumenCuotasCliente ); +} + +/*! + * \brief ReportesCuotas::resumenCuotasDeudaHistorica + */ +void ReportesCuotas::resumenCuotasDeudaHistorica() +{ + EReporte *rep = new EReporte( 0 ); + rep->especial( "CuotasHistoricas", ParameterList() ); + rep->hacerPDF( ParameterList(), QString( "Deudas Cuotas al %1" ).arg( QDate::currentDate().toString( "dd-MM-yyyy" ) ) ); + delete rep; +} + +/*! + * \brief ReportesCuotas::resumenCuotasMes + */ +void ReportesCuotas::resumenCuotasMes() +{ + QMessageBox::information( 0, "Error", "No implementado" ); + return; + bool ok = false; + QStringList meses; + meses << "Enero" << "Febrero" << "Marzo" << "Abril" << "Mayo" << "Junio" << "Julio" << "Agosto" << "Septiembre" << "Octubre" << "Noviembre" << "Diciembre"; + QString mes = QInputDialog::getItem( 0, "Elija el mes", "Elija el mes:", meses, QDate::currentDate().month(), false, &ok ); + if( ok ) { + EReporte *rep = new EReporte( 0 ); + ParameterList lista; + lista.append( Parameter( "mes", meses.indexOf( mes ) ) ); + rep->especial( "DeudaCuotasMes", lista ); + rep->hacerPDF( ParameterList(), QString( "Deudas Cuotas del mes %1-%2" ).arg( mes ).arg( QDate::currentDate().toString( "yyyy" ) ) ); + delete rep; + } +} + +/*! + * \brief ReportesCuotas::resumenCuotasCliente + * Muestra el resumen de cuotas de un cliente específico + */ +void ReportesCuotas::resumenCuotasCliente() +{ + QMessageBox::information( 0, "Error", "No implementado" ); + return; + /// @TODO: Implementar reporte de deuda segun cliente + EReporte *rep = new EReporte( 0 ); + int id_cliente = 1; + ParameterList lista; + lista.append( "id_cliente", id_cliente ); + rep->especial( "deudascuotascliente", lista ); + rep->hacerPDF( ParameterList(), + QString( "Deudas de Cuotas de %2 Al %1" ) + .arg( QDate::currentDate().toString( Qt::LocaleDate ) ) + .arg( MClientes::getRazonSocial( id_cliente ) ) ); + delete rep; +} + +Q_EXPORT_PLUGIN2( reportescuotas, ReportesCuotas ) diff --git a/pool/shard006/C++/0083704_Resource.cpp b/pool/shard006/C++/0083704_Resource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f38829f56ec8bb9ef1c1b24801742835879cc640 --- /dev/null +++ b/pool/shard006/C++/0083704_Resource.cpp @@ -0,0 +1,131 @@ +// +// Copyright (c) 2008-2016 the Urho3D project. +// +// 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 "../Precompiled.h" + +#include "../Core/Profiler.h" +#include "../IO/File.h" +#include "../IO/Log.h" +#include "../Resource/Resource.h" + +namespace Urho3D +{ + +Resource::Resource(Context* context) : + Object(context), + memoryUse_(0), + asyncLoadState_(ASYNC_DONE) +{ +} + +bool Resource::Load(Deserializer& source) +{ + // Because BeginLoad() / EndLoad() can be called from worker threads, where profiling would be a no-op, + // create a type name -based profile block here +#ifdef URHO3D_PROFILING + String profileBlockName("Load" + GetTypeName()); + + Profiler* profiler = GetSubsystem(); + if (profiler) + profiler->BeginBlock(profileBlockName.CString()); +#endif + + // If we are loading synchronously in a non-main thread, behave as if async loading (for example use + // GetTempResource() instead of GetResource() to load resource dependencies) + SetAsyncLoadState(Thread::IsMainThread() ? ASYNC_DONE : ASYNC_LOADING); + bool success = BeginLoad(source); + if (success) + success &= EndLoad(); + SetAsyncLoadState(ASYNC_DONE); + +#ifdef URHO3D_PROFILING + if (profiler) + profiler->EndBlock(); +#endif + + return success; +} + +bool Resource::BeginLoad(Deserializer& source) +{ + // This always needs to be overridden by subclasses + return false; +} + +bool Resource::EndLoad() +{ + // If no GPU upload step is necessary, no override is necessary + return true; +} + +bool Resource::Save(Serializer& dest) const +{ + URHO3D_LOGERROR("Save not supported for " + GetTypeName()); + return false; +} + +bool Resource::Load(const String& fileName) +{ + File file(context_); + return file.Open(fileName, FILE_READ) && Load(file); +} + +bool Resource::Save(const String& fileName) const +{ + File file(context_); + return file.Open(fileName, FILE_WRITE) && Save(file); +} + +void Resource::SetName(const String& name) +{ + name_ = name; + nameHash_ = name; +} + +void Resource::SetMemoryUse(unsigned size) +{ + memoryUse_ = size; +} + +void Resource::ResetUseTimer() +{ + useTimer_.Reset(); +} + +void Resource::SetAsyncLoadState(AsyncLoadState newState) +{ + asyncLoadState_ = newState; +} + +unsigned Resource::GetUseTimer() +{ + // If more references than the resource cache, return always 0 & reset the timer + if (Refs() > 1) + { + useTimer_.Reset(); + return 0; + } + else + return useTimer_.GetMSec(false); +} + +} diff --git a/pool/shard006/C++/0083713_CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp b/pool/shard006/C++/0083713_CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e601c54bc4fe6218d4915b0a9299df645f5555e4 --- /dev/null +++ b/pool/shard006/C++/0083713_CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp @@ -0,0 +1,119 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_console_w32_spawnvp_62a.cpp +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-62a.tmpl.cpp +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sinks: w32_spawnvp + * BadSink : execute command with spawnvp + * Flow Variant: 62 Data flow: data flows using a C++ reference from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "ls" +#define COMMAND_ARG2 "-la" +#define COMMAND_ARG3 data +#endif + +#include + +namespace CWE78_OS_Command_Injection__char_console_w32_spawnvp_62 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSource(char * &data); + +void bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + badSource(data); + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* spawnvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnvp(_P_WAIT, COMMAND_INT, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSource(char * &data); + +static void goodG2B() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + goodG2BSource(data); + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* spawnvp - searches for the location of the command among + * the directories specified by the PATH environment variable */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnvp(_P_WAIT, COMMAND_INT, args); + } +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE78_OS_Command_Injection__char_console_w32_spawnvp_62; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C++/0083722_InstanceFleetTimeline.cpp b/pool/shard006/C++/0083722_InstanceFleetTimeline.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1065062f614893c281bb2f19345d7a6c39ca6b0 --- /dev/null +++ b/pool/shard006/C++/0083722_InstanceFleetTimeline.cpp @@ -0,0 +1,96 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace EMR +{ +namespace Model +{ + +InstanceFleetTimeline::InstanceFleetTimeline() : + m_creationDateTimeHasBeenSet(false), + m_readyDateTimeHasBeenSet(false), + m_endDateTimeHasBeenSet(false) +{ +} + +InstanceFleetTimeline::InstanceFleetTimeline(JsonView jsonValue) : + m_creationDateTimeHasBeenSet(false), + m_readyDateTimeHasBeenSet(false), + m_endDateTimeHasBeenSet(false) +{ + *this = jsonValue; +} + +InstanceFleetTimeline& InstanceFleetTimeline::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("CreationDateTime")) + { + m_creationDateTime = jsonValue.GetDouble("CreationDateTime"); + + m_creationDateTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("ReadyDateTime")) + { + m_readyDateTime = jsonValue.GetDouble("ReadyDateTime"); + + m_readyDateTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("EndDateTime")) + { + m_endDateTime = jsonValue.GetDouble("EndDateTime"); + + m_endDateTimeHasBeenSet = true; + } + + return *this; +} + +JsonValue InstanceFleetTimeline::Jsonize() const +{ + JsonValue payload; + + if(m_creationDateTimeHasBeenSet) + { + payload.WithDouble("CreationDateTime", m_creationDateTime.SecondsWithMSPrecision()); + } + + if(m_readyDateTimeHasBeenSet) + { + payload.WithDouble("ReadyDateTime", m_readyDateTime.SecondsWithMSPrecision()); + } + + if(m_endDateTimeHasBeenSet) + { + payload.WithDouble("EndDateTime", m_endDateTime.SecondsWithMSPrecision()); + } + + return payload; +} + +} // namespace Model +} // namespace EMR +} // namespace Aws diff --git a/pool/shard006/C++/0083726_centered_continued_fraction.cpp b/pool/shard006/C++/0083726_centered_continued_fraction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6d357d2b913531339b6d2c137d858e86535e3c29 --- /dev/null +++ b/pool/shard006/C++/0083726_centered_continued_fraction.cpp @@ -0,0 +1,51 @@ +// (C) Copyright Nick Thompson 2020. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Deliberately contains some unicode characters: +// +// boost-no-inspect +// +#include +#include +#include +#include + +using boost::math::constants::root_two; +using boost::math::constants::phi; +using boost::math::constants::pi; +using boost::math::constants::e; +using boost::math::constants::zeta_three; +using boost::math::tools::centered_continued_fraction; +using boost::multiprecision::mpfr_float; + +int main() +{ + using Real = mpfr_float; + int p = 10000; + mpfr_float::default_precision(p); + auto phi_cfrac = centered_continued_fraction(phi()); + std::cout << "φ ≈ " << phi_cfrac << "\n"; + std::cout << "Khinchin mean: " << std::setprecision(10) << phi_cfrac.khinchin_geometric_mean() << "\n\n\n"; + + auto pi_cfrac = centered_continued_fraction(pi()); + std::cout << "π ≈ " << pi_cfrac << "\n"; + std::cout << "Khinchin mean: " << std::setprecision(10) << pi_cfrac.khinchin_geometric_mean() << "\n\n\n"; + + auto rt_cfrac = centered_continued_fraction(root_two()); + std::cout << "√2 ≈ " << rt_cfrac << "\n"; + std::cout << "Khinchin mean: " << std::setprecision(10) << rt_cfrac.khinchin_geometric_mean() << "\n\n\n"; + + auto e_cfrac = centered_continued_fraction(e()); + std::cout << "e ≈ " << e_cfrac << "\n"; + std::cout << "Khinchin mean: " << std::setprecision(10) << e_cfrac.khinchin_geometric_mean() << "\n\n\n"; + + auto z_cfrac = centered_continued_fraction(zeta_three()); + std::cout << "ζ(3) ≈ " << z_cfrac << "\n"; + std::cout << "Khinchin mean: " << std::setprecision(10) << z_cfrac.khinchin_geometric_mean() << "\n\n\n"; + + + // http://jeremiebourdon.free.fr/data/Khintchine.pdf + std::cout << "The expected Khinchin mean for a random centered continued fraction is 5.45451724454\n"; +} diff --git a/pool/shard006/C++/0083728_main.cpp b/pool/shard006/C++/0083728_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34bf5ed9048da7bc9ad243617eca33b26dd97711 --- /dev/null +++ b/pool/shard006/C++/0083728_main.cpp @@ -0,0 +1,81 @@ +/** + * @file main.cpp + * @brief Main file. + * @author Michal Policht + */ + +#include +#include +#include +#include +#include +#include "PortListener.h" + +class SerialThread: public QThread +{ + QextSerialPort * port; + + protected: + virtual void run() + { + QString inStr; + QTextStream in(stdin); + QTextStream out(stdout); + + out << "Special commands: open close bye" << endl << endl; + while(inStr.compare("bye") != 0) { + in >> inStr; + if (inStr.compare("close") == 0) { + out << "requesting close... " << endl; + port->close(); + } + else if (inStr.compare("open") == 0) { + out << "opening port... "; + out << port->open(QIODevice::ReadWrite); + out << endl; + } else if (inStr.compare("bye") != 0) + port->write(inStr.toAscii().constData(), inStr.length()); + } + port->close(); + } + + public: + SerialThread(QextSerialPort * port, QObject * parent = 0): + QThread(parent) + { + this->port = port; + } +}; + +int main(int argc, char *argv[]) +{ + QTextStream out(stdout); + QCoreApplication app(argc, argv); + + QextSerialPort * port = new QextSerialPort("COM1", QextSerialPort::EventDriven); + port->setBaudRate(BAUD56000); + port->setFlowControl(FLOW_OFF); + port->setParity(PAR_NONE); + port->setDataBits(DATA_8); + port->setStopBits(STOP_2); + port->open(QIODevice::ReadWrite); + if (!(port->lineStatus() & LS_DSR)) { + out << "warning: device is not turned on" << endl; + } + + PortListener * listener = new PortListener(port); + //Because port and listener are working in different threads + //Qt will choose queued connection. This may produce clusters of + //signals waiting in the queue. + listener->connect(port, SIGNAL(readyRead()), listener, SLOT(receive())); + listener->connect(port, SIGNAL(bytesWritten(qint64)), listener, SLOT(reportWritten(qint64))); + listener->connect(port, SIGNAL(aboutToClose()), listener, SLOT(reportClose())); + listener->connect(port, SIGNAL(dsrChanged(bool)), listener, SLOT(reportDsr(bool))); + + SerialThread * thread = new SerialThread(port); + app.connect(thread, SIGNAL(finished()), & app, SLOT(quit())); + thread->start(); + + //event loop is required to utilize signals and slots mechanism + return app.exec(); +} diff --git a/pool/shard006/C++/0083732_bonus.cpp b/pool/shard006/C++/0083732_bonus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26afbee7eb72f8bbd1d25594a8de629a73c16745 --- /dev/null +++ b/pool/shard006/C++/0083732_bonus.cpp @@ -0,0 +1,56 @@ +#include "bonus.h" + +/*! +* Instanciates a bonus depending its type +* @param type Type of bonus +*/ +Bonus::Bonus(int type) +{ + setRect(10, 10, 5, 5); + m_type = type; + for (int i = 0; i < 4; i++) { + m_attributes.append(0); + } + + switch(m_type) { + case BOMB_RANGE_UP: + if (qrand() % 2 == 1) { + setBrush(QColor::fromRgb (255, 150, 0)); + m_attributes.insert(BOMB_RANGE_UP, -1); + } else { + setBrush(Qt::red); + m_attributes.insert(BOMB_RANGE_UP, 1); + } + break; + case BOMB_CAPACITY_UP: + if (qrand() % 2 == 1) { + setBrush(Qt::cyan); + m_attributes.insert(BOMB_CAPACITY_UP, -1); + } else { + setBrush(Qt::blue); + m_attributes.insert(BOMB_CAPACITY_UP, 1); + } + break; + + case KICK_ACTIVATOR: + setBrush(Qt::darkMagenta); + m_attributes.insert(KICK_ACTIVATOR, 1); + break; + case LIFE_UP: + setBrush(Qt::green); + m_attributes.insert(LIFE_UP, 1); + break; + } +} + +Bonus::~Bonus() { +} + +int Bonus::type() { + return m_type; +} + +QList Bonus::attributes() { + return m_attributes; +} + diff --git a/pool/shard006/C++/0083736_CEGUIOgreResourceProvider.cpp b/pool/shard006/C++/0083736_CEGUIOgreResourceProvider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a401083745c26ed0071ab86f34ff68e14cc26b1 --- /dev/null +++ b/pool/shard006/C++/0083736_CEGUIOgreResourceProvider.cpp @@ -0,0 +1,115 @@ +/************************************************************************ + filename: CEGUIOgreResourceProvider.cpp + created: 8/7/2004 + author: James '_mental_' O'Sullivan + + purpose: Implements Ogre specific ResourceProvider +*************************************************************************/ +/*************************************************************************** + * Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team + * + * 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 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 "CEGUIOgreResourceProvider.h" +#include "CEGUIExceptions.h" + +#include + +// Start of CEGUI namespace section +namespace CEGUI +{ +//----------------------------------------------------------------------------// +OgreResourceProvider::OgreResourceProvider() +{ + // set deafult resource group for Ogre + d_defaultResourceGroup = + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str(); +} + +//----------------------------------------------------------------------------// +void OgreResourceProvider::loadRawDataContainer(const String& filename, + RawDataContainer& output, + const String& resourceGroup) +{ + String orpGroup; + if (resourceGroup.empty()) + orpGroup = d_defaultResourceGroup.empty() ? + Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME.c_str() : + d_defaultResourceGroup; + else + orpGroup = resourceGroup; + + Ogre::DataStreamPtr input = Ogre::ResourceGroupManager::getSingleton(). + openResource(filename.c_str(), orpGroup.c_str()); + + if (input.isNull()) + CEGUI_THROW(InvalidRequestException( + "OgreCEGUIResourceProvider::loadRawDataContainer: Unable to open " + "resource file '" + filename + "' in resource group '" + orpGroup + + "'.")); + + Ogre::String buf = input->getAsString(); + const size_t memBuffSize = buf.length(); + + unsigned char* mem = new unsigned char[memBuffSize]; + memcpy(mem, buf.c_str(), memBuffSize); + + output.setData(mem); + output.setSize(memBuffSize); +} + +//----------------------------------------------------------------------------// +void OgreResourceProvider::unloadRawDataContainer(RawDataContainer& data) +{ + if (data.getDataPtr()) + { + delete[] data.getDataPtr(); + data.setData(0); + data.setSize(0); + } +} + +//----------------------------------------------------------------------------// +size_t OgreResourceProvider::getResourceGroupFileNames( + std::vector& out_vec, const String& file_pattern, + const String& resource_group) +{ + // get list of files in the group that match the pattern. + Ogre::StringVectorPtr vp = + Ogre::ResourceGroupManager::getSingleton().findResourceNames( + (resource_group.empty() ? + d_defaultResourceGroup.c_str() : + resource_group.c_str()), + file_pattern.c_str()); + + size_t entries = 0; + Ogre::StringVector::iterator i = vp->begin(); + for (; i != vp->end(); ++i) + { + out_vec.push_back(*i); + ++entries; + } + + return entries; +} + +//----------------------------------------------------------------------------// + +} // End of CEGUI namespace section diff --git a/pool/shard006/C++/0083740_AssemblyContext.cpp b/pool/shard006/C++/0083740_AssemblyContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84b0232edd1f182c7cbdef232292355117fe8669 --- /dev/null +++ b/pool/shard006/C++/0083740_AssemblyContext.cpp @@ -0,0 +1,88 @@ +// Copyright (c) 2015-2016 The Khronos Group Inc. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and/or associated documentation files (the +// "Materials"), to deal in the Materials without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Materials, and to +// permit persons to whom the Materials are 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 Materials. +// +// MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS +// KHRONOS STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS +// SPECIFICATIONS AND HEADER INFORMATION ARE LOCATED AT +// https://www.khronos.org/registry/ +// +// THE MATERIALS ARE 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 +// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. + +#include "UnitSPIRV.h" + +#include +#include + +#include "source/instruction.h" + +using libspirv::AssemblyContext; +using spvtest::AutoText; +using spvtest::Concatenate; +using ::testing::Eq; + +namespace { + +struct EncodeStringCase { + std::string str; + std::vector initial_contents; +}; + +using EncodeStringTest = ::testing::TestWithParam; + +TEST_P(EncodeStringTest, Sample) { + AssemblyContext context(AutoText(""), nullptr); + spv_instruction_t inst; + inst.words = GetParam().initial_contents; + ASSERT_EQ(SPV_SUCCESS, + context.binaryEncodeString(GetParam().str.c_str(), &inst)); + // We already trust MakeVector + EXPECT_THAT(inst.words, + Eq(Concatenate({GetParam().initial_contents, + spvtest::MakeVector(GetParam().str)}))); +} + +// clang-format off +INSTANTIATE_TEST_CASE_P( + BinaryEncodeString, EncodeStringTest, + ::testing::ValuesIn(std::vector{ + // Use cases that exercise at least one to two words, + // and both empty and non-empty initial contents. + {"", {}}, + {"", {1,2,3}}, + {"a", {}}, + {"a", {4}}, + {"ab", {4}}, + {"abc", {}}, + {"abc", {18}}, + {"abcd", {}}, + {"abcd", {22}}, + {"abcde", {4}}, + {"abcdef", {}}, + {"abcdef", {99,42}}, + {"abcdefg", {}}, + {"abcdefg", {101}}, + {"abcdefgh", {}}, + {"abcdefgh", {102, 103, 104}}, + // A very long string, encoded after an initial word. + // SPIR-V limits strings to 65535 characters. + {std::string(65535, 'a'), {1}}, + }),); +// clang-format on + +} // anonymous namespace diff --git a/pool/shard006/C++/0083742_action_handler.cc b/pool/shard006/C++/0083742_action_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..70a90c495c88bf7a8848bee1274a1548175d6082 --- /dev/null +++ b/pool/shard006/C++/0083742_action_handler.cc @@ -0,0 +1,85 @@ +// Copyright (c) 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include +#include + +#include "base/bind.h" +#include "base/callback.h" +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/files/file_util.h" +#include "base/logging.h" +#include "base/memory/ref_counted.h" +#include "base/process/launch.h" +#include "base/process/process.h" +#include "base/task/post_task.h" +#include "base/task/thread_pool.h" +#include "base/threading/sequenced_task_runner_handle.h" +#include "base/time/time.h" +#include "chrome/updater/action_handler.h" +#include "components/update_client/update_client.h" + +namespace updater { + +class ActionHandler : public update_client::ActionHandler { + public: + ActionHandler() = default; + + private: + using Result = + std::tuple; + ~ActionHandler() override = default; + + // Overrides for update_client::ActionHandler. + void Handle(const base::FilePath& action, + const std::string& session_id, + Callback callback) override; + + // For Windows, the action is a path to an EXE file. + static Result RunCommand(const base::FilePath& exe_path); + + ActionHandler(const ActionHandler&) = delete; + ActionHandler& operator=(const ActionHandler&) = delete; +}; + +void ActionHandler::Handle(const base::FilePath& action, + const std::string&, + Callback callback) { + DCHECK(!action.empty()); + base::ThreadPool::PostTaskAndReplyWithResult( + FROM_HERE, + {base::MayBlock(), base::WithBaseSyncPrimitives(), + base::TaskPriority::BEST_EFFORT, + base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN}, + base::BindOnce(&ActionHandler::RunCommand, action), + base::BindOnce( + [](Callback callback, const Result& result) { + auto [succeeded, error_code, extra_code] = result; + base::SequencedTaskRunnerHandle::Get()->PostTask( + FROM_HERE, base::BindOnce(std::move(callback), succeeded, + error_code, extra_code)); + }, + std::move(callback))); +} + +ActionHandler::Result ActionHandler::RunCommand( + const base::FilePath& exe_path) { + base::CommandLine command_line(exe_path); + VLOG(1) << "run command: " << command_line.GetCommandLineString(); + base::LaunchOptions options; + options.start_hidden = true; + base::Process process = base::LaunchProcess(command_line, options); + int exit_code = 0; + const base::TimeDelta kMaxWaitTime = base::Seconds(600); + const bool succeeded = + process.WaitForExitWithTimeout(kMaxWaitTime, &exit_code); + return Result{succeeded, exit_code, 0}; +} + +scoped_refptr MakeActionHandler() { + return base::MakeRefCounted(); +} + +} // namespace updater diff --git a/pool/shard006/C++/0083750_KernelRidgeRegression.cpp b/pool/shard006/C++/0083750_KernelRidgeRegression.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfce188eefc48dd6d3fe2150fc9c92bcea096411 --- /dev/null +++ b/pool/shard006/C++/0083750_KernelRidgeRegression.cpp @@ -0,0 +1,79 @@ +/** + * @file + * @copyright This code is licensed under the 3-clause BSD license.\n + * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n + * See LICENSE.txt for details. + */ + +#include "KernelRidgeRegression.h" + +namespace Scine { +namespace Utils { +namespace MachineLearning { + +void KernelRidgeRegression::trainModel(const Eigen::MatrixXd& featureValues, const Eigen::MatrixXd& targetValues) { + if (targetValues.rows() != featureValues.rows()) + throw std::runtime_error("The number of data points do not match between the feature and target matrices."); + + // Transpose the feature and target matrices since they are column-major. + targetValues_ = targetValues.transpose(); + featureValues_ = featureValues.transpose(); + numDataPoints_ = static_cast(targetValues_.cols()); + + // Construct the kernel matrix + Eigen::MatrixXd kernelMatrix(numDataPoints_, numDataPoints_); +#pragma omp parallel for schedule(dynamic) + for (int i = 0; i < numDataPoints_; ++i) { + for (int j = i; j < numDataPoints_; ++j) { + double value = kernel_(featureValues_.col(i), featureValues_.col(j), hyperparameters_); + kernelMatrix(i, j) = value; + } + } + + kernelMatrix = kernelMatrix.selfadjointView(); + + // Inversion of the regularized kernel matrix + Eigen::MatrixXd identity = Eigen::MatrixXd::Identity(kernelMatrix.rows(), kernelMatrix.cols()); + Eigen::MatrixXd regularizedKernelMatrix = kernelMatrix + regularizationFactor_ * identity; + invertedRegularizedKernelMatrix_ = regularizedKernelMatrix.inverse(); +} + +Eigen::VectorXd KernelRidgeRegression::predict(const Eigen::VectorXd& data) const { + if (invertedRegularizedKernelMatrix_.size() == 0) + throw std::runtime_error("The model has not been trained yet!"); + + // Calculate kernel vector + Eigen::VectorXd kernelVector(numDataPoints_); +#pragma omp parallel for schedule(dynamic) + for (int i = 0; i < numDataPoints_; ++i) { + kernelVector(i) = kernel_(featureValues_.col(i), data, hyperparameters_); + } + + // Calculate and return prediction + Eigen::MatrixXd kernelProduct = invertedRegularizedKernelMatrix_ * kernelVector; + Eigen::VectorXd prediction = targetValues_ * kernelProduct; + + for (int k = 0; k < prediction.size(); ++k) { + if (std::isnan(prediction(k))) + throw std::runtime_error( + "One of the predicted results could not be obtained. The reason is probably that the regularization factor " + "is too small and therefore causes problems during the inversion of the kernel matrix."); + } + + return prediction; +} + +void KernelRidgeRegression::setRegularizationFactor(double factor) { + regularizationFactor_ = factor; +} + +void KernelRidgeRegression::setKernel( + std::function&)> kernel, + std::vector hyperparameters) { + kernel_ = std::move(kernel); + hyperparameters_ = hyperparameters; +} + +} // namespace MachineLearning +} // namespace Utils +} // namespace Scine diff --git a/pool/shard006/C++/0083752_boss_ambassador_hellmaw.cpp b/pool/shard006/C++/0083752_boss_ambassador_hellmaw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fec5074c1e7bc592d3ec838cc9e0cafd3188b621 --- /dev/null +++ b/pool/shard006/C++/0083752_boss_ambassador_hellmaw.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2008-2019 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +/* ScriptData +SDName: Boss_Ambassador_Hellmaw +SD%Complete: 80 +SDComment: Enrage spell missing/not known +SDCategory: Auchindoun, Shadow Labyrinth +EndScriptData */ + +#include "ScriptMgr.h" +#include "InstanceScript.h" +#include "ScriptedEscortAI.h" +#include "shadow_labyrinth.h" + +enum Yells +{ + SAY_INTRO = 0, + SAY_AGGRO = 1, + SAY_HELP = 2, + SAY_SLAY = 3, + SAY_DEATH = 4 +}; + +enum Spells +{ + SPELL_BANISH = 30231, + SPELL_CORROSIVE_ACID = 33551, + SPELL_FEAR = 33547, + SPELL_ENRAGE = 34970 +}; + +enum Events +{ + EVENT_CORROSIVE_ACID = 1, + EVENT_FEAR, + EVENT_BERSERK +}; + +class boss_ambassador_hellmaw : public CreatureScript +{ + public: + boss_ambassador_hellmaw() : CreatureScript("boss_ambassador_hellmaw") { } + + struct boss_ambassador_hellmawAI : public npc_escortAI + { + boss_ambassador_hellmawAI(Creature* creature) : npc_escortAI(creature) + { + _instance = creature->GetInstanceScript(); + _intro = false; + } + + void Reset() override + { + if (!me->IsAlive()) + return; + + _events.Reset(); + _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, NOT_STARTED); + + _events.ScheduleEvent(EVENT_CORROSIVE_ACID, urand(5000, 10000)); + _events.ScheduleEvent(EVENT_FEAR, urand(25000, 30000)); + if (IsHeroic()) + _events.ScheduleEvent(EVENT_BERSERK, 180000); + + DoAction(ACTION_AMBASSADOR_HELLMAW_BANISH); + } + + void MoveInLineOfSight(Unit* who) override + { + if (me->HasAura(SPELL_BANISH)) + return; + + npc_escortAI::MoveInLineOfSight(who); + } + + void WaypointReached(uint32 /*waypointId*/) override + { + } + + void DoAction(int32 actionId) override + { + if (actionId == ACTION_AMBASSADOR_HELLMAW_INTRO) + DoIntro(); + else if (actionId == ACTION_AMBASSADOR_HELLMAW_BANISH) + { + if (_instance->GetData(DATA_FEL_OVERSEER) && me->HasAura(SPELL_BANISH)) + DoCast(me, SPELL_BANISH, true); // this will not work, because he is immune to banish + } + } + + void DoIntro() + { + if (_intro) + return; + + _intro = true; + + if (me->HasAura(SPELL_BANISH)) + me->RemoveAurasDueToSpell(SPELL_BANISH); + + Talk(SAY_INTRO); + Start(true, false, ObjectGuid::Empty, NULL, false, true); + } + + void EnterCombat(Unit* /*who*/) override + { + _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, IN_PROGRESS); + Talk(SAY_AGGRO); + } + + void KilledUnit(Unit* who) override + { + if (who->GetTypeId() == TYPEID_PLAYER) + Talk(SAY_SLAY); + } + + void JustDied(Unit* /*killer*/) override + { + _instance->SetBossState(DATA_AMBASSADOR_HELLMAW, DONE); + Talk(SAY_DEATH); + } + + void UpdateEscortAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + if (me->HasAura(SPELL_BANISH)) + { + EnterEvadeMode(EVADE_REASON_OTHER); + return; + } + + _events.Update(diff); + + if (me->HasUnitState(UNIT_STATE_CASTING)) + return; + + while (uint32 eventId = _events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_CORROSIVE_ACID: + DoCastVictim(SPELL_CORROSIVE_ACID); + _events.ScheduleEvent(EVENT_CORROSIVE_ACID, urand(15000, 25000)); + break; + case EVENT_FEAR: + DoCastAOE(SPELL_FEAR); + _events.ScheduleEvent(EVENT_FEAR, urand(20000, 35000)); + break; + case EVENT_BERSERK: + DoCast(me, SPELL_ENRAGE, true); + break; + default: + break; + } + } + + DoMeleeAttackIfReady(); + } + + private: + InstanceScript* _instance; + EventMap _events; + bool _intro; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetShadowLabyrinthAI(creature); + } +}; + +void AddSC_boss_ambassador_hellmaw() +{ + new boss_ambassador_hellmaw(); +} diff --git a/pool/shard006/C++/0083759_PersistentParserState.cpp b/pool/shard006/C++/0083759_PersistentParserState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4834a433d11c5d3431cc99bb2466c75466b1375 --- /dev/null +++ b/pool/shard006/C++/0083759_PersistentParserState.cpp @@ -0,0 +1,88 @@ +//===--- PersistentParserState.cpp - Parser State Implementation ----------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file implements parser state persistent across multiple parses. +// +//===----------------------------------------------------------------------===// + +#include "swift/AST/Decl.h" +#include "swift/AST/Expr.h" +#include "swift/Parse/PersistentParserState.h" + +using namespace swift; + +void PersistentParserState::delayFunctionBodyParsing(AbstractFunctionDecl *AFD, + SourceRange BodyRange, + SourceLoc PreviousLoc) { + std::unique_ptr State; + State.reset(new FunctionBodyState(BodyRange, PreviousLoc, + ScopeInfo.saveCurrentScope())); + assert(DelayedFunctionBodies.find(AFD) == DelayedFunctionBodies.end() && + "Already recorded state for this body"); + DelayedFunctionBodies[AFD] = std::move(State); +} + +std::unique_ptr +PersistentParserState::takeFunctionBodyState(AbstractFunctionDecl *AFD) { + assert(AFD->getBodyKind() == AbstractFunctionDecl::BodyKind::Unparsed); + DelayedFunctionBodiesTy::iterator I = DelayedFunctionBodies.find(AFD); + assert(I != DelayedFunctionBodies.end() && "State should be saved"); + std::unique_ptr State = std::move(I->second); + DelayedFunctionBodies.erase(I); + return State; +} + +bool PersistentParserState::hasFunctionBodyState(AbstractFunctionDecl *AFD) { + return DelayedFunctionBodies.find(AFD) != DelayedFunctionBodies.end(); +} + +void PersistentParserState::delayAccessorBodyParsing(AbstractFunctionDecl *AFD, + SourceRange BodyRange, + SourceLoc PreviousLoc, + SourceLoc LBLoc) { + std::unique_ptr State; + State.reset(new AccessorBodyState(BodyRange, PreviousLoc, + ScopeInfo.saveCurrentScope(), LBLoc)); + assert(DelayedAccessorBodies.find(AFD) == DelayedAccessorBodies.end() && + "Already recorded state for this body"); + DelayedAccessorBodies[AFD] = std::move(State); +} + +std::unique_ptr +PersistentParserState::takeAccessorBodyState(AbstractFunctionDecl *AFD) { + assert(AFD->getBodyKind() == AbstractFunctionDecl::BodyKind::Unparsed); + DelayedAccessorBodiesTy::iterator I = DelayedAccessorBodies.find(AFD); + assert(I != DelayedAccessorBodies.end() && "State should be saved"); + std::unique_ptr State = std::move(I->second); + DelayedAccessorBodies.erase(I); + return State; +} + +void PersistentParserState::delayDecl(DelayedDeclKind Kind, + unsigned Flags, + DeclContext *ParentContext, + SourceRange BodyRange, + SourceLoc PreviousLoc) { + assert(!CodeCompletionDelayedDeclState.get() && + "only one decl can be delayed for code completion"); + CodeCompletionDelayedDeclState.reset(new DelayedDeclState( + Kind, Flags, ParentContext, BodyRange, PreviousLoc, + ScopeInfo.saveCurrentScope())); +} + +void PersistentParserState::delayTopLevel(TopLevelCodeDecl *TLCD, + SourceRange BodyRange, + SourceLoc PreviousLoc) { + delayDecl(DelayedDeclKind::TopLevelCodeDecl, 0U, TLCD, BodyRange, + PreviousLoc); +} + diff --git a/pool/shard006/C++/0083769_mysql_remap.cc b/pool/shard006/C++/0083769_mysql_remap.cc new file mode 100644 index 0000000000000000000000000000000000000000..d43637003c3edbb11d6d1427a032c679d1925d70 --- /dev/null +++ b/pool/shard006/C++/0083769_mysql_remap.cc @@ -0,0 +1,251 @@ +/* + Licensed to the Apache Software Foundation (ASF) under one + or more contributor license agreements. See the NOTICE file + distributed with this work for additional information + regarding copyright ownership. The ASF licenses this file + to you under the Apache License, Version 2.0 (the + "License"); you may not use this file except in compliance + with the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +#include +#include +#include +#include + +#include + +#include "lib/iniparser.h" +#include "default.h" + +MYSQL mysql; + +typedef struct { + char *query; +} my_data; + +bool +do_mysql_remap(TSCont contp, TSHttpTxn txnp) +{ + TSMBuffer reqp; + TSMLoc hdr_loc, url_loc, field_loc; + bool ret_val = false; + + const char *request_host; + int request_host_length = 0; + const char *request_scheme; + int request_scheme_length = 0; + int request_port = 80; + char *query; + + MYSQL_ROW row; + MYSQL_RES *res; + + my_data *data = static_cast(TSContDataGet(contp)); + query = data->query; + + if (TSHttpTxnClientReqGet(txnp, &reqp, &hdr_loc) != TS_SUCCESS) { + TSDebug(PLUGIN_NAME, "could not get request data"); + return false; + } + + TSHttpHdrUrlGet(reqp, hdr_loc, &url_loc); + + if (!url_loc) { + TSDebug(PLUGIN_NAME, "couldn't retrieve request url"); + goto release_hdr; + } + + field_loc = TSMimeHdrFieldFind(reqp, hdr_loc, TS_MIME_FIELD_HOST, TS_MIME_LEN_HOST); + + if (!field_loc) { + TSDebug(PLUGIN_NAME, "couldn't retrieve request HOST header"); + goto release_url; + } + + request_host = TSMimeHdrFieldValueStringGet(reqp, hdr_loc, field_loc, -1, &request_host_length); + if (!request_host_length) { + TSDebug(PLUGIN_NAME, "couldn't find request HOST header"); + goto release_field; + } + + request_scheme = TSUrlSchemeGet(reqp, url_loc, &request_scheme_length); + request_port = TSUrlPortGet(reqp, url_loc); + + TSDebug(PLUGIN_NAME, " +++++MYSQL REMAP+++++ "); + + TSDebug(PLUGIN_NAME, "\nINCOMING REQUEST ->\n ::: from_scheme_desc: %.*s\n ::: from_hostname: %.*s\n ::: from_port: %d", + request_scheme_length, request_scheme, request_host_length, request_host, request_port); + + snprintf(query, QSIZE, " \ + SELECT \ + t_scheme.scheme_desc, \ + t_host.hostname, \ + to_port \ + FROM map \ + INNER JOIN scheme as t_scheme ON (map.to_scheme_id = t_scheme.id) \ + INNER JOIN scheme as f_scheme ON (map.from_scheme_id = f_scheme.id) \ + INNER JOIN hostname as t_host ON (map.to_hostname_id = t_host.id) \ + INNER JOIN hostname as f_host ON (map.from_hostname_id = f_host.id) \ + WHERE \ + is_enabled=1 \ + AND f_host.hostname = '%.*s' \ + AND f_scheme.id = %d \ + AND from_port = %d \ + LIMIT 1", + request_host_length, request_host, (strcmp(request_scheme, "https") == 0) ? 2 : 1, request_port); + + mysql_real_query(&mysql, query, (unsigned int)strlen(query)); + res = mysql_use_result(&mysql); + + if (!res) + goto not_found; // TODO: define a fallback + + do { + row = mysql_fetch_row(res); + if (!row) + goto not_found; + TSDebug(PLUGIN_NAME, "\nOUTGOING REQUEST ->\n ::: to_scheme_desc: %s\n ::: to_hostname: %s\n ::: to_port: %s", row[0], row[1], + row[2]); + TSMimeHdrFieldValueStringSet(reqp, hdr_loc, field_loc, 0, row[1], -1); + TSUrlHostSet(reqp, url_loc, row[1], -1); + TSUrlSchemeSet(reqp, url_loc, row[0], -1); + TSUrlPortSet(reqp, url_loc, atoi(row[2])); + } while (false); + + ret_val = true; + +not_found: + if (!ret_val) { + // lets build up a nice 404 message for someone + TSHttpHdrStatusSet(reqp, hdr_loc, TS_HTTP_STATUS_NOT_FOUND); + TSHttpTxnStatusSet(txnp, TS_HTTP_STATUS_NOT_FOUND); + } + if (res) + mysql_free_result(res); +#if (TS_VERSION_NUMBER < 2001005) + if (request_host) + TSHandleStringRelease(reqp, hdr_loc, request_host); + if (request_scheme) + TSHandleStringRelease(reqp, hdr_loc, request_scheme); +#endif +release_field: + if (field_loc) { + TSHandleMLocRelease(reqp, hdr_loc, field_loc); + } +release_url: + if (url_loc) { + TSHandleMLocRelease(reqp, hdr_loc, url_loc); + } +release_hdr: + if (hdr_loc) { + TSHandleMLocRelease(reqp, TS_NULL_MLOC, hdr_loc); + } + + return ret_val; +} + +static int +mysql_remap(TSCont contp, TSEvent event, void *edata) +{ + TSHttpTxn txnp = static_cast(edata); + TSEvent reenable = TS_EVENT_HTTP_CONTINUE; + + switch (event) { + case TS_EVENT_HTTP_READ_REQUEST_HDR: + TSDebug(PLUGIN_NAME, "Reading Request"); + TSSkipRemappingSet(txnp, 1); + if (!do_mysql_remap(contp, txnp)) { + reenable = TS_EVENT_HTTP_ERROR; + } + break; + default: + break; + } + + TSHttpTxnReenable(txnp, reenable); + return 1; +} + +void +TSPluginInit(int argc, const char *argv[]) +{ + dictionary *ini; + const char *host; + int port; + const char *username; + const char *password; + const char *db; + + my_data *data = static_cast(malloc(1 * sizeof(my_data))); + + TSPluginRegistrationInfo info; + bool reconnect = true; + + info.plugin_name = const_cast(PLUGIN_NAME); + info.vendor_name = const_cast("Apache Software Foundation"); + info.support_email = const_cast("dev@trafficserver.apache.org"); + + if (TSPluginRegister(&info) != TS_SUCCESS) { + TSError("[mysql_remap] Plugin registration failed"); + } + + if (argc != 2) { + TSError("[mysql_remap] Usage: %s /path/to/sample.ini", argv[0]); + return; + } + + ini = iniparser_load(argv[1]); + if (!ini) { + TSError("[mysql_remap] Error with ini file (1)"); + TSDebug(PLUGIN_NAME, "Error parsing ini file(1)"); + return; + } + + host = iniparser_getstring(ini, "mysql_remap:mysql_host", (char *)"localhost"); + port = iniparser_getint(ini, "mysql_remap:mysql_port", 3306); + username = iniparser_getstring(ini, "mysql_remap:mysql_username", nullptr); + password = iniparser_getstring(ini, "mysql_remap:mysql_password", nullptr); + db = iniparser_getstring(ini, "mysql_remap:mysql_database", (char *)"mysql_remap"); + + if (mysql_library_init(0, NULL, NULL)) { + TSError("[mysql_remap] Error initializing mysql client library"); + TSDebug(PLUGIN_NAME, "Error initializing mysql client library"); + return; + } + + if (!mysql_init(&mysql)) { + TSError("[mysql_remap] Could not initialize MySQL"); + TSDebug(PLUGIN_NAME, "Could not initialize MySQL"); + return; + } + + mysql_options(&mysql, MYSQL_OPT_RECONNECT, &reconnect); + + if (!mysql_real_connect(&mysql, host, username, password, db, port, NULL, 0)) { + TSError("[mysql_remap] Could not connect to mysql"); + TSDebug(PLUGIN_NAME, "Could not connect to mysql: %s", mysql_error(&mysql)); + return; + } + + data->query = static_cast(TSmalloc(QSIZE * sizeof(char))); // TODO: malloc smarter sizes + + TSDebug(PLUGIN_NAME, "h: %s; u: %s; p: %s; p:%d; d:%s", host, username, password, port, db); + TSCont cont = TSContCreate(mysql_remap, TSMutexCreate()); + + TSHttpHookAdd(TS_HTTP_READ_REQUEST_HDR_HOOK, cont); + + TSContDataSet(cont, (void *)data); + + TSDebug(PLUGIN_NAME, "plugin is successfully initialized [plugin mode]"); + iniparser_freedict(ini); + return; +} diff --git a/pool/shard006/C++/0083771_DumpMassCharge.cpp b/pool/shard006/C++/0083771_DumpMassCharge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0aee8ba940aa5e67b4a1cee30e056da056a8bbfa --- /dev/null +++ b/pool/shard006/C++/0083771_DumpMassCharge.cpp @@ -0,0 +1,203 @@ +/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + Copyright (c) 2015-2020 The plumed team + (see the PEOPLE file at the root of the distribution for a list of names) + + See http://www.plumed.org for more information. + + This file is part of plumed, version 2. + + plumed is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + plumed 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 Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with plumed. If not, see . ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ +#include "core/ActionAtomistic.h" +#include "core/ActionPilot.h" +#include "core/ActionRegister.h" +#include "tools/File.h" +#include "core/PlumedMain.h" +#include "core/Atoms.h" + +using namespace std; + +namespace PLMD +{ +namespace generic { + +//+PLUMEDOC PRINTANALYSIS DUMPMASSCHARGE +/* +Dump masses and charges on a selected file. + +This command dumps a file containing charges and masses. +It does so only once in the simulation (at first step). +File can be recycled in the \ref driver tool. + +Notice that masses and charges are only written once at the beginning +of the simulation. In case no atom list is provided, charges and +masses for all atoms are written. + +\par Examples + +You can add the DUMPMASSCHARGE action at the end of the plumed.dat +file that you use during an MD simulations: + +\plumedfile +c1: COM ATOMS=1-10 +c2: COM ATOMS=11-20 +DUMPATOMS ATOMS=c1,c2 FILE=coms.xyz STRIDE=100 + +DUMPMASSCHARGE FILE=mcfile +\endplumedfile + +In this way, you will be able to use the same masses while processing +a trajectory from the \ref driver . To do so, you need to +add the --mc flag on the driver command line, e.g. +\verbatim +plumed driver --mc mcfile --plumed plumed.dat --ixyz traj.xyz +\endverbatim + +With the following input you can dump only the charges for a specific +group. +\plumedfile +solute_ions: GROUP ATOMS=1-121,200-2012 +DUMPATOMS FILE=traj.gro ATOMS=solute_ions STRIDE=100 +DUMPMASSCHARGE FILE=mcfile ATOMS=solute_ions +\endplumedfile +Notice however that if you want to process the charges +with the driver (e.g. reading traj.gro) you have to fix atom +numbers first, e.g. with the script +\verbatim +awk 'BEGIN{c=0}{ + if(match($0,"#")) print ; else {print c,$2,$3; c++} +}' < mc > newmc +}' +\endverbatim +then +\verbatim +plumed driver --mc newmc --plumed plumed.dat --ixyz traj.gro +\endverbatim + + +*/ +//+ENDPLUMEDOC + +class DumpMassCharge: + public ActionAtomistic, + public ActionPilot +{ + string file; + bool first; + bool second; + bool print_masses; + bool print_charges; +public: + explicit DumpMassCharge(const ActionOptions&); + ~DumpMassCharge(); + static void registerKeywords( Keywords& keys ); + void prepare() override; + void calculate() override {} + void apply() override {} + void update() override; +}; + +PLUMED_REGISTER_ACTION(DumpMassCharge,"DUMPMASSCHARGE") + +void DumpMassCharge::registerKeywords( Keywords& keys ) { + Action::registerKeywords( keys ); + ActionPilot::registerKeywords( keys ); + ActionAtomistic::registerKeywords( keys ); + keys.add("compulsory","STRIDE","1","the frequency with which the atoms should be output"); + keys.add("atoms", "ATOMS", "the atom indices whose charges and masses you would like to print out"); + keys.add("compulsory", "FILE", "file on which to output charges and masses."); + keys.addFlag("ONLY_MASSES",false,"Only output masses to file"); + keys.addFlag("ONLY_CHARGES",false,"Only output charges to file"); +} + +DumpMassCharge::DumpMassCharge(const ActionOptions&ao): + Action(ao), + ActionAtomistic(ao), + ActionPilot(ao), + first(true), + second(true), + print_masses(true), + print_charges(true) +{ + vector atoms; + parse("FILE",file); + if(file.length()==0) error("name of output file was not specified"); + log.printf(" output written to file %s\n",file.c_str()); + + parseAtomList("ATOMS",atoms); + + if(atoms.size()==0) { + for(int i=0; i()); + second=false; + } +} + +void DumpMassCharge::update() { + if(!first) return; + first=false; + + OFile of; + of.link(*this); + of.open(file); + + for(unsigned i=0; itype() == ui::wm::WINDOW_TYPE_POPUP) + return true; + + Widget* widget = Widget::GetWidgetForNativeView(window); + return widget && widget->is_top_level(); +} + +} // namespace + +DesktopScreenPositionClient::DesktopScreenPositionClient( + aura::Window* root_window) + : wm::DefaultScreenPositionClient(), root_window_(root_window) { + aura::client::SetScreenPositionClient(root_window_, this); +} + +DesktopScreenPositionClient::~DesktopScreenPositionClient() { + aura::client::SetScreenPositionClient(root_window_, NULL); +} + +void DesktopScreenPositionClient::SetBounds(aura::Window* window, + const gfx::Rect& bounds, + const gfx::Display& display) { + // TODO(jam): Use the 3rd parameter, |display|. + aura::Window* root = window->GetRootWindow(); + + // This method assumes that |window| does not have an associated + // DesktopNativeWidgetAura. + internal::NativeWidgetPrivate* desktop_native_widget = + DesktopNativeWidgetAura::ForWindow(root); + DCHECK(!desktop_native_widget || + desktop_native_widget->GetNativeView() != window); + + if (PositionWindowInScreenCoordinates(window)) { + // The caller expects windows we consider "embedded" to be placed in the + // screen coordinate system. So we need to offset the root window's + // position (which is in screen coordinates) from these bounds. + + gfx::Point origin = bounds.origin(); + aura::Window::ConvertPointToTarget(window->parent(), root, &origin); + + gfx::Point host_origin = GetOriginInScreen(root); + origin.Offset(-host_origin.x(), -host_origin.y()); + window->SetBounds(gfx::Rect(origin, bounds.size())); + return; + } + + window->SetBounds(bounds); +} + +} // namespace views diff --git a/pool/shard006/C++/0083780_a.cc b/pool/shard006/C++/0083780_a.cc new file mode 100644 index 0000000000000000000000000000000000000000..b7e04da4d2e61100e7aa5587f795fb48242c50bc --- /dev/null +++ b/pool/shard006/C++/0083780_a.cc @@ -0,0 +1,67 @@ +#include +#include + +using namespace std; + +class MyClass { + +private: + string name; + +public: + MyClass (string s) :name(s) {} + ~MyClass() { + cout << "Destroying " << name << endl; + } +}; + +void fa(); +void fb(); +void fc(); +void fd(); + +int main() { + + try { + + MyClass mainObj("M"); + fa(); + cout << "Mission accomplished!\n"; + + } catch (const char *e) { + + cout << "exception: " << e << endl; + cout << "Mission impossible!\n"; + } + + return 0; +} + +void fa() { + MyClass a("A"); + fb(); + cout << "return from fa()\n"; + return; +} + +void fb() { + MyClass b("B"); + fc(); + cout << "return from fb()\n"; + return; +} + +void fc() { + MyClass c("C"); + fd(); + cout << "return from fc()\n"; + return; +} + +void fd() { + MyClass d("D"); + throw "in fd(), something weird happened."; + cout << "return from fd()\n"; + return; +} + diff --git a/pool/shard006/C++/0083783_AudioManager.cpp b/pool/shard006/C++/0083783_AudioManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2fbfa5c9ee39c23c52fb4c9eb94c1c8d67b24e71 --- /dev/null +++ b/pool/shard006/C++/0083783_AudioManager.cpp @@ -0,0 +1,54 @@ +#include "AudioManager.h" + +AudioManager& AudioManager::getInstance() +{ + static AudioManager s; + return s; +} + +void AudioManager::playBackgroundAudio() +{ + if (_playing == true) + stopBackgroundAudio(); //only one sound thread can be played at the same time + background_audioID = AudioEngine::play2d(BACKGROUND_SOUND, true, 1.0f); + _playing = true; +} + +void AudioManager::stopBackgroundAudio() +{ + AudioEngine::stop(background_audioID); + _playing = false; +} + +void AudioManager::pauseBackgroundAudio() +{ + AudioEngine::pause(background_audioID); + _playing = false; +} + +void AudioManager::resumeBackgroundAudio() +{ + AudioEngine::resume(background_audioID); + _playing = true; +} + +void AudioManager::setBackgroundAudioVolume(float value) +{ + AudioEngine::setVolume(background_audioID, value); +} + +float AudioManager::getBackgroundAudioVolume() +{ + return AudioEngine::getVolume(background_audioID); +} + +void AudioManager::endAudio() +{ + _playing = false; + AudioEngine::end(); +} + +bool AudioManager::isBackgroundMusicPlaying() +{ + return _playing; +} diff --git a/pool/shard006/C++/0083789_GrGLShaderStringBuilder.cpp b/pool/shard006/C++/0083789_GrGLShaderStringBuilder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2e49a5cfb0b5716b988aa4d3aaec1d4a5451050 --- /dev/null +++ b/pool/shard006/C++/0083789_GrGLShaderStringBuilder.cpp @@ -0,0 +1,105 @@ +/* + * Copyright 2014 Google Inc. + * + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +#include "GrGLShaderStringBuilder.h" +#include "gl/GrGLGpu.h" +#include "gl/GrGLSLPrettyPrint.h" +#include "SkTraceEvent.h" + +#define GL_CALL(X) GR_GL_CALL(gpu->glInterface(), X) +#define GL_CALL_RET(R, X) GR_GL_CALL_RET(gpu->glInterface(), R, X) + +// Print the source code for all shaders generated. +static const bool c_PrintShaders{false}; + +static void print_shader_source(const char** strings, int* lengths, int count); + +GrGLuint GrGLCompileAndAttachShader(const GrGLContext& glCtx, + GrGLuint programId, + GrGLenum type, + const char** strings, + int* lengths, + int count, + GrGpu::Stats* stats) { + const GrGLInterface* gli = glCtx.interface(); + + GrGLuint shaderId; + GR_GL_CALL_RET(gli, shaderId, CreateShader(type)); + if (0 == shaderId) { + return 0; + } + +#ifdef SK_DEBUG + SkString prettySource = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, false); + const GrGLchar* sourceStr = prettySource.c_str(); + GrGLint sourceLength = static_cast(prettySource.size()); + GR_GL_CALL(gli, ShaderSource(shaderId, 1, &sourceStr, &sourceLength)); +#else + GR_GL_CALL(gli, ShaderSource(shaderId, count, strings, lengths)); +#endif + + // If tracing is enabled in chrome then we pretty print + bool traceShader; + TRACE_EVENT_CATEGORY_GROUP_ENABLED(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), &traceShader); + if (traceShader) { + SkString shader = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, false); + TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("skia.gpu"), "skia_gpu::GLShader", + TRACE_EVENT_SCOPE_THREAD, "shader", TRACE_STR_COPY(shader.c_str())); + } + + stats->incShaderCompilations(); + GR_GL_CALL(gli, CompileShader(shaderId)); + + // Calling GetShaderiv in Chromium is quite expensive. Assume success in release builds. + bool checkCompiled = kChromium_GrGLDriver != glCtx.driver(); +#ifdef SK_DEBUG + checkCompiled = true; +#endif + if (checkCompiled) { + GrGLint compiled = GR_GL_INIT_ZERO; + GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_COMPILE_STATUS, &compiled)); + + if (!compiled) { + GrGLint infoLen = GR_GL_INIT_ZERO; + GR_GL_CALL(gli, GetShaderiv(shaderId, GR_GL_INFO_LOG_LENGTH, &infoLen)); + SkAutoMalloc log(sizeof(char)*(infoLen+1)); // outside if for debugger + if (infoLen > 0) { + // retrieve length even though we don't need it to workaround bug in Chromium cmd + // buffer param validation. + GrGLsizei length = GR_GL_INIT_ZERO; + GR_GL_CALL(gli, GetShaderInfoLog(shaderId, infoLen+1, &length, (char*)log.get())); + print_shader_source(strings, lengths, count); + SkDebugf("\n%s", (const char*)log.get()); + } + SkDEBUGFAIL("Shader compilation failed!"); + GR_GL_CALL(gli, DeleteShader(shaderId)); + return 0; + } + } + + if (c_PrintShaders) { + print_shader_source(strings, lengths, count); + } + + // Attach the shader, but defer deletion until after we have linked the program. + // This works around a bug in the Android emulator's GLES2 wrapper which + // will immediately delete the shader object and free its memory even though it's + // attached to a program, which then causes glLinkProgram to fail. + GR_GL_CALL(gli, AttachShader(programId, shaderId)); + + return shaderId; +} + +static void print_shader_source(const char** strings, int* lengths, int count) { + const SkString& pretty = GrGLSLPrettyPrint::PrettyPrintGLSL(strings, lengths, count, true); + SkTArray lines; + SkStrSplit(pretty.c_str(), "\n", &lines); + for (const SkString& line : lines) { + // Print the shader one line at the time so it doesn't get truncated by the adb log. + SkDebugf("%s\n", line.c_str()); + } +} diff --git a/pool/shard006/C++/0083795_utest_gen_sentence.cpp b/pool/shard006/C++/0083795_utest_gen_sentence.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2de66cd884668f98caa175bb3685718d2202030 --- /dev/null +++ b/pool/shard006/C++/0083795_utest_gen_sentence.cpp @@ -0,0 +1,123 @@ +#include +#include +#include +#include +#include "cppunit/ui/text/TestRunner.h" +#include "cppunit/TestCaller.h" +#include "cppunit/extensions/HelperMacros.h" +#include "gen_sentence.h" + +using std::vector; +using std::string; +using std::logic_error; + + + +class GenAuxTest : public CppUnit::TestFixture { + +private: + + Grammar *grammar; + vector *recipe, *actualize, *location; + +public: + + void setUp() { + + grammar = new Grammar; + recipe = new vector; + actualize = new vector; + location = new vector; + + location->push_back("wherever"); + location->push_back("it"); + location->push_back("wants"); + (*grammar)[""].push_back(*location); + + recipe->push_back(""); + + actualize->push_back("the"); + actualize->push_back("dog"); + actualize->push_back("sits"); + } + + + void tearDown() { + delete grammar; + delete recipe; + delete actualize; + } + + + // check behavior for a literal (i.e. not a bracketed rule) word + void test_word_literal() { + + Grammar grammar_before = *grammar; + vector recipe_before = *recipe; + vector actualize_before = *actualize; + string word_literal = "yayaya!"; + + gen_aux(*grammar, word_literal, *recipe, *actualize); + + // these should remain unchanged + CPPUNIT_ASSERT(*grammar == grammar_before); + CPPUNIT_ASSERT(*recipe == recipe_before); + + // should simply append `word_literal' to `*actualize' + CPPUNIT_ASSERT(actualize->size() == 4); + CPPUNIT_ASSERT((*actualize)[0] == actualize_before[0]); + CPPUNIT_ASSERT((*actualize)[1] == actualize_before[1]); + CPPUNIT_ASSERT((*actualize)[2] == actualize_before[2]); + CPPUNIT_ASSERT((*actualize)[3] == word_literal); + } + + + // check behavior for a rule word + void test_word_rule() { + + Grammar grammar_before = *grammar; + vector recipe_before = *recipe; + vector actualize_before = *actualize; + string word_rule = ""; + + gen_aux(*grammar, word_rule, *recipe, *actualize); + + // these should location vector is reverse order + CPPUNIT_ASSERT(*grammar == grammar_before); + CPPUNIT_ASSERT(*actualize == actualize_before); + + // should append words from (*grammar)[""][0] to *recipe, in + // reverse + CPPUNIT_ASSERT(recipe->size() == 4); + CPPUNIT_ASSERT((*recipe)[0] == recipe_before[0]); + CPPUNIT_ASSERT((*recipe)[1] == (*location)[2]); + CPPUNIT_ASSERT((*recipe)[2] == (*location)[1]); + CPPUNIT_ASSERT((*recipe)[3] == (*location)[0]); + } + + + // check that providing a `word' not defined in `grammer' throws an + // exception + void test_illegal_word() { + CPPUNIT_ASSERT_THROW(gen_aux(*grammar, "", *recipe, *actualize), + logic_error); + } + + + CPPUNIT_TEST_SUITE(GenAuxTest); + CPPUNIT_TEST(test_word_literal); + CPPUNIT_TEST(test_word_rule); + CPPUNIT_TEST(test_illegal_word); + CPPUNIT_TEST_SUITE_END(); +}; + + + + +int main() { + + CppUnit::TextUi::TestRunner runner; + runner.addTest(GenAuxTest::suite()); + + return runner.run() ? 0 : 1; +} diff --git a/pool/shard006/C++/0083801_EPattern.cpp b/pool/shard006/C++/0083801_EPattern.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cf283b68c60f1ee66352c8493f41c002d60b752 --- /dev/null +++ b/pool/shard006/C++/0083801_EPattern.cpp @@ -0,0 +1,249 @@ +/* + * EPattern.cpp + * + * Created on: 2013-3-25 + * Author: cxxjava@163.com + */ + +#include "EPattern.hh" +#include "EPatternSyntaxException.hh" +#include "EMatcher.hh" + +namespace efc { + +EPattern::~EPattern() +{ + eso_pcre_free(&_pcre); +} + +EPattern::EPattern(const char* regex, int opetion) THROWS(EPatternSyntaxException) +{ + _pattern = regex; + + int v; + _pcre = eso_pcre_make(regex, opetion, &v); + if (!_pcre) { + throw EPatternSyntaxException(__FILE__, __LINE__); + } +} + +EString EPattern::pattern() +{ + return _pattern; +} + +EString EPattern::toString() +{ + return _pattern; +} + +es_pcre_t* EPattern::c_pcre() +{ + return _pcre; +} + +EMatcher* EPattern::newMatcher(const char* input) +{ + return new EMatcher(this, input); +} + +EArray EPattern::split(const char* input, int limit) +{ + const char *regex = _pattern.c_str(); + EArray res; + EString *s; + + if (!input || !*input) { + return res; + } + + if (!regex || !*regex) { + s = new EString(input); + res.add(s); + return res; + } + + int v, count, length; + int ovector[3]; + char *psrc = (char*)input; + + count = length = 0; + while (*psrc && ((limit == 0) || (count < limit))) { + v = eso_pcre_exec(_pcre, psrc, -1, 0, 0, ovector, 3); + if (v >= 0) { + res.add(new EString(psrc, 0, ovector[0])); + psrc += ovector[1]; + count++; + + continue; + } + else if (v == -1) { + res.add(new EString(psrc)); + break; + } + else if (v < -1) { + throw EPatternSyntaxException(__FILE__, __LINE__); + } + } + + return res; +} + +EArray EPattern::split(const char* regex, const char* input, + int limit) THROWS(EPatternSyntaxException) +{ + EArray res; + EString *s; + + if (!input) { + return res; + } + + if (!regex || !*regex) { + s = new EString(input); + res.add(s); + return res; + } + + //@see: openjdk-8/src/share/classes/java/lang/String.java#L2316 + + /* fastpath if the regex is a + (1)one-char String and this character is not one of the + RegEx's meta characters ".$|()[{^?*+\\", or + (2)two-char String and the first char is the backslash and + the second is not the ascii digit or ascii letter. + */ + char ch = 0; + if (((eso_strlen(regex) == 1 && + eso_strchr(".$|()[{^?*+\\", (ch = regex[0])) == NULL) || + (eso_strlen(regex) == 2 && + regex[0] == '\\' && + (((ch = regex[1])-'0')|('9'-ch)) < 0 && + ((ch-'a')|('z'-ch)) < 0 && + ((ch-'A')|('Z'-ch)) < 0))) + { + EString s(input); + int off = 0; + int next = 0; + boolean limited = limit > 0; + while ((next = s.indexOf(ch, off)) != -1) { + if (!limited || res.size() < limit - 1) { + res.add(new EString(s.substring(off, next))); + off = next + 1; + } else { // last one + //assert (res.size() == limit - 1); + res.add(new EString(s.substring(off, s.length()))); + off = s.length(); + break; + } + } + // If no match was found, return this + if (off == 0) { + res.add(new EString(input)); + return res; + } + + // Add remaining segment + if (!limited || res.size() < limit) + res.add(new EString(s.substring(off, s.length()))); + + /* @see: + // Construct result + int resultSize = list.size(); + if (limit == 0) { + while (resultSize > 0 && list.get(resultSize - 1).length() == 0) { + resultSize--; + } + } + String[] result = new String[resultSize]; + return list.subList(0, resultSize).toArray(result); + */ + int resultSize = res.size(); + for (int i=resultSize-1; i>=0; i--) { + if (res[i]->length() == 0) { + res.removeAt(i); + } else { + break; + } + } + + return res; + } + + //================================================= + + es_pcre_t *pcre; + int v, count, length; + int ovector[3]; + char *psrc = (char*)input; + + pcre = eso_pcre_make(regex, 0, &v); + if (!pcre) { + throw EPatternSyntaxException(__FILE__, __LINE__); + } + + count = length = 0; + while (*psrc && ((limit == 0) || (count < limit))) { + v = eso_pcre_exec(pcre, psrc, -1, 0, 0, ovector, 3); + if (v >= 0) { + res.add(new EString(psrc, 0, ovector[0])); + psrc += ovector[1]; + count++; + + continue; + } + else if (v == -1) { + res.add(new EString(psrc)); + break; + } + else if (v < -1) { + eso_pcre_free(&pcre); + throw EPatternSyntaxException(__FILE__, __LINE__); + } + } + + eso_pcre_free(&pcre); + + return res; +} + +boolean EPattern::matches(const char* regex, const char* input) THROWS(EPatternSyntaxException) +{ + if ((!input || !*input) && (!regex || !*regex)) { + return true; + } + + if (!input || !*input) { + return false; + } + + if (!regex || !*regex) { + return false; + } + + es_pcre_t *pcre; + int v; + int ovector[3]; + boolean ret; + + pcre = eso_pcre_make(regex, 0, &v); + if (!pcre) { + throw EPatternSyntaxException(__FILE__, __LINE__); + } + + v = eso_pcre_exec(pcre, input, -1, 0, 0, ovector, 3); + if (v >= 0) { + ret = true; + } else if (v == -1) { + ret = false; + } else if (v < -1) { + eso_pcre_free(&pcre); + throw EPatternSyntaxException(__FILE__, __LINE__); + } + + eso_pcre_free(&pcre); + + return ret; +} + +} /* namespace efc */ diff --git a/pool/shard006/C++/0083803_settlement_evaluator.cc b/pool/shard006/C++/0083803_settlement_evaluator.cc new file mode 100644 index 0000000000000000000000000000000000000000..335bbfc538c55d9d4318f062c280f6eed4590ce4 --- /dev/null +++ b/pool/shard006/C++/0083803_settlement_evaluator.cc @@ -0,0 +1,89 @@ +/* -*- mode: c++; indent-tabs-mode: nil -*- */ + +/* + Determining the molar fraction of a gas component within a gas mixture. + + License: BSD + Authors: +*/ + +#include "settlement_evaluator.hh" +#include "boost/math/constants/constants.hpp" + +namespace Amanzi { + +SettlementRateEvaluator :: SettlementRateEvaluator(Teuchos::ParameterList& plist) : + SecondaryVariableFieldEvaluator(plist) { + + Key domain_name = "surface"; + + velocity_key_ = plist_.get("velocity key", + Keys::getKey(domain_name,"velocity")); + + sediment_key_ = plist_.get("sediment key", + Keys::getKey(domain_name,"sediment")); + + tau_d_ = plist_.get("critical shear stress"); + ws_ = plist_.get("settling velocity"); + gamma_ = plist_.get("specific weight of water"); + sediment_density_ = plist_.get("sediment density [kg m^-3]"); + + + umax_ = plist_.get("max current"); + xi_ = plist_.get("Chezy parameter"); + + double pi = boost::math::constants::pi(); + + lambda_ = 8./(3*pi) * (umax_/(xi_*xi_)); + + dependencies_.insert("surface-pressure"); + dependencies_.insert(sediment_key_); + +} + + +SettlementRateEvaluator ::SettlementRateEvaluator (const SettlementRateEvaluator & other) : + SecondaryVariableFieldEvaluator(other), + velocity_key_(other.velocity_key_), sediment_key_(other.sediment_key_) { + + tau_d_ = other.tau_d_; + ws_ = other.ws_; + gamma_ = other.gamma_; + lambda_ = other.lambda_; + sediment_density_ = other.sediment_density_; +} + + +Teuchos::RCP SettlementRateEvaluator ::Clone() const { + return Teuchos::rcp(new SettlementRateEvaluator (*this)); +} + + +void SettlementRateEvaluator::EvaluateField_(const Teuchos::Ptr& S, + const Teuchos::Ptr& result) { + + const Epetra_MultiVector& vel = *S->GetFieldData(velocity_key_)->ViewComponent("cell"); + const Epetra_MultiVector& tcc = *S->GetFieldData(sediment_key_)->ViewComponent("cell"); + Epetra_MultiVector& result_c = *result->ViewComponent("cell"); + + for (int c=0; c& S, + Key wrt_key, + const Teuchos::Ptr& result) { + AMANZI_ASSERT(0); +} + + +} // namespace diff --git a/pool/shard006/C++/0083809_hud_ammo.cpp b/pool/shard006/C++/0083809_hud_ammo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..59ade1b6653a1ebed0c4da61fffa22c741dd0861 --- /dev/null +++ b/pool/shard006/C++/0083809_hud_ammo.cpp @@ -0,0 +1,300 @@ +//========= Copyright © 1996-2003, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +//============================================================================= + +#include "cbase.h" +#include "hud.h" +#include "hudelement.h" +#include "hud_macros.h" +#include "parsemsg.h" +#include "hud_numericdisplay.h" +#include "iclientmode.h" + +#include + +//----------------------------------------------------------------------------- +// Purpose: Displays current ammunition level +//----------------------------------------------------------------------------- +class CHudAmmo : public CHudNumericDisplay, public CHudElement +{ + DECLARE_CLASS_SIMPLE( CHudAmmo, CHudNumericDisplay ); + +public: + CHudAmmo( const char *pElementName ); + void Init( void ); + void VidInit( void ); + + void SetAmmo(int ammo, bool playAnimation); + void SetAmmo2(int ammo2, bool playAnimation); + +protected: + virtual void OnThink(); + +private: + CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon; + int m_iAmmo; + int m_iAmmo2; +}; + +DECLARE_HUDELEMENT( CHudAmmo ); + +//----------------------------------------------------------------------------- +// Purpose: Constructor +//----------------------------------------------------------------------------- +CHudAmmo::CHudAmmo( const char *pElementName ) : BaseClass(NULL, "HudAmmo"), CHudElement( pElementName ) +{ +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void CHudAmmo::Init( void ) +{ + m_iAmmo = -1; + m_iAmmo2 = -1; + + SetLabelText(L"AMMO"); +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void CHudAmmo::VidInit( void ) +{ +} + +//----------------------------------------------------------------------------- +// Purpose: called every frame to get ammo info from the weapon +//----------------------------------------------------------------------------- +void CHudAmmo::OnThink() +{ + C_BaseCombatWeapon *wpn = GetActiveWeapon(); + C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); + if (!wpn || !player || !wpn->UsesPrimaryAmmo()) + { + SetPaintEnabled(false); + SetPaintBackgroundEnabled(false); + return; + } + else + { + SetPaintEnabled(true); + SetPaintBackgroundEnabled(true); + } + + // get the ammo in our clip + int ammo1 = wpn->Clip1(); + int ammo2; + if (ammo1 < 0) + { + // we don't use clip ammo, just use the total ammo count + ammo1 = player->GetAmmoCount(wpn->GetPrimaryAmmoType()); + ammo2 = 0; + } + else + { + // we use clip ammo, so the second ammo is the total ammo + ammo2 = player->GetAmmoCount(wpn->GetPrimaryAmmoType()); + } + + if (wpn == m_hCurrentActiveWeapon) + { + // same weapon, just update counts + SetAmmo(ammo1, true); + SetAmmo2(ammo2, true); + } + else + { + // diferent weapon, change without triggering + SetAmmo(ammo1, false); + SetAmmo2(ammo2, false); + + // update whether or not we show the total ammo display + if (wpn->UsesClipsForAmmo1()) + { + SetShouldDisplaySecondaryValue(true); + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponUsesClips"); + + } + else + { + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponDoesNotUseClips"); + SetShouldDisplaySecondaryValue(false); + } + + if ( GetGameRestored() ) + { + SetGameRestored( false ); + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChangedRestore"); + } + else + { + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("WeaponChanged"); + } + m_hCurrentActiveWeapon = wpn; + } +} + +//----------------------------------------------------------------------------- +// Purpose: Updates ammo display +//----------------------------------------------------------------------------- +void CHudAmmo::SetAmmo(int ammo, bool playAnimation) +{ + if (ammo != m_iAmmo) + { + if (ammo == 0) + { + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoEmpty"); + } + else if (ammo < m_iAmmo) + { + // ammo has decreased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoDecreased"); + } + else + { + // ammunition has increased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoIncreased"); + } + + m_iAmmo = ammo; + } + + SetDisplayValue(ammo); +} + +//----------------------------------------------------------------------------- +// Purpose: Updates 2nd ammo display +//----------------------------------------------------------------------------- +void CHudAmmo::SetAmmo2(int ammo2, bool playAnimation) +{ + if (ammo2 != m_iAmmo2) + { + if (ammo2 == 0) + { + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Empty"); + } + else if (ammo2 < m_iAmmo2) + { + // ammo has decreased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Decreased"); + } + else + { + // ammunition has increased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("Ammo2Increased"); + } + + m_iAmmo2 = ammo2; + } + + SetSecondaryValue(ammo2); +} + +//----------------------------------------------------------------------------- +// Purpose: Displays the secondary ammunition level +//----------------------------------------------------------------------------- +class CHudSecondaryAmmo : public CHudNumericDisplay, public CHudElement +{ + DECLARE_CLASS_SIMPLE( CHudSecondaryAmmo, CHudNumericDisplay ); + +public: + CHudSecondaryAmmo( const char *pElementName ) : BaseClass( NULL, "HudAmmoSecondary" ), CHudElement( pElementName ) + { + m_iAmmo = -1; + } + + void Init( void ) + { + } + + void VidInit( void ) + { + } + + void SetAmmo( int ammo ) + { + if (ammo != m_iAmmo) + { + if (ammo == 0) + { + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryEmpty"); + } + else if (ammo < m_iAmmo) + { + // ammo has decreased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryDecreased"); + } + else + { + // ammunition has increased + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence("AmmoSecondaryIncreased"); + } + + m_iAmmo = ammo; + } + SetDisplayValue( ammo ); + } + +protected: + virtual void OnThink( void ) + { + // set whether or not the panel draws based on if we have a weapon that supports secondary ammo + C_BaseCombatWeapon *wpn = GetActiveWeapon(); + C_BasePlayer *player = C_BasePlayer::GetLocalPlayer(); + if (!wpn || !player) + { + m_hCurrentActiveWeapon = NULL; + SetPaintEnabled(false); + SetPaintBackgroundEnabled(false); + return; + } + else + { + SetPaintEnabled(true); + SetPaintBackgroundEnabled(true); + } + + if (wpn->UsesSecondaryAmmo()) + { + SetAmmo(player->GetAmmoCount(wpn->GetSecondaryAmmoType())); + } + + if ( m_hCurrentActiveWeapon != wpn ) + { + bool restored = false; + if ( GetGameRestored() ) + { + SetGameRestored( false ); + restored = true; + } + + if ( wpn->UsesSecondaryAmmo() ) + { + // we've changed to a weapon that uses secondary ammo + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence( + restored ? + "WeaponUsesSecondaryAmmoRestore" : + "WeaponUsesSecondaryAmmo"); + } + else + { + // we've changed away from a weapon that uses secondary ammo + g_pClientMode->GetViewportAnimationController()->StartAnimationSequence( + restored ? + "WeaponDoesNotUseSecondaryAmmoRestore" : + "WeaponDoesNotUseSecondaryAmmo" ); + } + m_hCurrentActiveWeapon = wpn; + } + } + +private: + CHandle< C_BaseCombatWeapon > m_hCurrentActiveWeapon; + int m_iAmmo; +}; + +DECLARE_HUDELEMENT( CHudSecondaryAmmo ); + diff --git a/pool/shard006/C++/0083818_DecoderPD.cpp b/pool/shard006/C++/0083818_DecoderPD.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d26b7a951c0310f64a6e2dba96c90431fca3bf6c --- /dev/null +++ b/pool/shard006/C++/0083818_DecoderPD.cpp @@ -0,0 +1,140 @@ +/* + * DecoderPD.cpp + * zxing + * + * Created by Hartmut Neubauer (hfn), 2012-05-25 (translated from Java source) + * Copyright 2010,2012 ZXing authors All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * 2012-06-27 hfn: PDF417 Reed-Solomon error correction, using following Java + * source code: + * http://code.google.com/p/zxing/issues/attachmentText?id=817&aid=8170033000&name=pdf417-java-reed-solomon-error-correction-2.patch&token=0819f5d7446ae2814fd91385eeec6a11 + */ + +#include +#include +#include +#include +#include +#include + + +namespace zxing { +namespace pdf417 { + +using namespace std; + +Decoder::Decoder() +{ +} + +const int Decoder::MAX_ERRORS = 3; /* 3; / 8? */ +const int Decoder::MAX_EC_CODEWORDS = 512; + +Ref Decoder::decode(Ref bits) { + // Construct a parser to read the data codewords and error-correction level + BitMatrixParser parser(bits); + size_t cwsize; + ArrayRef codewords(parser.readCodewords()); + cwsize = codewords.size(); + if (cwsize == 0) { + throw FormatException("PDF:Decoder:decode: cannot read codewords"); + } + + int ecLevel = parser.getECLevel(); + int numECCodewords = 1 << (ecLevel + 1); + ArrayRef erasures = parser.getErasures(); + + correctErrors(codewords, erasures, numECCodewords); + verifyCodewordCount(codewords, numECCodewords); + + // Decode the codewords + return DecodedBitStreamParser::decode(codewords); +} + + /** + * Verify that all is OK with the codeword array. + * + * @param codewords + * @return an index to the first data codeword. + * @throws FormatException + */ +void Decoder::verifyCodewordCount(ArrayRef codewords, int numECCodewords) +{ + int cwsize = codewords.size(); + if (cwsize < 4) { + // Codeword array size should be at least 4 allowing for + // Count CW, At least one Data CW, Error Correction CW, Error Correction CW + throw FormatException("PDF:Decoder:verifyCodewordCount: codeword array too small!"); + } + // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data + // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad + // codewords, but excluding the number of error correction codewords. + int numberOfCodewords = codewords[0]; + if (numberOfCodewords > cwsize) { + throw FormatException("PDF:Decoder:verifyCodewordCount: bad codeword number descriptor!"); + } + if (numberOfCodewords == 0) { + // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords) + if (numECCodewords < cwsize) { + codewords[0] = cwsize - numECCodewords; + } else { + throw FormatException("PDF:Decoder:verifyCodewordCount: bad error correction cw number!"); + } + } +} + +int Decoder::correctErrors(ArrayRef codewords, + ArrayRef erasures, int numECCodewords) { +#if (defined _WIN32 && defined(DEBUG)) + { + WCHAR sz[256]; + wsprintf(sz,L"Decoder::correctErrors: erasures.size=%d, numECCodewords=%d\n",erasures.size(),numECCodewords); + OutputDebugString(sz); + } +#endif + int numErasures = erasures.size(); + if (numErasures > numECCodewords - 3 + || numECCodewords < 0 || numECCodewords > MAX_EC_CODEWORDS) { + // Too many errors or EC Codewords is corrupted + throw FormatException("PDF:Decoder:correctErrors: Too many errors or EC Codewords corrupted"); + } + // Try to correct the errors + // Use class PDF417RSDecoder for Reed-Solomon error correction + Ref rsDecoder(new PDF417RSDecoder); + int synd_len = codewords.size() - codewords[0]; + int numCorrections = rsDecoder->correctErrors(codewords, + erasures, /* hint: "erasures" are ignored when num_eras=0! */ + 0, // erasures.size(), + codewords.size(),synd_len); + if(numCorrections < 0) + { + // Still too many errors + throw FormatException("PDF:Decoder:correctErrors: Error correction not possible!"); + } + + //* 2012-06-27 HFN if, despite of error correction, there are still codewords with invalid + //* value, throw an exception here: + int i; + for(i=0;i<(int)codewords.size();i++) { + if(codewords[i]<0) { + throw FormatException("PDF:Decoder:correctErrors: Error correction did not succeed!"); + } + } + + return numCorrections; +} + +} /* namespace pdf417 */ +} /* namespace zxing */ \ No newline at end of file diff --git a/pool/shard006/C++/0083820_test_polyhedron_io.cpp b/pool/shard006/C++/0083820_test_polyhedron_io.cpp new file mode 100644 index 0000000000000000000000000000000000000000..181062a7990a61f1a51a2cf56163ae5ed2eda3ec --- /dev/null +++ b/pool/shard006/C++/0083820_test_polyhedron_io.cpp @@ -0,0 +1,138 @@ +// ============================================================================ +// +// Copyright (c) 1997 The CGAL Consortium +// +// This software and related documentation is part of an INTERNAL release +// of the Computational Geometry Algorithms Library (CGAL). It is not +// intended for general use. +// +// ---------------------------------------------------------------------------- +// +// release : $CGAL_Revision: $ +// release_date : $CGAL_Date: $ +// +// file : test_polyhedron_io.C +// chapter : $CGAL_Chapter: Support Library ... $ +// package : $CGAL_Package: Polyhedron_IO 2.11 (04 Feb 2000) $ +// source : polyhedron_io.fw +// revision : $Id$ +// revision_date : $Date$ +// author(s) : Lutz Kettner +// +// coordinator : Herve Bronnimann +// +// Polyhedral Surface File IO: Scanner and Writer +// ============================================================================ + + +#include +#include + +// This is the test file for the new design. Skip new design test for +// disabled compilers. +#ifndef CGAL_USE_POLYHEDRON_DESIGN_ONE + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace CGAL; + +const char* triangle = "OFF\n" + "3 1 0\n" + "0 0 0\n" + "1 0 0\n" + "0 1 0\n" + "3 0 1 2\n"; +const char* tetra = "OFF\n" + "4 4 0\n" + "0 0 0.707107\n" + "1 1 0.707107\n" + "0 1 0\n" + "1 0 0\n" + "3 1 3 0\n" + "3 2 1 0\n" + "3 3 2 0\n" + "3 2 3 1\n"; + + +void test_file_IO_OFF() { + typedef Cartesian Kernel; + typedef Polyhedron_3 Polyhedron; + { + Polyhedron P; + std::istringstream in( triangle); + in >> P; /* 'in' is the stream where the object is read from. */ + assert(! in.fail()); + assert( P.is_triangle( P.halfedges_begin())); + std::stringstream stream; + stream << P << '\0'; + P = Polyhedron(); + scan_OFF( stream, P, true); + assert( ! ! stream); // ! ! to fool VC7 CL1310 + assert( P.is_triangle( P.halfedges_begin())); + + std::stringstream stream_new; + print_polyhedron_OFF( stream_new, P, true); + stream_new << '\0'; + P = Polyhedron(); + stream_new >> P; + assert( ! ! stream_new); // ! ! to fool VC7 CL1310 + assert( P.is_triangle( P.halfedges_begin())); + { + std::ofstream out2( "triangle_binary.off"); + print_polyhedron_OFF( out2, P, true); + } + std::ifstream filein( "triangle_binary.off"); + P = Polyhedron(); + filein >> P; + assert(! filein.fail()); + assert( P.is_triangle( P.halfedges_begin())); + }{ + Polyhedron P; + std::istringstream in( tetra); + in >> P; /* 'in' is the stream where the object is read from. */ + assert( P.is_tetrahedron( P.halfedges_begin())); + std::stringstream stream; + stream << P << '\0'; + P = Polyhedron(); + stream >> P; + assert( P.is_tetrahedron( P.halfedges_begin())); + { + std::ofstream out2( "tetra_binary.off"); + print_polyhedron_OFF( out2, P, true); + } + std::ifstream filein( "tetra_binary.off"); + P = Polyhedron(); + filein >> P; + assert( P.is_tetrahedron( P.halfedges_begin())); + } +} +void test_file_IO_wavefront() {} +void test_file_IO_inventor() {} +void test_file_IO_VRML_2() {} + +#endif // CGAL_USE_POLYHEDRON_DESIGN_ONE // + +int main(){ +// This is the test file for the new design. Skip new design test for +// disabled compilers. +#ifndef CGAL_USE_POLYHEDRON_DESIGN_ONE + test_file_IO_OFF(); + test_file_IO_wavefront(); + test_file_IO_inventor(); + test_file_IO_VRML_2(); +#endif // CGAL_USE_POLYHEDRON_DESIGN_ONE // + return 0; +} +// EOF // diff --git a/pool/shard006/C++/0083822_PlatformCanvas.cpp b/pool/shard006/C++/0083822_PlatformCanvas.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c5e38d6aa353ab3e60eb6fe172e87da4a89150c1 --- /dev/null +++ b/pool/shard006/C++/0083822_PlatformCanvas.cpp @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2011 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS 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 APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#include "PlatformCanvas.h" + +#include "GraphicsContext.h" + +#include "NativeImageSkia.h" +#include "PlatformContextSkia.h" +#include "SkColorPriv.h" +#include "skia/ext/platform_canvas.h" + +namespace WebCore { + +PlatformCanvas::PlatformCanvas() + : m_opaque(false) +{ +} + +PlatformCanvas::~PlatformCanvas() +{ +} + +void PlatformCanvas::resize(const IntSize& size) +{ + if (m_size == size) + return; + m_size = size; + createBackingCanvas(); +} + +void PlatformCanvas::setOpaque(bool opaque) +{ + if (opaque == m_opaque) + return; + + m_opaque = opaque; + createBackingCanvas(); +} + +void PlatformCanvas::createBackingCanvas() +{ + if (m_size.isEmpty()) + return; + + m_skiaCanvas = adoptPtr(skia::CreateBitmapCanvas(m_size.width(), m_size.height(), m_opaque)); +} + +PlatformCanvas::AutoLocker::AutoLocker(PlatformCanvas* canvas) + : m_canvas(canvas) +{ + if (m_canvas->m_skiaCanvas) { + m_bitmap = &m_canvas->m_skiaCanvas->getDevice()->accessBitmap(false); + m_bitmap->lockPixels(); + } else + m_bitmap = 0; +} + +PlatformCanvas::AutoLocker::~AutoLocker() +{ + if (m_bitmap) + m_bitmap->unlockPixels(); +} + +const uint8_t* PlatformCanvas::AutoLocker::pixels() const +{ + if (m_bitmap && m_bitmap->config() == SkBitmap::kARGB_8888_Config) + return static_cast(m_bitmap->getPixels()); + return 0; +} + +PlatformCanvas::Painter::Painter(PlatformCanvas* canvas, PlatformCanvas::Painter::TextOption option) +{ + m_skiaContext = adoptPtr(new PlatformContextSkia(canvas->m_skiaCanvas.get())); + + m_skiaContext->setDrawingToImageBuffer(option == GrayscaleText); + + m_context = adoptPtr(new GraphicsContext(reinterpret_cast(m_skiaContext.get()))); + context()->save(); +} + +PlatformCanvas::Painter::~Painter() +{ + context()->restore(); +} + +} // namespace WebCore diff --git a/pool/shard006/C++/0083825_MapWindowTraffic.cpp b/pool/shard006/C++/0083825_MapWindowTraffic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..154a9831bea1e5bc085a2237a79a8e0e117b61c1 --- /dev/null +++ b/pool/shard006/C++/0083825_MapWindowTraffic.cpp @@ -0,0 +1,134 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2012 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "MapWindow.hpp" +#include "Math/Screen.hpp" +#include "Math/Earth.hpp" +#include "Screen/Icon.hpp" +#include "Screen/Fonts.hpp" +#include "Screen/Layout.hpp" +#include "Screen/TextInBox.hpp" +#include "Util/StringUtil.hpp" +#include "GlideSolvers/GlidePolar.hpp" +#include "Formatter/UserUnits.hpp" +#include "Look/TrafficLook.hpp" +#include "Renderer/TrafficRenderer.hpp" + +#include + +/** + * Draws the FLARM traffic icons onto the given canvas + * @param canvas Canvas for drawing + */ +void +MapWindow::DrawFLARMTraffic(Canvas &canvas, + const RasterPoint aircraft_pos) const +{ + // Return if FLARM icons on moving map are disabled + if (!GetMapSettings().show_flarm_on_map) + return; + + // Return if FLARM data is not available + const FlarmState &flarm = Basic().flarm; + if (!flarm.available) + return; + + const WindowProjection &projection = render_projection; + + // if zoomed in too far out, dont draw traffic since it will be too close to + // the glider and so will be meaningless (serves only to clutter, cant help + // the pilot) + if (projection.GetMapScale() > fixed_int_constant(7300)) + return; + + // Circle through the FLARM targets + for (auto it = flarm.traffic.begin(), end = flarm.traffic.end(); + it != end; ++it) { + const FlarmTraffic &traffic = *it; + + if (!traffic.location_available) + continue; + + // Save the location of the FLARM target + GeoPoint target_loc = traffic.location; + + // Points for the screen coordinates for the icon, name and average climb + RasterPoint sc, sc_name, sc_av; + + // If FLARM target not on the screen, move to the next one + if (!projection.GeoToScreenIfVisible(target_loc, sc)) + continue; + + // Draw the name 16 points below the icon + sc_name = sc; + sc_name.y -= Layout::Scale(20); + + // Draw the average climb value above the icon + sc_av = sc; + sc_av.y += Layout::Scale(5); + + TextInBoxMode mode; + mode.mode = RM_OUTLINED; + + // JMW TODO enhancement: decluttering of FLARM altitudes (sort by max lift) + + int dx = sc_av.x - aircraft_pos.x; + int dy = sc_av.y - aircraft_pos.y; + + // only draw labels if not close to aircraft + if (dx * dx + dy * dy > Layout::Scale(30 * 30)) { + // If FLARM callsign/name available draw it to the canvas + if (traffic.HasName() && !StringIsEmpty(traffic.name)) + TextInBox(canvas, traffic.name, sc_name.x, sc_name.y, + mode, GetClientRect()); + + if (traffic.climb_rate_avg30s >= fixed(0.1)) { + // If average climb data available draw it to the canvas + TCHAR label_avg[100]; + FormatUserVerticalSpeed(traffic.climb_rate_avg30s, + label_avg, false); + TextInBox(canvas, label_avg, sc_av.x, sc_av.y, mode, GetClientRect()); + } + } + + TrafficRenderer::Draw(canvas, traffic_look, traffic, + traffic.track - projection.GetScreenAngle(), sc); + } +} + +/** + * Draws the teammate icon to the given canvas + * @param canvas Canvas for drawing + */ +void +MapWindow::DrawTeammate(Canvas &canvas) const +{ + const TeamInfo &teamcode_info = Calculated(); + + if (teamcode_info.teammate_available) { + RasterPoint sc; + if (render_projection.GeoToScreenIfVisible(teamcode_info.teammate_location, + sc)) + traffic_look.teammate_icon.Draw(canvas, sc); + } +} diff --git a/pool/shard006/C++/0083827_FontGenerator.cpp b/pool/shard006/C++/0083827_FontGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d6e67b3f954a3b3962896cdfdac7a66ed5eeb66a --- /dev/null +++ b/pool/shard006/C++/0083827_FontGenerator.cpp @@ -0,0 +1,112 @@ +//#define _DEBUG_GENERATE_TGA_FILES_ + +#include "FontGenerator.h" +#include +#include +#include +#include FT_FREETYPE_H + +#ifdef _DEBUG_GENERATE_TGA_FILES_ +# include +#endif + +static bool sFreeType_Initialized = false; +static FT_Library sLibrary; + +namespace pragma +{ + + static void ExtractGlyph(Font::Glyph& aGlyph, FT_Face aFace, uint32 aCharCode) + { + FT_UInt lGlyphIndex = FT_Get_Char_Index( aFace, aCharCode ); + FT_Load_Glyph(aFace, lGlyphIndex, 0); + FT_Render_Glyph(aFace->glyph, FT_RENDER_MODE_NORMAL); + + aGlyph.mCode = aCharCode; + aGlyph.mBitmap = aFace->glyph->bitmap.buffer; + aGlyph.mWidth = aFace->glyph->bitmap.width; + aGlyph.mHeight = aFace->glyph->bitmap.rows; + aGlyph.mStartX = aFace->glyph->bitmap_left; + aGlyph.mStartY = aFace->glyph->bitmap_top; + aGlyph.mAdvanceX = aFace->glyph->advance.x; + +#ifdef _DEBUG_GENERATE_TGA_FILES_ + char lNane[10]; + sprintf(lNane, "glyph%d.tga", aCharCode); + pragma::ExportToTGA( aGlyph.mBitmap + , aGlyph.mWidth + , aGlyph.mHeight + , lNane ); +#endif + } + + /** + * CreateFont_FreeType + */ + void CreateFont_FreeType( const char* aFontFile, size_t aSize, uint32* aRanges, Font& aFont ) + { + int error; + // Initialize FreeType library, if needed + if(!sFreeType_Initialized) + { + error = FT_Init_FreeType( &sLibrary ); + if(error) + { + printf( "CreateFont_FreeType: Error initializing FreeType library\n"); + return; + } + sFreeType_Initialized = true; + } + + // Initialize font face + FT_Face lFace; + error = FT_New_Face( sLibrary, aFontFile, 0, &lFace ); + + if(error) + { + printf( "Error opening font\n"); + return; + } + + // Set Font size + FT_Set_Char_Size ( lFace, 0, aSize << 6, 300, 300 ); + FT_Set_Pixel_Sizes( lFace, 0, aSize ); + + aFont.Init(aSize); + + if(aRanges == 0) + { // Extract all glyphs + FT_UInt lIndex; + FT_ULong lCharCode = FT_Get_First_Char(lFace, &lIndex); + for(size_t i = 0; i < lFace->num_glyphs; ++i) + { + Font::Glyph lGlyph; + ExtractGlyph(lGlyph, lFace, lCharCode); + aFont.AddGlyph(lGlyph); + lCharCode = FT_Get_Next_Char(lFace, lCharCode, &lIndex); + } + } + else + { // Extract only a range of glyphs + while(aRanges[0] <= aRanges[1]) + { + for(uint32 i = aRanges[0]; i <= aRanges[1]; ++i) + { + Font::Glyph lGlyph; + ExtractGlyph(lGlyph, lFace, i); + aFont.AddGlyph(lGlyph); + } + aRanges+=2; + } + } + + } + + /** + * CreateFont_FreeType + */ + void CreateFont_FreeType( const char* aFontFile, size_t aSize, Font& aFont ) + { + CreateFont_FreeType( aFontFile, aSize, 0, aFont); + } +} diff --git a/pool/shard006/C++/0083833_shape.cc b/pool/shard006/C++/0083833_shape.cc new file mode 100644 index 0000000000000000000000000000000000000000..cdfc733530b78f5bf6983c7c3d1af115e5dd8c65 --- /dev/null +++ b/pool/shard006/C++/0083833_shape.cc @@ -0,0 +1,177 @@ +#include "shape.h" + +#include "Contours.h" +#include "../common/Point.h" + +namespace ncv { + + namespace imgproc { + + void ShapeInit(Local &target) { + // connected components algorithms types + DEFINE_CONST_ENUM(CCL_WU); + DEFINE_CONST_ENUM(CCL_DEFAULT); + DEFINE_CONST_ENUM(CCL_GRANA); + + // connected components types + DEFINE_CONST_ENUM(CC_STAT_LEFT); + DEFINE_CONST_ENUM(CC_STAT_TOP); + DEFINE_CONST_ENUM(CC_STAT_WIDTH); + DEFINE_CONST_ENUM(CC_STAT_HEIGHT); + DEFINE_CONST_ENUM(CC_STAT_AREA); + DEFINE_CONST_ENUM(CC_STAT_MAX); + + // contour approximation modes + DEFINE_CONST_ENUM(CHAIN_APPROX_NONE); + DEFINE_CONST_ENUM(CHAIN_APPROX_SIMPLE); + DEFINE_CONST_ENUM(CHAIN_APPROX_TC89_L1); + DEFINE_CONST_ENUM(CHAIN_APPROX_TC89_KCOS); + + // rectangles intersect types + DEFINE_CONST_ENUM(INTERSECT_NONE); + DEFINE_CONST_ENUM(INTERSECT_PARTIAL); + DEFINE_CONST_ENUM(INTERSECT_FULL); + + // retrieval modes + DEFINE_CONST_ENUM(RETR_EXTERNAL); + DEFINE_CONST_ENUM(RETR_LIST); + DEFINE_CONST_ENUM(RETR_CCOMP); + DEFINE_CONST_ENUM(RETR_TREE); + DEFINE_CONST_ENUM(RETR_FLOODFILL); + + // shape match modes + DEFINE_CONST_ENUM(CONTOURS_MATCH_I1); + DEFINE_CONST_ENUM(CONTOURS_MATCH_I2); + DEFINE_CONST_ENUM(CONTOURS_MATCH_I3); + + Nan::SetMethod(target, "approxPolyDP", ApproxPolyDP); + Nan::SetMethod(target, "arcLength", ArcLength); + Nan::SetMethod(target, "boundingRect", BoundingRect); + Nan::SetMethod(target, "boxPoints", BoxPoints); + Nan::SetMethod(target, "connectedComponents", ConnectedComponents); + Nan::SetMethod(target, "connectedComponentsWithStats", ConnectedComponentsWithStats); + Nan::SetMethod(target, "contourArea", ContourArea); + Nan::SetMethod(target, "convexHull", ConvexHull); + Nan::SetMethod(target, "convexityDefects", ConvexityDefects); + Nan::SetMethod(target, "findContours", FindContours); + Nan::SetMethod(target, "fitEllipse", FitEllipse); + Nan::SetMethod(target, "fitLine", FitLine); + Nan::SetMethod(target, "huMoments", HuMoments); + Nan::SetMethod(target, "intersectConvexConvex", IntersectConvexConvex); + Nan::SetMethod(target, "isContourConvex", IsContourConvex); + Nan::SetMethod(target, "matchShapes", MatchShapes); + Nan::SetMethod(target, "minAreaRect", MinAreaRect); + Nan::SetMethod(target, "minEnclosingCircle", MinEnclosingCircle); + Nan::SetMethod(target, "minEnclosingTriangle", MinEnclosingTriangle); + Nan::SetMethod(target, "moments", Moments); + Nan::SetMethod(target, "pointPolygonTest", PointPolygonTest); + Nan::SetMethod(target, "rotatedRectangleIntersection", RotatedRectangleIntersection); + } + + NAN_METHOD(ApproxPolyDP) { + NotImplemented + } + + NAN_METHOD(ArcLength) { + NotImplemented + } + + NAN_METHOD(BoundingRect) { + NotImplemented + } + + NAN_METHOD(BoxPoints) { + NotImplemented + } + + NAN_METHOD(ConnectedComponents) { + NotImplemented + } + + NAN_METHOD(ConnectedComponentsWithStats) { + NotImplemented + } + + NAN_METHOD(ContourArea) { + NotImplemented + } + + NAN_METHOD(ConvexHull) { + NotImplemented + } + + NAN_METHOD(ConvexityDefects) { + NotImplemented + } + + NAN_METHOD(FindContours) { + FUNCTION_REQUIRE_ARGUMENTS_RANGE(3, 4); + Nan::HandleScope scope; + ASSERT_INPUTOUTPUTARRAY_FROM_ARGS(image, 0); + ASSERT_INT_FROM_ARGS(mode, 1); + ASSERT_INT_FROM_ARGS(method, 2); + DEFAULT_POINT_FROM_ARGS(offset, 2, cv::Point()); + + Local out = Contours::NewInstance(); + Contours* contours = UNWRAP_OBJECT(Contours, out); + TRY_CATCH_THROW_OPENCV(cv::findContours(image, contours->contours, contours->hierarchy, mode, method, offset)); + + info.GetReturnValue().Set(out); + } + + NAN_METHOD(FitEllipse) { + NotImplemented + } + + NAN_METHOD(FitLine) { + NotImplemented + } + + NAN_METHOD(HuMoments) { + NotImplemented + } + + NAN_METHOD(IntersectConvexConvex) { + NotImplemented + } + + NAN_METHOD(IsContourConvex) { + NotImplemented + } + + NAN_METHOD(MatchShapes) { + FUNCTION_REQUIRE_ARGUMENTS(4); + ASSERT_INPUTARRAY_FROM_ARGS(contour1, 0); + ASSERT_INPUTARRAY_FROM_ARGS(contour2, 1); + ASSERT_INT_FROM_ARGS(method, 2); + ASSERT_DOUBLE_FROM_ARGS(parameter, 3); + TRY_CATCH_THROW_OPENCV(info.GetReturnValue().Set(Nan::New(cv::matchShapes(contour1, contour2, method, parameter)))); + } + + NAN_METHOD(MinAreaRect) { + NotImplemented + } + + NAN_METHOD(MinEnclosingCircle) { + NotImplemented + } + + NAN_METHOD(MinEnclosingTriangle) { + NotImplemented + } + + NAN_METHOD(Moments) { + NotImplemented + } + + NAN_METHOD(PointPolygonTest) { + NotImplemented + } + + NAN_METHOD(RotatedRectangleIntersection) { + NotImplemented + } + + } + +} diff --git a/pool/shard006/C++/0083835_mat_mul.cpp b/pool/shard006/C++/0083835_mat_mul.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9887101c4fe5978d1eab1b55dc3ad3458d27670 --- /dev/null +++ b/pool/shard006/C++/0083835_mat_mul.cpp @@ -0,0 +1,104 @@ +/* $Id$ */ +/* -------------------------------------------------------------------------- +CppAD: C++ Algorithmic Differentiation: Copyright (C) 2003-12 Bradley M. Bell + +CppAD is distributed under multiple licenses. This distribution is under +the terms of the + Eclipse Public License Version 1.0. + +A copy of this license is included in the COPYING file of this distribution. +Please visit http://www.coin-or.org/CppAD/ for information on other licenses. +-------------------------------------------------------------------------- */ +/* +$begin fadbad_mat_mul.cpp$$ +$spell + badiff + sq + retape + typedef + diff + Fadbad + Adolc + cppad.hpp + bool + mul + dz + CppAD +$$ + +$section Fadbad Speed: Matrix Multiplication$$ + +$index link_mat_mul, fadbad$$ +$index fadbad, link_mat_mul$$ +$index speed, fadbad$$ +$index fadbad, speed$$ +$index matrix, speed fadbad$$ +$index multiply, speed fadbad$$ + +$head Specifications$$ +See $cref link_mat_mul$$. + +$head Implementation$$ + +$codep */ +# include +# include +# include +# include +bool link_mat_mul( + size_t size , + size_t repeat , + CppAD::vector& x , + CppAD::vector& z , + CppAD::vector& dz ) +{ + // speed test global option values + extern bool global_retape, global_atomic, global_optimize; + if( ! global_retape || global_atomic || global_optimize ) + return false; + + // The correctness check for this test is failing, so abort (for now). + return false; + + // ----------------------------------------------------- + // setup + + // object for computing determinant + typedef fadbad::B ADScalar; + typedef CppAD::vector ADVector; + + size_t j; // temporary index + size_t m = 1; // number of dependent variables + size_t n = size * size; // number of independent variables + ADVector X(n); // AD domain space vector + ADVector Y(n); // Store product matrix + ADVector Z(m); // AD range space vector + + // ------------------------------------------------------ + while(repeat--) + { // get the next matrix + CppAD::uniform_01(n, x); + + // set independent variable values + for(j = 0; j < n; j++) + X[j] = x[j]; + + // do the computation + mat_sum_sq(size, X, Y, Z); + + // create function object f : X -> Z + Z[0].diff(0, m); // index 0 of m dependent variables + + // evaluate and return gradient using reverse mode + for(j = 0; j < n; j++) + dz[j] = X[j].d(0); // partial Z[0] w.r.t X[j] + } + // return function value + z[0] = Z[0].x(); + + // --------------------------------------------------------- + return true; +} +/* $$ +$end +*/ diff --git a/pool/shard006/C++/0083836_core_types.cpp b/pool/shard006/C++/0083836_core_types.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ff5c7c6b7d3f595478875ef08ab90f66a0f4241 --- /dev/null +++ b/pool/shard006/C++/0083836_core_types.cpp @@ -0,0 +1,73 @@ +#include "core_types.h" +#include "error_macros.h" + +#include +#include + +bool Interval::isInTimePeriod(qint64 start, qint64 end) const +{ + return ((start >= startTime && end <= endTime) + || + (start >= startTime && end >= startTime && endTime >= start) + || + (start <= startTime && end >= startTime)); +} + +void Activity::updateStartAndEndTime() +{ + qint64 min = INT64_MAX, max = INT64_MIN; + if (intervals.count() == 0) return; + + for (const Interval & interval : intervals) + { + if (interval.startTime < min) min = interval.startTime; + if (interval.endTime > max) max = interval.endTime; + } + + startTime = min; + endTime = max; +} + +bool Activity::belongsToTimePeriod(qint64 startTime, qint64 endTime) const +{ + if (intervals.count() == 0) + { + return (startTime >= this->startTime && endTime <= this->endTime) + || + (startTime >= this->startTime && endTime >= this->startTime && this->endTime >= startTime) + || + (startTime <= this->startTime && endTime >= this->startTime); + } + + for (const Interval & interval : intervals) + { + /* this one is better i guess + (startTime >= interval.startTime && endTime >= interval.startTime && interval.endTime >= startTime) + || + (startTime <= interval.startTime && endTime >= interval.startTime); + */ + if ((startTime >= interval.startTime && endTime <= interval.endTime) + || + (startTime >= interval.startTime && endTime >= interval.startTime && interval.endTime >= startTime) + || + (startTime <= interval.startTime && endTime >= interval.startTime)) + { + return true; + } + } + + return false; +} + + +qint64 Activity::duration() const +{ + qint64 duration = 0; + + for (const Interval & interval : intervals) + { + duration += interval.duration(); + } + + return duration; +} diff --git a/pool/shard006/C++/0083838_QQSound.cpp b/pool/shard006/C++/0083838_QQSound.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67346f416af510eaba58329172cd186d27285ac2 --- /dev/null +++ b/pool/shard006/C++/0083838_QQSound.cpp @@ -0,0 +1,22 @@ +#include "QQSound.h" + +#include +#include + + +QQSound::QQSound(const QString & filename, + QObject *parent) + : QSound(filename, parent) +{ +} + +bool QQSound::play(const QString & filename) +{ + QFileInfo fi(filename); + fi.makeAbsolute(); + if ( ! fi.exists()) return false; + QString fn(fi.absoluteFilePath()); + fn = QDir::toNativeSeparators(fn); + QSound::play(fn); + return true; +} diff --git a/pool/shard006/C++/0083843_getcomputername.cpp b/pool/shard006/C++/0083843_getcomputername.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e480b9ad47d3497d58a7f7529058a1b9289701d --- /dev/null +++ b/pool/shard006/C++/0083843_getcomputername.cpp @@ -0,0 +1,45 @@ +//! @file getcomputername.cpp +//! @author George Fleming +//! @brief Implements GetComputerName Win32 API + +#include +#include +#include +#include "getcomputername.h" + +//! @brief GetComputerName retrieves the name of the host associated with +//! the current thread. +//! +//! @exception errno Passes these errors via errno to GetLastError: +//! - ERROR_INVALID_FUNCTION: getlogin_r() returned an unrecognized error code +//! - ERROR_INVALID_ADDRESS: buffer is an invalid address +//! - ERROR_GEN_FAILURE: buffer not large enough +//! +//! @retval username as UTF-8 string, or null if unsuccessful + +char* GetComputerName() +{ + errno = 0; + // Get computername from system, note that gethostname(2) gets the + // nodename from uname + std::string computername(_POSIX_HOST_NAME_MAX, 0); + int err = gethostname(&computername[0], computername.length()); + // Map errno to Win32 Error Codes + if (err != 0) + { + switch (errno) + { + case EFAULT: + errno = ERROR_INVALID_ADDRESS; + break; + case ENAMETOOLONG: + errno = ERROR_GEN_FAILURE; + break; + default: + errno = ERROR_INVALID_FUNCTION; + } + return NULL; + } + + return strdup(computername.c_str()); +} diff --git a/pool/shard006/C++/0083849_SdFatUtil.cpp b/pool/shard006/C++/0083849_SdFatUtil.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27b46bdc890b39aa3faec6e501e18a61908d2a12 --- /dev/null +++ b/pool/shard006/C++/0083849_SdFatUtil.cpp @@ -0,0 +1,74 @@ +/* Arduino SdFat Library + * Copyright (C) 2008 by William Greiman + * + * This file is part of the Arduino SdFat Library + * + * This Library is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This Library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + + * You should have received a copy of the GNU General Public License + * along with the Arduino SdFat Library. If not, see + * . + */ +#include +//------------------------------------------------------------------------------ +/** Amount of free RAM + * \return The number of free bytes. + */ +int SdFatUtil::FreeRam() { + extern int __bss_end; + extern int* __brkval; + int free_memory; + if (reinterpret_cast(__brkval) == 0) { + // if no heap use from end of bss section + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(&__bss_end); + } else { + // use from top of stack to heap + free_memory = reinterpret_cast(&free_memory) + - reinterpret_cast(__brkval); + } + return free_memory; +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory. + * + * \param[in] pr Print object for output. + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::print_P(Print* pr, PGM_P str) { + for (uint8_t c; (c = pgm_read_byte(str)); str++) pr->print(c); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory followed by a CR/LF. + * + * \param[in] pr Print object for output. + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::println_P(Print* pr, PGM_P str) { + print_P(pr, str); + pr->println(); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory to Serial. + * + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::SerialPrint_P(PGM_P str) { + print_P(&Serial, str); +} +//------------------------------------------------------------------------------ +/** %Print a string in flash memory to Serial followed by a CR/LF. + * + * \param[in] str Pointer to string stored in flash memory. + */ +void SdFatUtil::SerialPrintln_P(PGM_P str) { + println_P(&Serial, str); +} diff --git a/pool/shard006/C++/0083856_service_manager.cc b/pool/shard006/C++/0083856_service_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..1b0e800690f2a68e1cbd9b6f0abf22a85991b21a --- /dev/null +++ b/pool/shard006/C++/0083856_service_manager.cc @@ -0,0 +1,123 @@ +// This file is part of SWGANH which is released under the MIT license. +// See file LICENSE or go to http://swganh.com/LICENSE + +#include "service_manager.h" + +#include "anh/logger.h" + +#include +#include +#include + +#include "service_directory_interface.h" +#include "service_description.h" + +#ifndef WIN32 +#include +using boost::regex; +using boost::regex_search; +#else +#include +using std::regex; +using std::regex_search; +#endif + +using namespace swganh::service; +using namespace std; + +ServiceManager::ServiceManager(ServiceDirectoryInterface* service_directory) + : service_directory_(service_directory) +{} + +ServiceManager::~ServiceManager() +{ + auto it = services_.begin(); + for(it = services_.begin();it != services_.end();it++) + { + + service_directory_->removeService((it)->second->GetServiceDescription()); + } +} + +ServiceInterface* ServiceManager::GetService(string name) +{ + auto it = services_.find(name); + + if (it == services_.end()) + { + return nullptr; + } + + return it->second.get(); +} + +void ServiceManager::AddService(string name, shared_ptr service) +{ + auto current_service = GetService(name); + + if (current_service) + { + // throw exception here, service already exists + throw std::runtime_error("service already exists: " + name); + return; + } + + auto& service_description = service->GetServiceDescription(); + if (!service_directory_->registerService(service_description)) + { + throw std::runtime_error("Unable to register service " + service_description.name()); + } + + // update the status of the service + service_description.status(swganh::service::Galaxy::LOADING); + service_directory_->updateService(service_description); + + services_[name] = service; +} + +void ServiceManager::Start() +{ + // First pass initialization +//for (auto& service_entry : services_) + + auto it = services_.begin(); + for(it = services_.begin();it != services_.end();it++) + { + auto& service = it->second; + service->Initialize(); + } + + // After all resources are acquired services can be started + //for (auto& service_entry : services_) + //{ + it = services_.begin(); + for(it = services_.begin();it != services_.end();it++) + { + + auto& service = it->second; + + service->Startup(); + service->SetStatus(Galaxy::ONLINE); + + auto service_description = service->GetServiceDescription(); + service_directory_->updateService(service_description); + LOG(info) << "Started " << service_description.name(); + } +} + +void ServiceManager::Stop() +{ +//for (auto& service_entry : services_) + auto it = services_.begin(); + for(it = services_.begin();it != services_.end();it++) + { + auto& service = it->second; + + service->Shutdown(); + service->SetStatus(Galaxy::OFFLINE); + + auto service_description = service->GetServiceDescription(); + service_directory_->updateService(service_description); + LOG(info) << "Stopped " << service_description.name(); + } +} diff --git a/pool/shard006/C++/0083858_Pawn.cpp b/pool/shard006/C++/0083858_Pawn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e680b877c6e92976125356f2a2a266da36146cb1 --- /dev/null +++ b/pool/shard006/C++/0083858_Pawn.cpp @@ -0,0 +1,163 @@ +#include "Pawn.h" +#include "Board.h" + + + + +Pawn::Pawn(Coordinate coordinate) : hasYetToMove(true) +{ + symbol = ""; + this->coordinate = coordinate; + texture.loadFromFile("WhitePawn.png"); + setTexture(texture); + + + int row = (int)coordinate / 8; + int column = (int)coordinate % 8; + + //sf::RectangleShape::setPosition(sf::Vector2f(column * 50, 350 - row * 50)); + setPosition(sf::Vector2f(column * 50, 350 - row * 50)); + //setSize(sf::Vector2f(20, 20)); +} + +void Pawn::setCoordinate(const Coordinate position) +{ + Piece::setCoordinate(position); + hasYetToMove = false; +} + +void Pawn::setIsWhite(const bool isWhite) +{ + this->isWhite = isWhite; + + if (isWhite) + { + texture.loadFromFile("WhitePawn.png"); + } + else + { + texture.loadFromFile("BlackPawn.png"); + } + setTexture(texture); +} + + + +std::vector Pawn::computeMoves() +{ + //first clear past movablePositions + clearMoves(); + + //REQUIRES CHANGING TO ACCOUNT FOR and promotions. + + if (isWhite) + { + //capturing 1 up, 1 right piece + Coordinate upRight = CoordinateHelper::getCoordinateUpRight(coordinate); + + if (upRight != CoordinateHelper::getMostUpRightCoordinate(coordinate) || upRight != Coordinate::Invalid) + { + addCaptureMove(upRight); + } + + //capturing 1 up, 1 left piece + auto upLeft = CoordinateHelper::getCoordinateUpLeft(coordinate); + + if (upLeft != CoordinateHelper::getMostUpLeftCoordinate(coordinate) || upLeft != Coordinate::Invalid) + { + addCaptureMove(upLeft); + } + + auto oneUp = CoordinateHelper::getCoordinateUp(coordinate); + auto twoUp = CoordinateHelper::getCoordinateUp(oneUp); + + //moving + if (hasYetToMove) + { + if (board[oneUp].getPiece() != nullptr) + { + //don't add any positions to computePosition + } + else if (board[oneUp].getPiece() == nullptr && board[twoUp].getPiece() != nullptr) + { + moves.push_back(oneUp); + } + else if (board[oneUp].getPiece() == nullptr && board[twoUp].getPiece() == nullptr) + { + moves.push_back(oneUp); + moves.push_back(twoUp); + } + } + else + { + if (board[oneUp].getPiece() == nullptr) + { + moves.push_back(oneUp); + } + } + } + + else + { + //capturing 1 down, 1 right piece + auto downRight = CoordinateHelper::getCoordinateDownRight(coordinate); + + if (downRight != CoordinateHelper::getMostDownRightCoordinate(coordinate) || downRight != Coordinate::Invalid) + { + addCaptureMove(downRight); + } + + //capturing 1 down, 1 left piece + auto downLeft = CoordinateHelper::getCoordinateDownLeft(coordinate); + + if (downLeft != CoordinateHelper::getMostDownLeftCoordinate(coordinate) || downLeft != Coordinate::Invalid) + { + addCaptureMove(downLeft); + } + + auto oneDown = CoordinateHelper::getCoordinateDown(coordinate); + auto twoDown = CoordinateHelper::getCoordinateDown(oneDown); + + //moving + if (hasYetToMove) + { + if (board[oneDown].getPiece() != nullptr) + { + //don't add any positions to computePosition + } + else if (board[oneDown].getPiece() == nullptr && board[twoDown].getPiece() != nullptr) + { + moves.push_back(oneDown); + } + else if (board[oneDown].getPiece() == nullptr && board[twoDown].getPiece() == nullptr) + { + moves.push_back(oneDown); + moves.push_back(twoDown); + } + } + else + { + if (board[oneDown].getPiece() == nullptr) + { + moves.push_back(oneDown); + } + } + } + + return moves; +} + + +void Pawn::addCaptureMove(const Coordinate& coordinate) +{ + if (board[coordinate].getPiece() != nullptr) + { + if (board[coordinate].getPiece()->getIsWhite() != this->isWhite) + { + moves.push_back(coordinate); + + } + } +} + + diff --git a/pool/shard006/C++/0083862_capturerenderadapter.cc b/pool/shard006/C++/0083862_capturerenderadapter.cc new file mode 100644 index 0000000000000000000000000000000000000000..d7b3995d6e45f60d27d8e23a176857c6ed20cc13 --- /dev/null +++ b/pool/shard006/C++/0083862_capturerenderadapter.cc @@ -0,0 +1,135 @@ +/* + * libjingle + * Copyright 2012, Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "talk/media/base/capturerenderadapter.h" + +#include "talk/base/logging.h" +#include "talk/media/base/videocapturer.h" +#include "talk/media/base/videoprocessor.h" +#include "talk/media/base/videorenderer.h" + +namespace cricket { + +CaptureRenderAdapter::CaptureRenderAdapter(VideoCapturer* video_capturer) + : video_capturer_(video_capturer) { +} + +CaptureRenderAdapter::~CaptureRenderAdapter() { + // has_slots destructor will disconnect us from any signals we may be + // connected to. +} + +CaptureRenderAdapter* CaptureRenderAdapter::Create( + VideoCapturer* video_capturer) { + if (!video_capturer) { + return NULL; + } + CaptureRenderAdapter* return_value = new CaptureRenderAdapter(video_capturer); + return_value->Init(); // Can't fail. + return return_value; +} + +bool CaptureRenderAdapter::AddRenderer(VideoRenderer* video_renderer) { + if (!video_renderer) { + return false; + } + talk_base::CritScope cs(&capture_crit_); + if (IsRendererRegistered(*video_renderer)) { + return false; + } + video_renderers_.push_back(VideoRendererInfo(video_renderer)); + return true; +} + +bool CaptureRenderAdapter::RemoveRenderer(VideoRenderer* video_renderer) { + if (!video_renderer) { + return false; + } + talk_base::CritScope cs(&capture_crit_); + for (VideoRenderers::iterator iter = video_renderers_.begin(); + iter != video_renderers_.end(); ++iter) { + if (video_renderer == iter->renderer) { + video_renderers_.erase(iter); + return true; + } + } + return false; +} + +void CaptureRenderAdapter::Init() { + video_capturer_->SignalVideoFrame.connect( + this, + &CaptureRenderAdapter::OnVideoFrame); +} + +void CaptureRenderAdapter::OnVideoFrame(VideoCapturer* capturer, + const VideoFrame* video_frame) { + talk_base::CritScope cs(&capture_crit_); + if (video_renderers_.empty()) { + return; + } + MaybeSetRenderingSize(video_frame); + + for (VideoRenderers::iterator iter = video_renderers_.begin(); + iter != video_renderers_.end(); ++iter) { + VideoRenderer* video_renderer = iter->renderer; + video_renderer->RenderFrame(video_frame); + } +} + +// The renderer_crit_ lock needs to be taken when calling this function. +void CaptureRenderAdapter::MaybeSetRenderingSize(const VideoFrame* frame) { + for (VideoRenderers::iterator iter = video_renderers_.begin(); + iter != video_renderers_.end(); ++iter) { + const bool new_resolution = iter->render_width != frame->GetWidth() || + iter->render_height != frame->GetHeight(); + if (new_resolution) { + if (iter->renderer->SetSize(static_cast(frame->GetWidth()), + static_cast(frame->GetHeight()), 0)) { + iter->render_width = frame->GetWidth(); + iter->render_height = frame->GetHeight(); + } else { + LOG(LS_ERROR) << "Captured frame size not supported by renderer: " << + frame->GetWidth() << " x " << frame->GetHeight(); + } + } + } +} + +// The renderer_crit_ lock needs to be taken when calling this function. +bool CaptureRenderAdapter::IsRendererRegistered( + const VideoRenderer& video_renderer) const { + for (VideoRenderers::const_iterator iter = video_renderers_.begin(); + iter != video_renderers_.end(); ++iter) { + if (&video_renderer == iter->renderer) { + return true; + } + } + return false; +} + +} // namespace cricket diff --git a/pool/shard006/C++/0083870_main.cpp b/pool/shard006/C++/0083870_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db5fab51e1d3462f0caa086a4d8db064cbaf168d --- /dev/null +++ b/pool/shard006/C++/0083870_main.cpp @@ -0,0 +1,42 @@ +// +// main.cpp +// Q1046 +// +// Created by Pumpkin Lee on 1/29/14. +// Copyright (c) 2014 Pumpkin Lee. All rights reserved. +// + +#include + +using namespace std; + +int main(int argc, const char * argv[]) +{ + int n; + scanf("%d", &n); + + long *distance = new long[n + 1]; + distance[0] = 0; + for (int i = 1; i <= n; ++i) { + int d; + scanf("%d", &d); + distance[i] = d + distance[i - 1]; + } + + int nQuery; + scanf("%d", &nQuery); + for (int i = 0; i < nQuery; ++i) { + int src, dst; + scanf("%d %d", &src, &dst); + + long dist = abs(distance[dst - 1] - distance[src - 1]); + printf("%ld\n", min(dist, distance[n] - dist)); + } + + delete [] distance; + + return 0; +} + +// 时间要求严格 +// 必需预计算所有距离 diff --git a/pool/shard006/C++/0083884_AMRAudioRTPSink.cpp b/pool/shard006/C++/0083884_AMRAudioRTPSink.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01999dfbfa08845bf7a6b2eb423f1f1c146bc388 --- /dev/null +++ b/pool/shard006/C++/0083884_AMRAudioRTPSink.cpp @@ -0,0 +1,134 @@ +/********** +This library is free software; you can redistribute it and/or modify it under +the terms of the GNU Lesser General Public License as published by the +Free Software Foundation; either version 3 of the License, or (at your +option) any later version. (See .) + +This library 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 Lesser General Public License for +more details. + +You should have received a copy of the GNU Lesser General Public License +along with this library; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +**********/ +// "liveMedia" +// Copyright (c) 1996-2022 Live Networks, Inc. All rights reserved. +// RTP sink for AMR audio (RFC 4867) +// Implementation + +// NOTE: At present, this is just a limited implementation, supporting: +// octet-alignment only; no interleaving; no frame CRC; no robust-sorting. + +#include "AMRAudioRTPSink.hh" +#include "AMRAudioSource.hh" + +AMRAudioRTPSink* +AMRAudioRTPSink::createNew(UsageEnvironment& env, Groupsock* RTPgs, + unsigned char rtpPayloadFormat, + Boolean sourceIsWideband, + unsigned numChannelsInSource) { + return new AMRAudioRTPSink(env, RTPgs, rtpPayloadFormat, + sourceIsWideband, numChannelsInSource); +} + +AMRAudioRTPSink +::AMRAudioRTPSink(UsageEnvironment& env, Groupsock* RTPgs, + unsigned char rtpPayloadFormat, + Boolean sourceIsWideband, unsigned numChannelsInSource) + : AudioRTPSink(env, RTPgs, rtpPayloadFormat, + sourceIsWideband ? 16000 : 8000, + sourceIsWideband ? "AMR-WB": "AMR", + numChannelsInSource), + fSourceIsWideband(sourceIsWideband), fFmtpSDPLine(NULL) { +} + +AMRAudioRTPSink::~AMRAudioRTPSink() { + delete[] fFmtpSDPLine; +} + +Boolean AMRAudioRTPSink::sourceIsCompatibleWithUs(MediaSource& source) { + // Our source must be an AMR audio source: + if (!source.isAMRAudioSource()) return False; + + // Also, the source must be wideband iff we asked for this: + AMRAudioSource& amrSource = (AMRAudioSource&)source; + if ((amrSource.isWideband()^fSourceIsWideband) != 0) return False; + + // Also, the source must have the same number of channels that we + // specified. (It could, in principle, have more, but we don't + // support that.) + if (amrSource.numChannels() != numChannels()) return False; + + // Also, because in our current implementation we output only one + // frame in each RTP packet, this means that for multi-channel audio, + // each 'frame-block' will be split over multiple RTP packets, which + // may violate the spec. Warn about this: + if (amrSource.numChannels() > 1) { + envir() << "AMRAudioRTPSink: Warning: Input source has " << amrSource.numChannels() + << " audio channels. In the current implementation, the multi-frame frame-block will be split over multiple RTP packets\n"; + } + + return True; +} + +void AMRAudioRTPSink::doSpecialFrameHandling(unsigned fragmentationOffset, + unsigned char* frameStart, + unsigned numBytesInFrame, + struct timeval framePresentationTime, + unsigned numRemainingBytes) { + // If this is the 1st frame in the 1st packet, set the RTP 'M' (marker) + // bit (because this is considered the start of a talk spurt): + if (isFirstPacket() && isFirstFrameInPacket()) { + setMarkerBit(); + } + + // If this is the first frame in the packet, set the 1-byte payload + // header (using CMR 15) + if (isFirstFrameInPacket()) { + u_int8_t payloadHeader = 0xF0; + setSpecialHeaderBytes(&payloadHeader, 1, 0); + } + + // Set the TOC field for the current frame, based on the "FT" and "Q" + // values from our source: + AMRAudioSource* amrSource = (AMRAudioSource*)fSource; + if (amrSource == NULL) return; // sanity check + + u_int8_t toc = amrSource->lastFrameHeader(); + // Clear the "F" bit, because we're the last frame in this packet: ##### + toc &=~ 0x80; + setSpecialHeaderBytes(&toc, 1, 1+numFramesUsedSoFar()); + + // Important: Also call our base class's doSpecialFrameHandling(), + // to set the packet's timestamp: + MultiFramedRTPSink::doSpecialFrameHandling(fragmentationOffset, + frameStart, numBytesInFrame, + framePresentationTime, + numRemainingBytes); +} + +Boolean AMRAudioRTPSink +::frameCanAppearAfterPacketStart(unsigned char const* /*frameStart*/, + unsigned /*numBytesInFrame*/) const { + // For now, pack only one AMR frame into each outgoing RTP packet: ##### + return False; +} + +unsigned AMRAudioRTPSink::specialHeaderSize() const { + // For now, because we're packing only one frame per packet, + // there's just a 1-byte payload header, plus a 1-byte TOC ##### + return 2; +} + +char const* AMRAudioRTPSink::auxSDPLine() { + if (fFmtpSDPLine == NULL) { + // Generate a "a=fmtp:" line with "octet-aligned=1" + // (That is the only non-default parameter.) + char buf[100]; + sprintf(buf, "a=fmtp:%d octet-align=1\r\n", rtpPayloadType()); + delete[] fFmtpSDPLine; fFmtpSDPLine = strDup(buf); + } + return fFmtpSDPLine; +} diff --git a/pool/shard006/C++/0083890_apdft.cc b/pool/shard006/C++/0083890_apdft.cc new file mode 100644 index 0000000000000000000000000000000000000000..4a844aa60664c9c07e9fb0514da32bb83d64d905 --- /dev/null +++ b/pool/shard006/C++/0083890_apdft.cc @@ -0,0 +1,71 @@ +/* + * Copyright 2009-2020 The VOTCA Development Team (http://www.votca.org) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +// Standard includes +#include + +// Local VOTCA includes +#include "votca/xtp/density_integration.h" +#include "votca/xtp/orbitals.h" +#include "votca/xtp/vxc_grid.h" + +// Local private VOTCA includes +#include "apdft.h" + +namespace votca { +namespace xtp { + +void APDFT::ParseOptions(const tools::Property &options) { + + grid_accuracy_ = options.get(".grid").as(); + orbfile_ = options.ifExistsReturnElseReturnDefault( + ".input", job_name_ + ".orb"); + outputfile_ = options.ifExistsReturnElseReturnDefault( + ".output", job_name_ + "_state.dat"); + state_ = options.get(".state").as(); +} + +bool APDFT::Run() { + + Orbitals orb; + orb.ReadFromCpt(orbfile_); + AOBasis basis = orb.SetupDftBasis(); + Vxc_Grid grid; + grid.GridSetup(grid_accuracy_, orb.QMAtoms(), basis); + + DensityIntegration integration(grid); + + integration.IntegrateDensity(orb.DensityMatrixFull(state_)); + std::vector potential_values; + potential_values.reserve(orb.QMAtoms().size()); + for (const auto &atom : orb.QMAtoms()) { + potential_values.push_back(integration.IntegratePotential(atom.getPos())); + } + + std::fstream outfile; + outfile.open(outputfile_, std::fstream::out); + outfile << "AtomId, Element, Potential[Hartree]" << std::endl; + for (Index i = 0; i < orb.QMAtoms().size(); i++) { + outfile << orb.QMAtoms()[i].getId() << " " << orb.QMAtoms()[i].getElement() + << " " << std::setprecision(14) << potential_values[i] << std::endl; + } + outfile.close(); + return true; +} + +} // namespace xtp +} // namespace votca diff --git a/pool/shard006/C++/0083891_TerrainToolAutoBindingResolver.cpp b/pool/shard006/C++/0083891_TerrainToolAutoBindingResolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84f92d22acc37de4fb8616a0c5e16ad17f4ee0aa --- /dev/null +++ b/pool/shard006/C++/0083891_TerrainToolAutoBindingResolver.cpp @@ -0,0 +1,73 @@ +/* + Terrain Tool - Interactive terrain editor. + Copyright (C) 2014 Damyon Wiese + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "TerrainToolAutoBindingResolver.h" + + +TerrainToolAutoBindingResolver::TerrainToolAutoBindingResolver() + : _light(NULL) +{ + +} + +void TerrainToolAutoBindingResolver::setLight(Light* light) +{ + if (_light) { + SAFE_RELEASE(_light); + } + light->addRef(); + _light = light; +} + +TerrainToolAutoBindingResolver::~TerrainToolAutoBindingResolver() +{ + SAFE_RELEASE(_light); +} + +bool TerrainToolAutoBindingResolver::resolveAutoBinding(const char* autoBinding, Node* node, MaterialParameter* parameter) +{ + if (strcmp(autoBinding, "LIGHT_DIRECTION_0") == 0) + { + parameter->bindValue(this, &TerrainToolAutoBindingResolver::getLightDirection0); + return true; + } + else if (strcmp(autoBinding, "LIGHT_COLOR_0") == 0) + { + parameter->bindValue(this, &TerrainToolAutoBindingResolver::getLightColor0); + return true; + } + + return false; +} + + +Vector3 TerrainToolAutoBindingResolver::getLightColor0() const +{ + if (_light) { + return _light->getColor(); + } + return Vector3::one(); +} + +Vector3 TerrainToolAutoBindingResolver::getLightDirection0() const +{ + if (_light) { + return _light->getNode()->getForwardVectorView(); + } + return Vector3::one(); +} diff --git a/pool/shard006/C++/0083893_easy_remove_linked_list_elements.cpp b/pool/shard006/C++/0083893_easy_remove_linked_list_elements.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cd50ff3e50f664473003bf2b04119be0d7655d6 --- /dev/null +++ b/pool/shard006/C++/0083893_easy_remove_linked_list_elements.cpp @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +class mytimer +{ +private: + time_t start_; +public: + mytimer() + { + start_ = time(NULL); + } + ~mytimer() + { + time_t end = time(NULL); + cout << end - start_ << "s" << endl; + } +}; + +struct ListNode { + int val; + ListNode *next; + ListNode(int x) : val(x), next(NULL) {} +}; + +class Solution { + public: + ListNode* removeElements(ListNode* head, int val) { + ListNode* c = head; + ListNode* p = NULL; + while (c) + { + if (c->val == val) + { + if (p == NULL) // head + { + head = c->next; + delete c; + c = head; + } + else + { + p->next = c->next; + delete c; + c = p->next; + } + } + else + { + p = c; + c = c->next; + } + } + return head; + } +}; +/* a cool solution +class Solution { + public: + ListNode* removeElements(ListNode* head, int val) { + auto pp = &head; + while (*pp) { + if ((*pp)->val == val) { + *pp = (*pp)->next; + } + else { + pp = &((*pp)->next); + } + } + return head; + } +}; +*/ +int main() +{ + Solution s; + + { + + } + + std::cin.get(); + + return 0; +} + diff --git a/pool/shard006/C++/0083895_test_tetengo2.iterator.observable_forward_iterator.cpp b/pool/shard006/C++/0083895_test_tetengo2.iterator.observable_forward_iterator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4ca2bf32f8c80af4b495fc6026c6a740837d2784 --- /dev/null +++ b/pool/shard006/C++/0083895_test_tetengo2.iterator.observable_forward_iterator.cpp @@ -0,0 +1,189 @@ +/*! \file + \brief Test of class tetengo2::iterator::observable_forward_iterator. + + Copyright (C) 2007-2019 kaoru + + $Id$ +*/ + +#include +#include + +#include +#include +#include + +#include + + +BOOST_AUTO_TEST_SUITE(test_tetengo2) + BOOST_AUTO_TEST_SUITE(iterator) + BOOST_AUTO_TEST_SUITE(observable_forward_iterator) + // test cases + + BOOST_AUTO_TEST_CASE(construction) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + const tetengo2::iterator::observable_forward_iterator::iterator> iterator{ + list.begin() + }; + } + + BOOST_AUTO_TEST_CASE(dereference) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + tetengo2::iterator::observable_forward_iterator::iterator> iterator{ + list.begin() + }; + + BOOST_TEST(*iterator == 42); + + *iterator = 24; + + BOOST_TEST(list.front() == 24); + } + + BOOST_AUTO_TEST_CASE(equal) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + const tetengo2::iterator::observable_forward_iterator::iterator> iterator1{ + list.begin() + }; + const tetengo2::iterator::observable_forward_iterator::iterator> iterator2{ + list.begin() + }; + + BOOST_CHECK(iterator1 == iterator2); + } + + BOOST_AUTO_TEST_CASE(increment) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + tetengo2::iterator::observable_forward_iterator::iterator> iterator{ + list.begin() + }; + + ++iterator; + + BOOST_TEST(*iterator == 43); + + ++iterator; + ++iterator; + ++iterator; + + const tetengo2::iterator::observable_forward_iterator::iterator> last{ + list.end() + }; + BOOST_CHECK(iterator == last); + } + + BOOST_AUTO_TEST_CASE(distance_to) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + const tetengo2::iterator::observable_forward_iterator::iterator> iterator1{ + list.begin() + }; + const tetengo2::iterator::observable_forward_iterator::iterator> iterator2{ + list.end() + }; + + BOOST_TEST(iterator1.distance_to(iterator1) == 0); + BOOST_TEST(iterator1.distance_to(iterator2) == 4); + } + + BOOST_AUTO_TEST_CASE(set_increment_observer) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + tetengo2::iterator::observable_forward_iterator::iterator> iterator{ + list.begin() + }; + + int count = 0; + iterator.set_increment_observer( + [&count](const tetengo2::iterator::observable_forward_iterator::iterator>&) { + ++count; + }); + + ++iterator; + + BOOST_TEST(count == 1); + + ++iterator; + ++iterator; + ++iterator; + + BOOST_TEST(count == 4); + } + + + BOOST_AUTO_TEST_SUITE_END() + + + BOOST_AUTO_TEST_CASE(make_observable_forward_iterator) + { + BOOST_TEST_PASSPOINT(); + + std::forward_list list{ + 42, + 43, + 44, + 45, + }; + + const auto iterator = + tetengo2::iterator::make_observable_forward_iterator::iterator>(list.begin()); + + BOOST_TEST(*iterator == 42); + } + + + BOOST_AUTO_TEST_SUITE_END() +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard006/C++/0083900_addbook.cpp b/pool/shard006/C++/0083900_addbook.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e72bdb15bf6c282f6ebc973bc4ed3fbb0d123c0 --- /dev/null +++ b/pool/shard006/C++/0083900_addbook.cpp @@ -0,0 +1,62 @@ +#include "addbook.h" +#include "ui_addbook.h" + +#include +#include + +AddBook::AddBook(QWidget *parent) : QDialog(parent), ui(new Ui::AddBook){ + ui->setupUi(this); + + insEditBook = new EditBook; + insSiteManager = new SiteManager; + insSettingsManager = new SettingsManager; + + connect(ui->pushButton_cancel, SIGNAL(clicked()), this, SLOT(emitClose())); + + //Si c'est des films, on change + if(insSettingsManager->getSettings(Type).toString() == "films"){ + ui->labelTitre->setText("Ajouter un nouveau film"); + ui->lineEdit_recherche->setText("Titre, acteur, directeur"); + ui->buttonManuel->setText("Ajouter manuellement un film"); + ui->comboBox_recherche->addItems(insSiteManager->getPluginList("films")); + } + else{ + //Ajout des sites disponibles + ui->comboBox_recherche->addItems(insSiteManager->getPluginList()); + } + ui->comboBoxLangue->addItems(insSiteManager->getLanguePlugins()); + this->setModal(true); +} + +AddBook::~AddBook(){ + delete ui; + delete insEditBook; + delete insSiteManager; + delete insSettingsManager; +} + +void AddBook::addInternetBook(){ + if(ui->lineEdit_recherche->text().isEmpty()){ + QMessageBox::warning(this, tr("Chaîne vide"), tr("Impossible de démarrer la recherche, vous n'avez spécifié aucun terme")); + return; + } + if(ui->comboBox_recherche->currentText().isEmpty()){ + QMessageBox::warning(this, tr("Pas de site"), tr("Vous n'avez spécifié aucun site sur lequel effectuer la recherche")); + return; + } + //Si on est ici, c'est que tout est OK. + emit searchInternet(ui->lineEdit_recherche->text(), ui->comboBox_recherche->currentText(), ((ui->checkBoxLangue->isChecked()) ? ui->comboBoxLangue->currentText() : "")); +} + +void AddBook::addManualBook(){ + insEditBook->setManual(); + insEditBook->show(); + this->close(); + return; +} + +void AddBook::emitClose(){ + emit canceled(); + this->close(); + return; +} diff --git a/pool/shard006/C++/0083905_MachineLearning_Data.cpp b/pool/shard006/C++/0083905_MachineLearning_Data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e22a5fef7c62138af3c84294b89e7a5da5006bb3 --- /dev/null +++ b/pool/shard006/C++/0083905_MachineLearning_Data.cpp @@ -0,0 +1,85 @@ +#include "MachineLearning_Data.h" + +#include +#include +#include + + +namespace MachineLearning +{ + + +template +Data::Data (T class_, T score_, std::string tag_) : +mClass(class_), mScore(score_), mTag(tag_) +{ + ; +} + + +template +Data::~Data (void) +{ + ; +} + + +template +int Data::getMinIndexOfElement (void) const +{ + assert(size() != 0); + + int idx = INT_MAX; + for (unsigned int i=0; isize(); i++) + if (this->at(i).getIndex() < idx) idx = this->at(i).getIndex(); + + return idx; +} + + +template +int Data::getMaxIndexOfElement (void) const +{ + assert(size() != 0); + + int idx = INT_MIN; + for (unsigned int i=0; isize(); i++) + if (idx < this->at(i).getIndex()) idx = this->at(i).getIndex(); + + return idx; +} + + +template +T Data::getMinValueOfElement (void) const +{ + assert(size() != 0); + + T val = FLT_MAX; + for (unsigned int i=0; isize(); i++) + if (this->at(i).getValue() < val) val = this->at(i).getValue(); + + return val; +} + + +template +T Data::getMaxValueOfElement (void) const +{ + assert(size() != 0); + + T val = FLT_MIN; + for (unsigned int i=0; isize(); i++) + if (val < this->at(i).getValue()) val = this->at(i).getValue(); + + return val; +} + + +// Explicit Instantiation +template class Data; +template class Data; + + +} // namespace MachineLearning + diff --git a/pool/shard006/C++/0083912_VulkanAsset.cpp b/pool/shard006/C++/0083912_VulkanAsset.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c1d0be17f666ab15bc23be196092d17715e4c2fa --- /dev/null +++ b/pool/shard006/C++/0083912_VulkanAsset.cpp @@ -0,0 +1,79 @@ +/** + * Copyright (c) 2021 Darius Rückert + * Licensed under the MIT License. + * See LICENSE file for more information. + */ + +#include "VulkanAsset.h" + +#include "saiga/core/image/imageTransformations.h" +#include "saiga/vulkan/Shader/all.h" +#include "saiga/vulkan/Vertex.h" + +namespace Saiga +{ +namespace Vulkan +{ +void VulkanVertexColoredAsset::init(Saiga::Vulkan::VulkanBase& base) +{ + auto indices = getIndexList(); + + vertexBuffer.init(base, vertices.size(), vk::MemoryPropertyFlagBits::eDeviceLocal); + indexBuffer.init(base, indices.size(), vk::MemoryPropertyFlagBits::eDeviceLocal); + + vertexBuffer.stagedUpload(base, vertices.size() * sizeof(VertexType), vertices.data()); + indexBuffer.stagedUpload(base, indices.size() * sizeof(uint32_t), indices.data()); +} + + +void VulkanVertexColoredAsset::render(vk::CommandBuffer cmd) +{ + // if(!vertexBuffer.m_memoryLocation.buffer) return; + vertexBuffer.bind(cmd); + indexBuffer.bind(cmd); + indexBuffer.draw(cmd); +} + +void VulkanLineVertexColoredAsset::init(VulkanBase& base) +{ + auto lines = mesh.toLineList(); + auto newSize = lines.size(); + auto size = newSize * sizeof(VertexType); + vertexBuffer.init(base, newSize, vk::MemoryPropertyFlagBits::eDeviceLocal); + + + vertexBuffer.stagedUpload(base, size, lines.data()); +} + +void VulkanLineVertexColoredAsset::render(vk::CommandBuffer cmd) +{ + vertexBuffer.bind(cmd); + vertexBuffer.draw(cmd); +} + + + +void VulkanPointCloudAsset::init(VulkanBase& base, int _capacity) +{ + capacity = _capacity; + vertexBuffer.init(base, capacity, vk::MemoryPropertyFlagBits::eDeviceLocal); + stagingBuffer.init(base, capacity * sizeof(VertexType)); + pointCloud = ArrayView((VertexType*)stagingBuffer.getMappedPointer(), capacity); +} + +void VulkanPointCloudAsset::render(vk::CommandBuffer cmd, int start, int count) +{ + vertexBuffer.bind(cmd); + vertexBuffer.draw(cmd, count < 0 ? size : count, start); +} + +void VulkanPointCloudAsset::updateBuffer(vk::CommandBuffer cmd, int start, int count) +{ + stagingBuffer.copyTo(cmd, vertexBuffer, start * sizeof(VertexType), start * sizeof(VertexType), + (count < 0 ? size : count) * sizeof(VertexType)); +} + + + +} // namespace Vulkan +} // namespace Saiga diff --git a/pool/shard006/C++/0083913_OlaClientTester.cpp b/pool/shard006/C++/0083913_OlaClientTester.cpp new file mode 100644 index 0000000000000000000000000000000000000000..79d73085898ea483d4cc6c961b047e59ff7af4de --- /dev/null +++ b/pool/shard006/C++/0083913_OlaClientTester.cpp @@ -0,0 +1,35 @@ +/* + * 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 Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * OlaClientTester.cpp + * Runs all the Ola Client tests + * Copyright (C) 2005-2010 Simon Newton + */ + +#include +#include +#include + +int main(int argc, char* argv[]) { + CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest(); + CppUnit::TextUi::TestRunner runner; + runner.addTest(suite); + runner.setOutputter( + new CppUnit::CompilerOutputter(&runner.result(), std::cerr)); + bool wasSucessful = runner.run(); + return wasSucessful ? 0 : 1; + (void) argc; + (void) argv; +} diff --git a/pool/shard006/C++/0083916_cachemultimap_tests.cpp b/pool/shard006/C++/0083916_cachemultimap_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d287600688b78f1ba4009767147a6f7ed8e6f199 --- /dev/null +++ b/pool/shard006/C++/0083916_cachemultimap_tests.cpp @@ -0,0 +1,176 @@ +// Copyright (c) 2014-2017 The DiggCoin Core developers + +#include "cachemultimap.h" + +#include "test/test_diggcoin.h" + +#include +#include + +#include + +BOOST_FIXTURE_TEST_SUITE(cachemultimap_tests, BasicTestingSetup) + +void DumpMap(const CacheMultiMap& map) +{ + const CacheMultiMap::list_t& listItems = map.GetItemList(); + for(CacheMultiMap::list_cit it = listItems.begin(); it != listItems.end(); ++it) { + const CacheItem& item = *it; + std::cout << item.key << " : " << item.value << std::endl; + } +} + +bool Compare(const CacheMultiMap& map1, const CacheMultiMap& map2 ) +{ + if(map1.GetMaxSize() != map2.GetMaxSize()) { + std::cout << "Compare returning false: max size mismatch" << std::endl; + return false; + } + + if(map1.GetSize() != map2.GetSize()) { + std::cout << "Compare returning false: size mismatch" << std::endl; + return false; + } + + const CacheMultiMap::list_t& items1 = map1.GetItemList(); + const CacheMultiMap::list_t& items2 = map2.GetItemList(); + CacheMultiMap::list_cit it2 = items2.begin(); + for(CacheMultiMap::list_cit it1 = items1.begin(); it1 != items1.end(); ++it1) { + const CacheItem& item1 = *it1; + const CacheItem& item2 = *it2; + if(item1.key != item2.key) { + return false; + } + if(item1.value != item2.value) { + return false; + } + ++it2; + } + + return true; +} + +bool CheckExpected(const CacheMultiMap& map, int* expected, CacheMultiMap::size_type nSize) +{ + if(map.GetSize() != nSize) { + return false; + } + for(CacheMultiMap::size_type i = 0; i < nSize; ++i) { + int nVal = 0; + int eVal = expected[i]; + if(!map.Get(eVal, nVal)) { + return false; + } + if(nVal != eVal) { + return false; + } + } + return true; +} + +BOOST_AUTO_TEST_CASE(cachemultimap_test) +{ + // create a CacheMultiMap limited to 10 items + CacheMultiMap mapTest1(10); + + // check that the max size is 10 + BOOST_CHECK(mapTest1.GetMaxSize() == 10); + + // check that the size is 0 + BOOST_CHECK(mapTest1.GetSize() == 0); + + // insert (-1, -1) + mapTest1.Insert(-1, -1); + + // make sure that the size is updated + BOOST_CHECK(mapTest1.GetSize() == 1); + + // make sure the map contains the key + BOOST_CHECK(mapTest1.HasKey(-1) == true); + + // add 10 items + for(int i = 0; i < 10; ++i) { + mapTest1.Insert(i, i); + } + + // check that the size is 10 + BOOST_CHECK(mapTest1.GetSize() == 10); + + // check that the map contains the expected items + for(int i = 0; i < 10; ++i) { + int nVal = 0; + BOOST_CHECK(mapTest1.Get(i, nVal) == true); + BOOST_CHECK(nVal == i); + } + + // check that the map no longer contains the first item + BOOST_CHECK(mapTest1.HasKey(-1) == false); + + // erase an item + mapTest1.Erase(5); + + // check the size + BOOST_CHECK(mapTest1.GetSize() == 9); + + // check that the map no longer contains the item + BOOST_CHECK(mapTest1.HasKey(5) == false); + + // check that the map contains the expected items + int expected[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 }; + BOOST_CHECK(CheckExpected(mapTest1, expected, 9 ) == true); + + // add multiple items for the same key + mapTest1.Insert(5, 2); + mapTest1.Insert(5, 1); + mapTest1.Insert(5, 4); + + // check the size + BOOST_CHECK(mapTest1.GetSize() == 10); + + // check that 2 keys have been removed + BOOST_CHECK(mapTest1.HasKey(0) == false); + BOOST_CHECK(mapTest1.HasKey(1) == false); + BOOST_CHECK(mapTest1.HasKey(2) == true); + + // check multiple values + std::vector vecVals; + BOOST_CHECK(mapTest1.GetAll(5, vecVals) == true); + BOOST_CHECK(vecVals.size() == 3); + BOOST_CHECK(vecVals[0] == 1); + BOOST_CHECK(vecVals[1] == 2); + BOOST_CHECK(vecVals[2] == 4); + +// std::cout << "mapTest1 dump:" << std::endl; +// DumpMap(mapTest1); + + // test serialization + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss << mapTest1; + + CacheMultiMap mapTest2; + ss >> mapTest2; + +// std::cout << "mapTest2 dump:" << std::endl; +// DumpMap(mapTest2); + + // check multiple values + std::vector vecVals2; + BOOST_CHECK(mapTest2.GetAll(5, vecVals2) == true); + BOOST_CHECK(vecVals2.size() == 3); + BOOST_CHECK(vecVals2[0] == 1); + BOOST_CHECK(vecVals2[1] == 2); + BOOST_CHECK(vecVals2[2] == 4); + + BOOST_CHECK(Compare(mapTest1, mapTest2)); + + // test copy constructor + CacheMultiMap mapTest3(mapTest1); + BOOST_CHECK(Compare(mapTest1, mapTest3)); + + // test assignment operator + CacheMultiMap mapTest4; + mapTest4 = mapTest1; + BOOST_CHECK(Compare(mapTest1, mapTest4)); +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard006/C++/0083917_DevianceTrace.cc b/pool/shard006/C++/0083917_DevianceTrace.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c020344ae857294d71f4fc508ddd8d83da61242 --- /dev/null +++ b/pool/shard006/C++/0083917_DevianceTrace.cc @@ -0,0 +1,68 @@ +#include "DevianceTrace.h" + +#include + +#include + +using std::vector; +using std::string; +using std::copy; + +static vector toNode(vector const &nodes) +{ + vector ans(nodes.size()); + for (unsigned int i = 0; i < nodes.size(); ++i) { + ans[i] = nodes[i]; + } + return ans; +} + +namespace dic { + + DevianceTrace::DevianceTrace(vector const & + snodes) + : Monitor("trace", toNode(snodes)), _values(snodes[0]->nchain()), + _snodes(snodes) + { + } + + vector DevianceTrace::dim() const + { + return vector(1,1); + } + + vector const &DevianceTrace::value(unsigned int chain) const + { + return _values[chain]; + } + + void DevianceTrace::update() + { + unsigned int nchain = _snodes[0]->nchain(); + for (unsigned int ch = 0; ch < nchain; ++ch) { + double loglik = 0; + for (unsigned int i = 0; i < _snodes.size(); ++i) { + loglik += _snodes[i]->logDensity(ch, PDF_FULL); + } + _values[ch].push_back(-2 * loglik); + } + } + + void DevianceTrace::reserve(unsigned int niter) + { + for (unsigned int ch = 0; ch < _values.size(); ++ch) { + _values[ch].reserve(_values[ch].size() + niter); + } + } + + bool DevianceTrace::poolChains() const + { + return false; + } + + bool DevianceTrace::poolIterations() const + { + return false; + } + +} diff --git a/pool/shard006/C++/0083921_fix2tfpose.cpp b/pool/shard006/C++/0083921_fix2tfpose.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6861a5e3549993d8bf0c281dedc26c0463165d68 --- /dev/null +++ b/pool/shard006/C++/0083921_fix2tfpose.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2015, Nagoya University + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of Autoware nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "geo_pos_conv.hh" + +static ros::Publisher pose_publisher; + +static ros::Publisher stat_publisher; +static std_msgs::Bool gnss_stat_msg; + +static geometry_msgs::PoseStamped _prev_pose; +static geometry_msgs::Quaternion _quat; +static double yaw; + +static void GNSSCallback(const sensor_msgs::NavSatFixConstPtr &msg) +{ + geo_pos_conv geo; + + geo.set_plane(7); + geo.llh_to_xyz(msg->latitude, msg->longitude, msg->altitude); + + static tf::TransformBroadcaster pose_broadcaster; + tf::Transform pose_transform; + tf::Quaternion pose_q; + + geometry_msgs::PoseStamped pose; + pose.header = msg->header; + // pose.header.stamp = ros::Time::now(); + pose.header.frame_id = "map"; + pose.pose.position.x = geo.y(); + pose.pose.position.y = geo.x(); + pose.pose.position.z = geo.z(); + + // set gnss_stat + if(pose.pose.position.x == 0.0 || pose.pose.position.y == 0.0 || pose.pose.position.z == 0.0){ + gnss_stat_msg.data = false; + } else{ + gnss_stat_msg.data = true; + } + + double distance = sqrt( + pow(pose.pose.position.y - _prev_pose.pose.position.y, 2) + + pow(pose.pose.position.x - _prev_pose.pose.position.x, + 2)); + std::cout << "distance : " << distance << std::endl; + + if (distance > 0.2) { + yaw = atan2(pose.pose.position.y - _prev_pose.pose.position.y, + pose.pose.position.x - _prev_pose.pose.position.x); + _quat = tf::createQuaternionMsgFromYaw(yaw); + _prev_pose = pose; + } + + pose.pose.orientation = _quat; + pose_publisher.publish(pose); + stat_publisher.publish(gnss_stat_msg); + + //座標変換 + static tf::TransformBroadcaster br; + tf::Transform transform; + tf::Quaternion q; + transform.setOrigin( + tf::Vector3(pose.pose.position.x, pose.pose.position.y, + pose.pose.position.z)); + q.setRPY(0, 0, yaw); + transform.setRotation(q); + br.sendTransform( + tf::StampedTransform(transform, msg->header.stamp, "map", + "gps")); +} + +int main(int argc, char **argv) +{ + ros::init(argc, argv, "gnss_pos"); + ros::NodeHandle nh; + pose_publisher = nh.advertise("gnss_pose", + 1000); + stat_publisher = nh.advertise("/gnss_stat", 1000); + ros::Subscriber gnss_pose_subscriber = nh.subscribe("fix", 100, + GNSSCallback); + + ros::spin(); + return 0; +} diff --git a/pool/shard006/C++/0083928_MaterialItemContainer.cpp b/pool/shard006/C++/0083928_MaterialItemContainer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3eef24aa3af6b1e19fb2de80c68eeda05c396b38 --- /dev/null +++ b/pool/shard006/C++/0083928_MaterialItemContainer.cpp @@ -0,0 +1,52 @@ +// ************************************************************************************************ +// +// BornAgain: simulate and fit reflection and scattering +// +//! @file GUI/coregui/Models/MaterialItemContainer.cpp +//! @brief Implements class MaterialItemContainer +//! +//! @homepage http://www.bornagainproject.org +//! @license GNU General Public License v3 or higher (see COPYING) +//! @copyright Forschungszentrum Jülich GmbH 2018 +//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) +// +// ************************************************************************************************ + +#include "GUI/coregui/Models/MaterialItemContainer.h" +#include "GUI/coregui/Models/MaterialItem.h" +#include "GUI/coregui/Models/SessionModel.h" +#include "GUI/coregui/utils/GUIHelpers.h" + +const QString MaterialItemContainer::T_MATERIALS = "MaterialVector"; + +MaterialItemContainer::MaterialItemContainer() : SessionItem("MaterialContainer") +{ + setItemName("Materials"); + registerTag(T_MATERIALS, 0, -1, QStringList{"Material"}); +} + +MaterialItem* MaterialItemContainer::insertCopy(MaterialItem* material_item) +{ + MaterialItem* item_copy = + dynamic_cast(model()->copyItem(material_item, this, T_MATERIALS)); + item_copy->setItemValue(MaterialItem::P_IDENTIFIER, GUIHelpers::createUuid()); + + return item_copy; +} + +MaterialItem* MaterialItemContainer::findMaterialById(QString id) +{ + return const_cast( + static_cast(this)->findMaterialById(id)); +} + +const MaterialItem* MaterialItemContainer::findMaterialById(QString id) const +{ + auto materials = getItems(T_MATERIALS); + for (auto item : materials) { + auto material = dynamic_cast(item); + if (material->identifier() == id) + return material; + } + return nullptr; +} diff --git a/pool/shard006/C++/0083929_config_adapter.cpp b/pool/shard006/C++/0083929_config_adapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb65fc3f11b2ea59d1d6d7b801ddd73a3ab3b414 --- /dev/null +++ b/pool/shard006/C++/0083929_config_adapter.cpp @@ -0,0 +1,83 @@ +#include + +#include "config_adapter.h" +#include "Emu/system_config.h" + +LOG_CHANNEL(cfg_log, "CFG"); + +// Helper methods to interact with YAML and the config settings. +namespace cfg_adapter +{ + static cfg::_base& get_cfg(cfg::_base& root, const std::string& name) + { + if (root.get_type() == cfg::type::node) + { + for (const auto& node : static_cast(root).get_nodes()) + { + if (node->get_name() == name) + { + return *node; + } + } + } + + fmt::throw_exception("Node not found: %s", name); + } + + static cfg::_base& get_cfg(cfg::_base& root, cfg_location::const_iterator begin, cfg_location::const_iterator end) + { + return begin == end ? root : get_cfg(get_cfg(root, *begin), begin + 1, end); + } + + YAML::Node get_node(const YAML::Node& node, cfg_location::const_iterator begin, cfg_location::const_iterator end) + { + if (begin == end) + { + return node; + } + + if (!node || !node.IsMap()) + { + cfg_log.fatal("Node error. A cfg_location does not match its cfg::node"); + return YAML::Node(); + } + + return get_node(node[*begin], begin + 1, end); // TODO + } + + YAML::Node get_node(const YAML::Node& node, cfg_location loc) + { + return get_node(node, loc.cbegin(), loc.cend()); + } + + QStringList get_options(cfg_location location) + { + QStringList values; + auto begin = location.cbegin(); + auto end = location.cend(); + for (const auto& v : cfg_adapter::get_cfg(g_cfg, begin, end).to_list()) + { + values.append(QString::fromStdString(v)); + } + return values; + } + + static bool get_is_dynamic(cfg_location location) + { + auto begin = location.cbegin(); + auto end = location.cend(); + return cfg_adapter::get_cfg(g_cfg, begin, end).get_is_dynamic(); + } + + bool get_is_dynamic(emu_settings_type type) + { + const cfg_location loc = settings_location[type]; + return get_is_dynamic(loc); + } + + std::string get_setting_name(emu_settings_type type) + { + const cfg_location loc = settings_location[type]; + return loc[loc.size() - 1]; + } +} diff --git a/pool/shard006/C++/0083930_cellUserInfo.cpp b/pool/shard006/C++/0083930_cellUserInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f53f60af06c405ac0d5f1c21441ed45f58ae313 --- /dev/null +++ b/pool/shard006/C++/0083930_cellUserInfo.cpp @@ -0,0 +1,119 @@ +#include "stdafx.h" +#include "Emu/System.h" +#include "Emu/Cell/PPUModule.h" + +#include "cellUserInfo.h" + +#include "Utilities/StrUtil.h" + +logs::channel cellUserInfo("cellUserInfo", logs::level::notice); + +template<> +void fmt_class_string::format(std::string& out, u64 arg) +{ + format_enum(out, arg, [](auto error) + { + switch (error) + { + STR_CASE(CELL_USERINFO_ERROR_BUSY); + STR_CASE(CELL_USERINFO_ERROR_INTERNAL); + STR_CASE(CELL_USERINFO_ERROR_PARAM); + STR_CASE(CELL_USERINFO_ERROR_NOUSER); + } + + return unknown; + }); +} + +s32 cellUserInfoGetStat(u32 id, vm::ptr stat) +{ + cellUserInfo.warning("cellUserInfoGetStat(id=%d, stat=*0x%x)", id, stat); + + if (id > CELL_SYSUTIL_USERID_MAX) + { + return CELL_USERINFO_ERROR_NOUSER; + } + + if (id == CELL_SYSUTIL_USERID_CURRENT) + { + // TODO: Return current user/profile when that is implemented + id = 1; + } + + const std::string& path = vfs::get(fmt::format("/dev_hdd0/home/%08d/", id)); + + if (!fs::is_dir(path)) + { + cellUserInfo.error("cellUserInfoGetStat(): CELL_USERINFO_ERROR_NOUSER. User %d doesn't exist. Did you delete the user folder?", id); + return CELL_USERINFO_ERROR_NOUSER; + } + + const fs::file f(path + "localusername"); + + if (!f) + { + cellUserInfo.error("cellUserInfoGetStat(): CELL_USERINFO_ERROR_INTERNAL. Username for user %d doesn't exist. Did you delete the username file?", id); + return CELL_USERINFO_ERROR_INTERNAL; + } + + stat->id = id; + strcpy_trunc(stat->name, f.to_string()); + + return CELL_OK; +} + +s32 cellUserInfoSelectUser_ListType() +{ + UNIMPLEMENTED_FUNC(cellUserInfo); + return CELL_OK; +} + +s32 cellUserInfoSelectUser_SetList() +{ + UNIMPLEMENTED_FUNC(cellUserInfo); + return CELL_OK; +} + +s32 cellUserInfoEnableOverlay() +{ + UNIMPLEMENTED_FUNC(cellUserInfo); + return CELL_OK; +} + +error_code cellUserInfoGetList(vm::ptr listNum, vm::ptr listBuf, vm::ptr currentUserId) +{ + cellUserInfo.todo("cellUserInfoGetList(listNum=*0x%x, listBuf=*0x%x, currentUserId=*0x%x)", listNum, listBuf, currentUserId); + + // If only listNum is NULL, an error will be returned + if (listBuf && !listNum) + { + return CELL_USERINFO_ERROR_PARAM; + } + + if (listNum) + { + *listNum = 1; + } + + if (listBuf) + { + listBuf->userId[0] = 1; + } + + if (currentUserId) + { + // TODO: Properly set the current user ID here, once implemented + *currentUserId = 1; + } + + return CELL_OK; +} + +DECLARE(ppu_module_manager::cellUserInfo)("cellUserInfo", []() +{ + REG_FUNC(cellUserInfo, cellUserInfoGetStat); + REG_FUNC(cellUserInfo, cellUserInfoSelectUser_ListType); + REG_FUNC(cellUserInfo, cellUserInfoSelectUser_SetList); + REG_FUNC(cellUserInfo, cellUserInfoEnableOverlay); + REG_FUNC(cellUserInfo, cellUserInfoGetList); +}); diff --git a/pool/shard006/C++/0083936_Error.cc b/pool/shard006/C++/0083936_Error.cc new file mode 100644 index 0000000000000000000000000000000000000000..9d044bc7ef5513a6b09db2c5bf131f7cf05f18a1 --- /dev/null +++ b/pool/shard006/C++/0083936_Error.cc @@ -0,0 +1,84 @@ +//======================================================================== +// +// Error.cc +// +// Copyright 1996-2003 Glyph & Cog, LLC +// +//======================================================================== + +//======================================================================== +// +// Modified under the Poppler project - http://poppler.freedesktop.org +// +// All changes made under the Poppler project to this file are licensed +// under GPL version 2 or later +// +// Copyright (C) 2005, 2007 Jeff Muizelaar +// Copyright (C) 2005 Albert Astals Cid +// Copyright (C) 2007 Krzysztof Kowalczyk +// +// To see a description of the changes please see the Changelog file that +// came with your tarball or type make ChangeLog if you are building from git +// +//======================================================================== + +#include + +#ifdef USE_GCC_PRAGMAS +#pragma implementation +#endif + +#include +#include +#include +#include "GooString.h" +#include "GlobalParams.h" +#include "Error.h" + +static const char *errorCategoryNames[] = { + "Syntax Warning", + "Syntax Error", + "Config Error", + "Command Line Error", + "I/O Error", + "Permission Error", + "Unimplemented Feature", + "Internal Error" +}; + +static void (*errorCbk)(void *data, ErrorCategory category, + int pos, char *msg) = NULL; +static void *errorCbkData = NULL; + +void setErrorCallback(void (*cbk)(void *data, ErrorCategory category, + int pos, char *msg), + void *data) { + errorCbk = cbk; + errorCbkData = data; +} + +void CDECL error(ErrorCategory category, int pos, const char *msg, ...) { + va_list args; + GooString *s; + + // NB: this can be called before the globalParams object is created + if (!errorCbk && globalParams && globalParams->getErrQuiet()) { + return; + } + va_start(args, msg); + s = GooString::formatv(msg, args); + va_end(args); + if (errorCbk) { + (*errorCbk)(errorCbkData, category, pos, s->getCString()); + } else { + if (pos >= 0) { + fprintf(stderr, "%s (%d): %s\n", + errorCategoryNames[category], pos, s->getCString()); + } else { + fprintf(stderr, "%s: %s\n", + errorCategoryNames[category], s->getCString()); + } + fflush(stderr); + } + delete s; +} diff --git a/pool/shard006/C++/0083939_SerialCommand.cpp b/pool/shard006/C++/0083939_SerialCommand.cpp new file mode 100644 index 0000000000000000000000000000000000000000..164e4e801fbda582a68105acc9917100bb6447d7 --- /dev/null +++ b/pool/shard006/C++/0083939_SerialCommand.cpp @@ -0,0 +1,193 @@ +/* + * This version is not original. + * Its edited for OpenLap to work with a wifi connection. + */ + + +/******************************************************************************* +SerialCommand - An Arduino library to tokenize and parse commands received over +a serial port. +Copyright (C) 2011-2013 Steven Cogswell +http://awtfy.com + +See SerialCommand.h for version history. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library 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 +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +***********************************************************************************/ + +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" +#else +#include "WProgram.h" +#endif + +#include "SerialCommand.h" + + +#include +#ifndef SERIALCOMMAND_HARDWAREONLY +#include +#endif + + +// Constructor makes sure some things are set. +SerialCommand::SerialCommand() +{ + usingSoftwareSerial=0; + strncpy(delim," ",MAXDELIMETER); // strtok_r needs a null-terminated string + term='\r'; // return character, default terminator for commands + numCommand=0; // Number of callback handlers installed + clearBuffer(); +} + +#ifndef SERIALCOMMAND_HARDWAREONLY +// Constructor to use a SoftwareSerial object +SerialCommand::SerialCommand(WiFiClient &_wifi) +{ + usingSoftwareSerial=1; + wifiClient = &_wifi; + strncpy(delim," ",MAXDELIMETER); // strtok_r needs a null-terminated string + term='\r'; // return character, default terminator for commands + numCommand=0; // Number of callback handlers installed + clearBuffer(); +} +#endif + + +// +// Initialize the command buffer being processed to all null characters +// +void SerialCommand::clearBuffer() +{ + for (int i=0; i 0) + #else + while ((usingSoftwareSerial==0 && Serial.available() > 0) || (usingSoftwareSerial==1 && wifiClient->available() > 0) ) + #endif + { + int i; + boolean matched; + if (usingSoftwareSerial==0) { + // Hardware serial port + inChar=Serial.read(); // Read single available character, there may be more waiting + } else { + #ifndef SERIALCOMMAND_HARDWAREONLY + // SoftwareSerial port + inChar = wifiClient->read(); // Read single available character, there may be more waiting + #endif + } + #ifdef SERIALCOMMANDDEBUG + Serial.print(inChar); // Echo back to serial stream + #endif + if (inChar==term) { // Check for the terminator (default '\r') meaning end of command + #ifdef SERIALCOMMANDDEBUG + Serial.print("Received: "); + Serial.println(buffer); + #endif + bufPos=0; // Reset to start of buffer + token = strtok_r(buffer,delim,&last); // Search for command at start of buffer + if (token == NULL) return; + matched=false; + for (i=0; i SERIALCOMMANDBUFFER-1) bufPos=0; // wrap buffer around if full + } + } +} + +// Adds a "command" and a handler function to the list of available commands. +// This is used for matching a found token in the buffer, and gives the pointer +// to the handler function to deal with it. +void SerialCommand::addCommand(const char *command, void (*function)()) +{ + if (numCommand < MAXSERIALCOMMANDS) { + #ifdef SERIALCOMMANDDEBUG + Serial.print(numCommand); + Serial.print("-"); + Serial.print("Adding command for "); + Serial.println(command); + #endif + + strncpy(CommandList[numCommand].command,command,SERIALCOMMANDBUFFER); + CommandList[numCommand].function = function; + numCommand++; + } else { + // In this case, you tried to push more commands into the buffer than it is compiled to hold. + // Not much we can do since there is no real visible error assertion, we just ignore adding + // the command + #ifdef SERIALCOMMANDDEBUG + Serial.println("Too many handlers - recompile changing MAXSERIALCOMMANDS"); + #endif + } +} + +// This sets up a handler to be called in the event that the receveived command string +// isn't in the list of things with handlers. +void SerialCommand::addDefaultHandler(void (*function)()) +{ + defaultHandler = function; +} diff --git a/pool/shard006/C++/0083940_shadingengineexporter.cpp b/pool/shard006/C++/0083940_shadingengineexporter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c93e9e4e045419803d04934279d5e8ebccc89b91 --- /dev/null +++ b/pool/shard006/C++/0083940_shadingengineexporter.cpp @@ -0,0 +1,140 @@ + +// +// This source file is part of appleseed. +// Visit https://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2016-2019 Esteban Tovagliari, The appleseedhq Organization +// +// 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. +// + +// Interface header. +#include "shadingengineexporter.h" + +// appleseed-maya headers. +#include "appleseedmaya/attributeutils.h" +#include "appleseedmaya/exporters/shadingnetworkexporter.h" + +// Build options header. +#include "foundation/core/buildoptions.h" + +// appleseed.renderer headers. +#include "renderer/api/scene.h" + +// Maya headers. +#include "appleseedmaya/_beginmayaheaders.h" +#include +#include +#include +#include "appleseedmaya/_endmayaheaders.h" + +namespace asf = foundation; +namespace asr = renderer; + +ShadingEngineExporter::ShadingEngineExporter( + const MObject& object, + asr::Assembly& mainAssembly, + AppleseedSession::SessionMode sessionMode) + : m_sessionMode(sessionMode) + , m_object(object) + , m_mainAssembly(mainAssembly) +{ +} + +ShadingEngineExporter::~ShadingEngineExporter() +{ + if (m_sessionMode == AppleseedSession::ProgressiveRenderSession) + { + m_mainAssembly.materials().remove(m_material.get()); + + if (m_surfaceShader.get()) + m_mainAssembly.surface_shaders().remove(m_surfaceShader.get()); + } +} + +void ShadingEngineExporter::createExporters(const AppleseedSession::IExporterFactory& exporter_factory) +{ + MFnDependencyNode depNodeFn(m_object); + + MStatus status; + const MPlug plug = depNodeFn.findPlug("surfaceShader", /*wantNetworkedPlug=*/ false, &status); + if (plug.isConnected()) + { + MPlugArray otherPlugs; + plug.connectedTo(otherPlugs, true, false, &status); + if (otherPlugs.length() == 1) + { + MObject otherNode = otherPlugs[0].node(); + depNodeFn.setObject(otherNode); + m_surfaceNetworkExporter = exporter_factory.createShadingNetworkExporter( + SurfaceNetworkContext, + otherNode, + otherPlugs[0]); + } + } + else if (plug.numConnectedChildren() != 0) + { + RENDERER_LOG_WARNING("Unsupported component connection to shading engine."); + } +} + +void ShadingEngineExporter::createEntities(const AppleseedSession::Options& options) +{ + MFnDependencyNode depNodeFn(m_object); + const MString appleseedName = depNodeFn.name(); + + // Create a surface shader if needed. + int numSamples = 1; + AttributeUtils::get(depNodeFn, "asShadingSamples", numSamples); + + if (numSamples > 1) + { + MString surfaceShaderName = appleseedName + MString("_surface_shader"); + m_surfaceShader.reset( + asr::PhysicalSurfaceShaderFactory().create( + surfaceShaderName.asChar(), + asr::ParamArray().insert("lighting_samples", numSamples))); + } + + // Create the material. + MString materialName = appleseedName + MString("_material"); + m_material.reset(asr::OSLMaterialFactory().create( + materialName.asChar(), asr::ParamArray())); + + // Set the surface shader in the material. + if (m_surfaceShader.get()) + m_material->get_parameters().insert("surface_shader", m_surfaceShader->get_name()); +} + +void ShadingEngineExporter::flushEntities() +{ + if (m_surfaceShader.get()) + m_mainAssembly.surface_shaders().insert(m_surfaceShader.release()); + + if (m_surfaceNetworkExporter) + { + m_material->get_parameters().insert( + "osl_surface", + m_surfaceNetworkExporter->shaderGroupName().asChar()); + } + + m_mainAssembly.materials().insert(m_material.release()); +} diff --git a/pool/shard006/C++/0083941_boss_ramstein_the_gorger.cpp b/pool/shard006/C++/0083941_boss_ramstein_the_gorger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a2c64544a6759a01552b9ad9dc386aed48b87ac --- /dev/null +++ b/pool/shard006/C++/0083941_boss_ramstein_the_gorger.cpp @@ -0,0 +1,107 @@ +/* + * Copyright (C) 2011-2012 Project SkyFire + * Copyright (C) 2008-2012 TrinityCore + * Copyright (C) 2006-2012 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +/* ScriptData +SDName: Boss_Ramstein_The_Gorger +SD%Complete: 70 +SDComment: +SDCategory: Stratholme +EndScriptData */ + +#include "ScriptPCH.h" +#include "stratholme.h" + +#define SPELL_TRAMPLE 5568 +#define SPELL_KNOCKOUT 17307 + + #define C_MINDLESS_UNDEAD 11030 + +class boss_ramstein_the_gorger : public CreatureScript +{ +public: + boss_ramstein_the_gorger() : CreatureScript("boss_ramstein_the_gorger") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_ramstein_the_gorgerAI (creature); + } + + struct boss_ramstein_the_gorgerAI : public ScriptedAI + { + boss_ramstein_the_gorgerAI(Creature* creature) : ScriptedAI(creature) + { + instance = me->GetInstanceScript(); + } + + InstanceScript* instance; + + uint32 Trample_Timer; + uint32 Knockout_Timer; + + void Reset() + { + Trample_Timer = 3000; + Knockout_Timer = 12000; + } + + void EnterCombat(Unit* /*who*/) + { + } + + void JustDied(Unit* /*Killer*/) + { + for (uint8 i = 0; i < 30; ++i) + { + if (Creature* mob = me->SummonCreature(C_MINDLESS_UNDEAD, 3969.35f+irand(-10, 10), -3391.87f+irand(-10, 10), 119.11f, 5.91f, TEMPSUMMON_TIMED_OR_DEAD_DESPAWN, 1800000)) + mob->AI()->AttackStart(me->SelectNearestTarget(100.0f)); + } + + if (instance) + instance->SetData(TYPE_RAMSTEIN, DONE); + } + + void UpdateAI(const uint32 diff) + { + //Return since we have no target + if (!UpdateVictim()) + return; + + //Trample + if (Trample_Timer <= diff) + { + DoCast(me, SPELL_TRAMPLE); + Trample_Timer = 7000; + } else Trample_Timer -= diff; + + //Knockout + if (Knockout_Timer <= diff) + { + DoCast(me->getVictim(), SPELL_KNOCKOUT); + Knockout_Timer = 10000; + } else Knockout_Timer -= diff; + + DoMeleeAttackIfReady(); + } + }; +}; + +void AddSC_boss_ramstein_the_gorger() +{ + new boss_ramstein_the_gorger(); +} \ No newline at end of file diff --git a/pool/shard006/C++/0083946_arena_test.cpp b/pool/shard006/C++/0083946_arena_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7194fb2fab5aaf5885de456c381e97e0a0826797 --- /dev/null +++ b/pool/shard006/C++/0083946_arena_test.cpp @@ -0,0 +1,81 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#include +#include "util/arena.h" +#include "util/random.h" + +namespace doris { + +class ArenaTest : public testing::Test { }; + +TEST_F(ArenaTest, Empty) { + Arena arena; +} + +TEST_F(ArenaTest, Simple) { + std::vector > allocated; + Arena arena; + const int N = 100000; + size_t bytes = 0; + Random rnd(301); + for (int i = 0; i < N; i++) { + size_t s; + if (i % (N / 10) == 0) { + s = i; + } else { + s = rnd.OneIn(4000) ? rnd.Uniform(6000) : + (rnd.OneIn(10) ? rnd.Uniform(100) : rnd.Uniform(20)); + } + if (s == 0) { + // Our arena disallows size 0 allocations. + s = 1; + } + char* r; + if (rnd.OneIn(10)) { + r = arena.AllocateAligned(s); + } else { + r = arena.Allocate(s); + } + + for (size_t b = 0; b < s; b++) { + // Fill the "i"th allocation with a known bit pattern + r[b] = i % 256; + } + bytes += s; + allocated.push_back(std::make_pair(s, r)); + ASSERT_GE(arena.MemoryUsage(), bytes); + if (i > N / 10) { + ASSERT_LE(arena.MemoryUsage(), bytes * 1.10); + } + } + for (size_t i = 0; i < allocated.size(); i++) { + size_t num_bytes = allocated[i].first; + const char* p = allocated[i].second; + for (size_t b = 0; b < num_bytes; b++) { + // Check the "i"th allocation for the known bit pattern + ASSERT_EQ(int(p[b]) & 0xff, i % 256); + } + } +} + +} // namespace doris + +int main(int argc, char** argv) { + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/pool/shard006/C++/0083953_viterbi.cpp b/pool/shard006/C++/0083953_viterbi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b194b0e977460a3b1c0046d56fc815ffb7132b8 --- /dev/null +++ b/pool/shard006/C++/0083953_viterbi.cpp @@ -0,0 +1,94 @@ +#include "ProbabilisticModel.hpp" +#include "DecodableModel.hpp" +#include "SequenceEntry.hpp" +#include "SequenceFormat.hpp" +#include "ProbabilisticModelParameterAdapter.hpp" +#include "ProbabilisticModelCreatorClient.hpp" +#include "Alphabet.hpp" +#include "Symbol.hpp" + +extern "C" { +#include +#include +#include +#include +#include +#include +#include +#include +#include +} +#include "tops_to_R.hpp" +#include "ProbabilisticModelParameterAdapter.hpp" +#include +#include +using namespace tops; +SEXP viterbi(SEXP exp) +{ + exp = CDR(exp); + int nargs = length(exp); + + if(nargs >= 2) { + ProbabilisticModelParameterValueFactory factory; + SEXP par = CAR(exp); + SEXP seq = CAR(CDR(exp)); + + ProbabilisticModelParameterValueAdapterPtr adapter = factory.adapter(par); + if(adapter == NULL) + { + std::cerr << "ERROR: viterbi(SEXP exp)" << std::endl; + return R_NilValue; + } + + adapter->getParameterValue()->setIsRoot(true); + tops::ProbabilisticModelCreatorClient client; + ProbabilisticModelPtr m = client.create(adapter->getParameterValue()->getParameters()); + std::vector seqstr; + tops::SequenceFactory seqfactory(m->alphabet()); + ProbabilisticModelParameterValueAdapterPtr seqAdapter = factory.adapter(seq); + tops::Sequence s = seqfactory.createSequence(seqAdapter->getParameterValue()->getStringVector()); + tops::Sequence p; + if(m == NULL) + { + return R_NilValue; + } + tops::Matrix v; + double score = m->decodable()->viterbi(s, p, v); + + if (m->alphabet()->size() > 0) { + + SEXP result, sequence, path, names; + + DoubleParameterValueAdapterPtr dblAdapter = DoubleParameterValueAdapterPtr(new DoubleParameterValueAdapter()); + dblAdapter->initialize(tops::DoubleParameterValuePtr(new DoubleParameterValue(score))); + SEXP score2 = dblAdapter->getSEXP(); + + PROTECT(result = allocVector(VECSXP, 3)); + PROTECT(names = allocVector(STRSXP, 3)); + PROTECT(sequence = allocVector(STRSXP, s.size())); + for(int i = 0; i < s.size(); i++) + { + SET_STRING_ELT(sequence, i, mkChar((m->alphabet()->getSymbol(s[i])->name()). c_str())); + } + SET_STRING_ELT(names, 0, mkChar("sequence")); + SET_VECTOR_ELT(result, 0, sequence); + + UNPROTECT(1); + + PROTECT(path = allocVector(STRSXP, p.size())); + for(int i = 0; i < p.size(); i++) + { + SET_STRING_ELT(path, i, mkChar((m->getStateNames()->getSymbol(p[i])->name()). c_str())); + } + SET_VECTOR_ELT(result, 1, path); + SET_VECTOR_ELT(result, 2, score2); + SET_STRING_ELT(names, 1, mkChar("path")); + SET_STRING_ELT(names, 2, mkChar("score")); + UNPROTECT(1); + setAttrib(result, R_NamesSymbol, names); + UNPROTECT(2); + return result; + } + } + return R_NilValue; +} diff --git a/pool/shard006/C++/0083957_GUISkillItem.cpp b/pool/shard006/C++/0083957_GUISkillItem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..801739519214d14daf1da1be1acd86ff7743c79a --- /dev/null +++ b/pool/shard006/C++/0083957_GUISkillItem.cpp @@ -0,0 +1,151 @@ +// This is an open source non-commercial project. Dear PVS-Studio, please check it. +// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com +/*********************************************************************************** +** +** GUISkillItem.cpp +** +** Copyright (C) August 2016 Hotride +** +************************************************************************************ +*/ +//---------------------------------------------------------------------------------- +#include "stdafx.h" +//---------------------------------------------------------------------------------- +CGUISkillItem::CGUISkillItem(int serial, int useSerial, int statusSerial, int index, int x, int y) + : CBaseGUI(GOT_SKILLITEM, serial, 0, 0, x, y) + , Index(index) +{ + WISPFUN_DEBUG("c76_f1"); + CSkill *skill = g_SkillsManager.Get(Index); + + if (skill != NULL) + { + if (skill->Button != 0) + m_ButtonUse = new CGUIButton(useSerial, 0x0837, 0x0838, 0x0838, 8, 0); + else + m_ButtonUse = NULL; + + m_Status = skill->Status; + + ushort graphic = GetStatusButtonGraphic(); + m_ButtonStatus = new CGUIButton(statusSerial, graphic, graphic, graphic, 251, 0); + m_ButtonStatus->CheckPolygone = true; + + g_FontManager.GenerateA(9, m_NameText, skill->Name, 0x0288); + + CreateValueText(); + } +} +//---------------------------------------------------------------------------------- +CGUISkillItem::~CGUISkillItem() +{ + WISPFUN_DEBUG("c76_f2"); + m_NameText.Clear(); + m_ValueText.Clear(); + + RELEASE_POINTER(m_ButtonUse); + RELEASE_POINTER(m_ButtonStatus); +} +//---------------------------------------------------------------------------------- +void CGUISkillItem::SetStatus(uchar val) +{ + WISPFUN_DEBUG("c76_f3"); + m_Status = val; + + ushort graphic = GetStatusButtonGraphic(); + + m_ButtonStatus->Graphic = graphic; + m_ButtonStatus->GraphicSelected = graphic; + m_ButtonStatus->GraphicPressed = graphic; +} +//---------------------------------------------------------------------------------- +ushort CGUISkillItem::GetStatusButtonGraphic() +{ + WISPFUN_DEBUG("c76_f4"); + ushort graphic = 0x0984; //Up + + if (m_Status == 1) + graphic = 0x0986; //Down + else if (m_Status == 2) + graphic = 0x082C; //Lock + + return graphic; +} +//---------------------------------------------------------------------------------- +void CGUISkillItem::CreateValueText(bool showReal, bool showCap) +{ + WISPFUN_DEBUG("c76_f5"); + CSkill *skill = g_SkillsManager.Get(Index); + + if (skill != NULL) + { + //Значение скилла (учитывая выбранный флаг отображения) + float val = skill->BaseValue; + if (showReal) + val = skill->Value; + else if (showCap) + val = skill->Cap; + + char sbf[10] = { 0 }; + sprintf_s(sbf, "%.1f", val); + + g_FontManager.GenerateA(9, m_ValueText, sbf, 0x0288); + } +} +//---------------------------------------------------------------------------------- +void CGUISkillItem::PrepareTextures() +{ + WISPFUN_DEBUG("c76_f6"); + if (m_ButtonUse != NULL) + m_ButtonUse->PrepareTextures(); + + m_ButtonStatus->PrepareTextures(); +} +//---------------------------------------------------------------------------------- +CBaseGUI *CGUISkillItem::SelectedItem() +{ + WISPFUN_DEBUG("c76_f7"); + CBaseGUI *selected = this; + + if (g_Orion.PolygonePixelsInXY( + m_X + m_ButtonStatus->GetX(), m_Y + m_ButtonStatus->GetY(), 14, 14)) + selected = m_ButtonStatus; + else if (m_ButtonUse != NULL) + { + if (g_Orion.GumpPixelsInXY( + m_ButtonUse->Graphic, m_X + m_ButtonUse->GetX(), m_Y + m_ButtonUse->GetY())) + selected = m_ButtonUse; + } + + return selected; +} +//---------------------------------------------------------------------------------- +void CGUISkillItem::Draw(bool checktrans) +{ + WISPFUN_DEBUG("c76_f8"); + glTranslatef((GLfloat)m_X, (GLfloat)m_Y, 0.0f); + + if (m_ButtonUse != NULL) + m_ButtonUse->Draw(checktrans); + + if (g_PressedObject.LeftObject == this) + g_GL.DrawPolygone(20, 0, 250, 14); + + m_NameText.Draw(22, 0, checktrans); + + m_ButtonStatus->Draw(checktrans); + + m_ValueText.Draw(250 - m_ValueText.Width, 0); + + glTranslatef((GLfloat)-m_X, (GLfloat)-m_Y, 0.0f); +} +//---------------------------------------------------------------------------------- +bool CGUISkillItem::Select() +{ + WISPFUN_DEBUG("c76_f9"); + int x = g_MouseManager.Position.X - m_X; + int y = g_MouseManager.Position.Y - m_Y; + + return (x >= 0 && y >= 0 && x < 255 && y < 17); +} +//---------------------------------------------------------------------------------- diff --git a/pool/shard006/C++/0083965_qdemo.cpp b/pool/shard006/C++/0083965_qdemo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e907ff3d84ef4b1c17607ae9338a737a53eb9adb --- /dev/null +++ b/pool/shard006/C++/0083965_qdemo.cpp @@ -0,0 +1,67 @@ +#include +#include +#include + +QTextStream cout(stdout); +QTextStream cerr(stderr); + +int main() { + QString str, newstr; + QTextStream strbuf(&str); /* strbuf is initialized with the address of str.*/ + + int lucky = 7; + float pi = 3.14; + double e = 2.71; + + cout << "An in-memory stream" << endl; + strbuf << "luckynumber: " << lucky << endl + << "pi: " << pi << endl + << "e: " << e << endl; + + cout << str; + + QFile data("mydata"); + data.open(QIODevice::WriteOnly); /* Creates (or overwrites) + a disk file for output. */ + QTextStream out(&data); /* An output file stream. */ + out << str ; + data.close(); + + cout << "Read data from the file - watch for errors." << endl; + if(data.open(QIODevice::ReadOnly)) { /* Make sure the file exists before + attempting to read.*/ + QTextStream in(&data); /* An input file stream. */ + int lucky2; + in >> newstr >> lucky2; + if (lucky != lucky2) + cerr << "ERROR! wrong " << newstr << lucky2 << endl; + else + cout << newstr << " OK" << endl; + + float pi2; + in >> newstr >> pi2; + if (pi2 != pi) + cerr << "ERROR! Wrong " << newstr << pi2 << endl; + else + cout << newstr << " OK" << endl; + + double e2; + in >> newstr >> e2; + if (e2 != e) + cerr << "ERROR: Wrong " << newstr << e2 << endl; + else + cout << newstr << " OK" << endl; + data.close(); + } + + cout << "Read from file line-by-line" << endl; + if(data.open(QIODevice::ReadOnly)) { + QTextStream in(&data); /* An input file stream. */ + while (not in.atEnd()) { + newstr = in.readLine(); + cout << newstr << endl; + } + data.close(); + } + return 0; +} diff --git a/pool/shard006/C++/0083968_test_registrar.cpp b/pool/shard006/C++/0083968_test_registrar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9aca3abc7d4d32d82170f82ad1dcb93fb84e492f --- /dev/null +++ b/pool/shard006/C++/0083968_test_registrar.cpp @@ -0,0 +1,129 @@ + +// +// This source file is part of appleseed. +// Visit https://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited +// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization +// +// 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. +// + +// appleseed.foundation headers. +#include "foundation/core/concepts/iunknown.h" +#include "foundation/memory/autoreleaseptr.h" +#include "foundation/utility/registrar.h" +#include "foundation/utility/test.h" + +using namespace foundation; + +TEST_SUITE(Foundation_Utility_Registrar) +{ + struct Item + : public IUnknown + { + int m_value; + + explicit Item(const int value) + : m_value(value) + { + } + + void release() override + { + delete this; + } + }; + + TEST_CASE(Lookup_GivenNameOfRegisteredItem_ReturnsItem) + { + Registrar registrar; + registrar.insert("key", auto_release_ptr(new Item(42))); + + const Item* item = registrar.lookup("key"); + + ASSERT_NEQ(0, item); + EXPECT_EQ(42, item->m_value); + } + + TEST_CASE(Lookup_GivenNameOfNonRegisteredItem_ReturnsZero) + { + Registrar registrar; + + const Item* item = registrar.lookup("key"); + + EXPECT_EQ(0, item); + } + + TEST_CASE(Insert_GivenNameOfAlreadyRegisteredItem_ReplacesItem) + { + Registrar registrar; + registrar.insert("key", auto_release_ptr(new Item(42))); + registrar.insert("key", auto_release_ptr(new Item(66))); + + const Item* item = registrar.lookup("key"); + + ASSERT_NEQ(0, item); + EXPECT_EQ(66, item->m_value); + } + + struct ItemWithReleaseCheck + : public IUnknown + { + bool* m_release_was_called; + + explicit ItemWithReleaseCheck(bool* release_was_called = nullptr) + : m_release_was_called(release_was_called) + { + } + + void release() override + { + if (m_release_was_called != nullptr) + *m_release_was_called = true; + + delete this; + } + }; + + TEST_CASE(Insert_GivenNameOfAlreadyRegisteredItem_DestructsPreviousItem) + { + bool release_was_called = false; + + Registrar registrar; + registrar.insert("key", auto_release_ptr(new ItemWithReleaseCheck(&release_was_called))); + registrar.insert("key", auto_release_ptr(new ItemWithReleaseCheck())); + + EXPECT_TRUE(release_was_called); + } + + TEST_CASE(Destructor_DestructsItems) + { + bool release_was_called = false; + + { + Registrar registrar; + registrar.insert("key", auto_release_ptr(new ItemWithReleaseCheck(&release_was_called))); + } + + EXPECT_TRUE(release_was_called); + } +} diff --git a/pool/shard006/C++/0083977_IDStorage.cc b/pool/shard006/C++/0083977_IDStorage.cc new file mode 100644 index 0000000000000000000000000000000000000000..cabbd03aad8f3e67d3f41ca7632c3115e33b6e7b --- /dev/null +++ b/pool/shard006/C++/0083977_IDStorage.cc @@ -0,0 +1,140 @@ +/** + * Notes.CC + * + * MIT/X11 License + * Copyright (c) 2014 Qball Cow + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void IDStorage::read () +{ + FILE *fp = fopen ( cache_path.c_str (), "r" ); + char buffer[1024]; + + if ( fp == nullptr ) { + return; + } + + while ( fgets ( buffer, 1024, fp ) != nullptr ) { + char *endpt = nullptr; + unsigned int id = (unsigned int) strtoul ( buffer, &endpt, 10 ); + if ( endpt != nullptr && *endpt != '\n' ) { + endpt++; + endpt[strlen ( endpt ) - 1] = '\0'; + idmap[endpt] = id; + } + } + fclose ( fp ); +} + +void IDStorage::write () +{ + FILE *fp = fopen ( cache_path.c_str (), "w" ); + if ( fp == nullptr ) { + notes_print_error ( "Failed to open id cache for writing: %s\n", + strerror ( errno ) ); + return; + } + for ( auto& x : idmap ) { + fprintf ( fp, "%u=%s\n", x.second, x.first.c_str () ); + } + + fclose ( fp ); +} + +void IDStorage::gc ( std::vector notes ) +{ + idmap.clear (); + for ( auto note : notes ) { + idmap[note->get_relative_path ()] = note->get_id (); + } + changed = true; + notes_print_info ( "Vacuumed the id Cache.\n" ); +} +unsigned int IDStorage::get_id ( const std::string path ) +{ + // Not efficient, but only done once at loading. + auto i = idmap.find ( path ); + if ( i != idmap.end () ) { + return i->second; + } + // Create new id. + // Inefficient O(n^2)? + unsigned int id = 1; + while ( true ) { + bool found = false; + for ( auto x = idmap.begin (); !found && x != idmap.end (); x++ ) { + if ( x->second == id ) { + found = true; + break; + } + } + if ( !found ) { + idmap[path] = id; + changed = true; + return id; + } + id++; + } +} +IDStorage::IDStorage ( const std::string &repo_path ) +{ + this->cache_path = repo_path + "/.idcache"; + + read (); +} +IDStorage::~IDStorage () +{ + if ( changed ) { + write (); + } +} +void IDStorage::move_id ( const std::string path_old, const std::string path_new ) +{ + if ( idmap.find ( path_old ) != idmap.end () ) { + // Get id. + unsigned int id = idmap[path_old]; + // Delete old entry. + idmap.erase ( path_old ); + // Add new entry. + idmap[path_new] = id; + changed = true; + } +} +void IDStorage::delete_id ( const std::string path_old ) +{ + if ( idmap.find ( path_old ) != idmap.end () ) { + idmap.erase ( path_old ); + changed = true; + } +} diff --git a/pool/shard006/C++/0083983_gotowindow.cpp b/pool/shard006/C++/0083983_gotowindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..519f5e1bb93538cef8ce2a3a342bdcf087206021 --- /dev/null +++ b/pool/shard006/C++/0083983_gotowindow.cpp @@ -0,0 +1,195 @@ +/*************************************************************************** + * Copyright (C) 2008 by A.R. Offringa * + * offringa@astro.rug.nl * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ +#include "gotowindow.h" + +#include + +#include + +#include "../strategy/imagesets/msimageset.h" + +#include "rfiguiwindow.h" + + +GoToWindow::GoToWindow(RFIGuiWindow &rfiGuiWindow) : Gtk::Window(), + _antenna1Frame("Antenna 1"), _antenna2Frame("Antenna 2"), + _bandFrame("Band"), _sequenceFrame("Time sequence"), + _loadButton("Load"), + _rfiGuiWindow(rfiGuiWindow), + _imageSet(&dynamic_cast(rfiGuiWindow.GetImageSet())) +{ + _antennaeStore = Gtk::ListStore::create(_antennaModelColumns); + _bandStore = Gtk::ListStore::create(_bandModelColumns); + _sequenceStore = Gtk::ListStore::create(_sequenceModelColumns); + + const std::vector &_sequences = + _imageSet->Reader()->Set().GetSequences(); + + const rfiStrategy::MSImageSetIndex &setIndex = + static_cast(_rfiGuiWindow.GetImageSetIndex()); + const unsigned antenna1Index = _imageSet->GetAntenna1(setIndex); + const unsigned antenna2Index = _imageSet->GetAntenna2(setIndex); + const unsigned bandIndex = _imageSet->GetBand(setIndex); + const unsigned sequenceIndex = _imageSet->GetSequenceId(setIndex); + + // First, the baseline pairs are iterated to get all antenna indices. + std::set set; + for(std::vector::const_iterator i=_sequences.begin(); + i != _sequences.end() ; ++i) + { + set.insert(i->antenna1); + set.insert(i->antenna2); + } + + Gtk::TreeModel::iterator a1Row, a2Row, bandRow, sequenceRow; + + // Now we make a store that contains all antennas. This store is shared for both a1 and a2 views. + for(std::set::const_iterator i=set.begin();i!=set.end();++i) + { + Gtk::TreeModel::iterator iter = _antennaeStore->append(); + (*iter)[_antennaModelColumns.antennaIndex] = *i; + AntennaInfo antenna = _imageSet->GetAntennaInfo(*i); + (*iter)[_antennaModelColumns.antennaName] = antenna.name; + if(antenna1Index == *i) + a1Row = iter; + if(antenna2Index == *i) + a2Row = iter; + } + + size_t bandCount = _imageSet->BandCount(); + for(size_t i=0;iappend(); + (*iter)[_bandModelColumns.bandIndex] = i; + std::stringstream desc; + BandInfo band = _imageSet->GetBandInfo(i); + desc << Frequency::ToString(band.channels.front().frequencyHz); + desc << " - "; + desc << Frequency::ToString(band.channels.back().frequencyHz); + (*iter)[_bandModelColumns.bandDescription] = desc.str(); + if(i == bandIndex) + bandRow = iter; + } + + size_t sequenceCount = _imageSet->SequenceCount(); + for(size_t i=0;iappend(); + (*iter)[_sequenceModelColumns.sequenceIndex] = i; + std::stringstream desc; + std::auto_ptr index(_imageSet->Index(antenna1Index, antenna2Index, bandIndex, i)); + size_t fIndex = _imageSet->GetField(*index); + FieldInfo field = _imageSet->GetFieldInfo(fIndex); + desc << field.name << " (" << fIndex << ')'; + (*iter)[_sequenceModelColumns.sequenceDescription] = desc.str(); + if(i == sequenceIndex) + sequenceRow = iter; + } + + _antenna1View.set_model(_antennaeStore); + _antenna1View.append_column("Index", _antennaModelColumns.antennaIndex); + _antenna1View.append_column("Name", _antennaModelColumns.antennaName); + _antenna1View.set_size_request(150, 512); + _antenna1View.get_selection()->select(a1Row); + _antenna1Scroll.add(_antenna1View); + _antenna1Frame.add(_antenna1Scroll); + _antenna1Scroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + _hBox.pack_start(_antenna1Frame); + + _antenna2View.set_model(_antennaeStore); + _antenna2View.append_column("Index", _antennaModelColumns.antennaIndex); + _antenna2View.append_column("Name", _antennaModelColumns.antennaName); + _antenna2View.set_size_request(150, 512); + _antenna2View.get_selection()->select(a2Row); + _antenna2Scroll.add(_antenna2View); + _antenna2Frame.add(_antenna2Scroll); + _antenna2Scroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + _hBox.pack_start(_antenna2Frame); + + _bandView.set_model(_bandStore); + _bandView.append_column("Index", _bandModelColumns.bandIndex); + _bandView.append_column("Description", _bandModelColumns.bandDescription); + //_bandView.set_size_request(-1, 512); + _bandView.get_selection()->select(bandRow); + _bandScroll.add(_bandView); + _bandFrame.add(_bandScroll); + _bandScroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + _bandFrameBox.pack_start(_bandFrame); + + _sequenceView.set_model(_sequenceStore); + _sequenceView.append_column("Index", _sequenceModelColumns.sequenceIndex); + _sequenceView.append_column("Source", _sequenceModelColumns.sequenceDescription); + //_sequenceView.set_size_request(-1, 512); + _sequenceView.get_selection()->select(sequenceRow); + _sequenceScroll.add(_sequenceView); + _sequenceFrame.add(_sequenceScroll); + _sequenceScroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_AUTOMATIC); + _bandFrameBox.pack_start(_sequenceFrame); + + _hBox.pack_start(_bandFrameBox); + + _vBox.pack_start(_hBox); + + _loadButton.signal_clicked().connect(sigc::mem_fun(*this, &GoToWindow::onLoadClicked)); + _buttonBox.pack_start(_loadButton); + + _vBox.pack_start(_buttonBox, Gtk::PACK_SHRINK, 0); + + add(_vBox); + _vBox.show_all(); +} + +GoToWindow::~GoToWindow() +{ +} + +void GoToWindow::onLoadClicked() +{ + Glib::RefPtr a1 = + _antenna1View.get_selection(); + Gtk::TreeModel::iterator iterA1 = a1->get_selected(); + + Glib::RefPtr a2 = + _antenna2View.get_selection(); + Gtk::TreeModel::iterator iterA2 = a2->get_selected(); + + Glib::RefPtr b = + _bandView.get_selection(); + Gtk::TreeModel::iterator iterB = b->get_selected(); + + Glib::RefPtr s = + _sequenceView.get_selection(); + Gtk::TreeModel::iterator iterS = s->get_selected(); + + if(iterA1 && iterA2 && iterB && iterS) + { + Gtk::TreeModel::Row a1Row = *iterA1; + Gtk::TreeModel::Row a2Row = *iterA2; + Gtk::TreeModel::Row bRow = *iterB; + Gtk::TreeModel::Row sRow = *iterS; + size_t a1Index = a1Row[_antennaModelColumns.antennaIndex]; + size_t a2Index = a2Row[_antennaModelColumns.antennaIndex]; + size_t bIndex = bRow[_bandModelColumns.bandIndex]; + size_t sIndex = sRow[_sequenceModelColumns.sequenceIndex]; + _rfiGuiWindow.SetImageSetIndex(_imageSet->Index(a1Index, a2Index, bIndex, sIndex)); + hide(); + } +} + diff --git a/pool/shard006/C++/0083988_heap.cpp b/pool/shard006/C++/0083988_heap.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0300a4a6e447609af306df9f0d90b5e752c4ec3c --- /dev/null +++ b/pool/shard006/C++/0083988_heap.cpp @@ -0,0 +1,38 @@ +// recursive function f() is called three times +// f() has a local variable (local_variable) and a dynamically allocated +// variable (ptr) +// +// f() prints the addresses of local_variable and the address returned by new +// +// this demonstrates how the stack grows one way and the heap grows another +// HOWEVER: heap is more complicated than this an does not always strictly +// grow in one direction + +#include +using namespace std; + +void f(int count) +{ + int local_variable; + + int *ptr = new int; + + cout << "start of f(), &local_variable = " << &local_variable + << " ptr = " << ptr + << " count = " << count << endl; + + if (count > 0) + { + f(count - 1); + } + cout << "end of f() count = " << count << endl; +} + +int main() +{ + cout << "start of main()" << endl; + f(500000); + cout << "end of main()" << endl; + + return 0; +} diff --git a/pool/shard006/C++/0083994_iterator1.cpp b/pool/shard006/C++/0083994_iterator1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13e3b8c089a5ce3940aef284456892b233a0b7d6 --- /dev/null +++ b/pool/shard006/C++/0083994_iterator1.cpp @@ -0,0 +1,82 @@ +//============================================================================ +// Name : iterator.cpp +// Author : Børge Moe +// Version : +// Copyright : Your copyright notice +// Description : Hello World in C++, Ansi-style +//============================================================================ + +#include +#include +#include +#include +#include "CSV.h" + + +using namespace std; +using namespace miutil::container; + +namespace miutil { +namespace container { + int nTuples=0; +} +} +std::ostream& +print( std::ostream &out, const ITupleContainer &container ) +{ + cerr << " ----- print ------ \n"; + + int i=0; + + for( auto_ptr it( container.iterator() ); it->hasNext(); ++i ) { + ITuple& tuple = it->next(); + + out << tuple.at( "validtimefrom" ).c_str() << " - " + << tuple.at( "validtimeto" ).c_str() << ": '" + << tuple.at( "valueparametername" ).c_str() << "' " + << tuple.at( "value" ).as() << " " + <3 ) +// break; + } + + return out; +} + + +int +main() +{ + string fileName("/home/borgem/projects/test-data.csv"); + ifstream ist( fileName.c_str() ); + + if( ! ist.is_open() ) { + cerr << "Could not open: " << fileName << endl; + return 1; + } + + SimpleTupleContainer *simpleContainer = readCSV( ist ); + + if( ! simpleContainer ) { + cerr << "Could not read the CSV file: " << fileName << endl; + return false; + } + + vector fieldNames = simpleContainer->columnNames(); + + cerr << "Fieldnames: " << endl; + cerr << "---------- " << endl; + + for( unsigned int i=0; i < fieldNames.size(); ++i ) + cerr << fieldNames[i] << endl; + cerr << endl; + + + print( cerr, *simpleContainer ); + + delete simpleContainer; + +// cerr << "nTuples: " << nTuples << endl; +} + diff --git a/pool/shard006/C++/0083995_CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67a.cpp b/pool/shard006/C++/0083995_CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d1fb567f0aa5814d7a9db6b2d4b47b87faadad7 --- /dev/null +++ b/pool/shard006/C++/0083995_CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67a.cpp @@ -0,0 +1,117 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67a.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml +Template File: sources-sinks-67a.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: calloc Allocate data using calloc() + * GoodSource: Allocate data using new + * Sinks: + * GoodSink: Deallocate data using free() + * BadSink : Deallocate data using delete + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67 +{ + +typedef struct _structType +{ + TwoIntsClass * structFirst; +} structType; + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(structType myStruct); + +void bad() +{ + TwoIntsClass * data; + structType myStruct; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ + data = (TwoIntsClass *)calloc(100, sizeof(TwoIntsClass)); + if (data == NULL) {exit(-1);} + myStruct.structFirst = data; + badSink(myStruct); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(structType myStruct); + +static void goodG2B() +{ + TwoIntsClass * data; + structType myStruct; + /* Initialize data*/ + data = NULL; + /* FIX: Allocate memory from the heap using new */ + data = new TwoIntsClass; + myStruct.structFirst = data; + goodG2BSink(myStruct); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(structType myStruct); + +static void goodB2G() +{ + TwoIntsClass * data; + structType myStruct; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ + data = (TwoIntsClass *)calloc(100, sizeof(TwoIntsClass)); + if (data == NULL) {exit(-1);} + myStruct.structFirst = data; + goodB2GSink(myStruct); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE762_Mismatched_Memory_Management_Routines__delete_class_calloc_67; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C++/0084001_jsepsessiondescription.cc b/pool/shard006/C++/0084001_jsepsessiondescription.cc new file mode 100644 index 0000000000000000000000000000000000000000..23a7cdde60a469b0d56b4be43fda3a4563b3fa38 --- /dev/null +++ b/pool/shard006/C++/0084001_jsepsessiondescription.cc @@ -0,0 +1,196 @@ +/* libjingle + * Copyright 2012, Google Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "talk/app/webrtc/jsepsessiondescription.h" + +#include "talk/app/webrtc/webrtcsdp.h" +#include "talk/session/media/mediasession.h" +#include "webrtc/base/stringencode.h" + +using rtc::scoped_ptr; +using cricket::SessionDescription; + +namespace webrtc { + +static const char* kSupportedTypes[] = { + JsepSessionDescription::kOffer, + JsepSessionDescription::kPrAnswer, + JsepSessionDescription::kAnswer +}; + +static bool IsTypeSupported(const std::string& type) { + bool type_supported = false; + for (size_t i = 0; i < ARRAY_SIZE(kSupportedTypes); ++i) { + if (kSupportedTypes[i] == type) { + type_supported = true; + break; + } + } + return type_supported; +} + +const char SessionDescriptionInterface::kOffer[] = "offer"; +const char SessionDescriptionInterface::kPrAnswer[] = "pranswer"; +const char SessionDescriptionInterface::kAnswer[] = "answer"; + +const int JsepSessionDescription::kDefaultVideoCodecId = 100; +const int JsepSessionDescription::kDefaultVideoCodecFramerate = 30; +const char JsepSessionDescription::kDefaultVideoCodecName[] = "VP8"; +// Used as default max video codec size before we have it in signaling. +const int JsepSessionDescription::kMaxVideoCodecWidth = 3840; +const int JsepSessionDescription::kMaxVideoCodecHeight = 2160; +const int JsepSessionDescription::kDefaultVideoCodecPreference = 1; + +SessionDescriptionInterface* CreateSessionDescription(const std::string& type, + const std::string& sdp) { + return CreateSessionDescription(type, sdp, NULL); +} + +SessionDescriptionInterface* CreateSessionDescription(const std::string& type, + const std::string& sdp, + SdpParseError* error) { + if (!IsTypeSupported(type)) { + return NULL; + } + + JsepSessionDescription* jsep_desc = new JsepSessionDescription(type); + if (!jsep_desc->Initialize(sdp, error)) { + delete jsep_desc; + return NULL; + } + return jsep_desc; +} + +JsepSessionDescription::JsepSessionDescription(const std::string& type) + : type_(type) { +} + +JsepSessionDescription::~JsepSessionDescription() {} + +bool JsepSessionDescription::Initialize( + cricket::SessionDescription* description, + const std::string& session_id, + const std::string& session_version) { + if (!description) + return false; + + session_id_ = session_id; + session_version_ = session_version; + description_.reset(description); + candidate_collection_.resize(number_of_mediasections()); + return true; +} + +bool JsepSessionDescription::Initialize(const std::string& sdp, + SdpParseError* error) { + return SdpDeserialize(sdp, this, error); +} + +bool JsepSessionDescription::AddCandidate( + const IceCandidateInterface* candidate) { + if (!candidate || candidate->sdp_mline_index() < 0) + return false; + size_t mediasection_index = 0; + if (!GetMediasectionIndex(candidate, &mediasection_index)) { + return false; + } + if (mediasection_index >= number_of_mediasections()) + return false; + const std::string content_name = + description_->contents()[mediasection_index].name; + const cricket::TransportInfo* transport_info = + description_->GetTransportInfoByName(content_name); + if (!transport_info) { + return false; + } + + cricket::Candidate updated_candidate = candidate->candidate(); + if (updated_candidate.username().empty()) { + updated_candidate.set_username(transport_info->description.ice_ufrag); + } + if (updated_candidate.password().empty()) { + updated_candidate.set_password(transport_info->description.ice_pwd); + } + + scoped_ptr updated_candidate_wrapper( + new JsepIceCandidate(candidate->sdp_mid(), + static_cast(mediasection_index), + updated_candidate)); + if (!candidate_collection_[mediasection_index].HasCandidate( + updated_candidate_wrapper.get())) + candidate_collection_[mediasection_index].add( + updated_candidate_wrapper.release()); + + return true; +} + +size_t JsepSessionDescription::number_of_mediasections() const { + if (!description_) + return 0; + return description_->contents().size(); +} + +const IceCandidateCollection* JsepSessionDescription::candidates( + size_t mediasection_index) const { + if (mediasection_index >= candidate_collection_.size()) + return NULL; + return &candidate_collection_[mediasection_index]; +} + +bool JsepSessionDescription::ToString(std::string* out) const { + if (!description_ || !out) + return false; + *out = SdpSerialize(*this); + return !out->empty(); +} + +bool JsepSessionDescription::GetMediasectionIndex( + const IceCandidateInterface* candidate, + size_t* index) { + if (!candidate || !index) { + return false; + } + *index = static_cast(candidate->sdp_mline_index()); + if (description_ && !candidate->sdp_mid().empty()) { + bool found = false; + // Try to match the sdp_mid with content name. + for (size_t i = 0; i < description_->contents().size(); ++i) { + if (candidate->sdp_mid() == description_->contents().at(i).name) { + *index = i; + found = true; + break; + } + } + if (!found) { + // If the sdp_mid is presented but we can't find a match, we consider + // this as an error. + return false; + } + } + return true; +} + +} // namespace webrtc diff --git a/pool/shard006/C++/0084011_gmock-internal-utils.cc b/pool/shard006/C++/0084011_gmock-internal-utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..658fa62d85e7f8b80cae73b3f54259743872bdc0 --- /dev/null +++ b/pool/shard006/C++/0084011_gmock-internal-utils.cc @@ -0,0 +1,192 @@ +// Copyright 2007, Google Inc. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: wan@google.com (Zhanyong Wan) + +// Google Mock - a framework for writing C++ mock classes. +// +// This file defines some utilities useful for implementing Google +// Mock. They are subject to change without notice, so please DO NOT +// USE THEM IN USER CODE. + +#include "gmock/internal/gmock-internal-utils.h" + +#include +#include // NOLINT +#include +#include "gmock/gmock.h" +#include "gmock/internal/gmock-port.h" +#include "gtest/gtest.h" + +namespace testing { +namespace internal { + +// Joins a vector of strings as if they are fields of a tuple; returns +// the joined string. +GTEST_API_ std::string JoinAsTuple(const Strings& fields) { + switch (fields.size()) { + case 0: + return ""; + case 1: + return fields[0]; + default: + std::string result = "(" + fields[0]; + for (size_t i = 1; i < fields.size(); i++) { + result += ", "; + result += fields[i]; + } + result += ")"; + return result; + } +} + +// Converts an identifier name to a space-separated list of lower-case +// words. Each maximum substring of the form [A-Za-z][a-z]*|\d+ is +// treated as one word. For example, both "FooBar123" and +// "foo_bar_123" are converted to "foo bar 123". +GTEST_API_ string ConvertIdentifierNameToWords(const char* id_name) { + string result; + char prev_char = '\0'; + for (const char* p = id_name; *p != '\0'; prev_char = *(p++)) { + // We don't care about the current locale as the input is + // guaranteed to be a valid C++ identifier name. + const bool starts_new_word = IsUpper(*p) || + (!IsAlpha(prev_char) && IsLower(*p)) || + (!IsDigit(prev_char) && IsDigit(*p)); + + if (IsAlNum(*p)) { + if (starts_new_word && result != "") + result += ' '; + result += ToLower(*p); + } + } + return result; +} + +// This class reports Google Mock failures as Google Test failures. A +// user can define another class in a similar fashion if they intend to +// use Google Mock with a testing framework other than Google Test. +class GoogleTestFailureReporter : public FailureReporterInterface { + public: + virtual void ReportFailure(FailureType type, const char* file, int line, + const std::string& message) { + AssertHelper(type == kFatal ? + TestPartResult::kFatalFailure : + TestPartResult::kNonFatalFailure, + file, + line, + message.c_str()) = Message(); + if (type == kFatal) { + posix::Abort(); + } + } +}; + +// Returns the global failure reporter. Will create a +// GoogleTestFailureReporter and return it the first time called. +GTEST_API_ FailureReporterInterface* GetFailureReporter() { + // Points to the global failure reporter used by Google Mock. gcc + // guarantees that the following use of failure_reporter is + // thread-safe. We may need to add additional synchronization to + // protect failure_reporter if we port Google Mock to other + // compilers. + static FailureReporterInterface* const failure_reporter = + new GoogleTestFailureReporter(); + return failure_reporter; +} + +// Protects global resources (stdout in particular) used by Log(). +static GTEST_DEFINE_STATIC_MUTEX_(g_log_mutex); + +// Returns true iff a log with the given severity is visible according +// to the --gmock_verbose flag. +GTEST_API_ bool LogIsVisible(LogSeverity severity) { + if (GMOCK_FLAG(verbose) == kInfoVerbosity) { + // Always show the log if --gmock_verbose=info. + return true; + } else if (GMOCK_FLAG(verbose) == kErrorVerbosity) { + // Always hide it if --gmock_verbose=error. + return false; + } else { + // If --gmock_verbose is neither "info" nor "error", we treat it + // as "warning" (its default value). + return severity == kWarning; + } +} + +// Prints the given message to stdout iff 'severity' >= the level +// specified by the --gmock_verbose flag. If stack_frames_to_skip >= +// 0, also prints the stack trace excluding the top +// stack_frames_to_skip frames. In opt mode, any positive +// stack_frames_to_skip is treated as 0, since we don't know which +// function calls will be inlined by the compiler and need to be +// conservative. +GTEST_API_ void Log(LogSeverity severity, const std::string& message, + int stack_frames_to_skip) { + if (!LogIsVisible(severity)) + return; + + // Ensures that logs from different threads don't interleave. + MutexLock l(&g_log_mutex); + + // "using ::std::cout;" doesn't work with Symbian's STLport, where cout is a + // macro. + + if (severity == kWarning) { + // Prints a GMOCK WARNING marker to make the warnings easily searchable. + std::cout << "\nGMOCK WARNING:"; + } + // Pre-pends a new-line to message if it doesn't start with one. + if (message.empty() || message[0] != '\n') { + std::cout << "\n"; + } + std::cout << message; + if (stack_frames_to_skip >= 0) { +#ifdef NDEBUG + // In opt mode, we have to be conservative and skip no stack frame. + const int actual_to_skip = 0; +#else + // In dbg mode, we can do what the caller tell us to do (plus one + // for skipping this function's stack frame). + const int actual_to_skip = stack_frames_to_skip + 1; +#endif // NDEBUG + + // Appends a new-line to message if it doesn't end with one. + if (!message.empty() && *message.rbegin() != '\n') { + std::cout << "\n"; + } + std::cout << "Stack trace:\n" + << ::testing::internal::GetCurrentOsStackTraceExceptTop( + ::testing::UnitTest::GetInstance(), actual_to_skip); + } + std::cout << ::std::flush; +} + +} // namespace internal +} // namespace testing diff --git a/pool/shard006/C++/0084014_tst_qwebenginespellcheck.cpp b/pool/shard006/C++/0084014_tst_qwebenginespellcheck.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c7b0836604fd46d2c049eb25ad4f8510084448de --- /dev/null +++ b/pool/shard006/C++/0084014_tst_qwebenginespellcheck.cpp @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the QtWebEngine module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:GPL-EXCEPT$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "util.h" +#include +#include +#include +#include +#include + +class WebView : public QWebEngineView +{ + Q_OBJECT +public: + void activateMenu(QWidget *widget, const QPoint &position) + { + QTest::mouseMove(widget, position); + QTest::mousePress(widget, Qt::RightButton, 0, position); + QContextMenuEvent evcont(QContextMenuEvent::Mouse, position, mapToGlobal(position)); + event(&evcont); + QTest::mouseRelease(widget, Qt::RightButton, 0, position); + } + + const QWebEngineContextMenuData& data() + { + return m_data; + } + +signals: + void menuReady(); + +protected: + void contextMenuEvent(QContextMenuEvent *) + { + m_data = page()->contextMenuData(); + emit menuReady(); + } +private: + QWebEngineContextMenuData m_data; +}; + +class tst_QWebEngineSpellcheck : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void init(); + void cleanup(); + void initTestCase(); + void spellCheckLanguage(); + void spellCheckLanguages(); + void spellCheckEnabled(); + void spellcheck(); + void spellcheck_data(); + +private: + void load(); + WebView *m_view; +}; + +void tst_QWebEngineSpellcheck::initTestCase() +{ + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + QVERIFY(profile); + QVERIFY(!profile->isSpellCheckEnabled()); + QVERIFY(profile->spellCheckLanguages().isEmpty()); +} + +void tst_QWebEngineSpellcheck::init() +{ + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + profile->setSpellCheckEnabled(false); + profile->setSpellCheckLanguages(QStringList()); + m_view = new WebView(); +} + +void tst_QWebEngineSpellcheck::load() +{ + m_view->page()->load(QUrl("qrc:///resources/index.html")); + m_view->show(); + QSignalSpy spyFinished(m_view->page(), &QWebEnginePage::loadFinished); + QVERIFY(spyFinished.wait()); + +} + +void tst_QWebEngineSpellcheck::cleanup() +{ + delete m_view; +} + +void tst_QWebEngineSpellcheck::spellCheckLanguage() +{ + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + QVERIFY(profile); + profile->setSpellCheckLanguages({"en-US"}); + QVERIFY(profile->spellCheckLanguages() == QStringList({"en-US"})); +} + +void tst_QWebEngineSpellcheck::spellCheckLanguages() +{ + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + QVERIFY(profile); + profile->setSpellCheckLanguages({"en-US","de-DE"}); + QVERIFY(profile->spellCheckLanguages() == QStringList({"en-US","de-DE"})); +} + + +void tst_QWebEngineSpellcheck::spellCheckEnabled() +{ + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + QVERIFY(profile); + profile->setSpellCheckEnabled(true); + QVERIFY(profile->isSpellCheckEnabled()); +} + +void tst_QWebEngineSpellcheck::spellcheck() +{ + QFETCH(QStringList, languages); + QFETCH(QStringList, suggestions); + + QWebEngineProfile *profile = QWebEngineProfile::defaultProfile(); + QVERIFY(profile); + profile->setSpellCheckLanguages(languages); + profile->setSpellCheckEnabled(true); + load(); + + // make textarea editable + evaluateJavaScriptSync(m_view->page(), "makeEditable();"); + + // calcuate position of misspelled word + QVariantList list = evaluateJavaScriptSync(m_view->page(), "findWordPosition('I lovee Qt ....','lovee');").toList(); + QRect rect(list[0].value(),list[1].value(),list[2].value(),list[3].value()); + + //type text, spellchecker needs time + QTest::mouseMove(m_view->focusWidget(), QPoint(20,20)); + QTest::mousePress(m_view->focusWidget(), Qt::LeftButton, 0, QPoint(20,20)); + QTest::mouseRelease(m_view->focusWidget(), Qt::LeftButton, 0, QPoint(20,20)); + QString text("I lovee Qt ...."); + for (int i = 0; i < text.length(); i++) { + QTest::keyClicks(m_view->focusWidget(), text.at(i)); + QTest::qWait(60); + } + + // make sure text is there + QString result = evaluateJavaScriptSync(m_view->page(), "text();").toString(); + QVERIFY(result == text); + + // open menu on misspelled word + m_view->activateMenu(m_view->focusWidget(), rect.center()); + QSignalSpy spyMenuReady(m_view, &WebView::menuReady); + QVERIFY(spyMenuReady.wait()); + + // check if menu is valid + QVERIFY(m_view->data().isValid()); + QVERIFY(m_view->data().isContentEditable()); + + // check misspelled word + QVERIFY(m_view->data().misspelledWord() == "lovee"); + + // check suggestions + QVERIFY(m_view->data().spellCheckerSuggestions() == suggestions); + + // check replace word + m_view->page()->replaceMisspelledWord("love"); + text = "I love Qt ...."; + QTRY_VERIFY(evaluateJavaScriptSync(m_view->page(), "text();").toString() == text); +} + +void tst_QWebEngineSpellcheck::spellcheck_data() +{ + QTest::addColumn("languages"); + QTest::addColumn("suggestions"); + QTest::newRow("en-US") << QStringList({"en-US"}) << QStringList({"love", "loves"}); + QTest::newRow("en-US,de-DE") << QStringList({"en-US","de-DE"}) << QStringList({"love", "liebe", "loves"}); +} + +QTEST_MAIN(tst_QWebEngineSpellcheck) +#include "tst_qwebenginespellcheck.moc" diff --git a/pool/shard006/C++/0084015_c_control_builder_gwen_checkbox.cpp b/pool/shard006/C++/0084015_c_control_builder_gwen_checkbox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a40d6feaca8fe2d803f4c34b79422c037cf4e6a5 --- /dev/null +++ b/pool/shard006/C++/0084015_c_control_builder_gwen_checkbox.cpp @@ -0,0 +1,87 @@ +/* + Yelo: Open Sauce SDK + Halo 1 (CE) Edition + + See license\OpenSauce\Halo1_CE for specific license information +*/ +#include "Common/Precompile.hpp" +#include "Interface/OpenSauceUI/GwenUI/ControlBuilders/c_control_builder_gwen_checkbox.hpp" + +#if !PLATFORM_IS_DEDI + +#include +#include + +#include "Interface/OpenSauceUI/Control/control_property_ids.hpp" +#include "Interface/OpenSauceUI/Control/control_event_ids.hpp" +#include "Interface/OpenSauceUI/Control/c_control_base.hpp" +#include "Interface/OpenSauceUI/GwenUI/ControlBuilders/gwen_control_util_label.hpp" +#include "Interface/OpenSauceUI/GwenUI/c_event_handler_gwen.hpp" + +namespace Yelo +{ + namespace Interface { namespace OpenSauceUI { namespace GwenUI { namespace ControlBuilders + { + DEFINE_PROPERTY_INTERFACE(checkbox_checked, + [](Control::i_control& control, Control::s_interface_value& output) + { + auto& gwen_control = GWEN_CTRL_REF(CheckBox, control.GetControlPtr()); + + output.m_bool = gwen_control.IsChecked(); + }, + [](Control::i_control& control, const Control::s_interface_value& value) + { + auto& gwen_control = GWEN_CTRL_REF(CheckBox, control.GetControlPtr()); + + gwen_control.SetChecked(value.m_bool); + }, + [](Control::i_control& control, cstring value_string) + { + auto& gwen_control = GWEN_CTRL_REF(CheckBox, control.GetControlPtr()); + + bool value; + ValueConversion::FromString(value_string, value); + gwen_control.SetChecked(value); + } + ); + + Gwen::Controls::Base* c_control_builder_gwen_checkbox::CreateInstance(Gwen::Controls::Base* parent) const + { + return new Gwen::Controls::CheckBox(parent); + } + + void c_control_builder_gwen_checkbox::SetDefaultValues(Gwen::Controls::Base* control) const + { + c_control_builder_gwen_base::SetDefaultValues(control); + + auto& gwen_control = GWEN_CTRL_REF(CheckBox, control); + + gwen_control.SetChecked(false); + } + + void c_control_builder_gwen_checkbox::GetPropertyInterfaces(Control::property_interface_map_t& property_interfaces) const + { + c_control_builder_gwen_base::GetPropertyInterfaces(property_interfaces); + + property_interfaces[K_PROPERTY_CHECKED_ID] = GET_PROPERTY_INTERFACE(checkbox_checked); + } + + void c_control_builder_gwen_checkbox::GetEventHandlers(Gwen::Controls::Base* control, Control::event_handler_map_t& event_handlers) const + { + c_control_builder_gwen_base::GetEventHandlers(control, event_handlers); + + auto& gwen_control = GWEN_CTRL_REF(CheckBox, control); + + event_handlers[K_EVENT_CHECKED_ID] = std::make_unique(gwen_control.onChecked); + event_handlers[K_EVENT_UNCHECKED_ID] = std::make_unique(gwen_control.onUnChecked); + event_handlers[K_EVENT_CHECKCHANGED_ID] = std::make_unique(gwen_control.onCheckChanged, + [](Gwen::Event::Info& info, Control::s_interface_value& output) + { + auto& gwen_control = GWEN_CTRL_REF(CheckBox, info.ControlCaller); + + output.m_bool = gwen_control.IsChecked(); + }); + } + };};};}; +}; +#endif \ No newline at end of file diff --git a/pool/shard006/C++/0084018_save.cpp b/pool/shard006/C++/0084018_save.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b1912b2cc0e5ecf4e4245f78721b7250abd60ce5 --- /dev/null +++ b/pool/shard006/C++/0084018_save.cpp @@ -0,0 +1,32 @@ +#include "commandline.hpp" +#include + + +int main(int ac, char *av[]) { + cout << ac << "Arguments received" << endl; + + + if (ac < 2) + cout << "Invalid arguments" << endl; + + + model cloud_model; + std::vector file_path; + + for (int i = 0; i < ac; i++) { + string temp = "./temp/MK" + boost::lexical_cast(i) + ".pcd"; + boost::filesystem::path p(temp); + if (boost::filesystem::exists(p)) { + file_path.push_back(temp); + cout << file_path.back() << endl; // find until last MK_i file then break. + } else + break; + + } + cout << "Opening..." << endl; + cout << cloud_model.open_files(file_path) << "Files" << endl; + + string temp = string(av[1]); + cout << "Saving..." << cloud_model.save_files(temp); + return 0; +} diff --git a/pool/shard006/C++/0084021_upload_data_stream.cc b/pool/shard006/C++/0084021_upload_data_stream.cc new file mode 100644 index 0000000000000000000000000000000000000000..d22929abbab1dd452b2d7de47fcfe706c252f04e --- /dev/null +++ b/pool/shard006/C++/0084021_upload_data_stream.cc @@ -0,0 +1,111 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/base/upload_data_stream.h" + +#include "base/logging.h" +#include "net/base/io_buffer.h" +#include "net/base/net_errors.h" + +namespace net { + +UploadDataStream::UploadDataStream(const UploadData* data) + : data_(data), + buf_(new IOBuffer(kBufSize)), + buf_len_(0), + next_element_(data->elements().begin()), + next_element_offset_(0), + next_element_remaining_(0), + total_size_(data->GetContentLength()), + current_position_(0) { + FillBuf(); +} + +UploadDataStream::~UploadDataStream() { +} + +void UploadDataStream::DidConsume(size_t num_bytes) { + // TODO(vandebo): Change back to a DCHECK when issue 27870 is resolved. + CHECK(num_bytes <= buf_len_); + + buf_len_ -= num_bytes; + if (buf_len_) + memmove(buf_->data(), buf_->data() + num_bytes, buf_len_); + + FillBuf(); + + current_position_ += num_bytes; +} + +void UploadDataStream::FillBuf() { + std::vector::const_iterator end = + data_->elements().end(); + + while (buf_len_ < kBufSize && next_element_ != end) { + bool advance_to_next_element = false; + + const UploadData::Element& element = *next_element_; + + size_t size_remaining = kBufSize - buf_len_; + if (element.type() == UploadData::TYPE_BYTES) { + const std::vector& d = element.bytes(); + size_t count = d.size() - next_element_offset_; + + size_t bytes_copied = std::min(count, size_remaining); + + memcpy(buf_->data() + buf_len_, &d[next_element_offset_], bytes_copied); + buf_len_ += bytes_copied; + + if (bytes_copied == count) { + advance_to_next_element = true; + } else { + next_element_offset_ += bytes_copied; + } + } else { + DCHECK(element.type() == UploadData::TYPE_FILE); + + if (!next_element_stream_.IsOpen()) { + int flags = base::PLATFORM_FILE_OPEN | + base::PLATFORM_FILE_READ; + int rv = next_element_stream_.Open(element.file_path(), flags); + // If the file does not exist, that's technically okay.. we'll just + // upload an empty file. This is for consistency with Mozilla. + DLOG_IF(WARNING, rv != OK) << "Failed to open \"" + << element.file_path().value() + << "\" for reading: " << rv; + + next_element_remaining_ = 0; // Default to reading nothing. + if (rv == OK) { + uint64 offset = element.file_range_offset(); + if (offset && next_element_stream_.Seek(FROM_BEGIN, offset) < 0) { + DLOG(WARNING) << "Failed to seek \"" << element.file_path().value() + << "\" to offset: " << offset; + } else { + next_element_remaining_ = element.file_range_length(); + } + } + } + + int rv = 0; + int count = static_cast(std::min( + static_cast(size_remaining), next_element_remaining_)); + if (count > 0 && + (rv = next_element_stream_.Read(buf_->data() + buf_len_, + count, NULL)) > 0) { + buf_len_ += rv; + next_element_remaining_ -= rv; + } else { + advance_to_next_element = true; + } + } + + if (advance_to_next_element) { + ++next_element_; + next_element_offset_ = 0; + next_element_stream_.Close(); + } + } +} + +} // namespace net diff --git a/pool/shard006/C++/0084024_DeliveryStreamStatus.cpp b/pool/shard006/C++/0084024_DeliveryStreamStatus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..44158ddb2d03a750ee375581a9111ac8677fefe9 --- /dev/null +++ b/pool/shard006/C++/0084024_DeliveryStreamStatus.cpp @@ -0,0 +1,91 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace Firehose + { + namespace Model + { + namespace DeliveryStreamStatusMapper + { + + static const int CREATING_HASH = HashingUtils::HashString("CREATING"); + static const int CREATING_FAILED_HASH = HashingUtils::HashString("CREATING_FAILED"); + static const int DELETING_HASH = HashingUtils::HashString("DELETING"); + static const int DELETING_FAILED_HASH = HashingUtils::HashString("DELETING_FAILED"); + static const int ACTIVE_HASH = HashingUtils::HashString("ACTIVE"); + + + DeliveryStreamStatus GetDeliveryStreamStatusForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == CREATING_HASH) + { + return DeliveryStreamStatus::CREATING; + } + else if (hashCode == CREATING_FAILED_HASH) + { + return DeliveryStreamStatus::CREATING_FAILED; + } + else if (hashCode == DELETING_HASH) + { + return DeliveryStreamStatus::DELETING; + } + else if (hashCode == DELETING_FAILED_HASH) + { + return DeliveryStreamStatus::DELETING_FAILED; + } + else if (hashCode == ACTIVE_HASH) + { + return DeliveryStreamStatus::ACTIVE; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast(hashCode); + } + + return DeliveryStreamStatus::NOT_SET; + } + + Aws::String GetNameForDeliveryStreamStatus(DeliveryStreamStatus enumValue) + { + switch(enumValue) + { + case DeliveryStreamStatus::CREATING: + return "CREATING"; + case DeliveryStreamStatus::CREATING_FAILED: + return "CREATING_FAILED"; + case DeliveryStreamStatus::DELETING: + return "DELETING"; + case DeliveryStreamStatus::DELETING_FAILED: + return "DELETING_FAILED"; + case DeliveryStreamStatus::ACTIVE: + return "ACTIVE"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast(enumValue)); + } + + return {}; + } + } + + } // namespace DeliveryStreamStatusMapper + } // namespace Model + } // namespace Firehose +} // namespace Aws diff --git a/pool/shard006/C++/0084025_rpcdump.cpp b/pool/shard006/C++/0084025_rpcdump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d91870c81095cb83551ca093b4e38c81adaefae1 --- /dev/null +++ b/pool/shard006/C++/0084025_rpcdump.cpp @@ -0,0 +1,92 @@ +// Copyright (c) 2009-2012 Bitcoin Developers +// Copyright (c) 2011-2012 Litecoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" // for pwalletMain +#include "bitcoinrpc.h" +#include "ui_interface.h" +#include "base58.h" + +#include + +#define printf OutputDebugStringF + +using namespace json_spirit; +using namespace std; + +class CTxDump +{ +public: + CBlockIndex *pindex; + int64 nValue; + bool fSpent; + CWalletTx* ptx; + int nOut; + CTxDump(CWalletTx* ptx = NULL, int nOut = -1) + { + pindex = NULL; + nValue = 0; + fSpent = false; + this->ptx = ptx; + this->nOut = nOut; + } +}; + +Value importprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 2) + throw runtime_error( + "importprivkey [label]\n" + "Adds a private key (as returned by dumpprivkey) to your wallet."); + + string strSecret = params[0].get_str(); + string strLabel = ""; + if (params.size() > 1) + strLabel = params[1].get_str(); + CBitcoinSecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) throw JSONRPCError(-5,"Invalid private key"); + + CKey key; + bool fCompressed; + CSecret secret = vchSecret.GetSecret(fCompressed); + key.SetSecret(secret, fCompressed); + CKeyID vchAddress = key.GetPubKey().GetID(); + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + pwalletMain->SetAddressBookName(vchAddress, strLabel); + + if (!pwalletMain->AddKey(key)) + throw JSONRPCError(-4,"Error adding key to wallet"); + + pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); + pwalletMain->ReacceptWalletTransactions(); + } + + return Value::null; +} + +Value dumpprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "dumpprivkey \n" + "Reveals the private key corresponding to ."); + + string strAddress = params[0].get_str(); + CBitcoinAddress address; + if (!address.SetString(strAddress)) + throw JSONRPCError(-5, "Invalid AvaCoin address"); + CKeyID keyID; + if (!address.GetKeyID(keyID)) + throw JSONRPCError(-3, "Address does not refer to a key"); + CSecret vchSecret; + bool fCompressed; + if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) + throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); + return CBitcoinSecret(vchSecret, fCompressed).ToString(); +} diff --git a/pool/shard006/C++/0084032_app_list_main_view.cc b/pool/shard006/C++/0084032_app_list_main_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..d3791ad9c9a5a556b9046efcb325ea13c1cc1be2 --- /dev/null +++ b/pool/shard006/C++/0084032_app_list_main_view.cc @@ -0,0 +1,229 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/app_list/views/app_list_main_view.h" + +#include + +#include "base/callback.h" +#include "base/files/file_path.h" +#include "base/strings/string_util.h" +#include "ui/app_list/app_list_constants.h" +#include "ui/app_list/app_list_item_model.h" +#include "ui/app_list/app_list_model.h" +#include "ui/app_list/app_list_view_delegate.h" +#include "ui/app_list/pagination_model.h" +#include "ui/app_list/search_box_model.h" +#include "ui/app_list/views/app_list_item_view.h" +#include "ui/app_list/views/contents_view.h" +#include "ui/app_list/views/search_box_view.h" +#include "ui/views/controls/textfield/textfield.h" +#include "ui/views/layout/box_layout.h" +#include "ui/views/widget/widget.h" + +namespace app_list { + +namespace { + +// Inner padding space in pixels of bubble contents. +const int kInnerPadding = 1; + +// The maximum allowed time to wait for icon loading in milliseconds. +const int kMaxIconLoadingWaitTimeInMs = 50; + +} // namespace + +//////////////////////////////////////////////////////////////////////////////// +// AppListMainView::IconLoader + +class AppListMainView::IconLoader : public AppListItemModelObserver { + public: + IconLoader(AppListMainView* owner, + AppListItemModel* item, + ui::ScaleFactor scale_factor) + : owner_(owner), + item_(item) { + item_->AddObserver(this); + + // Triggers icon loading for given |scale_factor|. + item_->icon().GetRepresentation(scale_factor); + } + + virtual ~IconLoader() { + item_->RemoveObserver(this); + } + + private: + // AppListItemModelObserver overrides: + virtual void ItemIconChanged() OVERRIDE { + owner_->OnItemIconLoaded(this); + // Note that IconLoader is released here. + } + virtual void ItemTitleChanged() OVERRIDE {} + virtual void ItemHighlightedChanged() OVERRIDE {} + virtual void ItemIsInstallingChanged() OVERRIDE {} + virtual void ItemPercentDownloadedChanged() OVERRIDE {} + + AppListMainView* owner_; + AppListItemModel* item_; + + DISALLOW_COPY_AND_ASSIGN(IconLoader); +}; + +//////////////////////////////////////////////////////////////////////////////// +// AppListMainView: + +AppListMainView::AppListMainView(AppListViewDelegate* delegate, + AppListModel* model, + PaginationModel* pagination_model, + views::View* anchor) + : delegate_(delegate), + model_(model), + search_box_view_(NULL), + contents_view_(NULL) { + // Starts icon loading early. + PreloadIcons(pagination_model, anchor); + + SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, + kInnerPadding, + kInnerPadding, + kInnerPadding)); + + search_box_view_ = new SearchBoxView(this, delegate); + AddChildView(search_box_view_); + + contents_view_ = new ContentsView(this, pagination_model); + AddChildView(contents_view_); + + search_box_view_->set_contents_view(contents_view_); + +#if defined(USE_AURA) + contents_view_->SetPaintToLayer(true); + contents_view_->SetFillsBoundsOpaquely(false); + contents_view_->layer()->SetMasksToBounds(true); +#endif + + search_box_view_->SetModel(model_->search_box()); + contents_view_->SetModel(model_); +} + +AppListMainView::~AppListMainView() { + pending_icon_loaders_.clear(); +} + +void AppListMainView::ShowAppListWhenReady() { + if (pending_icon_loaders_.empty()) { + icon_loading_wait_timer_.Stop(); + GetWidget()->Show(); + return; + } + + if (icon_loading_wait_timer_.IsRunning()) + return; + + icon_loading_wait_timer_.Start( + FROM_HERE, + base::TimeDelta::FromMilliseconds(kMaxIconLoadingWaitTimeInMs), + this, &AppListMainView::OnIconLoadingWaitTimer); +} + +void AppListMainView::Close() { + icon_loading_wait_timer_.Stop(); +} + +void AppListMainView::Prerender() { + contents_view_->Prerender(); +} + +void AppListMainView::SetDragAndDropHostOfCurrentAppList( + app_list::ApplicationDragAndDropHost* drag_and_drop_host) { + contents_view_->SetDragAndDropHostOfCurrentAppList(drag_and_drop_host); +} + +void AppListMainView::PreloadIcons(PaginationModel* pagination_model, + views::View* anchor) { + ui::ScaleFactor scale_factor = ui::SCALE_FACTOR_100P; + if (anchor && anchor->GetWidget()) { + scale_factor = ui::GetScaleFactorForNativeView( + anchor->GetWidget()->GetNativeView()); + } + + // |pagination_model| could have -1 as the initial selected page and + // assumes first page (i.e. index 0) will be used in this case. + const int selected_page = std::max(0, pagination_model->selected_page()); + + const int tiles_per_page = kPreferredCols * kPreferredRows; + const int start_model_index = selected_page * tiles_per_page; + const int end_model_index = std::min( + static_cast(model_->apps()->item_count()), + start_model_index + tiles_per_page); + + pending_icon_loaders_.clear(); + for (int i = start_model_index; i < end_model_index; ++i) { + AppListItemModel* item = model_->apps()->GetItemAt(i); + if (item->icon().HasRepresentation(scale_factor)) + continue; + + pending_icon_loaders_.push_back(new IconLoader(this, item, scale_factor)); + } +} + +void AppListMainView::OnIconLoadingWaitTimer() { + GetWidget()->Show(); +} + +void AppListMainView::OnItemIconLoaded(IconLoader* loader) { + ScopedVector::iterator it = std::find( + pending_icon_loaders_.begin(), pending_icon_loaders_.end(), loader); + DCHECK(it != pending_icon_loaders_.end()); + pending_icon_loaders_.erase(it); + + if (pending_icon_loaders_.empty() && icon_loading_wait_timer_.IsRunning()) { + icon_loading_wait_timer_.Stop(); + GetWidget()->Show(); + } +} + +void AppListMainView::ActivateApp(AppListItemModel* item, int event_flags) { + if (delegate_) + delegate_->ActivateAppListItem(item, event_flags); +} + +void AppListMainView::GetShortcutPathForApp( + const std::string& app_id, + const base::Callback& callback) { + if (delegate_) { + delegate_->GetShortcutPathForApp(app_id, callback); + return; + } + callback.Run(base::FilePath()); +} + +void AppListMainView::QueryChanged(SearchBoxView* sender) { + base::string16 query; + TrimWhitespace(model_->search_box()->text(), TRIM_ALL, &query); + bool should_show_search = !query.empty(); + contents_view_->ShowSearchResults(should_show_search); + + if (delegate_) { + if (should_show_search) + delegate_->StartSearch(); + else + delegate_->StopSearch(); + } +} + +void AppListMainView::OpenResult(SearchResult* result, int event_flags) { + if (delegate_) + delegate_->OpenSearchResult(result, event_flags); +} + +void AppListMainView::InvokeResultAction(SearchResult* result, + int action_index, + int event_flags) { + if (delegate_) + delegate_->InvokeSearchResultAction(result, action_index, event_flags); +} + +} // namespace app_list diff --git a/pool/shard006/C++/0084035_loj1037.cpp b/pool/shard006/C++/0084035_loj1037.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b0544d963a16394a66b7ff4a5957fb4e9e38844 --- /dev/null +++ b/pool/shard006/C++/0084035_loj1037.cpp @@ -0,0 +1,115 @@ +/* Tariq ahmed khan - Daffodil */ + +#include + +#define _ ios_base::sync_with_stdio(0);cin.tie(0); // I/O optimization + + +#define pi 2*acos(0.0) +#define scan(x) scanf("%d",&x) +#define sf scanf +#define pf printf +#define pb push_back +#define memoclr(n,x) memset(n,x,sizeof(n) ) +#define INF 1 << 30 + + +typedef long long LLI; +typedef unsigned long long LLU; + +template T gcd(T x, T y){if (y==0) return x; return gcd(y,x%y);} +template T lcm(T x, T y){return ((x/gcd(x,y))*y);} +template T maxt(T x, T y){if (x > y) return x; else return y;} +template T mint(T x, T y){if (x < y) return x; else return y;} +template T power(T x, T y){T res=1,a = x; while(y){if(y&1){res*=a;}a*=a;y>>=1;}return res;} +template T bigmod(T x,T y,T mod){T res=1,a=x; while(y){if(y&1){res=(res*a)%mod;}a=(a*a)%mod;y>>=1;}return res;} + + +int dir[8][2]={{-1,0} + ,{1,0} + ,{0,-1} + ,{0,1} + ,{-1,-1} + ,{-1,1} + ,{1,-1} + ,{1,1}}; + + +using namespace std; + +int n,mem0[16][1<<16],life[16]; +char gun[16][16]; + + +int dp(int i,int mask) +{ + if(mask == ((1< +#include "HEADERS_AND_CONSTANTS_H.h" +#include "DATA_TRANSFER_H.h" +#include "FILE_TRANSFER_SERVER_H.h" +/* This function sends fragment of file and is called by each thread */ +void sendFragment(int client,DataTransfer *dataTransfer){ + + /* get offset and size of this fragment*/ + int offset=dataTransfer->getInitialOffset(); + int size=dataTransfer->getPartFileSize(); + + char block[MAX_BYTES]; + struct FragmentHeader fragmentheader; + + /* set fragment header values */ + fragmentheader.file_size=size; + fragmentheader.part_no=dataTransfer->getPartSeq(); + dataTransfer->getExtension(fragmentheader.filename); //set filename to be sent as extension + + cout<<"Thread no :"<getPartSeq()<<"=> Connected to client sending file Header..."<getPartSeq()<<"=> Received acknowledgement sending data .."<readFragment(block,min(MAX_BYTES,size-local_offset),offset); + send(client,block,readbytes,0); + + offset+=readbytes; + local_offset+=readbytes; + + } + + cout<<"Thread no :"<getPartSeq()<<"=> Sent data waiting for tear down packet .."<server_socket,(struct sockaddr *)(&client_addr),&add_size); + + /* call threads in parallel for execution*/ + myThreads[i]=thread(sendFragment,client,&dataTransfer[i]); + i++; + } + + /* wait for all threads to finish */ + for(i=0;igetInfo()["Title"] + " Sample"); + sp->addSample(s); + Root::getSingleton().installPlugin(sp); +} + +extern "C" _OgreSampleExport void dllStopPlugin() +{ + Root::getSingleton().uninstallPlugin(sp); + OGRE_DELETE sp; + delete s; +} + +#endif diff --git a/pool/shard006/C++/0084057_rs232.cpp b/pool/shard006/C++/0084057_rs232.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8271234343992c846a29b27d52c33518c1c678ce --- /dev/null +++ b/pool/shard006/C++/0084057_rs232.cpp @@ -0,0 +1,127 @@ +// license:BSD-3-Clause +// copyright-holders:smf +#include "rs232.h" + +const device_type RS232_PORT = &device_creator; + +rs232_port_device::rs232_port_device(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : + device_t(mconfig, RS232_PORT, "RS232 Port", tag, owner, clock, "rs232", __FILE__), + device_slot_interface(mconfig, *this), + m_rxd(0), + m_dcd(0), + m_dsr(0), + m_ri(0), + m_cts(0), + m_rxd_handler(*this), + m_dcd_handler(*this), + m_dsr_handler(*this), + m_ri_handler(*this), + m_cts_handler(*this), + m_dev(nullptr) +{ +} + +rs232_port_device::rs232_port_device(const machine_config &mconfig, device_type type, const char *name, const char *tag, device_t *owner, UINT32 clock, const char *shortname, const char *source) + : device_t(mconfig, type, name, tag, owner, clock, shortname, source), + device_slot_interface(mconfig, *this), + m_rxd(0), + m_dcd(0), + m_dsr(0), + m_ri(0), + m_cts(0), + m_rxd_handler(*this), + m_dcd_handler(*this), + m_dsr_handler(*this), + m_ri_handler(*this), + m_cts_handler(*this), + m_dev(nullptr) +{ +} + +rs232_port_device::~rs232_port_device() +{ +} + +void rs232_port_device::device_config_complete() +{ + m_dev = dynamic_cast(get_card_device()); +} + +void rs232_port_device::device_start() +{ + m_rxd_handler.resolve_safe(); + m_dcd_handler.resolve_safe(); + m_dsr_handler.resolve_safe(); + m_ri_handler.resolve_safe(); + m_cts_handler.resolve_safe(); + + save_item(NAME(m_rxd)); + save_item(NAME(m_dcd)); + save_item(NAME(m_dsr)); + save_item(NAME(m_ri)); + save_item(NAME(m_cts)); + + m_rxd = 1; + m_dcd = 1; + m_dsr = 1; + m_ri = 1; + m_cts = 1; + + m_rxd_handler(1); + m_dcd_handler(1); + m_dsr_handler(1); + m_ri_handler(1); + m_cts_handler(1); +} + +WRITE_LINE_MEMBER( rs232_port_device::write_txd ) +{ + if(m_dev) + m_dev->input_txd(state); +} + +WRITE_LINE_MEMBER( rs232_port_device::write_dtr ) +{ + if(m_dev) + m_dev->input_dtr(state); +} + +WRITE_LINE_MEMBER( rs232_port_device::write_rts ) +{ + if(m_dev) + m_dev->input_rts(state); +} + +WRITE_LINE_MEMBER( rs232_port_device::write_etc ) +{ + if(m_dev) + m_dev->input_etc(state); +} + +device_rs232_port_interface::device_rs232_port_interface(const machine_config &mconfig, device_t &device) + : device_slot_card_interface(mconfig, device) +{ + m_port = dynamic_cast(device.owner()); +} + +device_rs232_port_interface::~device_rs232_port_interface() +{ +} + +#include "keyboard.h" +#include "loopback.h" +#include "null_modem.h" +#include "printer.h" +#include "pty.h" +#include "sun_kbd.h" +#include "terminal.h" + +SLOT_INTERFACE_START( default_rs232_devices ) + SLOT_INTERFACE("keyboard", SERIAL_KEYBOARD) + SLOT_INTERFACE("loopback", RS232_LOOPBACK) + SLOT_INTERFACE("null_modem", NULL_MODEM) + SLOT_INTERFACE("printer", SERIAL_PRINTER) + SLOT_INTERFACE("terminal", SERIAL_TERMINAL) + SLOT_INTERFACE("pty", PSEUDO_TERMINAL) + SLOT_INTERFACE("sunkbd", SUN_KBD_ADAPTOR) +SLOT_INTERFACE_END diff --git a/pool/shard006/C++/0084058_VertexArray.cpp b/pool/shard006/C++/0084058_VertexArray.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58feec9b99c35dfdaa32a2cfcb6999606d3a4a5c --- /dev/null +++ b/pool/shard006/C++/0084058_VertexArray.cpp @@ -0,0 +1,77 @@ +// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen +// Distributed under the MIT License. +// (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) + +#include "Graphics/VertexArray.h" + +#include "Graphics/Renderer.h" + +using rainbow::graphics::VertexArray; + +void VertexArray::unbind() +{ +#ifdef USE_VERTEX_ARRAY_OBJECT + glBindVertexArray(0); +#else + glBindBuffer(GL_ARRAY_BUFFER, 0); +#endif +} + +VertexArray::VertexArray(VertexArray&& va) noexcept : array_(va.array_) +{ +#ifdef USE_VERTEX_ARRAY_OBJECT + va.array_ = 0; +#endif +} + +VertexArray::~VertexArray() +{ +#ifdef USE_VERTEX_ARRAY_OBJECT + if (array_ == 0) + return; + + glDeleteVertexArrays(1, &array_); +#endif +} + +void VertexArray::bind() const +{ +#ifdef USE_VERTEX_ARRAY_OBJECT + glBindVertexArray(array_); +#else + array_(); +#endif +} + +auto VertexArray::init_state() const -> GLuint +{ +#ifdef USE_VERTEX_ARRAY_OBJECT + GLuint array; + glGenVertexArrays(1, &array); + glBindVertexArray(array); + graphics::bind_element_array(); + return array; +#else + return 0; +#endif +} + +void rainbow::graphics::draw(const VertexArray& array, uint32_t count) +{ + array.bind(); + glDrawElements( + GL_TRIANGLES, narrow_cast(count), GL_UNSIGNED_SHORT, nullptr); + + IF_DEBUG(increment_draw_count()); +} + +void rainbow::graphics::draw(const VertexArray& array, + uint32_t first, + uint32_t count) +{ + array.bind(); + glDrawArrays( + GL_TRIANGLES, narrow_cast(first), narrow_cast(count)); + + IF_DEBUG(increment_draw_count()); +} diff --git a/pool/shard006/C++/0084070_A.cc b/pool/shard006/C++/0084070_A.cc new file mode 100644 index 0000000000000000000000000000000000000000..4ad9f41db99753046141957c03572416bddee0c9 --- /dev/null +++ b/pool/shard006/C++/0084070_A.cc @@ -0,0 +1,34 @@ +#include +#include +#include +#include +#include +using namespace std; +#define iF if(Te) +#define MS(m) memset(m,0,sizeof(m)) +#ifdef XS + #include + const int Te=1; +#else + const int Te=0; +#endif + +typedef unsigned U; +typedef pair P; +void inp(); +int main(){ + ios_base::sync_with_stdio(0); + cin.tie(0); + int t; + cin>>t; + while(t--)inp(); + return 0; +} +void inp(){ + int a,b; + cin>>a>>b; + if(a>b)swap(a,b); + cout<(&Info); + size = FixTy.getFixedSize(); + } else { + // FIXME: Handle NonFixedTypeInfo here or assert that we won't + // encounter one. + size = Size(0); + } + return DebugTypeInfo(DC, Ty.getPointer(), Info.getStorageType(), size, + Info.getBestKnownAlignment()); +} + +DebugTypeInfo DebugTypeInfo::getLocalVariable(DeclContext *DeclCtx, + VarDecl *Decl, swift::Type Ty, + const TypeInfo &Info, + bool Unwrap) { + + auto DeclType = Ty; + if (DeclCtx) + DeclType = (Decl->hasType() + ? Decl->getType() + : DeclCtx->mapTypeIntoContext(Decl->getInterfaceType())); + auto RealType = Ty; + if (Unwrap) { + DeclType = DeclType->getInOutObjectType(); + RealType = RealType->getInOutObjectType(); + } + + // DynamicSelfType is also sugar as far as debug info is concerned. + auto DeclSelfType = DeclType; + if (auto DynSelfTy = DeclType->getAs()) + DeclSelfType = DynSelfTy->getSelfType(); + + // Prefer the original, potentially sugared version of the type if + // the type hasn't been mucked with by an optimization pass. + auto *Type = DeclSelfType->isEqual(RealType) ? DeclType.getPointer() + : RealType.getPointer(); + return getFromTypeInfo(DeclCtx, Type, Info); +} + +DebugTypeInfo DebugTypeInfo::getMetadata(swift::Type Ty, llvm::Type *StorageTy, + Size size, Alignment align) { + DebugTypeInfo DbgTy = {nullptr, Ty.getPointer(), StorageTy, size, align}; + assert(!DbgTy.isArchetype() && "type metadata cannot contain an archetype"); + return DbgTy; +} + +DebugTypeInfo DebugTypeInfo::getGlobal(SILGlobalVariable *GV, + llvm::Type *StorageTy, Size size, + Alignment align) { + // Prefer the original, potentially sugared version of the type if + // the type hasn't been mucked with by an optimization pass. + auto LowTy = GV->getLoweredType().getSwiftType(); + auto *Type = LowTy.getPointer(); + if (auto *Decl = GV->getDecl()) { + auto DeclType = + (Decl->hasType() ? Decl->getType() + : Decl->getDeclContext()->mapTypeIntoContext( + Decl->getInterfaceType())); + if (DeclType->isEqual(LowTy)) + Type = DeclType.getPointer(); + } + DebugTypeInfo DbgTy = {nullptr, Type, StorageTy, size, align}; + assert(StorageTy && "StorageType is a nullptr"); + assert(!DbgTy.isArchetype() && + "type of a global var cannot contain an archetype"); + assert(align.getValue() != 0); + return DbgTy; +} + +DebugTypeInfo DebugTypeInfo::getObjCClass(ClassDecl *theClass, + llvm::Type *StorageType, Size size, + Alignment align) { + DebugTypeInfo DbgTy(nullptr, theClass->getInterfaceType().getPointer(), + StorageType, size, align); + assert(!DbgTy.isArchetype() && + "type of an objc class cannot contain an archetype"); + return DbgTy; +} + +static bool typesEqual(Type A, Type B) { + if (A.getPointer() == B.getPointer()) + return true; + + // nullptr. + if (A.isNull() || B.isNull()) + return false; + + // Tombstone. + auto Tombstone = + llvm::DenseMapInfo::getTombstoneKey().getPointer(); + if ((A.getPointer() == Tombstone) || (B.getPointer() == Tombstone)) + return false; + + // Pointers are safe, do the real comparison. + return A->isSpelledLike(B.getPointer()); +} + +bool DebugTypeInfo::operator==(DebugTypeInfo T) const { + return typesEqual(getType(), T.getType()) && size == T.size && + align == T.align; +} + +bool DebugTypeInfo::operator!=(DebugTypeInfo T) const { return !operator==(T); } + +TypeDecl *DebugTypeInfo::getDecl() const { + if (auto *N = dyn_cast(Type)) + return N->getDecl(); + if (auto *TA = dyn_cast(Type)) + return TA->getDecl(); + if (auto *UBG = dyn_cast(Type)) + return UBG->getDecl(); + if (auto *BG = dyn_cast(Type)) + return BG->getDecl(); + return nullptr; +} + +void DebugTypeInfo::dump() const { + llvm::errs() << "[Size " << size.getValue() << " Alignment " + << align.getValue() << "] "; + + getType()->dump(); + if (StorageType) { + llvm::errs() << "StorageType="; + StorageType->dump(); + } +} diff --git a/pool/shard006/C++/0084080_Utility.cc b/pool/shard006/C++/0084080_Utility.cc new file mode 100644 index 0000000000000000000000000000000000000000..202d74c6ee8f3bf9f6c35c5ae277e2b7db3e8b68 --- /dev/null +++ b/pool/shard006/C++/0084080_Utility.cc @@ -0,0 +1,109 @@ +/* + * Copyright 2019 Applied Research Center for Computer Networks + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include + +#include + +namespace runos { + +struct ExecutionContext { + promise out; + + std::string stdout; + std::string stderr; +}; + +std::string Utility::quote(std::string_view arg) +{ + std::string ret; + ret.reserve(arg.size() + 10); + + ret += "\""; + for (auto c : arg) { + if (c == '"') { + ret += "\\\""; + } else if (c == '\\') { + ret += "\\\\"; + } else { + ret += c; + } + } + ret += "\""; + + return ret; +} + +future +Utility::exec(std::initializer_list args) const +{ + if (m_executable.empty()) { + THROW(UtilityError(""), "Executable is not set"); + } + + auto ctx = std::make_shared(); + + std::string cmd = m_executable.string(); + for (auto& arg : m_args) { cmd += " "; cmd += arg; } + for (auto& arg : args) { cmd += " "; cmd += quote(arg); } + + std::thread([cmd = std::move(cmd), ctx]() { + auto on_stdout = [ctx](const char* data, size_t size) { + ctx->stdout.append(data, size); + }; + + auto on_stderr = [ctx](const char* data, size_t size) { + ctx->stderr.append(data, size); + }; + + Process p {cmd, "", on_stdout, on_stderr}; + + auto status = p.get_exit_status(); + if (WIFEXITED(status)) { + auto code = WEXITSTATUS(status); + if (code == 0) { + ctx->out.set_value(std::move(ctx->stdout)); + } else if (code == 126) { + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityOSError(cmd), "Command invoked cannot execute")); + } else if (code == 127) { + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityOSError(cmd), "Command not found")); + } else if (code == 128) { + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityOSError(cmd), "Invalid argument to exit")); + } else { + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityProcessError(cmd), "Exited with code {}: {}", + code, std::move(ctx->stderr))); + } + } else if (WIFSIGNALED(status)) { + auto sig = WTERMSIG(status); + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityProcessError(cmd), "Killed by signal {}", sig)); + } else { + ctx->out.set_exception(MAKE_EXCEPTION( + UtilityError(cmd), "Unknown exit status: {]", status)); + } + }).detach(); + + return ctx->out.get_future();; +} + +} // runos diff --git a/pool/shard006/C++/0084084_StrBasedVTrie.cpp b/pool/shard006/C++/0084084_StrBasedVTrie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af4a83eed05b1e52b51f13ed859af2493fb96afc --- /dev/null +++ b/pool/shard006/C++/0084084_StrBasedVTrie.cpp @@ -0,0 +1,70 @@ +/* + * \file StrBasedVTrie.cpp + * \brief + * \date May 4, 2010 + * \author Vernkin Chen + */ + +#include "icma/util/StrBasedVTrie.h" + +namespace cma +{ + +bool createVTrie( const vector& words, VTrie& trie ) +{ + VTrieNode node; + node.data = 1; + for( vector::const_iterator itr = words.begin(); itr != words.end(); ++itr ) + { + trie.insert( itr->data(), &node ); + } + return true; +} + + +StrBasedVTrie::StrBasedVTrie( VTrie* pTrie ) + : trie(pTrie), + completeSearch(false) +{ +} + + +void StrBasedVTrie::reset() +{ + completeSearch = true; + node.init(); +} + + +bool StrBasedVTrie::search( const char *p ) +{ + if(!completeSearch) + return false; + + while(node.moreLong && *p) + { + trie->find(*p, &node); + //cout<<"finding,"< 0 || node.moreLong); + + return completeSearch; +} + + +bool StrBasedVTrie::firstSearch( const char* p ) +{ + reset(); + return search( p ); +} + + +bool StrBasedVTrie::exists() +{ + return completeSearch && node.data > 0; +} + +} diff --git a/pool/shard006/C++/0084089_mitkCESTImageNormalizationFilter.cpp b/pool/shard006/C++/0084089_mitkCESTImageNormalizationFilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b57ad942f68c85609dab3db0ab1f480fa293e64 --- /dev/null +++ b/pool/shard006/C++/0084089_mitkCESTImageNormalizationFilter.cpp @@ -0,0 +1,167 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include "mitkCESTImageNormalizationFilter.h" + +#include +#include +#include +#include + +#include + +mitk::CESTImageNormalizationFilter::CESTImageNormalizationFilter() +{ +} + +mitk::CESTImageNormalizationFilter::~CESTImageNormalizationFilter() +{ +} + +void mitk::CESTImageNormalizationFilter::GenerateData() +{ + mitk::Image::ConstPointer inputImage = this->GetInput(0); + if ((inputImage->GetDimension() != 4)) + { + mitkThrow() << "mitk::CESTImageNormalizationFilter:GenerateData works only with 4D images, sorry."; + return; + } + + auto resultMitkImage = this->GetOutput(); + AccessFixedDimensionByItk(inputImage, NormalizeTimeSteps, 4); + + resultMitkImage->SetClonedTimeGeometry(inputImage->GetTimeGeometry()); + +} + +template +void mitk::CESTImageNormalizationFilter::NormalizeTimeSteps(const itk::Image* image) +{ + typedef itk::Image ImageType; + typedef itk::Image OutputImageType; + + std::string offsets = ""; + this->GetInput()->GetPropertyList()->GetStringProperty(mitk::CustomTagParser::m_OffsetsPropertyName.c_str(), offsets); + + std::vector parts; + boost::split(parts, offsets, boost::is_any_of(" ")); + + // determine normalization images + std::vector mZeroIndices; + for (unsigned int index = 0; index < parts.size(); ++index) + { + if ((std::stod(parts.at(index)) < -299) || (std::stod(parts.at(index)) > 299)) + { + mZeroIndices.push_back(index); + } + } + + auto resultImage = OutputImageType::New(); + resultImage->SetRegions(image->GetLargestPossibleRegion()); + resultImage->Allocate(); + resultImage->FillBuffer(0); + + unsigned int numberOfTimesteps = image->GetLargestPossibleRegion().GetSize(3); + + typename ImageType::RegionType lowerMZeroRegion = image->GetLargestPossibleRegion(); + lowerMZeroRegion.SetSize(3, 1); + typename ImageType::RegionType upperMZeroRegion = image->GetLargestPossibleRegion(); + upperMZeroRegion.SetSize(3, 1); + typename ImageType::RegionType sourceRegion = image->GetLargestPossibleRegion(); + sourceRegion.SetSize(3, 1); + typename OutputImageType::RegionType targetRegion = resultImage->GetLargestPossibleRegion(); + targetRegion.SetSize(3, 1); + + for (unsigned int timestep = 0; timestep < numberOfTimesteps; ++timestep) + { + unsigned int lowerMZeroIndex = mZeroIndices[0]; + unsigned int upperMZeroIndex = mZeroIndices[0]; + for (unsigned int loop = 0; loop < mZeroIndices.size(); ++loop) + { + if (mZeroIndices[loop] <= timestep) + { + lowerMZeroIndex = mZeroIndices[loop]; + } + if (mZeroIndices[loop] > timestep) + { + upperMZeroIndex = mZeroIndices[loop]; + break; + } + } + bool isMZero = (lowerMZeroIndex == timestep); + + double weight = 0.0; + if (lowerMZeroIndex == upperMZeroIndex) + { + weight = 1.0; + } + else + { + weight = 1.0 - double(timestep - lowerMZeroIndex) / double(upperMZeroIndex - lowerMZeroIndex); + } + + lowerMZeroRegion.SetIndex(3, lowerMZeroIndex); + upperMZeroRegion.SetIndex(3, upperMZeroIndex); + sourceRegion.SetIndex(3, timestep); + targetRegion.SetIndex(3, timestep); + + + itk::ImageRegionConstIterator lowerMZeroIterator(image, lowerMZeroRegion); + itk::ImageRegionConstIterator upperMZeroIterator(image, upperMZeroRegion); + itk::ImageRegionConstIterator sourceIterator(image, sourceRegion); + itk::ImageRegionIterator targetIterator(resultImage.GetPointer(), targetRegion); + + if (isMZero) + { + while (!sourceIterator.IsAtEnd()) + { + targetIterator.Set(double(sourceIterator.Get())); + + ++sourceIterator; + ++targetIterator; + } + } + else + { + while (!sourceIterator.IsAtEnd()) + { + targetIterator.Set(double(sourceIterator.Get()) / + (weight * lowerMZeroIterator.Get() + (1.0 - weight) * upperMZeroIterator.Get())); + + ++lowerMZeroIterator; + ++upperMZeroIterator; + ++sourceIterator; + ++targetIterator; + } + } + } + + // get Pointer to output image + mitk::Image::Pointer resultMitkImage = this->GetOutput(); + // write into output image + mitk::CastToMitkImage(resultImage, resultMitkImage); +} + +void mitk::CESTImageNormalizationFilter::GenerateOutputInformation() +{ + mitk::Image::ConstPointer input = this->GetInput(); + mitk::Image::Pointer output = this->GetOutput(); + + itkDebugMacro(<< "GenerateOutputInformation()"); + + output->SetClonedTimeGeometry(input->GetTimeGeometry()); + output->SetPropertyList(input->GetPropertyList()->Clone()); +} diff --git a/pool/shard006/C++/0084092_wave-mac-low.cc b/pool/shard006/C++/0084092_wave-mac-low.cc new file mode 100644 index 0000000000000000000000000000000000000000..259966f930c9a8532664b5d14322e2f839627fe1 --- /dev/null +++ b/pool/shard006/C++/0084092_wave-mac-low.cc @@ -0,0 +1,135 @@ +/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ +/* + * Copyright (c) 2008 INRIA + * Copyright (c) 2013 Dalian University of Technology + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation; + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Author: Mathieu Lacage + * Junling Bu + */ +#include "ns3/log.h" +#include "wave-mac-low.h" +#include "higher-tx-tag.h" + +namespace ns3 { + +NS_LOG_COMPONENT_DEFINE ("WaveMacLow"); + +NS_OBJECT_ENSURE_REGISTERED (WaveMacLow); + +TypeId +WaveMacLow::GetTypeId (void) +{ + static TypeId tid = TypeId ("ns3::WaveMacLow") + .SetParent () + .SetGroupName ("Wave") + .AddConstructor () + ; + return tid; +} +WaveMacLow::WaveMacLow () +{ + NS_LOG_FUNCTION (this); +} +WaveMacLow::~WaveMacLow () +{ + NS_LOG_FUNCTION (this); +} + +void +WaveMacLow::SetWaveNetDevice (Ptr device) +{ + m_scheduler = device->GetChannelScheduler (); + m_coordinator = device->GetChannelCoordinator (); + NS_ASSERT (m_scheduler != 0 && m_coordinator != 0); +} + +WifiTxVector +WaveMacLow::GetDataTxVector (Ptr packet, const WifiMacHeader *hdr) const +{ + NS_LOG_FUNCTION (this << packet << hdr); + HigherLayerTxVectorTag datatag; + bool found; + found = ConstCast (packet)->PeekPacketTag (datatag); + // if high layer has not controlled transmit parameters, the real transmit parameters + // will be determined by MAC layer itself. + if (!found) + { + return MacLow::GetDataTxVector (packet, hdr); + } + + // if high layer has set the transmit parameters with non-adaption mode, + // the real transmit parameters are determined by high layer. + if (!datatag.IsAdaptable ()) + { + return datatag.GetTxVector (); + } + + // if high layer has set the transmit parameters with non-adaption mode, + // the real transmit parameters are determined by both high layer and MAC layer. + WifiTxVector txHigher = datatag.GetTxVector (); + WifiTxVector txMac = MacLow::GetDataTxVector (packet, hdr); + WifiTxVector txAdapter; + // the DataRate set by higher layer is the minimum data rate + // which is the lower bound for the actual data rate. + if (txHigher.GetMode ().GetDataRate () > txMac.GetMode ().GetDataRate ()) + { + txAdapter.SetMode (txHigher.GetMode ()); + } + else + { + txAdapter.SetMode (txMac.GetMode ()); + } + // the TxPwr_Level set by higher layer is the maximum transmit + // power which is the upper bound for the actual transmit power; + txAdapter.SetTxPowerLevel (std::min (txHigher.GetTxPowerLevel (), txMac.GetTxPowerLevel ())); + + return txAdapter; +} + +void +WaveMacLow::StartTransmission (Ptr packet, + const WifiMacHeader* hdr, + MacLowTransmissionParameters params, + MacLowTransmissionListener *listener) +{ + NS_LOG_FUNCTION (this << packet << hdr << params << listener); + Ptr phy = MacLow::GetPhy (); + uint32_t curChannel = phy->GetChannelNumber (); + // if current channel access is not AlternatingAccess, just do as MacLow. + if (!m_scheduler->IsAlternatingAccessAssigned (curChannel)) + { + MacLow::StartTransmission (packet, hdr, params, listener); + return; + } + + Time transmissionTime = MacLow::CalculateTransmissionTime (packet, hdr, params); + Time remainingTime = m_coordinator->NeedTimeToGuardInterval (); + + if (transmissionTime > remainingTime) + { + // The attempt for this transmission will be canceled; + // and this packet will be pending for next transmission by EdcaTxopN class + NS_LOG_DEBUG ("Because the required transmission time = " << transmissionTime.GetMilliSeconds () + << "ms exceeds the remainingTime = " << remainingTime.GetMilliSeconds () + << "ms, currently this packet will not be transmitted."); + } + else + { + MacLow::StartTransmission (packet, hdr, params, listener); + } +} + +} // namespace ns3 diff --git a/pool/shard006/C++/0084095_cmdschematicnetlabeladd.cpp b/pool/shard006/C++/0084095_cmdschematicnetlabeladd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fdbeb0faba1a554973f37398aa39720a85c0c99 --- /dev/null +++ b/pool/shard006/C++/0084095_cmdschematicnetlabeladd.cpp @@ -0,0 +1,77 @@ +/* + * LibrePCB - Professional EDA for everyone! + * Copyright (C) 2013 Urban Bruhin + * http://librepcb.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 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +/***************************************************************************************** + * Includes + ****************************************************************************************/ +#include +#include "cmdschematicnetlabeladd.h" +#include "../schematic.h" +#include "../items/si_netlabel.h" + +/***************************************************************************************** + * Namespace + ****************************************************************************************/ +namespace librepcb { +namespace project { + +/***************************************************************************************** + * Constructors / Destructor + ****************************************************************************************/ + +CmdSchematicNetLabelAdd::CmdSchematicNetLabelAdd(Schematic& schematic, NetSignal& netsignal, + const Point& position) noexcept : + UndoCommand(tr("Add netlabel")), + mSchematic(schematic), mNetSignal(&netsignal), mPosition(position), mNetLabel(nullptr) +{ +} + +CmdSchematicNetLabelAdd::~CmdSchematicNetLabelAdd() noexcept +{ +} + +/***************************************************************************************** + * Inherited from UndoCommand + ****************************************************************************************/ + +bool CmdSchematicNetLabelAdd::performExecute() throw (Exception) +{ + mNetLabel = new SI_NetLabel(mSchematic, *mNetSignal, mPosition); // can throw + + performRedo(); // can throw + + return true; +} + +void CmdSchematicNetLabelAdd::performUndo() throw (Exception) +{ + mSchematic.removeNetLabel(*mNetLabel); // can throw +} + +void CmdSchematicNetLabelAdd::performRedo() throw (Exception) +{ + mSchematic.addNetLabel(*mNetLabel); // can throw +} + +/***************************************************************************************** + * End of File + ****************************************************************************************/ + +} // namespace project +} // namespace librepcb diff --git a/pool/shard006/C++/0084097_psoundpositionedsource.cpp b/pool/shard006/C++/0084097_psoundpositionedsource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47e0f5da3e364bad1689d2a33bde34fb9483e268 --- /dev/null +++ b/pool/shard006/C++/0084097_psoundpositionedsource.cpp @@ -0,0 +1,100 @@ +#include +#include + +#include +#include +#include + +#include +#include + + + + +using namespace pSound ; + + + + +int +main(int argc, char** argv) +{ + // + // [0] Create a context immediately. This is mandatory on Winzows + // + ALState::instance() ; + + + + // + // [1] Read the buffer + // + + Buffer* buffer = dynamic_cast( osgDB::readObjectFile("sound.wav") ) ; +// Buffer* buffer = ( osgDB::readObjectFile("sound.ogg") ) ; + + if( ! buffer ) { + std::cerr << "Cannot read \"sound.wav\"" << std::endl ; + exit( -1 ) ; + } + + + + + + // + // [2] Create and setup the source + // + + Source* source = new Source() ; + + source->setBuffer( buffer ) ; + source->setAutoPlay( true ) ; + + source->setParam( Source::LOOPING, AL_TRUE ) ; +#if 0 + source->setParam( Source::REFERENCE_DISTANCE, atof( argv[1] )) ; + source->setVelocityMixingFactor( atof(argv[2]) ) ; +#endif + + + + + + // + // [3] create the graphics + // + + osg::Geode* graphics = new osg::Geode() ; + + graphics->addDrawable( + + new osg::ShapeDrawable( + new osg::Sphere() + ) + + ) ; + + + + + // + // [4] write out the graph + // + + osg::ref_ptr root = new osg::Group() ; + + root->addChild( source ) ; + root->addChild( graphics ) ; + + + + std::cout << "Writing graph to output.osgb.." << std::endl ; + + osgDB::writeNodeFile(*root, "output.osgb") ; + + std::cout << "Done!" << std::endl ; + + + return 0 ; +} diff --git a/pool/shard006/C++/0084101_tiledb_array_write_sparse_2.cc b/pool/shard006/C++/0084101_tiledb_array_write_sparse_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..347fdaaa073035ab9fa45b21fb1aa1564522a48a --- /dev/null +++ b/pool/shard006/C++/0084101_tiledb_array_write_sparse_2.cc @@ -0,0 +1,107 @@ +/** + * @file tiledb_array_write_sparse_2.cc + * + * @section LICENSE + * + * The MIT License + * + * @copyright Copyright (c) 2016 MIT and Intel Corporation + * + * 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. + * + * @section DESCRIPTION + * + * It shows how to write to a sparse array with two sorted batch writes. + */ + +#include "tiledb.h" + +int main() { + // Initialize context with the default configuration parameters + TileDB_CTX* tiledb_ctx; + tiledb_ctx_init(&tiledb_ctx, NULL); + + // Initialize array + TileDB_Array* tiledb_array; + tiledb_array_init( + tiledb_ctx, // Context + &tiledb_array, // Array object + "my_workspace/sparse_arrays/my_array_B", // Array name + TILEDB_ARRAY_WRITE, // Mode + NULL, // Entire domain + NULL, // All attributes + 0); // Number of attributes + + // Prepare cell buffers - #1 + int buffer_a1[] = { 0, 1, 2 }; + size_t buffer_a2[] = { 0, 1, 3, 6, 10, 11, 13, 16 }; + const char buffer_var_a2[] = "abbcccddddeffggghhhh"; + float buffer_a3[] = + { + 0.1, 0.2, 1.1, 1.2, 2.1, 2.2, 3.1, 3.2, + 4.1, 4.2, 5.1, 5.2, 6.1, 6.2, 7.1, 7.2 + }; + int64_t buffer_coords[] = { 1, 1, 1, 2 }; + const void* buffers[] = + { buffer_a1, buffer_a2, buffer_var_a2, buffer_a3, buffer_coords }; + size_t buffer_sizes[] = + { + sizeof(buffer_a1), + sizeof(buffer_a2), + sizeof(buffer_var_a2)-1, // No need to store the last '\0' character + sizeof(buffer_a3), + sizeof(buffer_coords) + }; + + // Write to array - #1 + tiledb_array_write(tiledb_array, buffers, buffer_sizes); + + // Prepare cell buffers - #2 + int buffer_a1_2[] = { 3, 4, 5, 6, 7 }; + size_t* buffer_a2_2 = NULL; + const char* buffer_var_a2_2 = NULL; + float* buffer_a3_2 = NULL; + int64_t buffer_coords_2[] = { 1, 4, 2, 3, 3, 1, 4, 2, 3, 3, 3, 4 }; + const void* buffers_2[] = + { + buffer_a1_2, + buffer_a2_2, + buffer_var_a2_2, + buffer_a3_2, + buffer_coords_2 }; + size_t buffer_sizes_2[] = + { + sizeof(buffer_a1_2), + 0, + 0, + 0, + sizeof(buffer_coords_2) + }; + + // Write to array - #2 + tiledb_array_write(tiledb_array, buffers_2, buffer_sizes_2); + + // Finalize array + tiledb_array_finalize(tiledb_array); + + // Finalize context + tiledb_ctx_finalize(tiledb_ctx); + + return 0; +} diff --git a/pool/shard006/C++/0084104_speech_recognition_dispatcher.cc b/pool/shard006/C++/0084104_speech_recognition_dispatcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..b5437e94b67c1013d5c201b44841280113fd0521 --- /dev/null +++ b/pool/shard006/C++/0084104_speech_recognition_dispatcher.cc @@ -0,0 +1,244 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/renderer/speech_recognition_dispatcher.h" + +#include "base/basictypes.h" +#include "base/utf_string_conversions.h" +#include "content/common/speech_recognition_messages.h" +#include "content/renderer/render_view_impl.h" +#include "third_party/WebKit/Source/Platform/chromium/public/WebString.h" +#include "third_party/WebKit/Source/Platform/chromium/public/WebVector.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSpeechGrammar.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSpeechRecognitionParams.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSpeechRecognitionResult.h" +#include "third_party/WebKit/Source/WebKit/chromium/public/WebSpeechRecognizerClient.h" + +using WebKit::WebVector; +using WebKit::WebString; +using WebKit::WebSpeechGrammar; +using WebKit::WebSpeechRecognitionHandle; +using WebKit::WebSpeechRecognitionResult; +using WebKit::WebSpeechRecognitionParams; +using WebKit::WebSpeechRecognizerClient; + +namespace content { + +SpeechRecognitionDispatcher::SpeechRecognitionDispatcher( + RenderViewImpl* render_view) + : RenderViewObserver(render_view), + recognizer_client_(NULL), + next_id_(1) { +} + +SpeechRecognitionDispatcher::~SpeechRecognitionDispatcher() { +} + +bool SpeechRecognitionDispatcher::OnMessageReceived( + const IPC::Message& message) { + bool handled = true; + IPC_BEGIN_MESSAGE_MAP(SpeechRecognitionDispatcher, message) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_Started, OnRecognitionStarted) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_AudioStarted, OnAudioStarted) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_SoundStarted, OnSoundStarted) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_SoundEnded, OnSoundEnded) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_AudioEnded, OnAudioEnded) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_ErrorOccurred, OnErrorOccurred) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_Ended, OnRecognitionEnded) + IPC_MESSAGE_HANDLER(SpeechRecognitionMsg_ResultRetrieved, + OnResultsRetrieved) + IPC_MESSAGE_UNHANDLED(handled = false) + IPC_END_MESSAGE_MAP() + return handled; +} + +void SpeechRecognitionDispatcher::start( + const WebSpeechRecognitionHandle& handle, + const WebSpeechRecognitionParams& params, + WebSpeechRecognizerClient* recognizer_client) { + DCHECK(!recognizer_client_ || recognizer_client_ == recognizer_client); + recognizer_client_ = recognizer_client; + + SpeechRecognitionHostMsg_StartRequest_Params msg_params; + for (size_t i = 0; i < params.grammars().size(); ++i) { + const WebSpeechGrammar& grammar = params.grammars()[i]; + msg_params.grammars.push_back( + SpeechRecognitionGrammar(grammar.src().spec(), grammar.weight())); + } + msg_params.language = UTF16ToUTF8(params.language()); + msg_params.max_hypotheses = static_cast(params.maxAlternatives()); + msg_params.continuous = params.continuous(); + msg_params.interim_results = params.interimResults(); + msg_params.origin_url = params.origin().toString().utf8(); + msg_params.render_view_id = routing_id(); + msg_params.request_id = GetOrCreateIDForHandle(handle); + // The handle mapping will be removed in |OnRecognitionEnd|. + Send(new SpeechRecognitionHostMsg_StartRequest(msg_params)); +} + +void SpeechRecognitionDispatcher::stop( + const WebSpeechRecognitionHandle& handle, + WebSpeechRecognizerClient* recognizer_client) { + // Ignore a |stop| issued without a matching |start|. + if (recognizer_client_ != recognizer_client || !HandleExists(handle)) + return; + Send(new SpeechRecognitionHostMsg_StopCaptureRequest( + routing_id(), GetOrCreateIDForHandle(handle))); +} + +void SpeechRecognitionDispatcher::abort( + const WebSpeechRecognitionHandle& handle, + WebSpeechRecognizerClient* recognizer_client) { + // Ignore an |abort| issued without a matching |start|. + if (recognizer_client_ != recognizer_client || !HandleExists(handle)) + return; + Send(new SpeechRecognitionHostMsg_AbortRequest( + routing_id(), GetOrCreateIDForHandle(handle))); +} + +void SpeechRecognitionDispatcher::OnRecognitionStarted(int request_id) { + recognizer_client_->didStart(GetHandleFromID(request_id)); +} + +void SpeechRecognitionDispatcher::OnAudioStarted(int request_id) { + recognizer_client_->didStartAudio(GetHandleFromID(request_id)); +} + +void SpeechRecognitionDispatcher::OnSoundStarted(int request_id) { + recognizer_client_->didStartSound(GetHandleFromID(request_id)); +} + +void SpeechRecognitionDispatcher::OnSoundEnded(int request_id) { + recognizer_client_->didEndSound(GetHandleFromID(request_id)); +} + +void SpeechRecognitionDispatcher::OnAudioEnded(int request_id) { + recognizer_client_->didEndAudio(GetHandleFromID(request_id)); +} + +static WebSpeechRecognizerClient::ErrorCode WebKitErrorCode( + SpeechRecognitionErrorCode e) { + switch (e) { + case SPEECH_RECOGNITION_ERROR_NONE: + NOTREACHED(); + return WebSpeechRecognizerClient::OtherError; + case SPEECH_RECOGNITION_ERROR_ABORTED: + return WebSpeechRecognizerClient::AbortedError; + case SPEECH_RECOGNITION_ERROR_AUDIO: + return WebSpeechRecognizerClient::AudioCaptureError; + case SPEECH_RECOGNITION_ERROR_NETWORK: + return WebSpeechRecognizerClient::NetworkError; + case SPEECH_RECOGNITION_ERROR_NOT_ALLOWED: + return WebSpeechRecognizerClient::NotAllowedError; + case SPEECH_RECOGNITION_ERROR_NO_SPEECH: + return WebSpeechRecognizerClient::NoSpeechError; + case SPEECH_RECOGNITION_ERROR_NO_MATCH: + NOTREACHED(); + return WebSpeechRecognizerClient::OtherError; + case SPEECH_RECOGNITION_ERROR_BAD_GRAMMAR: + return WebSpeechRecognizerClient::BadGrammarError; + } + NOTREACHED(); + return WebSpeechRecognizerClient::OtherError; +} + +void SpeechRecognitionDispatcher::OnErrorOccurred( + int request_id, const SpeechRecognitionError& error) { + if (error.code == SPEECH_RECOGNITION_ERROR_NO_MATCH) { + recognizer_client_->didReceiveNoMatch(GetHandleFromID(request_id), + WebSpeechRecognitionResult()); + } else { + recognizer_client_->didReceiveError( + GetHandleFromID(request_id), + WebString(), // TODO(primiano): message? + WebKitErrorCode(error.code)); + } +} + +void SpeechRecognitionDispatcher::OnRecognitionEnded(int request_id) { + // TODO(tommi): It is possible that the handle isn't found in the array if + // the user just refreshed the page. It seems that we then get a notification + // for the previously loaded instance of the page. + HandleMap::iterator iter = handle_map_.find(request_id); + if (iter == handle_map_.end()) { + DLOG(ERROR) << "OnRecognitionEnded called for a handle that doesn't exist"; + } else { + WebSpeechRecognitionHandle handle = iter->second; + // Note: we need to erase the handle from the map *before* calling didEnd. + // didEnd may call back synchronously to start a new recognition session, + // and we don't want to delete the handle from the map after that happens. + handle_map_.erase(request_id); + recognizer_client_->didEnd(handle); + } +} + +void SpeechRecognitionDispatcher::OnResultsRetrieved( + int request_id, const SpeechRecognitionResults& results) { + size_t provisional_count = 0; + SpeechRecognitionResults::const_iterator it = results.begin(); + for (; it != results.end(); ++it) { + if (it->is_provisional) + ++provisional_count; + } + + WebVector provisional(provisional_count); + WebVector final( + results.size() - provisional_count); + + int provisional_index = 0, final_index = 0; + for (it = results.begin(); it != results.end(); ++it) { + const SpeechRecognitionResult& result = (*it); + WebSpeechRecognitionResult* webkit_result = result.is_provisional ? + &provisional[provisional_index++] : &final[final_index++]; + + const size_t num_hypotheses = result.hypotheses.size(); + WebVector transcripts(num_hypotheses); + WebVector confidences(num_hypotheses); + for (size_t i = 0; i < num_hypotheses; ++i) { + transcripts[i] = result.hypotheses[i].utterance; + confidences[i] = static_cast(result.hypotheses[i].confidence); + } + webkit_result->assign(transcripts, confidences, !result.is_provisional); + } + + recognizer_client_->didReceiveResults( + GetHandleFromID(request_id), final, provisional); +} + + +int SpeechRecognitionDispatcher::GetOrCreateIDForHandle( + const WebSpeechRecognitionHandle& handle) { + // Search first for an existing mapping. + for (HandleMap::iterator iter = handle_map_.begin(); + iter != handle_map_.end(); + ++iter) { + if (iter->second.equals(handle)) + return iter->first; + } + // If no existing mapping found, create a new one. + const int new_id = next_id_; + handle_map_[new_id] = handle; + ++next_id_; + return new_id; +} + +bool SpeechRecognitionDispatcher::HandleExists( + const WebSpeechRecognitionHandle& handle) { + for (HandleMap::iterator iter = handle_map_.begin(); + iter != handle_map_.end(); + ++iter) { + if (iter->second.equals(handle)) + return true; + } + return false; +} + +const WebSpeechRecognitionHandle& SpeechRecognitionDispatcher::GetHandleFromID( + int request_id) { + HandleMap::iterator iter = handle_map_.find(request_id); + DCHECK(iter != handle_map_.end()); + return iter->second; +} + +} // namespace content diff --git a/pool/shard006/C++/0084115_read_jpeg_image.cpp b/pool/shard006/C++/0084115_read_jpeg_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..319b27ed477749c1f10a0d534f7e30fc004637a8 --- /dev/null +++ b/pool/shard006/C++/0084115_read_jpeg_image.cpp @@ -0,0 +1,83 @@ +/* + * libgphoto++ - modern c++ wrapper library for gphoto2 + * Copyright (C) 2016 Marco Gulino + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program. If not, see . +*/ + +#include "read_jpeg_image.h" + #include + #include + #include +#define cimg_plugin "plugins/jpeg_buffer.h" + +#include +#include +#include +#include +using namespace GPhotoCPP; +using namespace cimg_library; +using namespace std; + + +DPTR_CLASS(ReadJPEGImage) { +public: + Private(ReadJPEGImage *q); + typedef function &)> LoadImage; + ReadImage::Image read_from(LoadImage loader, const std::string &filename); +private: + ReadJPEGImage *q; +}; + +ReadJPEGImage::Private::Private(ReadJPEGImage* q) : q{q} +{ +} + +ReadJPEGImage::ReadJPEGImage() : dptr(this) +{ +} + +ReadJPEGImage::~ReadJPEGImage() +{ +} + +ReadImage::Image ReadJPEGImage::read(const vector< uint8_t >& data, const string& filename) +{ + return d->read_from([&](CImg &img){ + img.load_jpeg_buffer(data.data(), data.size()); + }, filename); +} + + +ReadImage::Image ReadJPEGImage::read(const string& file_path) +{ + return d->read_from([&](CImg &img) { img.load_jpeg(file_path.c_str()); }, file_path); +} + +ReadImage::Image ReadJPEGImage::Private::read_from(ReadJPEGImage::Private::LoadImage loader, const string& filename) +{ + CImg cimg_image; + loader(cimg_image); + Image image{cimg_image.width(), cimg_image.height(), 8, filename}; + auto channels = cimg_image.get_split('c'); + static vector channels_map{ Image::Red, Image::Green, Image::Blue, Image::Grey }; + + auto channels_map_offset = channels.size() == 1 ? 3 : 0; + for(int i=0; iinit_channel(image, channels_map[i+channels_map_offset]); + copy(channels[i].begin(), channels[i].end(), pixels.begin()); + } + return image; + +} diff --git a/pool/shard006/C++/0084121_template-typing.cpp b/pool/shard006/C++/0084121_template-typing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97533358f2cc39d94341900a1b6a2525f19d7979 --- /dev/null +++ b/pool/shard006/C++/0084121_template-typing.cpp @@ -0,0 +1,25 @@ +#include +#include + +template class A { +public: + A(A &&src) = default; + A(const A &src) = default; + A() {} + + typedef T value_type; +}; + +template +auto foo(const A &a) + -> decltype(std::cos(typename A::value_type())) { + return std::cos(typename A::value_type()); +} + +int main() { + A a1; + A a2(a1); + A a3; + auto result = foo(a3); + std::cout << result << std::endl; +} diff --git a/pool/shard006/C++/0084125_CApply.cpp b/pool/shard006/C++/0084125_CApply.cpp new file mode 100644 index 0000000000000000000000000000000000000000..066c5e08331e04dd3057ebed1ab7dd5d8a894fea --- /dev/null +++ b/pool/shard006/C++/0084125_CApply.cpp @@ -0,0 +1,77 @@ +#include "CApply.h" + +CApply::CApply(string name,vector * arguments) + : CExpr() +{ +// cout << "created CApply"<(); +} +CApply::~CApply() +{ + if(m_eArguments) + { + while (m_eArguments->size()>0) + { + delete m_eArguments->back(); + m_eArguments->pop_back(); + } + } + delete m_eArguments; + +} + + +CExpr* CApply::clone() +{ + CApply *result=new CApply(m_sFunction); + for(int i=0;isize();i++) + { + result->addArgument(getArgument(i)->clone()); + } + return result; +} + +void CApply::accept(CVisitor* v) +{ + if(v) v->visit(this); +} + +void CApply::addArgument(CExpr* e) { + m_eArguments->push_back(e); +} + +int CApply::getNumArguments() { + return m_eArguments->size(); +} +CExpr* CApply::getArgument(unsigned int i) { + if(i>=m_eArguments->size()) { + return 0; //ERROR + } + return m_eArguments->at(i); +} + +string CApply::getFunction(){ + return m_sFunction; +} + +bool CApply::operator== (CExpr& other) +{ + CApply* a= dynamic_cast (&other); + if(a==0) + return false; + if(m_sFunction!=a->m_sFunction) + return false; + int n=getNumArguments(); + if(n!=a->getNumArguments()) + return false; + for(int i=0; igetArgument(i))) + return false; + } + return true; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084133_SynchronousLoaderClientCFNet.cpp b/pool/shard006/C++/0084133_SynchronousLoaderClientCFNet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65758089056627e24a901b174f8cc6ff5c62e3ba --- /dev/null +++ b/pool/shard006/C++/0084133_SynchronousLoaderClientCFNet.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "SynchronousLoaderClient.h" + +#if USE(CFNETWORK) + +#include "AuthenticationChallenge.h" +#include "ResourceHandle.h" +#include + +namespace WebCore { + +void SynchronousLoaderClient::didReceiveAuthenticationChallenge(ResourceHandle* handle, const AuthenticationChallenge& challenge) +{ + // FIXME: The user should be asked for credentials, as in async case. + CFURLConnectionUseCredential(handle->connection(), 0, challenge.cfURLAuthChallengeRef()); +} + +ResourceError SynchronousLoaderClient::platformBadResponseError() +{ + RetainPtr cfError = adoptCF(CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainCFNetwork, kCFURLErrorBadServerResponse, 0)); + return cfError.get(); +} + +} // namespace WebCore + +#endif // USE(CFNETWORK) diff --git a/pool/shard006/C++/0084134_RtpsTransportHeader.cpp b/pool/shard006/C++/0084134_RtpsTransportHeader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abec13624f4678ecd2d14344563fbbbc15434d7c --- /dev/null +++ b/pool/shard006/C++/0084134_RtpsTransportHeader.cpp @@ -0,0 +1,56 @@ +/* + * $Id: RtpsTransportHeader.cpp 4982 2011-10-12 14:46:06Z mitza $ + * + * + * Distributed under the OpenDDS License. + * See: http://www.opendds.org/license.html + */ + +#include "RtpsTransportHeader.h" + +#include "dds/DCPS/Serializer.h" +#include "dds/DCPS/RTPS/BaseMessageTypes.h" +#include "dds/DCPS/RTPS/RtpsMessageTypesTypeSupportImpl.h" + +#ifndef __ACE_INLINE__ +#include "RtpsTransportHeader.inl" +#endif + +namespace { + const ACE_CDR::Octet PROTOCOL_RTPS[] = {'R', 'T', 'P', 'S'}; + const OpenDDS::DCPS::SequenceNumber dummy; +} + +namespace OpenDDS { +namespace DCPS { + +void +RtpsTransportHeader::init(ACE_Message_Block& mb) +{ + // Byte order doesn't matter for RTPS::Header, since it's + // exclusively structs/arrays of octet. + Serializer ser(&mb, false, Serializer::ALIGN_CDR); + valid_ = (ser >> header_); + + if (valid_) { + + // length_ started as the total number of bytes in the datagram's payload. + // When we return to the TransportReceiveStrategy it must be the number + // of bytes remaining after processing this RTPS::Header. + length_ -= max_marshaled_size(); + + // RTPS spec v2.1 section 8.3.6.3 + valid_ = std::equal(header_.prefix, header_.prefix + sizeof(header_.prefix), + PROTOCOL_RTPS); + valid_ &= (header_.version.major == OpenDDS::RTPS::PROTOCOLVERSION.major); + } +} + +const SequenceNumber& +RtpsTransportHeader::sequence() +{ + return dummy; +} + +} +} diff --git a/pool/shard006/C++/0084138_GUIDialogPVRChannelGuide.cpp b/pool/shard006/C++/0084138_GUIDialogPVRChannelGuide.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43f5da6914faf18fa3d8b1c1701b89101d876889 --- /dev/null +++ b/pool/shard006/C++/0084138_GUIDialogPVRChannelGuide.cpp @@ -0,0 +1,161 @@ +/* + * Copyright (C) 2012-2013 Team XBMC + * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see + * . + * + */ + +#include "GUIDialogPVRChannelGuide.h" + +#include "FileItem.h" +#include "guilib/GUIWindowManager.h" +#include "input/Key.h" +#include "ServiceBroker.h" +#include "view/ViewState.h" + +#include "pvr/PVRGUIActions.h" +#include "pvr/PVRManager.h" +#include "pvr/epg/Epg.h" + +using namespace PVR; + +#define CONTROL_LIST 11 + +CGUIDialogPVRChannelGuide::CGUIDialogPVRChannelGuide() + : CGUIDialog(WINDOW_DIALOG_PVR_CHANNEL_GUIDE, "DialogPVRChannelGuide.xml") +{ + m_loadType = LOAD_ON_GUI_INIT; + m_vecItems.reset(new CFileItemList); +} + +CGUIDialogPVRChannelGuide::~CGUIDialogPVRChannelGuide() = default; + +bool CGUIDialogPVRChannelGuide::OnMessage(CGUIMessage& message) +{ + switch (message.GetMessage()) + { + case GUI_MSG_CLICKED: + { + int iControl = message.GetSenderId(); + + if (m_viewControl.HasControl(iControl)) // list/thumb control + { + int iItem = m_viewControl.GetSelectedItem(); + int iAction = message.GetParam1(); + + if (iAction == ACTION_SELECT_ITEM || iAction == ACTION_MOUSE_LEFT_CLICK) + { + ShowInfo(iItem); + return true; + } + } + } + break; + } + + return CGUIDialog::OnMessage(message); +} + +void CGUIDialogPVRChannelGuide::Open(const CPVRChannelPtr &channel) +{ + m_channel = channel; + CGUIDialog::Open(); +} + +void CGUIDialogPVRChannelGuide::OnInitWindow() +{ + // no user-specific channel is set use current playing channel + if (!m_channel) + m_channel = CServiceBroker::GetPVRManager().GetCurrentChannel(); + + // no channel at all, close the dialog + if (!m_channel) + { + Close(); + return; + } + + // lock our display, as this window is rendered from the player thread + g_graphicsContext.Lock(); + m_viewControl.SetCurrentView(DEFAULT_VIEW_LIST); + + // empty the list ready for population + Clear(); + + m_channel->GetEPG(*m_vecItems); + m_viewControl.SetItems(*m_vecItems); + + g_graphicsContext.Unlock(); + + // call init + CGUIDialog::OnInitWindow(); + + // select the active entry + unsigned int iSelectedItem = 0; + for (int iEpgPtr = 0; iEpgPtr < m_vecItems->Size(); ++iEpgPtr) + { + CFileItemPtr entry = m_vecItems->Get(iEpgPtr); + if (entry->HasEPGInfoTag() && entry->GetEPGInfoTag()->IsActive()) + { + iSelectedItem = iEpgPtr; + break; + } + } + m_viewControl.SetSelectedItem(iSelectedItem); +} + +void CGUIDialogPVRChannelGuide::OnDeinitWindow(int nextWindowID) +{ + CGUIDialog::OnDeinitWindow(nextWindowID); + m_channel.reset(); + Clear(); +} + +void CGUIDialogPVRChannelGuide::Clear() +{ + m_viewControl.Clear(); + m_vecItems->Clear(); +} + +void CGUIDialogPVRChannelGuide::ShowInfo(int item) +{ + if (item < 0 || item >= (int)m_vecItems->Size()) + return; + + CServiceBroker::GetPVRManager().GUIActions()->ShowEPGInfo(m_vecItems->Get(item)); +} + +void CGUIDialogPVRChannelGuide::OnWindowLoaded() +{ + CGUIDialog::OnWindowLoaded(); + m_viewControl.Reset(); + m_viewControl.SetParentWindow(GetID()); + m_viewControl.AddView(GetControl(CONTROL_LIST)); +} + +void CGUIDialogPVRChannelGuide::OnWindowUnload() +{ + CGUIDialog::OnWindowUnload(); + m_viewControl.Reset(); +} + +CGUIControl *CGUIDialogPVRChannelGuide::GetFirstFocusableControl(int id) +{ + if (m_viewControl.HasControl(id)) + id = m_viewControl.GetCurrentControl(); + + return CGUIWindow::GetFirstFocusableControl(id); +} diff --git a/pool/shard006/C++/0084139_password_store_factory_util.cc b/pool/shard006/C++/0084139_password_store_factory_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c73f481468a7e5a5a66ded21fcb985884fb1c9b --- /dev/null +++ b/pool/shard006/C++/0084139_password_store_factory_util.cc @@ -0,0 +1,97 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/password_manager/core/browser/password_store_factory_util.h" + +#include + +#include "base/memory/ptr_util.h" +#include "components/password_manager/core/browser/affiliated_match_helper.h" +#include "components/password_manager/core/browser/affiliation_service.h" +#include "components/password_manager/core/browser/affiliation_utils.h" +#include "components/password_manager/core/browser/password_manager_constants.h" +#include "components/password_manager/core/common/password_manager_features.h" + +namespace password_manager { + +namespace { + +bool ShouldAffiliationBasedMatchingBeActive( + sync_driver::SyncService* sync_service) { + return base::FeatureList::IsEnabled(features::kAffiliationBasedMatching) && + sync_service && sync_service->CanSyncStart() && + sync_service->IsSyncActive() && + sync_service->GetPreferredDataTypes().Has(syncer::PASSWORDS) && + !sync_service->IsUsingSecondaryPassphrase(); +} + +void ActivateAffiliationBasedMatching( + PasswordStore* password_store, + net::URLRequestContextGetter* request_context_getter, + const base::FilePath& db_path, + scoped_refptr db_thread_runner) { + // The PasswordStore is so far the only consumer of the AffiliationService, + // therefore the service is owned by the AffiliatedMatchHelper, which in + // turn is owned by the PasswordStore. + std::unique_ptr affiliation_service( + new AffiliationService(db_thread_runner)); + affiliation_service->Initialize(request_context_getter, db_path); + std::unique_ptr affiliated_match_helper( + new AffiliatedMatchHelper(password_store, + std::move(affiliation_service))); + affiliated_match_helper->Initialize(); + password_store->SetAffiliatedMatchHelper(std::move(affiliated_match_helper)); + + password_store->enable_propagating_password_changes_to_web_credentials( + base::FeatureList::IsEnabled(features::kAffiliationBasedMatching)); +} + +base::FilePath GetAffiliationDatabasePath(const base::FilePath& profile_path) { + return profile_path.Append(kAffiliationDatabaseFileName); +} + +} // namespace + +void ToggleAffiliationBasedMatchingBasedOnPasswordSyncedState( + PasswordStore* password_store, + sync_driver::SyncService* sync_service, + net::URLRequestContextGetter* request_context_getter, + const base::FilePath& profile_path, + scoped_refptr db_thread_runner) { + DCHECK(password_store); + + const bool matching_should_be_active = + ShouldAffiliationBasedMatchingBeActive(sync_service); + const bool matching_is_active = + password_store->affiliated_match_helper() != nullptr; + + if (matching_should_be_active && !matching_is_active) { + ActivateAffiliationBasedMatching(password_store, request_context_getter, + GetAffiliationDatabasePath(profile_path), + db_thread_runner); + } else if (!matching_should_be_active && matching_is_active) { + password_store->SetAffiliatedMatchHelper( + base::WrapUnique(nullptr)); + } +} + +void TrimOrDeleteAffiliationCacheForStoreAndPath( + PasswordStore* password_store, + const base::FilePath& profile_path, + scoped_refptr db_thread_runner) { + if (password_store && password_store->affiliated_match_helper()) { + password_store->TrimAffiliationCache(); + } else { + AffiliationService::DeleteCache(GetAffiliationDatabasePath(profile_path), + db_thread_runner.get()); + } +} + +std::unique_ptr CreateLoginDatabase( + const base::FilePath& profile_path) { + base::FilePath login_db_file_path = profile_path.Append(kLoginDataFileName); + return base::WrapUnique(new LoginDatabase(login_db_file_path)); +} + +} // namespace password_manager diff --git a/pool/shard006/C++/0084142_Graph.cpp b/pool/shard006/C++/0084142_Graph.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb22aee0bffa0f2117a1a6817621d4a468235c90 --- /dev/null +++ b/pool/shard006/C++/0084142_Graph.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +using namespace seqan; + +int main () +{ + typedef unsigned int TCargo; + typedef Graph > TGraph; + typedef VertexDescriptor::Type TVertexDescriptor; + + TGraph g; + + TVertexDescriptor vert0 = addVertex(g); + TVertexDescriptor vert1 = addVertex(g); + TVertexDescriptor vert2 = addVertex(g); + TVertexDescriptor vert3 = addVertex(g); + TVertexDescriptor vert4 = addVertex(g); + TVertexDescriptor vert5 = addVertex(g); + TVertexDescriptor vert6 = addVertex(g); + TVertexDescriptor vert7 = addVertex(g); + + /*addEdge(g, vertBerlin, vertHamburg, 289); + addEdge(g, vertBerlin, vertHannover, 286); + addEdge(g, vertBerlin, vertMainz, 573); + addEdge(g, vertBerlin, vertMuenchen, 586); + addEdge(g, vertHannover, vertMuenchen, 572); + addEdge(g, vertHamburg, vertMainz, 521);*/ + + TVertexDescriptor arrayedges[]={vert1,vert0,vert0,vert4,vert2,vert1,vert4,vert1,vert5,vert1,vert6,vert2,vert3,vert2,vert2,vert3,vert7,vert3,vert5,vert4,vert6,vert5,vert5,vert6,vert7,vert6,vert7,b + vert7}; + + addEdges(g,arrayedges,14); + //FILE* strmWrite = fopen("graph.dot", "w"); + //write(strmWrite, g, DotDrawing()); + //fclose(strmWrite); + ::std::cout << g << ::std::endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084150_bitcoind.cpp b/pool/shard006/C++/0084150_bitcoind.cpp new file mode 100644 index 0000000000000000000000000000000000000000..204ebd7df632fa889e945db29ed2e3f7cd74c27b --- /dev/null +++ b/pool/shard006/C++/0084150_bitcoind.cpp @@ -0,0 +1,177 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2019 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#if defined(HAVE_CONFIG_H) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +const std::function G_TRANSLATION_FUN = nullptr; + +static void WaitForShutdown(NodeContext& node) +{ + while (!ShutdownRequested()) + { + UninterruptibleSleep(std::chrono::milliseconds{200}); + } + Interrupt(node); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Start +// +static bool AppInit(int argc, char* argv[]) +{ + NodeContext node; + node.chain = interfaces::MakeChain(node); + + bool fRet = false; + + util::ThreadSetInternalName("init"); + + // + // Parameters + // + // If Qt is used, parameters/bitcoin.conf are parsed in qt/vertcoin.cpp's main() + SetupServerArgs(); + std::string error; + if (!gArgs.ParseParameters(argc, argv, error)) { + return InitError(strprintf("Error parsing command line arguments: %s\n", error)); + } + + // Process help and version before taking care about datadir + if (HelpRequested(gArgs) || gArgs.IsArgSet("-version")) { + std::string strUsage = PACKAGE_NAME " version " + FormatFullVersion() + "\n"; + + if (gArgs.IsArgSet("-version")) + { + strUsage += FormatParagraph(LicenseInfo()) + "\n"; + } + else + { + strUsage += "\nUsage: vertcoind [options] Start " PACKAGE_NAME "\n"; + strUsage += "\n" + gArgs.GetHelpMessage(); + } + + tfm::format(std::cout, "%s", strUsage); + return true; + } + + try + { + if (!CheckDataDirOption()) { + return InitError(strprintf("Specified data directory \"%s\" does not exist.\n", gArgs.GetArg("-datadir", ""))); + } + if (!gArgs.ReadConfigFiles(error, true)) { + return InitError(strprintf("Error reading configuration file: %s\n", error)); + } + // Check for -chain, -testnet or -regtest parameter (Params() calls are only valid after this clause) + try { + SelectParams(gArgs.GetChainName()); + } catch (const std::exception& e) { + return InitError(strprintf("%s\n", e.what())); + } + + // Error out when loose non-argument tokens are encountered on command line + for (int i = 1; i < argc; i++) { + if (!IsSwitchChar(argv[i][0])) { + return InitError(strprintf("Command line contains unexpected token '%s', see bitcoind -h for a list of options.\n", argv[i])); + } + } + + // -server defaults to true for bitcoind but not for the GUI so do this here + gArgs.SoftSetBoolArg("-server", true); + // Set this early so that parameter interactions go to console + InitLogging(); + InitParameterInteraction(); + if (!AppInitBasicSetup()) + { + // InitError will have been called with detailed error, which ends up on console + return false; + } + if (!AppInitParameterInteraction()) + { + // InitError will have been called with detailed error, which ends up on console + return false; + } + if (!AppInitSanityChecks()) + { + // InitError will have been called with detailed error, which ends up on console + return false; + } + if (gArgs.GetBoolArg("-daemon", false)) + { +#if HAVE_DECL_DAEMON +#if defined(MAC_OSX) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + tfm::format(std::cout, PACKAGE_NAME " starting\n"); + + // Daemonize + if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) + return InitError(strprintf("daemon() failed: %s\n", strerror(errno))); + } +#if defined(MAC_OSX) +#pragma GCC diagnostic pop +#endif +#else + return InitError("-daemon is not supported on this operating system\n"); +#endif // HAVE_DECL_DAEMON + } + // Lock data directory after daemonization + if (!AppInitLockDataDirectory()) + { + // If locking the data directory failed, exit immediately + return false; + } + fRet = AppInitMain(node); + } + catch (const std::exception& e) { + PrintExceptionContinue(&e, "AppInit()"); + } catch (...) { + PrintExceptionContinue(nullptr, "AppInit()"); + } + + if (!fRet) + { + Interrupt(node); + } else { + WaitForShutdown(node); + } + Shutdown(node); + + return fRet; +} + +int main(int argc, char* argv[]) +{ +#ifdef WIN32 + util::WinCmdLineArgs winArgs; + std::tie(argc, argv) = winArgs.get(); +#endif + SetupEnvironment(); + + // Connect bitcoind signal handlers + noui_connect(); + + return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); +} diff --git a/pool/shard006/C++/0084151_AutoCurrentCapacityController.cpp b/pool/shard006/C++/0084151_AutoCurrentCapacityController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..764776148ab4fa997681a277a62914d6d8e275bf --- /dev/null +++ b/pool/shard006/C++/0084151_AutoCurrentCapacityController.cpp @@ -0,0 +1,67 @@ +// Copyright (C) 2016 Sam C. Lin +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License +// +// 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. +// +// See LICENSE for a copy of the GNU General Public License or see +// it online at . + +#include "open_evse.h" + +#ifdef PP_AUTO_AMPACITY + +static PP_AMPS s_ppAmps[] = { + {0,0}, + {93,63}, // 100 = 93 + {185,32}, // 220 = 185 + {415,20}, // 680 = 415 + {615,13}, // 1.5K = 615 + {1023,0} +}; + +AutoCurrentCapacityController::AutoCurrentCapacityController() : + adcPP(PP_PIN) +{ +} + +uint8_t AutoCurrentCapacityController::ReadPPMaxAmps() +{ + // n.b. should probably sample a few times and average it + uint16_t adcval = adcPP.read(); + + uint8_t amps = 0; + for (uint8_t i=1;i < sizeof(s_ppAmps)/sizeof(s_ppAmps[0]);i++) { + if (adcval <= (s_ppAmps[i].adcVal - (s_ppAmps[i].adcVal - s_ppAmps[i-1].adcVal)/2)) { + amps = s_ppAmps[i-1].amps; + break; + } + } + + // Serial.print("pp: ");Serial.print(adcval);Serial.print(" amps: ");Serial.println(amps); + + return amps; +} + + +uint8_t AutoCurrentCapacityController::AutoSetCurrentCapacity() +{ + uint8_t amps = ReadPPMaxAmps(); + + if (amps) { + g_EvseController.SetCurrentCapacity(amps,0,1); + return 0; + } + else { + return 1; + } +} + +#endif //PP_AUTO_AMPACITY + + diff --git a/pool/shard006/C++/0084157_chrome_appcache_service.cc b/pool/shard006/C++/0084157_chrome_appcache_service.cc new file mode 100644 index 0000000000000000000000000000000000000000..ca429b92c08205b62c6d2529a7e0abf864e9b31f --- /dev/null +++ b/pool/shard006/C++/0084157_chrome_appcache_service.cc @@ -0,0 +1,81 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/appcache/chrome_appcache_service.h" + +#include "base/files/file_path.h" +#include "content/browser/appcache/appcache_storage_impl.h" +#include "content/public/browser/browser_thread.h" +#include "content/public/browser/content_browser_client.h" +#include "content/public/browser/resource_context.h" +#include "net/base/net_errors.h" +#include "net/url_request/url_request_context_getter.h" +#include "webkit/browser/quota/quota_manager.h" + +namespace content { + +ChromeAppCacheService::ChromeAppCacheService( + storage::QuotaManagerProxy* quota_manager_proxy) + : AppCacheServiceImpl(quota_manager_proxy), resource_context_(NULL) { +} + +void ChromeAppCacheService::InitializeOnIOThread( + const base::FilePath& cache_path, + ResourceContext* resource_context, + net::URLRequestContextGetter* request_context_getter, + scoped_refptr special_storage_policy) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + + cache_path_ = cache_path; + resource_context_ = resource_context; + + // The |request_context_getter| can be NULL in some unit tests. + // + // TODO(ajwong): TestProfile is difficult to work with. The + // SafeBrowsing tests require that GetRequestContext return NULL + // so we can't depend on having a non-NULL value here. See crbug/149783. + if (request_context_getter) + set_request_context(request_context_getter->GetURLRequestContext()); + + // Init our base class. + Initialize( + cache_path_, + BrowserThread::GetMessageLoopProxyForThread( + BrowserThread::FILE_USER_BLOCKING) + .get(), + BrowserThread::GetMessageLoopProxyForThread(BrowserThread::CACHE).get()); + set_appcache_policy(this); + set_special_storage_policy(special_storage_policy.get()); +} + +bool ChromeAppCacheService::CanLoadAppCache(const GURL& manifest_url, + const GURL& first_party) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + // We don't prompt for read access. + return GetContentClient()->browser()->AllowAppCache( + manifest_url, first_party, resource_context_); +} + +bool ChromeAppCacheService::CanCreateAppCache( + const GURL& manifest_url, const GURL& first_party) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); + return GetContentClient()->browser()->AllowAppCache( + manifest_url, first_party, resource_context_); +} + +ChromeAppCacheService::~ChromeAppCacheService() {} + +void ChromeAppCacheService::DeleteOnCorrectThread() const { + if (BrowserThread::CurrentlyOn(BrowserThread::IO)) { + delete this; + return; + } + if (BrowserThread::IsMessageLoopValid(BrowserThread::IO)) { + BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE, this); + return; + } + // Better to leak than crash on shutdown. +} + +} // namespace content diff --git a/pool/shard006/C++/0084165_MainMenuState.cpp b/pool/shard006/C++/0084165_MainMenuState.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04bf78105c66632a19b27be8f7f645288413e3ba --- /dev/null +++ b/pool/shard006/C++/0084165_MainMenuState.cpp @@ -0,0 +1,193 @@ +//******************************************************************************************** +//* +//* This file is part of Egoboo. +//* +//* Egoboo is free software: you can redistribute it and/or modify it +//* under the terms of the GNU General Public License as published by +//* the Free Software Foundation, either version 3 of the License, or +//* (at your option) any later version. +//* +//* Egoboo 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 Egoboo. If not, see . +//* +//******************************************************************************************** + +/// @file game/GameStates/MainMenuState.cpp +/// @details The Main Menu of the game, the first screen presented to the players +/// @author Johan Jansen + +#include "game/GameStates/MainMenuState.hpp" +#include "game/GameStates/DebugMainMenuState.hpp" +#include "game/GameStates/SelectModuleState.hpp" +#include "game/GameStates/SelectPlayersState.hpp" +#include "game/GameStates/OptionsScreen.hpp" +#include "game/GameStates/MapEditorSelectModuleState.hpp" +#include "game/Core/GameEngine.hpp" +#include "game/game.h" +#include "game/GUI/Button.hpp" +#include "game/GUI/Image.hpp" +#include "game/GUI/Label.hpp" + +MainMenuState::MainMenuState() : + _slidyButtons() +{ + std::shared_ptr background; + std::shared_ptr gameLogo; + + //Special xmas theme + if (Zeitgeist::CheckTime(Zeitgeist::Time::Christmas)) + { + background = std::make_shared("mp_data/menu/menu_xmas"); + gameLogo = std::make_shared("mp_data/menu/snowy_logo"); + } + + //Special Halloween theme + else if (Zeitgeist::CheckTime(Zeitgeist::Time::Halloween)) + { + background = std::make_shared("mp_data/menu/menu_halloween"); + gameLogo = std::make_shared("mp_data/menu/creepy_logo"); + } + + //Default egoboo theme + else + { + background = std::make_shared("mp_data/menu/menu_main"); + gameLogo = std::make_shared("mp_data/menu/menu_logo"); + } + + const int SCREEN_WIDTH = _gameEngine->getUIManager()->getScreenWidth(); + const int SCREEN_HEIGHT = _gameEngine->getUIManager()->getScreenHeight(); + + // calculate the centered position of the background + background->setSize(Vector2f(background->getTextureWidth(), background->getTextureHeight())); + background->setCenterPosition(Point2f(SCREEN_WIDTH/2, SCREEN_HEIGHT/2)); + addComponent(background); + + // calculate the position of the logo + gameLogo->setPosition(background->getPosition()); + gameLogo->setSize(Vector2f(gameLogo->getTextureWidth(), gameLogo->getTextureHeight())); + addComponent(gameLogo); + + //Add the buttons + int yOffset = SCREEN_HEIGHT-80; + auto exitButton = std::make_shared("Exit Game", SDLK_ESCAPE); + exitButton->setPosition(Point2f(20, yOffset)); + exitButton->setSize(Vector2f(200, 30)); + _onExitButtonClicked = exitButton->Clicked.subscribe( + []{ + _gameEngine->shutdown(); + }); + addComponent(exitButton); + _slidyButtons.push_front(exitButton); + + yOffset -= exitButton->getHeight() + 10; + + auto optionsButton = std::make_shared("Options", SDLK_o); + optionsButton->setPosition(Point2f(20, yOffset)); + optionsButton->setSize(Vector2f(200, 30)); + _onOptionsButtonClicked = optionsButton->Clicked.subscribe( + []{ + _gameEngine->pushGameState(std::make_shared()); + }); + addComponent(optionsButton); + _slidyButtons.push_front(optionsButton); + + yOffset -= optionsButton->getHeight() + 10; + + auto loadGameButton = std::make_shared("Load Game", SDLK_l); + loadGameButton->setPosition(Point2f(20, yOffset)); + loadGameButton->setSize(Vector2f(200, 30)); + _onLoadGameButtonClicked = loadGameButton->Clicked.subscribe( + []{ + _gameEngine->pushGameState(std::make_shared()); + }); + addComponent(loadGameButton); + _slidyButtons.push_front(loadGameButton); + + yOffset -= loadGameButton->getHeight() + 10; + + auto newGameButton = std::make_shared("New Game", SDLK_n); + newGameButton->setPosition(Point2f(20, yOffset)); + newGameButton->setSize(Vector2f(200, 30)); + _onNewGameButtonClicked = newGameButton->Clicked.subscribe( + []{ + _gameEngine->pushGameState(std::make_shared()); + }); + addComponent(newGameButton); + _slidyButtons.push_front(newGameButton); + + yOffset -= newGameButton->getHeight() + 10; + + if (egoboo_config_t::get().debug_developerMode_enable.getValue()) + { + auto debugButton = std::make_shared("Debug", SDLK_UNKNOWN); + debugButton->setPosition(Point2f(20, yOffset)); + debugButton->setSize(Vector2f(200, 30)); + _onDebugButtonClicked = debugButton->Clicked.subscribe( + []{ + _gameEngine->pushGameState(std::make_shared()); + }); + addComponent(debugButton); + _slidyButtons.push_front(debugButton); + + yOffset -= debugButton->getHeight() + 10; + + auto mapEditorButton = std::make_shared("Map Editor", SDLK_m); + mapEditorButton->setPosition(Point2f(20, yOffset)); + mapEditorButton->setSize(Vector2f(200, 30)); + _onMapEditorButtonClicked = mapEditorButton->Clicked.subscribe( + []{ + _gameEngine->pushGameState(std::make_shared()); + }); + addComponent(mapEditorButton); + _slidyButtons.push_front(mapEditorButton); + } + + //Add version label and copyright text + auto welcomeLabel = std::make_shared( + "Welcome to Egoboo!\n" + "http://egoboo.sourceforge.net\n" + "Version 2.9.0"); + welcomeLabel->setPosition(Point2f(exitButton->getX() + exitButton->getWidth() + 40, + SCREEN_HEIGHT - SCREEN_HEIGHT/60 - welcomeLabel->getHeight())); + addComponent(welcomeLabel); +} + +MainMenuState::~MainMenuState() { + _onOptionsButtonClicked.disconnect(); + _onNewGameButtonClicked.disconnect(); + _onLoadGameButtonClicked.disconnect(); + _onDebugButtonClicked.disconnect(); + _onMapEditorButtonClicked.disconnect(); +} + +void MainMenuState::update() +{ +} + +void MainMenuState::drawContainer(Ego::GUI::DrawingContext& drawingContext) +{ + +} + +void MainMenuState::beginState() +{ + // menu settings + Ego::GraphicsSystem::get().window->setGrabEnabled(false); + _gameEngine->enableMouseCursor(); + + //Play the Egoboo theme music + playMainMenuSong(); + + float offset = 0; + for(const auto& button : _slidyButtons) + { + button->beginSlidyButtonEffect(button->getWidth() + offset); + offset += 20; + } +} diff --git a/pool/shard006/C++/0084168_filehttprequesthandler.cpp b/pool/shard006/C++/0084168_filehttprequesthandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f7d0d4905bcab013f45fc988ada24a06d18030a --- /dev/null +++ b/pool/shard006/C++/0084168_filehttprequesthandler.cpp @@ -0,0 +1,162 @@ +#include +#include +#include +#include +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + #include +#endif +#include + +#include "filehttprequesthandler.h" + +FileHTTPRequestHandler::FileHTTPRequestHandler(const QHash &s) : + HTTPRequestHandler(s), chunkSize(512*1024) +{ + unsigned int chunk_size_val; + bool ok; + chunk_size_val = settings["chunksize"].toUInt(&ok); + + if(ok){ + chunkSize = chunk_size_val*1024; + } +} + +void FileHTTPRequestHandler::createResponse(const HTTPRequest &requestData) +{ + response.clear(); + + QString fullPath = settings["docroot"].toString() + requestData.url.path(); + QFileInfo fileInfo(fullPath); + + if(!fileInfo.exists()){ + response.setStatusCode(404); + response.setReasonPhrase("Not Found"); + + emit responseWritten(response); + emit endOfWriting(); + + return; + } + + if(!fileInfo.isReadable()){ + qDebug() << "Not readable!"; + + response.setStatusCode(403); + response.setReasonPhrase("Forbidden"); + response.setBody("Permission denied\n"); + + emit responseWritten(response); + emit endOfWriting(); + + return; + } + + if(fileInfo.isDir()){ + serveDirContents(fullPath); + } + else{ + serveFileContents(fullPath); + } +} + +void FileHTTPRequestHandler::serveDirContents(const QString &path) +{ + QDir dir(path); + QStringList dirList = dir.entryList(); + + response.setStatusCode(200); + response.setReasonPhrase("OK"); + response.setHeaderField("Content-Type", "text/plain"); + response.setBody(dirList.join("\n")); + + emit responseWritten(response); + emit endOfWriting(); +} + +void FileHTTPRequestHandler::serveFileContents(const QString &path) +{ + QFile file(path); + + if(!file.open(QIODevice::ReadOnly)){ + qDebug() << "Cannot open " << path; + + response.setStatusCode(500); + response.setReasonPhrase("Internal Server Error"); + + emit responseWritten(response); + emit endOfWriting(); + + return; + } + + unsigned int fileSize = file.size(); + if(fileSize < chunkSize){ + chunkSize = fileSize; + } + + uchar *data = file.map(0, chunkSize); + + if(0 == data){ + response.setStatusCode(500); + response.setReasonPhrase("Internal Server Error"); + + emit responseWritten(response); + emit endOfWriting(); + + return; + } + + response.setStatusCode(200); + response.setReasonPhrase("OK"); + + #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + QMimeDatabase db; + QMimeType type = db.mimeTypeForFile(path); + if(type.isValid()){ + qDebug() << "Mime type:" << type.name(); + response.setHeaderField("Content-Type", type.name()); + } + #endif + + emit responseWritten(response); //send the headers + + emit rawDataWritten(data, chunkSize); //send the first part of the file + + if(chunkSize < fileSize){ + unsigned int pos = chunkSize; + unsigned int notSent = fileSize-chunkSize; + + for(; pos<=notSent; pos+=chunkSize){ + data = file.map(pos, chunkSize); + + if(0 == data){ + qDebug() << "for, data=0"; + emit endOfWriting(); + return; + } + + emit rawDataWritten(data, chunkSize); + } + + int diff = fileSize % chunkSize; + + if(0 == diff){ + qDebug() << "diff=0, done"; + emit endOfWriting(); + return; + } + + //what happens if diff is 0 + data = file.map(pos, diff); + + if(0 == data){ + qDebug() << "diff, data=0"; + emit endOfWriting(); + return; + } + + emit rawDataWritten(data, diff); + } + + emit endOfWriting(); +} diff --git a/pool/shard006/C++/0084171_GuardAI.cpp b/pool/shard006/C++/0084171_GuardAI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4e4daf354ed40bcb6cac0436fd5cbb74595477cc --- /dev/null +++ b/pool/shard006/C++/0084171_GuardAI.cpp @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2008-2019 TrinityCore + * Copyright (C) 2005-2009 MaNGOS + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "GuardAI.h" +#include "Creature.h" +#include "Errors.h" +#include "Log.h" +#include "MotionMaster.h" +#include "Player.h" + +GuardAI::GuardAI(Creature* creature) : ScriptedAI(creature) +{ +} + +int GuardAI::Permissible(Creature const* creature) +{ + if (creature->IsGuard()) + return PERMIT_BASE_SPECIAL; + + return PERMIT_BASE_NO; +} + +void GuardAI::UpdateAI(uint32 /*diff*/) +{ + if (!UpdateVictim()) + return; + + DoMeleeAttackIfReady(); +} + +bool GuardAI::CanSeeAlways(WorldObject const* obj) +{ + if (!obj->isType(TYPEMASK_UNIT)) + return false; + + ThreatContainer::StorageType threatList = me->getThreatManager().getThreatList(); + for (ThreatContainer::StorageType::const_iterator itr = threatList.begin(); itr != threatList.end(); ++itr) + if ((*itr)->getUnitGuid() == obj->GetGUID()) + return true; + + return false; +} + +void GuardAI::EnterEvadeMode(EvadeReason /*why*/) +{ + if (!me->IsAlive()) + { + me->GetMotionMaster()->MoveIdle(); + me->CombatStop(true); + me->DeleteThreatList(); + return; + } + + TC_LOG_DEBUG("entities.unit", "Guard entry: %u enters evade mode.", me->GetEntry()); + + me->RemoveAllAuras(); + me->DeleteThreatList(); + me->CombatStop(true); + + // Remove ChaseMovementGenerator from MotionMaster stack list, and add HomeMovementGenerator instead + if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == CHASE_MOTION_TYPE) + me->GetMotionMaster()->MoveTargetedHome(); +} + +void GuardAI::JustDied(Unit* killer) +{ + if (Player* player = killer->GetCharmerOrOwnerPlayerOrPlayerItself()) + me->SendZoneUnderAttackMessage(player); +} diff --git a/pool/shard006/C++/0084178_editaddressdialog.cpp b/pool/shard006/C++/0084178_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd3b0190606089eb4597ea8de99348a208e2a135 --- /dev/null +++ b/pool/shard006/C++/0084178_editaddressdialog.cpp @@ -0,0 +1,128 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setDisabled(true); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid RootCoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + } + + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard006/C++/0084179_MidiSenseWidget.cpp b/pool/shard006/C++/0084179_MidiSenseWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a819882248c769bcadda41e8c983b9601b42991 --- /dev/null +++ b/pool/shard006/C++/0084179_MidiSenseWidget.cpp @@ -0,0 +1,126 @@ +/* + * Hydrogen + * Copyright(c) 2002-2008 by Alex >Comix< Cominu [comix@users.sourceforge.net] + * + * http://www.hydrogen-music.org + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY, without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include "hydrogen/midi_map.h" +#include "MidiSenseWidget.h" +#include + +const char* MidiSenseWidget::__class_name = "MidiSenseWidget"; + +MidiSenseWidget::MidiSenseWidget(QWidget* pParent, bool directWr, MidiAction* midiAction): QDialog( pParent ) , Object(__class_name) +{ + m_DirectWrite = directWr; + m_pAction = midiAction; + + setWindowTitle( "Waiting.." ); + setFixedSize( 280, 100 ); + + bool midiOperable = false; + + m_pURLLabel = new QLabel( this ); + m_pURLLabel->setAlignment( Qt::AlignCenter ); + + if(m_pAction != NULL){ + m_pURLLabel->setText( "Waiting for midi input..." ); + midiOperable = true; + } else { + + /* + * Check if this widget got called from the midiTable in the preferences + * window(directWrite=false) or by clicking on a midiLearn-capable gui item(directWrite=true) + */ + + if(m_DirectWrite){ + m_pURLLabel->setText( trUtf8("This element is not midi operable.") ); + midiOperable = false; + } else { + m_pURLLabel->setText( trUtf8("Waiting for midi input...") ); + midiOperable = true; + } + } + + QVBoxLayout* pVBox = new QVBoxLayout( this ); + pVBox->addWidget( m_pURLLabel ); + setLayout( pVBox ); + + H2Core::Hydrogen *pEngine = H2Core::Hydrogen::get_instance(); + pEngine->lastMidiEvent = ""; + pEngine->lastMidiEventParameter = 0; + + m_LastMidiEventParameter = 0; + + m_pUpdateTimer = new QTimer( this ); + + if(midiOperable) + { + /* + * If the widget is not midi operable, we can omit + * starting the timer which listens to midi input.. + */ + + connect( m_pUpdateTimer, SIGNAL( timeout() ), this, SLOT( updateMidi() ) ); + m_pUpdateTimer->start( 100 ); + } +}; + +MidiSenseWidget::~MidiSenseWidget(){ + INFOLOG("DESTROY"); + m_pUpdateTimer->stop(); +} + +void MidiSenseWidget::updateMidi(){ + H2Core::Hydrogen *pEngine = H2Core::Hydrogen::get_instance(); + if( !pEngine->lastMidiEvent.isEmpty() ){ + m_sLastMidiEvent = pEngine->lastMidiEvent; + m_LastMidiEventParameter = pEngine->lastMidiEventParameter; + + + if( m_DirectWrite ){ + //write the action / parameter combination to the midiMap + MidiMap *pMidiMap = MidiMap::get_instance(); + + assert(m_pAction); + + MidiAction* pAction = new MidiAction( m_pAction->getType() ); + + pAction->setParameter1( m_pAction->getParameter1() ); + + if( m_sLastMidiEvent.left(2) == "CC" ){ + pMidiMap->registerCCEvent( m_LastMidiEventParameter , pAction ); + } else if( m_sLastMidiEvent.left(3) == "MMC" ){ + pMidiMap->registerMMCEvent( m_sLastMidiEvent , pAction ); + } else if( m_sLastMidiEvent.left(4) == "NOTE" ){ + pMidiMap->registerNoteEvent( m_LastMidiEventParameter , pAction ); + } else if (m_sLastMidiEvent.left(14) == "PROGRAM_CHANGE" ){ + pMidiMap->registerPCEvent( pAction ); + } else { + /* In all other cases, the midiMap cares for deleting the pointer */ + + delete pAction; + } + } + + close(); + } + +} + diff --git a/pool/shard006/C++/0084188_chrome_connected_header_helper.cc b/pool/shard006/C++/0084188_chrome_connected_header_helper.cc new file mode 100644 index 0000000000000000000000000000000000000000..56e2f2bf13da55eef6c3e08f6a6d4cf55be856db --- /dev/null +++ b/pool/shard006/C++/0084188_chrome_connected_header_helper.cc @@ -0,0 +1,218 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/signin/core/browser/chrome_connected_header_helper.h" + +#include + +#include "base/feature_list.h" +#include "base/logging.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_util.h" +#include "base/strings/stringprintf.h" +#include "build/build_config.h" +#include "components/google/core/common/google_util.h" +#include "components/signin/core/browser/cookie_settings_util.h" +#include "google_apis/gaia/gaia_auth_util.h" +#include "net/base/registry_controlled_domains/registry_controlled_domain.h" +#include "url/gurl.h" + +namespace signin { + +namespace { + +const char kConsistencyEnabledByDefaultAttrName[] = + "consistency_enabled_by_default"; +const char kContinueUrlAttrName[] = "continue_url"; +const char kEmailAttrName[] = "email"; +const char kEnableAccountConsistencyAttrName[] = "enable_account_consistency"; +const char kGaiaIdAttrName[] = "id"; +const char kIsSameTabAttrName[] = "is_same_tab"; +const char kIsSamlAttrName[] = "is_saml"; +const char kProfileModeAttrName[] = "mode"; +const char kServiceTypeAttrName[] = "action"; +#if defined(OS_ANDROID) +const char kEligibleForConsistency[] = "eligible_for_consistency"; +const char kShowConsistencyPromo[] = "show_consistency_promo"; +#endif + +// Determines the service type that has been passed from Gaia in the header. +GAIAServiceType GetGAIAServiceTypeFromHeader(const std::string& header_value) { + if (header_value == "SIGNOUT") + return GAIA_SERVICE_TYPE_SIGNOUT; + else if (header_value == "INCOGNITO") + return GAIA_SERVICE_TYPE_INCOGNITO; + else if (header_value == "ADDSESSION") + return GAIA_SERVICE_TYPE_ADDSESSION; + else if (header_value == "SIGNUP") + return GAIA_SERVICE_TYPE_SIGNUP; + else if (header_value == "DEFAULT") + return GAIA_SERVICE_TYPE_DEFAULT; + else + return GAIA_SERVICE_TYPE_NONE; +} + +} // namespace + +ChromeConnectedHeaderHelper::ChromeConnectedHeaderHelper( + AccountConsistencyMethod account_consistency) + : account_consistency_(account_consistency) {} + +// static +std::string ChromeConnectedHeaderHelper::BuildRequestCookieIfPossible( + const GURL& url, + const std::string& gaia_id, + AccountConsistencyMethod account_consistency, + const content_settings::CookieSettings* cookie_settings, + int profile_mode_mask) { + ChromeConnectedHeaderHelper chrome_connected_helper(account_consistency); + if (!chrome_connected_helper.ShouldBuildRequestHeader(url, cookie_settings)) + return ""; + return chrome_connected_helper.BuildRequestHeader( + false /* is_header_request */, url, gaia_id, profile_mode_mask); +} + +// static +ManageAccountsParams ChromeConnectedHeaderHelper::BuildManageAccountsParams( + const std::string& header_value) { + DCHECK(!header_value.empty()); + ManageAccountsParams params; + ResponseHeaderDictionary header_dictionary = + ParseAccountConsistencyResponseHeader(header_value); + ResponseHeaderDictionary::const_iterator it = header_dictionary.begin(); + for (; it != header_dictionary.end(); ++it) { + const std::string key_name(it->first); + const std::string value(it->second); + if (key_name == kServiceTypeAttrName) { + params.service_type = GetGAIAServiceTypeFromHeader(value); + } else if (key_name == kEmailAttrName) { + params.email = value; + } else if (key_name == kIsSamlAttrName) { + params.is_saml = value == "true"; + } else if (key_name == kContinueUrlAttrName) { + params.continue_url = value; + } else if (key_name == kIsSameTabAttrName) { + params.is_same_tab = value == "true"; +#if defined(OS_ANDROID) + } else if (key_name == kShowConsistencyPromo) { + params.show_consistency_promo = value == "true"; +#endif + } else { + DLOG(WARNING) << "Unexpected Gaia header attribute '" << key_name << "'."; + } + } + return params; +} + +bool ChromeConnectedHeaderHelper::ShouldBuildRequestHeader( + const GURL& url, + const content_settings::CookieSettings* cookie_settings) { + // If signin cookies are not allowed, don't add the header. + if (!SettingsAllowSigninCookies(cookie_settings)) + return false; + + // Check if url is eligible for the header. + if (!IsUrlEligibleForRequestHeader(url)) + return false; + + return true; +} + +bool ChromeConnectedHeaderHelper::IsUrlEligibleToIncludeGaiaId( + const GURL& url, + bool is_header_request) { + if (is_header_request) { + // Gaia ID is only necessary for Drive. Don't set it otherwise. + return IsDriveOrigin(url.GetOrigin()); + } + + // Cookie requests don't have the granularity to only include the Gaia ID for + // Drive origin. Set it on all google.com instead. + if (!url.SchemeIsCryptographic()) + return false; + + const std::string kGoogleDomain = "google.com"; + std::string domain = net::registry_controlled_domains::GetDomainAndRegistry( + url, net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES); + return domain == kGoogleDomain; +} + +bool ChromeConnectedHeaderHelper::IsDriveOrigin(const GURL& url) { + if (!url.SchemeIsCryptographic()) + return false; + + const GURL kGoogleDriveURL("https://drive.google.com"); + const GURL kGoogleDocsURL("https://docs.google.com"); + return url == kGoogleDriveURL || url == kGoogleDocsURL; +} + +bool ChromeConnectedHeaderHelper::IsUrlEligibleForRequestHeader( + const GURL& url) { + // Only set the header for Drive and Gaia always, and other Google properties + // if account consistency is enabled. Vasquette, which is integrated with most + // Google properties, needs the header to redirect certain user actions to + // Chrome native UI. Drive and Gaia need the header to tell if the current + // user is connected. + + // Consider the account ID sensitive and limit it to secure domains. + if (!url.SchemeIsCryptographic()) + return false; + + GURL origin(url.GetOrigin()); + bool is_google_url = + google_util::IsGoogleDomainUrl( + url, google_util::ALLOW_SUBDOMAIN, + google_util::DISALLOW_NON_STANDARD_PORTS) || + google_util::IsYoutubeDomainUrl(url, google_util::ALLOW_SUBDOMAIN, + google_util::DISALLOW_NON_STANDARD_PORTS); + bool is_mirror_enabled = + account_consistency_ == AccountConsistencyMethod::kMirror; + return (is_mirror_enabled && is_google_url) || IsDriveOrigin(origin) || + gaia::IsGaiaSignonRealm(origin); +} + +std::string ChromeConnectedHeaderHelper::BuildRequestHeader( + bool is_header_request, + const GURL& url, + const std::string& gaia_id, + int profile_mode_mask) { +// If we are on mobile or desktop, an empty |account_id| corresponds to the user +// not signed into Sync. Do not enforce account consistency, unless Mice is +// enabled on Android. +// On Chrome OS, an empty |account_id| corresponds to Public Sessions, Guest +// Sessions and Active Directory logins. Guest Sessions have already been +// filtered upstream and we want to enforce account consistency in Public +// Sessions and Active Directory logins. +#if !defined(OS_CHROMEOS) + if (gaia_id.empty()) { +#if defined(OS_ANDROID) + if (base::FeatureList::IsEnabled(kMobileIdentityConsistency)) { + return base::StringPrintf("%s=%s", kEligibleForConsistency, "true"); + } +#endif // defined(OS_ANDROID) + return std::string(); + } +#endif // !defined(OS_CHROMEOS) + + std::vector parts; + if (!gaia_id.empty() && + IsUrlEligibleToIncludeGaiaId(url, is_header_request)) { + // Only set the Gaia ID on domains that actually require it. + parts.push_back( + base::StringPrintf("%s=%s", kGaiaIdAttrName, gaia_id.c_str())); + } + parts.push_back( + base::StringPrintf("%s=%s", kProfileModeAttrName, + base::NumberToString(profile_mode_mask).c_str())); + bool is_mirror_enabled = + account_consistency_ == AccountConsistencyMethod::kMirror; + parts.push_back(base::StringPrintf("%s=%s", kEnableAccountConsistencyAttrName, + is_mirror_enabled ? "true" : "false")); + parts.push_back(base::StringPrintf( + "%s=%s", kConsistencyEnabledByDefaultAttrName, "false")); + + return base::JoinString(parts, is_header_request ? "," : ":"); +} + +} // namespace signin diff --git a/pool/shard006/C++/0084193_HttpInitiateConnectionCommand.cc b/pool/shard006/C++/0084193_HttpInitiateConnectionCommand.cc new file mode 100644 index 0000000000000000000000000000000000000000..74c74b7a748277b6bc677a7fee72c3fd86dfa1d5 --- /dev/null +++ b/pool/shard006/C++/0084193_HttpInitiateConnectionCommand.cc @@ -0,0 +1,150 @@ +/* */ +#include "HttpInitiateConnectionCommand.h" +#include "Request.h" +#include "DownloadEngine.h" +#include "HttpConnection.h" +#include "HttpRequest.h" +#include "Segment.h" +#include "HttpRequestCommand.h" +#include "HttpProxyRequestCommand.h" +#include "DlAbortEx.h" +#include "Option.h" +#include "Logger.h" +#include "LogFactory.h" +#include "SocketCore.h" +#include "message.h" +#include "prefs.h" +#include "A2STR.h" +#include "util.h" +#include "fmt.h" +#include "SocketRecvBuffer.h" +#include "BackupIPv4ConnectCommand.h" +#include "ConnectCommand.h" +#include "HttpRequestConnectChain.h" +#include "HttpProxyRequestConnectChain.h" + +namespace aria2 { + +HttpInitiateConnectionCommand::HttpInitiateConnectionCommand( + cuid_t cuid, const std::shared_ptr& req, + const std::shared_ptr& fileEntry, RequestGroup* requestGroup, + DownloadEngine* e) + : InitiateConnectionCommand(cuid, req, fileEntry, requestGroup, e) +{ +} + +HttpInitiateConnectionCommand::~HttpInitiateConnectionCommand() = default; + +std::unique_ptr HttpInitiateConnectionCommand::createNextCommand( + const std::string& hostname, const std::string& addr, uint16_t port, + const std::vector& resolvedAddresses, + const std::shared_ptr& proxyRequest) +{ + if (proxyRequest) { + std::shared_ptr pooledSocket = + getDownloadEngine()->popPooledSocket( + getRequest()->getHost(), getRequest()->getPort(), + proxyRequest->getHost(), proxyRequest->getPort()); + std::string proxyMethod = resolveProxyMethod(getRequest()->getProtocol()); + if (!pooledSocket) { + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, getCuid(), addr.c_str(), port)); + createSocket(); + getSocket()->establishConnection(addr, port); + + getRequest()->setConnectedAddrInfo(hostname, addr, port); + auto c = make_unique( + getCuid(), getRequest(), proxyRequest, getFileEntry(), + getRequestGroup(), getDownloadEngine(), getSocket()); + if (proxyMethod == V_TUNNEL) { + c->setControlChain(std::make_shared()); + } + else if (proxyMethod == V_GET) { + c->setControlChain(std::make_shared()); + } + else { + // Unreachable + assert(0); + } + setupBackupConnection(hostname, addr, port, c.get()); + return std::move(c); + } + else { + setConnectedAddrInfo(getRequest(), hostname, pooledSocket); + auto c = make_unique( + getCuid(), getRequest(), getFileEntry(), getRequestGroup(), + std::make_shared( + getCuid(), pooledSocket, + std::make_shared(pooledSocket)), + getDownloadEngine(), pooledSocket); + if (proxyMethod == V_GET) { + c->setProxyRequest(proxyRequest); + } + return std::move(c); + } + } + else { + std::shared_ptr pooledSocket = + getDownloadEngine()->popPooledSocket(resolvedAddresses, + getRequest()->getPort()); + if (!pooledSocket) { + A2_LOG_INFO(fmt(MSG_CONNECTING_TO_SERVER, getCuid(), addr.c_str(), port)); + createSocket(); + getSocket()->establishConnection(addr, port); + + getRequest()->setConnectedAddrInfo(hostname, addr, port); + auto c = make_unique(getCuid(), getRequest(), + proxyRequest, // must be null + getFileEntry(), getRequestGroup(), + getDownloadEngine(), getSocket()); + c->setControlChain(std::make_shared()); + setupBackupConnection(hostname, addr, port, c.get()); + return std::move(c); + } + else { + setSocket(pooledSocket); + setConnectedAddrInfo(getRequest(), hostname, pooledSocket); + + return make_unique( + getCuid(), getRequest(), getFileEntry(), getRequestGroup(), + std::make_shared( + getCuid(), getSocket(), + std::make_shared(getSocket())), + getDownloadEngine(), getSocket()); + } + } +} + +} // namespace aria2 diff --git a/pool/shard006/C++/0084200_recentrequeststablemodel.cpp b/pool/shard006/C++/0084200_recentrequeststablemodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..808d3f110eb50182c12ef74edfe62d5ea2dadcde --- /dev/null +++ b/pool/shard006/C++/0084200_recentrequeststablemodel.cpp @@ -0,0 +1,208 @@ +// Copyright (c) 2011-2014 The CoinsBazar developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "recentrequeststablemodel.h" + +#include "bitcoinunits.h" +#include "guiutil.h" +#include "optionsmodel.h" + +RecentRequestsTableModel::RecentRequestsTableModel(CWallet *wallet, WalletModel *parent) : + walletModel(parent) +{ + Q_UNUSED(wallet); + nReceiveRequestsMaxId = 0; + + // Load entries from wallet + std::vector vReceiveRequests; + parent->loadReceiveRequests(vReceiveRequests); + BOOST_FOREACH(const std::string& request, vReceiveRequests) + addNewRequest(request); + + /* These columns must match the indices in the ColumnIndex enumeration */ + columns << tr("Date") << tr("Label") << tr("Message") << tr("Amount"); +} + +RecentRequestsTableModel::~RecentRequestsTableModel() +{ + /* Intentionally left empty */ +} + +int RecentRequestsTableModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + + return list.length(); +} + +int RecentRequestsTableModel::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + + return columns.length(); +} + +QVariant RecentRequestsTableModel::data(const QModelIndex &index, int role) const +{ + if(!index.isValid() || index.row() >= list.length()) + return QVariant(); + + const RecentRequestEntry *rec = &list[index.row()]; + + if(role == Qt::DisplayRole || role == Qt::EditRole) + { + switch(index.column()) + { + case Date: + return GUIUtil::dateTimeStr(rec->date); + case Label: + if(rec->recipient.label.isEmpty() && role == Qt::DisplayRole) + { + return tr("(no label)"); + } + else + { + return rec->recipient.label; + } + case Message: + if(rec->recipient.message.isEmpty() && role == Qt::DisplayRole) + { + return tr("(no message)"); + } + else + { + return rec->recipient.message; + } + case Amount: + if (rec->recipient.amount == 0 && role == Qt::DisplayRole) + return tr("(no amount)"); + else + return CoinsBazarUnits::format(walletModel->getOptionsModel()->getDisplayUnit(), rec->recipient.amount); + } + } + return QVariant(); +} + +bool RecentRequestsTableModel::setData(const QModelIndex &index, const QVariant &value, int role) +{ + return true; +} + +QVariant RecentRequestsTableModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + if(orientation == Qt::Horizontal) + { + if(role == Qt::DisplayRole && section < columns.size()) + { + return columns[section]; + } + } + return QVariant(); +} + +QModelIndex RecentRequestsTableModel::index(int row, int column, const QModelIndex &parent) const +{ + Q_UNUSED(parent); + + return createIndex(row, column); +} + +bool RecentRequestsTableModel::removeRows(int row, int count, const QModelIndex &parent) +{ + Q_UNUSED(parent); + + if(count > 0 && row >= 0 && (row+count) <= list.size()) + { + const RecentRequestEntry *rec; + for (int i = 0; i < count; ++i) + { + rec = &list[row+i]; + if (!walletModel->saveReceiveRequest(rec->recipient.address.toStdString(), rec->id, "")) + return false; + } + + beginRemoveRows(parent, row, row + count - 1); + list.erase(list.begin() + row, list.begin() + row + count); + endRemoveRows(); + return true; + } else { + return false; + } +} + +Qt::ItemFlags RecentRequestsTableModel::flags(const QModelIndex &index) const +{ + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; +} + +// called when adding a request from the GUI +void RecentRequestsTableModel::addNewRequest(const SendCoinsRecipient &recipient) +{ + RecentRequestEntry newEntry; + newEntry.id = ++nReceiveRequestsMaxId; + newEntry.date = QDateTime::currentDateTime(); + newEntry.recipient = recipient; + + CDataStream ss(SER_DISK, CLIENT_VERSION); + ss << newEntry; + + if (!walletModel->saveReceiveRequest(recipient.address.toStdString(), newEntry.id, ss.str())) + return; + + addNewRequest(newEntry); +} + +// called from ctor when loading from wallet +void RecentRequestsTableModel::addNewRequest(const std::string &recipient) +{ + std::vector data(recipient.begin(), recipient.end()); + CDataStream ss(data, SER_DISK, CLIENT_VERSION); + + RecentRequestEntry entry; + ss >> entry; + + if (entry.id == 0) // should not happen + return; + + if (entry.id > nReceiveRequestsMaxId) + nReceiveRequestsMaxId = entry.id; + + addNewRequest(entry); +} + +// actually add to table in GUI +void RecentRequestsTableModel::addNewRequest(RecentRequestEntry &recipient) +{ + beginInsertRows(QModelIndex(), 0, 0); + list.prepend(recipient); + endInsertRows(); +} + +void RecentRequestsTableModel::sort(int column, Qt::SortOrder order) +{ + qSort(list.begin(), list.end(), RecentRequestEntryLessThan(column, order)); + emit dataChanged(index(0, 0, QModelIndex()), index(list.size() - 1, NUMBER_OF_COLUMNS - 1, QModelIndex())); +} + +bool RecentRequestEntryLessThan::operator()(RecentRequestEntry &left, RecentRequestEntry &right) const +{ + RecentRequestEntry *pLeft = &left; + RecentRequestEntry *pRight = &right; + if (order == Qt::DescendingOrder) + std::swap(pLeft, pRight); + + switch(column) + { + case RecentRequestsTableModel::Date: + return pLeft->date.toTime_t() < pRight->date.toTime_t(); + case RecentRequestsTableModel::Label: + return pLeft->recipient.label < pRight->recipient.label; + case RecentRequestsTableModel::Message: + return pLeft->recipient.message < pRight->recipient.message; + case RecentRequestsTableModel::Amount: + return pLeft->recipient.amount < pRight->recipient.amount; + default: + return pLeft->id < pRight->id; + } +} diff --git a/pool/shard006/C++/0084201_IPFIXObservationBridge.cpp b/pool/shard006/C++/0084201_IPFIXObservationBridge.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88792b24759c32010b6f31a60078a03b584de55c --- /dev/null +++ b/pool/shard006/C++/0084201_IPFIXObservationBridge.cpp @@ -0,0 +1,80 @@ +/* Copyright (c) 2011-2012 ETH Zürich. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the names of ETH Zürich nor the names of other contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL [8]", + "observationLabel(35566/805)[v]", + (const char*)0)); +} + + +bool IPFIXObservationBridge::canExport (std::shared_ptr& m) { + + // for now we only can handle bog-standard Observations. + return (m->type() == MSG_ID(Observation)); +} + +void IPFIXObservationBridge::exportMsg(std::shared_ptr& m, IPFIX::Exporter& e) { + + std::shared_ptr f = std::dynamic_pointer_cast(m); + + std::cerr << "exporter got observation" << std::endl; + + e.setTemplate(m_tid); + e.beginRecord(); + e.reserveVarlen(m_ievec[2], f->label().length()); + e.commitVarlen(); + e.putValue(m_ievec[0], f->otime()); + e.putValue(m_ievec[1], f->value()); + e.putValue(m_ievec[2], f->label()); + e.exportRecord(); +} + +void IPFIXObservationBridge::receiveRecord() { + + ustime_t time; + uint64_t value; + std::string label; + + assert(getValue(m_ievec[0], time)); + assert(getValue(m_ievec[1], value)); + assert(getValue(m_ievec[2], label)); + + std::cerr << "collector got record" << std::endl; + + sendMsg(std::move(std::make_shared(time, label, value))); + +} + +} diff --git a/pool/shard006/C++/0084208_stealth-secret.cpp b/pool/shard006/C++/0084208_stealth-secret.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd498c6a86ac5a92e9cb97523897b71a7b1d3963 --- /dev/null +++ b/pool/shard006/C++/0084208_stealth-secret.cpp @@ -0,0 +1,52 @@ +/** + * Copyright (c) 2011-2015 libgroestlcoin developers (see AUTHORS) + * + * This file is part of libgroestlcoin-explorer. + * + * libgroestlcoin-explorer is free software: you can redistribute it and/or + * modify it under the terms of the GNU Affero General Public License with + * additional permissions to the one published by the Free Software + * Foundation, either version 3 of the License, or (at your option) + * any later version. For more information see LICENSE. + * + * 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +#include + +#include +#include +#include +#include + +using namespace bc::explorer; +using namespace bc::explorer::commands; +using namespace bc::explorer::primitives; + +// This is the same as ec-add-secrets, except limited to two. +console_result stealth_secret::invoke(std::ostream& output, + std::ostream& error) +{ + // Bound parameters. + const auto& scan_secret = get_spend_secret_argument(); + const auto& shared_secret = get_shared_secret_argument(); + + // We avoid bc::uncover_stealth_secret because it eats the failure code. + + ec_private sum(scan_secret); + if (!bc::ec_add(sum.data(), shared_secret)) + { + error << BX_STEALTH_SECRET_OUT_OF_RANGE << std::endl; + return console_result::failure; + } + + output << sum << std::endl; + return console_result::okay; +} + diff --git a/pool/shard006/C++/0084217_Sink.cpp b/pool/shard006/C++/0084217_Sink.cpp new file mode 100644 index 0000000000000000000000000000000000000000..903b675fdd56e3ae56e166677801ae5b3e1d4073 --- /dev/null +++ b/pool/shard006/C++/0084217_Sink.cpp @@ -0,0 +1,279 @@ +//===-- Sink.cpp - Code Sinking -------------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This pass moves instructions into successor blocks, when possible, so that +// they aren't executed on paths where their results aren't needed. +// +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/Scalar.h" +#include "llvm/ADT/Statistic.h" +#include "llvm/Analysis/AliasAnalysis.h" +#include "llvm/Analysis/LoopInfo.h" +#include "llvm/Analysis/ValueTracking.h" +#include "llvm/IR/CFG.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/IR/Dominators.h" +#include "llvm/IR/IntrinsicInst.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/raw_ostream.h" +using namespace llvm; + +#define DEBUG_TYPE "sink" + +STATISTIC(NumSunk, "Number of instructions sunk"); +STATISTIC(NumSinkIter, "Number of sinking iterations"); + +namespace { + class Sinking : public FunctionPass { + DominatorTree *DT; + LoopInfo *LI; + AliasAnalysis *AA; + const DataLayout *DL; + + public: + static char ID; // Pass identification + Sinking() : FunctionPass(ID) { + initializeSinkingPass(*PassRegistry::getPassRegistry()); + } + + bool runOnFunction(Function &F) override; + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.setPreservesCFG(); + FunctionPass::getAnalysisUsage(AU); + AU.addRequired(); + AU.addRequired(); + AU.addRequired(); + AU.addPreserved(); + AU.addPreserved(); + } + private: + bool ProcessBlock(BasicBlock &BB); + bool SinkInstruction(Instruction *I, SmallPtrSetImpl &Stores); + bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const; + bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const; + }; +} // end anonymous namespace + +char Sinking::ID = 0; +INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false) +INITIALIZE_PASS_DEPENDENCY(LoopInfo) +INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) +INITIALIZE_AG_DEPENDENCY(AliasAnalysis) +INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false) + +FunctionPass *llvm::createSinkingPass() { return new Sinking(); } + +/// AllUsesDominatedByBlock - Return true if all uses of the specified value +/// occur in blocks dominated by the specified block. +bool Sinking::AllUsesDominatedByBlock(Instruction *Inst, + BasicBlock *BB) const { + // Ignoring debug uses is necessary so debug info doesn't affect the code. + // This may leave a referencing dbg_value in the original block, before + // the definition of the vreg. Dwarf generator handles this although the + // user might not get the right info at runtime. + for (Use &U : Inst->uses()) { + // Determine the block of the use. + Instruction *UseInst = cast(U.getUser()); + BasicBlock *UseBlock = UseInst->getParent(); + if (PHINode *PN = dyn_cast(UseInst)) { + // PHI nodes use the operand in the predecessor block, not the block with + // the PHI. + unsigned Num = PHINode::getIncomingValueNumForOperand(U.getOperandNo()); + UseBlock = PN->getIncomingBlock(Num); + } + // Check that it dominates. + if (!DT->dominates(BB, UseBlock)) + return false; + } + return true; +} + +bool Sinking::runOnFunction(Function &F) { + DT = &getAnalysis().getDomTree(); + LI = &getAnalysis(); + AA = &getAnalysis(); + DataLayoutPass *DLP = getAnalysisIfAvailable(); + DL = DLP ? &DLP->getDataLayout() : nullptr; + + bool MadeChange, EverMadeChange = false; + + do { + MadeChange = false; + DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n"); + // Process all basic blocks. + for (Function::iterator I = F.begin(), E = F.end(); + I != E; ++I) + MadeChange |= ProcessBlock(*I); + EverMadeChange |= MadeChange; + NumSinkIter++; + } while (MadeChange); + + return EverMadeChange; +} + +bool Sinking::ProcessBlock(BasicBlock &BB) { + // Can't sink anything out of a block that has less than two successors. + if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false; + + // Don't bother sinking code out of unreachable blocks. In addition to being + // unprofitable, it can also lead to infinite looping, because in an + // unreachable loop there may be nowhere to stop. + if (!DT->isReachableFromEntry(&BB)) return false; + + bool MadeChange = false; + + // Walk the basic block bottom-up. Remember if we saw a store. + BasicBlock::iterator I = BB.end(); + --I; + bool ProcessedBegin = false; + SmallPtrSet Stores; + do { + Instruction *Inst = I; // The instruction to sink. + + // Predecrement I (if it's not begin) so that it isn't invalidated by + // sinking. + ProcessedBegin = I == BB.begin(); + if (!ProcessedBegin) + --I; + + if (isa(Inst)) + continue; + + if (SinkInstruction(Inst, Stores)) + ++NumSunk, MadeChange = true; + + // If we just processed the first instruction in the block, we're done. + } while (!ProcessedBegin); + + return MadeChange; +} + +static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA, + SmallPtrSetImpl &Stores) { + + if (Inst->mayWriteToMemory()) { + Stores.insert(Inst); + return false; + } + + if (LoadInst *L = dyn_cast(Inst)) { + AliasAnalysis::Location Loc = AA->getLocation(L); + for (Instruction *S : Stores) + if (AA->getModRefInfo(S, Loc) & AliasAnalysis::Mod) + return false; + } + + if (isa(Inst) || isa(Inst)) + return false; + + return true; +} + +/// IsAcceptableTarget - Return true if it is possible to sink the instruction +/// in the specified basic block. +bool Sinking::IsAcceptableTarget(Instruction *Inst, + BasicBlock *SuccToSinkTo) const { + assert(Inst && "Instruction to be sunk is null"); + assert(SuccToSinkTo && "Candidate sink target is null"); + + // It is not possible to sink an instruction into its own block. This can + // happen with loops. + if (Inst->getParent() == SuccToSinkTo) + return false; + + // If the block has multiple predecessors, this would introduce computation + // on different code paths. We could split the critical edge, but for now we + // just punt. + // FIXME: Split critical edges if not backedges. + if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) { + // We cannot sink a load across a critical edge - there may be stores in + // other code paths. + if (!isSafeToSpeculativelyExecute(Inst, DL)) + return false; + + // We don't want to sink across a critical edge if we don't dominate the + // successor. We could be introducing calculations to new code paths. + if (!DT->dominates(Inst->getParent(), SuccToSinkTo)) + return false; + + // Don't sink instructions into a loop. + Loop *succ = LI->getLoopFor(SuccToSinkTo); + Loop *cur = LI->getLoopFor(Inst->getParent()); + if (succ != nullptr && succ != cur) + return false; + } + + // Finally, check that all the uses of the instruction are actually + // dominated by the candidate + return AllUsesDominatedByBlock(Inst, SuccToSinkTo); +} + +/// SinkInstruction - Determine whether it is safe to sink the specified machine +/// instruction out of its current block into a successor. +bool Sinking::SinkInstruction(Instruction *Inst, + SmallPtrSetImpl &Stores) { + + // Don't sink static alloca instructions. CodeGen assumes allocas outside the + // entry block are dynamically sized stack objects. + if (AllocaInst *AI = dyn_cast(Inst)) + if (AI->isStaticAlloca()) + return false; + + // Check if it's safe to move the instruction. + if (!isSafeToMove(Inst, AA, Stores)) + return false; + + // FIXME: This should include support for sinking instructions within the + // block they are currently in to shorten the live ranges. We often get + // instructions sunk into the top of a large block, but it would be better to + // also sink them down before their first use in the block. This xform has to + // be careful not to *increase* register pressure though, e.g. sinking + // "x = y + z" down if it kills y and z would increase the live ranges of y + // and z and only shrink the live range of x. + + // SuccToSinkTo - This is the successor to sink this instruction to, once we + // decide. + BasicBlock *SuccToSinkTo = nullptr; + + // Instructions can only be sunk if all their uses are in blocks + // dominated by one of the successors. + // Look at all the postdominators and see if we can sink it in one. + DomTreeNode *DTN = DT->getNode(Inst->getParent()); + for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end(); + I != E && SuccToSinkTo == nullptr; ++I) { + BasicBlock *Candidate = (*I)->getBlock(); + if ((*I)->getIDom()->getBlock() == Inst->getParent() && + IsAcceptableTarget(Inst, Candidate)) + SuccToSinkTo = Candidate; + } + + // If no suitable postdominator was found, look at all the successors and + // decide which one we should sink to, if any. + for (succ_iterator I = succ_begin(Inst->getParent()), + E = succ_end(Inst->getParent()); I != E && !SuccToSinkTo; ++I) { + if (IsAcceptableTarget(Inst, *I)) + SuccToSinkTo = *I; + } + + // If we couldn't find a block to sink to, ignore this instruction. + if (!SuccToSinkTo) + return false; + + DEBUG(dbgs() << "Sink" << *Inst << " ("; + Inst->getParent()->printAsOperand(dbgs(), false); + dbgs() << " -> "; + SuccToSinkTo->printAsOperand(dbgs(), false); + dbgs() << ")\n"); + + // Move the instruction. + Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt()); + return true; +} diff --git a/pool/shard006/C++/0084219_image_tagged_message.cpp b/pool/shard006/C++/0084219_image_tagged_message.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9de4bb64244ba8fe354393c4b6837783dfb65baa --- /dev/null +++ b/pool/shard006/C++/0084219_image_tagged_message.cpp @@ -0,0 +1,236 @@ +//=================================================================== +// Includes +//=================================================================== +// System Includes +#include +#include +#include +#include +#include +#include +// GCOM Includes +#include "modules/uas_message/image_tagged_message.hpp" +#include "modules/uas_message/path_tagged_message.hpp" + +//=================================================================== +// Defines +//=================================================================== +#define PACK_LAT_LON(x) (double) (x*1e7) +#define PACK_ALT(x) (float) (x*1e3) +#define PACK_HDG(x) (float) (x*1e2) + +#define UNPACK_LAT_LON(x) (double) (x/1e7) +#define UNPACK_ALT(x) (float) (x/1e3) +#define UNPACK_HDG(x) (float) (x/1e2) + +//=================================================================== +// Constants +//=================================================================== +const int SIZE_LAT_LON = 4; +const int SIZE_ALT = 4; +const int SIZE_HDG = 2; + +const int COORD_OFFSET = 1; +const int ALT_OFFSET = COORD_OFFSET + SIZE_LAT_LON * 2; +const int HDG_OFFSET = ALT_OFFSET + SIZE_ALT * 2; +const int IMAGE_DATA_OFFSET = HDG_OFFSET + SIZE_HDG; + +const int LAT_RANGE = 90; +const int LON_RANGE = 180; +// assume altitude is no less than 500m under sea level +const int ALT_RANGE = 500; + +//=================================================================== +// Class Definitions +//=================================================================== +ImageTaggedMessage::ImageTaggedMessage(uint8_t sequenceNumber, double latitude, double longitude, + float altitudeAbs, float altitudeRel, float heading, + uint8_t* imageData, size_t dataSize) : + ImageUntaggedMessage(sequenceNumber, imageData, dataSize) +{ + this->latitudeRaw = PACK_LAT_LON(latitude); + this->longitudeRaw = PACK_LAT_LON(longitude); + this->altitudeAbsRaw = PACK_ALT(altitudeAbs); + this->altitudeRelRaw = PACK_ALT(altitudeRel); + this->headingRaw = PACK_HDG(heading); +} + +ImageTaggedMessage::ImageTaggedMessage(uint8_t sequenceNumber, int32_t latitude, int32_t longitude, + int32_t altitudeAbs, int32_t altitudeRel, uint16_t heading, + uint8_t* imageData, size_t dataSize) : + ImageUntaggedMessage(sequenceNumber, imageData, dataSize) +{ + this->latitudeRaw = latitude; + this->longitudeRaw = longitude; + this->altitudeAbsRaw = altitudeAbs; + this->altitudeRelRaw = altitudeRel; + this->headingRaw = heading; +} + +ImageTaggedMessage::ImageTaggedMessage(const std::vector &serializedMessage) +{ + sequenceNumber = serializedMessage.front(); + + // Reconstruct the image data + + // Extract subvector holding the coordinates + std::vector serializedCoords(std::begin(serializedMessage) + COORD_OFFSET, + std::begin(serializedMessage) + ALT_OFFSET); + + // Extract subvector holding the altitudes + std::vector serializedAlts(std::begin(serializedMessage) + ALT_OFFSET, + std::begin(serializedMessage) + HDG_OFFSET); + + // Extract subvector holding the heading + std::vector serializedHdg(std::begin(serializedMessage) + HDG_OFFSET, + std::begin(serializedMessage) + IMAGE_DATA_OFFSET); + + uint32_t packedLat = 0; + uint32_t packedLon = 0; + uint32_t packedAltAbs = 0; + uint32_t packedAltRel = 0; + headingRaw = 0; + + for (int byte_index = 0; byte_index < SIZE_LAT_LON; byte_index++) + { + packedLat |= (serializedCoords[byte_index] << (8*(SIZE_LAT_LON - byte_index - 1))); + packedLon |= (serializedCoords[SIZE_LAT_LON + byte_index] << (8*(SIZE_LAT_LON - byte_index - 1))); + } + + for (int byte_index = 0; byte_index < SIZE_ALT; byte_index++) + { + packedAltAbs |= (serializedAlts[byte_index] << (8*(SIZE_ALT - byte_index - 1))); + packedAltRel |= (serializedAlts[SIZE_ALT + byte_index] << (8*(SIZE_ALT - byte_index - 1))); + } + + for (int byte_index = 0; byte_index < SIZE_HDG; byte_index++) + { + headingRaw |= (serializedHdg[byte_index] << (8*(SIZE_HDG - byte_index - 1))); + } + + // Convert values back by shifting values back + latitudeRaw = packedLat - PACK_LAT_LON(LAT_RANGE); + longitudeRaw = packedLon - PACK_LAT_LON(LON_RANGE); + + altitudeAbsRaw = packedAltAbs - PACK_ALT(ALT_RANGE); + altitudeRelRaw = packedAltRel - PACK_ALT(ALT_RANGE); + + imageData.assign(serializedMessage.begin() + IMAGE_DATA_OFFSET, serializedMessage.end()); +} + +ImageTaggedMessage::~ImageTaggedMessage() +{ + +} + +UASMessage::MessageID ImageTaggedMessage::type() +{ + return MessageID::DATA_IMAGE_TAGGED; +} + +std::vector ImageTaggedMessage::serialize() +{ + std::vector serializedMessage = ImageUntaggedMessage::serialize(); + + uint32_t packedLat; + uint32_t packedLon; + uint32_t packedAltAbs; + uint32_t packedAltRel; + + // Pack image data by shifting values so they are unsigned + packedLat = latitudeRaw + PACK_LAT_LON(LAT_RANGE); + packedLon = longitudeRaw + PACK_LAT_LON(LON_RANGE); + + packedAltAbs = altitudeAbsRaw + PACK_ALT(ALT_RANGE); + packedAltRel = altitudeRelRaw + PACK_ALT(ALT_RANGE); + + // Serialize the coordinates + std::vector serializedCoords; + serializedCoords.resize(SIZE_LAT_LON * 2); + + for (int byte_index = 0; byte_index < SIZE_LAT_LON; byte_index++) + { + serializedCoords[byte_index] = (packedLat >> (8*(SIZE_LAT_LON - byte_index - 1))) & 0xFF; + serializedCoords[SIZE_LAT_LON + byte_index] = + (packedLon >> (8*(SIZE_LAT_LON - byte_index - 1))) & 0xFF; + } + + // Serialize the altitudes + std::vector serializedAlts; + serializedAlts.resize(SIZE_ALT * 2); + + for (int byte_index = 0; byte_index < SIZE_ALT; byte_index++) + { + serializedAlts[byte_index] = (packedAltAbs >> (8*(SIZE_ALT - byte_index - 1))) & 0xFF; + serializedAlts[SIZE_LAT_LON + byte_index] = + (packedAltRel >> (8*(SIZE_ALT - byte_index - 1))) & 0xFF; + } + + // Serialize the heading + std::vector serializedHdg; + serializedHdg.resize(SIZE_HDG); + + for (int byte_index = 0; byte_index < SIZE_HDG; byte_index++) + { + serializedHdg[byte_index] = (headingRaw >> (8*(SIZE_HDG - byte_index - 1))) & 0xFF; + } + + // Insert serialized coordinates into byte vector created by superclass + serializedMessage.insert(std::begin(serializedMessage) + COORD_OFFSET, + std::begin(serializedCoords), std::end(serializedCoords)); + + // Insert serialized altitudes + serializedMessage.insert(std::begin(serializedMessage) + ALT_OFFSET, + std::begin(serializedAlts), std::end(serializedAlts)); + + // Insert serialized heading + serializedMessage.insert(std::begin(serializedMessage) + HDG_OFFSET, + std::begin(serializedHdg), std::end(serializedHdg)); + + return serializedMessage; +} + +//=================================================================== +// Tag Methods +//=================================================================== + +double ImageTaggedMessage::latitude() { + return UNPACK_LAT_LON(latitudeRaw); +} + +double ImageTaggedMessage::longitude() { + return UNPACK_LAT_LON(longitudeRaw); +} + +float ImageTaggedMessage::altitude_abs() { + return UNPACK_ALT(altitudeAbsRaw); +} + +float ImageTaggedMessage::altitude_rel() { + return UNPACK_ALT(altitudeRelRaw); +} + +float ImageTaggedMessage::heading() { + return UNPACK_HDG(headingRaw); +} + +UASMessage::MessageID PathTaggedMessage::type() +{ + return MessageID::DATA_PATH_TAGGED; +} + +std::vector PathTaggedMessage::serialize() +{ + throw std::invalid_argument("Cannot serialize TaggedPathMessage"); +} + +PathTaggedMessage::PathTaggedMessage(uint8_t sequenceNumber, int32_t latitude, int32_t longitude, + int32_t altitudeAbs, int32_t altitudeRel, uint16_t heading, + uint8_t* imageData, size_t dataSize) : + ImageTaggedMessage(sequenceNumber, latitude, longitude, + altitudeAbs, altitudeRel, heading, + imageData, dataSize) +{ + +} + diff --git a/pool/shard006/C++/0084223_rpcdump.cpp b/pool/shard006/C++/0084223_rpcdump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..99d635b9db58e38b7aafc303cf1a90af7134c127 --- /dev/null +++ b/pool/shard006/C++/0084223_rpcdump.cpp @@ -0,0 +1,106 @@ +// Copyright (c) 2009-2012 Paccoin Developers +// Copyright (c) 2012-2013 The PACCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" // for pwalletMain +#include "paccoinrpc.h" +#include "ui_interface.h" + +#include + +#include "json/json_spirit_reader_template.h" +#include "json/json_spirit_writer_template.h" +#include "json/json_spirit_utils.h" + +#define printf OutputDebugStringF + +// using namespace boost::asio; +using namespace json_spirit; +using namespace std; + +extern Object JSONRPCError(int code, const string& message); + +class CTxDump +{ +public: + CBlockIndex *pindex; + int64 nValue; + bool fSpent; + CWalletTx* ptx; + int nOut; + CTxDump(CWalletTx* ptx = NULL, int nOut = -1) + { + pindex = NULL; + nValue = 0; + fSpent = false; + this->ptx = ptx; + this->nOut = nOut; + } +}; + +Value importprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 2) + throw runtime_error( + "importprivkey [label]\n" + "Adds a private key (as returned by dumpprivkey) to your wallet."); + + string strSecret = params[0].get_str(); + string strLabel = ""; + if (params.size() > 1) + strLabel = params[1].get_str(); + CPaccoinSecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) throw JSONRPCError(-5,"Invalid private key"); + if (pwalletMain->IsLocked()) + throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); + if (fWalletUnlockMintOnly) // paccoin: no importprivkey in mint-only mode + throw JSONRPCError(-102, "Wallet is unlocked for minting only."); + + CKey key; + bool fCompressed; + CSecret secret = vchSecret.GetSecret(fCompressed); + key.SetSecret(secret, fCompressed); + CPaccoinAddress vchAddress = CPaccoinAddress(key.GetPubKey()); + + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + pwalletMain->SetAddressBookName(vchAddress, strLabel); + + if (!pwalletMain->AddKey(key)) + throw JSONRPCError(-4,"Error adding key to wallet"); + + pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); + pwalletMain->ReacceptWalletTransactions(); + } + + MainFrameRepaint(); + + return Value::null; +} + +Value dumpprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "dumpprivkey \n" + "Reveals the private key corresponding to ."); + + string strAddress = params[0].get_str(); + CPaccoinAddress address; + if (!address.SetString(strAddress)) + throw JSONRPCError(-5, "Invalid paccoin address"); + if (pwalletMain->IsLocked()) + throw JSONRPCError(-13, "Error: Please enter the wallet passphrase with walletpassphrase first."); + if (fWalletUnlockMintOnly) // paccoin: no dumpprivkey in mint-only mode + throw JSONRPCError(-102, "Wallet is unlocked for minting only."); + CSecret vchSecret; + bool fCompressed; + if (!pwalletMain->GetSecret(address, vchSecret, fCompressed)) + throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); + return CPaccoinSecret(vchSecret, fCompressed).ToString(); +} diff --git a/pool/shard006/C++/0084225_Provider.cpp b/pool/shard006/C++/0084225_Provider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c890ce10ebc9ab2ba558faf9ba5d25bfb75dc31 --- /dev/null +++ b/pool/shard006/C++/0084225_Provider.cpp @@ -0,0 +1,212 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace pwn +{ +namespace render +{ + namespace fse + { + Link::Link(const string& aname) : name(aname) + { + } + + Link::~Link() + { + } + + void + Link::provide(World3* world, RenderArgs ra) + { + prov->doProvide(world, ra); + } + + void + Link::sortout(LinkerPtr usr) + { + prov = usr->getProvider(name); + } + + void + Provider::setId(const string& aid) + { + if (id.empty()) + { + id = aid; + } + else + { + throw FseException( + "Unable to change id from " + id + " to " + aid); + } + } + + const string + Provider::getId() const + { + return id; + } + + void + Provider::provide(World3* world, const RenderArgs& ra) + { + if (autocallCommands) + { + callCommands(); + } + + target->apply(*this, world, ra); + } + + std::vector& + Provider::getProviders() + { + return providers; + } + + void + Provider::link(Linker* linker) + { + if (false == targetname.empty()) + { + try + { + target = linker->getTarget(targetname); + } + catch (FseException& e) + { + e.addMessage( + core::Str() << "From provider: " << toString()); + throw; + } + target->setProvider(this); + } + + BOOST_FOREACH (CommandPtr c, commands) + { + c->link(linker); + } + + doLink(linker); + } + + void + Provider::bind(Binder* bd, ShaderPool* pool) + { + const string file = shaderdata.data(); + if (file.empty()) + { + boost::optional source = + shaderdata.get_child_optional("source"); + + if (source) + { + shader = pool->getFromSource( + source.get(), + core::Str() << this->file << ":" << id); + } + } + else + { + shader = bd->getShader(file); + } + doBind(bd); + + BOOST_FOREACH (CommandPtr c, commands) + { + c->bind(bd); + } + } + + TargetPtr + Provider::getTarget() + { + return target; + } + + BufferReferencePtr + Provider::createBuffer(const string& name) + { + return BufferReferencePtr(new BufferReference(name)); + } + + void + Provider::postlink(Linker* linker) + { + BOOST_FOREACH (CommandPtr c, commands) + { + c->link(linker); + + BOOST_FOREACH (Provider* p, c->getDependencies()) + { + providers.push_back(p); + } + } + } + + ShaderPtr + Provider::getShader() + { + return shader; + } + + void + Provider::denyAutocallOfCommands() + { + autocallCommands = false; + } + + void + Provider::callCommands() + { + BOOST_FOREACH (CommandPtr c, commands) + { + c->apply(); + } + } + + Provider::Provider(const core::Ptree& el, const string& afile) + : autocallCommands(true) + , shaderdata(el.get_child("shader")) + , targetname(el.get("target")) + , file(afile) + { + // foreach (const core::Ptree& e in Xml.Elements(el)) + BOOST_FOREACH ( + const core::Ptree::value_type& e, + el.get_child("commands")) + { + const string& type = e.first; + const core::Ptree& data = e.second; + + commands.push_back(Commands_Create(type, data, this)); + } + } + + Provider::~Provider() + { + } + + string + Provider::toString() const + { + return core::Str() << getId() << "(" << targetname << "): <" + << core::StringSeperator() + .english() + .iterate(commands) + .toString() + << ">"; + } + } +} +} diff --git a/pool/shard006/C++/0084234_BST.cpp b/pool/shard006/C++/0084234_BST.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f4c65dbd23b900ddfd269387d542a6725972711 --- /dev/null +++ b/pool/shard006/C++/0084234_BST.cpp @@ -0,0 +1,126 @@ +#include // nothrow + +// Estrutura do Nodo +struct Node +{ + int key; // Chave + Node *l, *r; // Filho à esquerda, Filho à direita + + Node(int key) + { + this->key = key; + l = r = nullptr; + } +}; + +// Estrutura da BST +class BST +{ +private: + Node* root; // Raiz da árvore + +protected: + Node* makeEmpty(Node* N); // Destrói a árvore + Node* getNewNode(int key); // Aloca um novo Nodo + Node* search(int key, Node* N); // Função completa de busca + Node* remove(int key, Node* N); // Função completa de remoção + void insert(int key, Node* &N); // Função completa de inserção + int minValueNode(Node* N); // Retorna o valor do menor Nodo após a chamada + +public: + BST() { root = nullptr; } // Construtor + ~BST() { root = makeEmpty(root); } // Destruidor + Node* begin() { return root; } // Retorna um ponteiro para a raiz da árvore + Node* search(int key); // Busca + void insert(int key); // Inserção + void remove(int key); // Remoção +}; + +// Destrói a árvore +Node* BST::makeEmpty(Node* N) +{ + if(N != nullptr) + { + N->l = makeEmpty(N->l); + N->r = makeEmpty(N->r); + delete N; + } + return nullptr; +} + +// Aloca um novo nodo +Node* BST::getNewNode(int key) +{ + Node* tmp = new (std::nothrow) Node(key); + return tmp; +} + +// Inserção +void BST::insert(int key) { insert(key, root); } + +void BST::insert(int key, Node* &N) +{ + if(N == nullptr) + N = getNewNode(key); + else if(key < N->key) + insert(key, N->l); + else if(key > N->key) + insert(key, N->r); +} + +// Busca. Retorna um ponteiro para o Nodo caso encontrado. Caso contrário retorna nullptr. +Node* BST::search(int key) {return search(key, root); } + +Node* BST::search(int key, Node* N) +{ + if(N == nullptr) + return nullptr; + else if(key == N->key) + return N; + else if(key < N->key) + return search(key, N->l); + else + return search(key, N->r); +} + +// Retorna o valor da chave do menor Nodo da subárvore direita do Nodo atual +int BST::minValueNode(Node* N) +{ + return (N->l == nullptr) ? N->key : minValueNode(N->l); +} + +// Remoção +void BST::remove(int key) { root = remove(key, root); } + +Node* BST::remove(int key, Node* N) +{ + if(N == nullptr) + return N; + else if(key < N->key) + N->l = remove(key, N->l); + else if(key > N->key) + N->r = remove(key, N->r); + else + { + if(N->l == nullptr) + { + Node* tmp = N->r; + delete N; + return tmp; + } + else if(N->r == nullptr) + { + Node* tmp = N->l; + delete N; + return tmp; + } + else + { + key = minValueNode(N->r); + N->key = key; + N->r = remove(key, N->r); + } + } + + return N; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084238_basic_example.cc b/pool/shard006/C++/0084238_basic_example.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc61c32c74cee7990bd70772d76c9d4853557a0f --- /dev/null +++ b/pool/shard006/C++/0084238_basic_example.cc @@ -0,0 +1,69 @@ +// Copyright 2010-2021 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Minimal example to call the GLOP solver. +// [START program] +// [START import] +#include "ortools/linear_solver/linear_solver.h" +// [END import] + +namespace operations_research { +void BasicExample() { + // [START solver] + // Create the linear solver with the GLOP backend. + std::unique_ptr solver(MPSolver::CreateSolver("GLOP")); + // [END solver] + + // [START variables] + // Create the variables x and y. + MPVariable* const x = solver->MakeNumVar(0.0, 1, "x"); + MPVariable* const y = solver->MakeNumVar(0.0, 2, "y"); + + LOG(INFO) << "Number of variables = " << solver->NumVariables(); + // [END variables] + + // [START constraints] + // Create a linear constraint, 0 <= x + y <= 2. + MPConstraint* const ct = solver->MakeRowConstraint(0.0, 2.0, "ct"); + ct->SetCoefficient(x, 1); + ct->SetCoefficient(y, 1); + + LOG(INFO) << "Number of constraints = " << solver->NumConstraints(); + // [END constraints] + + // [START objective] + // Create the objective function, 3 * x + y. + MPObjective* const objective = solver->MutableObjective(); + objective->SetCoefficient(x, 3); + objective->SetCoefficient(y, 1); + objective->SetMaximization(); + // [END objective] + + // [START solve] + solver->Solve(); + // [END solve] + + // [START print_solution] + LOG(INFO) << "Solution:" << std::endl; + LOG(INFO) << "Objective value = " << objective->Value(); + LOG(INFO) << "x = " << x->solution_value(); + LOG(INFO) << "y = " << y->solution_value(); + // [END print_solution] +} +} // namespace operations_research + +int main() { + operations_research::BasicExample(); + return EXIT_SUCCESS; +} +// [END program] diff --git a/pool/shard006/C++/0084239_boss_halycon.cpp b/pool/shard006/C++/0084239_boss_halycon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..022e58051e7ad04cf1214128a1636251d9e0d9dd --- /dev/null +++ b/pool/shard006/C++/0084239_boss_halycon.cpp @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2008-2011 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "blackrock_spire.h" + +enum Spells +{ + SPELL_CROWDPUMMEL = 10887, + SPELL_MIGHTYBLOW = 14099, +}; + +enum Events +{ + EVENT_CROWD_PUMMEL = 1, + EVENT_MIGHTY_BLOW = 2, +}; + +const Position SummonLocation = { -169.839f, -324.961f, 64.401f, 3.124f }; + +class boss_halycon : public CreatureScript +{ +public: + boss_halycon() : CreatureScript("boss_halycon") { } + + CreatureAI* GetAI(Creature* creature) const + { + return new boss_halyconAI(creature); + } + + struct boss_halyconAI : public BossAI + { + boss_halyconAI(Creature* creature) : BossAI(creature, DATA_HALYCON) {} + + bool Summoned; + + void Reset() + { + _Reset(); + Summoned = false; + } + + void EnterCombat(Unit* /*who*/) + { + _EnterCombat(); + events.ScheduleEvent(EVENT_CROWD_PUMMEL, 8*IN_MILLISECONDS); + events.ScheduleEvent(EVENT_MIGHTY_BLOW, 14*IN_MILLISECONDS); + } + + void JustDied(Unit* /*who*/) + { + _JustDied(); + } + + void UpdateAI(uint32 const diff) + { + if (!UpdateVictim()) + return; + + //Summon Gizrul + if (!Summoned && HealthBelowPct(25)) + { + me->SummonCreature(NPC_GIZRUL_THE_SLAVENER, SummonLocation, TEMPSUMMON_TIMED_DESPAWN, 300*IN_MILLISECONDS); + Summoned = true; + } + + events.Update(diff); + + if (me->HasUnitState(UNIT_STAT_CASTING)) + return; + + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_CROWD_PUMMEL: + DoCast(me->getVictim(), SPELL_CROWDPUMMEL); + events.ScheduleEvent(EVENT_CROWD_PUMMEL, 14*IN_MILLISECONDS); + break; + case EVENT_MIGHTY_BLOW: + DoCast(me->getVictim(), SPELL_MIGHTYBLOW); + events.ScheduleEvent(EVENT_MIGHTY_BLOW, 10*IN_MILLISECONDS); + break; + } + } + DoMeleeAttackIfReady(); + } + }; + +}; + +void AddSC_boss_halycon() +{ + new boss_halycon(); +} diff --git a/pool/shard006/C++/0084246_window.cpp b/pool/shard006/C++/0084246_window.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cfd790c0625059456cee5c48f92ce8c537f0107 --- /dev/null +++ b/pool/shard006/C++/0084246_window.cpp @@ -0,0 +1,84 @@ +#include "window.h" + +#include "myglheaders.h" +#include "stdio.h" + +namespace window{ + +static void error_callback(int error, const char* description){ + puts(description); +} + +static void onWindowResize(GLFWwindow* window, int x, int y){ + glViewport(0, 0, x, y); +} + +GLFWwindow* init(int width, int height, int major_ver, int minor_ver, const char* title){ + glfwSetErrorCallback(error_callback); + if(!glfwInit()){ + puts("Failed to init glfw"); + return NULL; + } + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major_ver); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor_ver); + glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + GLFWwindow* window = glfwCreateWindow(width, height, title, NULL, NULL); + if (!window){ + puts("Failed to get window from glfw"); + glfwTerminate(); + return NULL; + } + glfwMakeContextCurrent(window); + glewExperimental=1; + if(glewInit() != GLEW_OK){ + puts("Failed to init glew"); + glfwTerminate(); + return NULL; + } + glGetError(); // invalid enumerant shows up here, just part of glew being itself. + glfwSwapInterval(1); + glfwSetWindowSizeCallback(window, onWindowResize); + glViewport(0, 0, width, height); + return window; +} +void destroy(GLFWwindow* w){ + glfwDestroyWindow(w); + glfwTerminate(); +} +int is_open(GLFWwindow* w){ + return !glfwWindowShouldClose(w); +} +void close(GLFWwindow* w){ + glfwSetWindowShouldClose(w, GL_TRUE); +} +void swap(GLFWwindow* w){ + glfwSwapBuffers(w); + glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); + glfwPollEvents(); +} +void depth_test(int on){ + if(on) + glEnable(GL_DEPTH_TEST); + else + glDisable(GL_DEPTH_TEST); +} +void cull_face(int on){ + if(on) + glEnable(GL_CULL_FACE); + else + glDisable(GL_CULL_FACE); +} + +float get_width(GLFWwindow* w){ + int x, y; + glfwGetWindowSize(w, &x, &y); + return float(x); +} +float get_height(GLFWwindow* w){ + int x, y; + glfwGetWindowSize(w, &x, &y); + return float(y); +} + +}; diff --git a/pool/shard006/C++/0084247_excepts_test.cc b/pool/shard006/C++/0084247_excepts_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..2515a498907cf244cc2e7fb248b7dffa7b31ae56 --- /dev/null +++ b/pool/shard006/C++/0084247_excepts_test.cc @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2010, Diego Souza + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of the nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +namespace rpmctl_test +{ + + TEST(rpmctl_except_what_should_return_string_provided_in_ctor) + { + rpmctl::rpmctl_except except("foobar"); + CHECK(std::strcmp("foobar", except.what()) == 0); + } + + TEST(rpmctl_except_copy_ctor_should_copy_message_from_original_obj) + { + rpmctl::rpmctl_except except_a("foobar"); + rpmctl::rpmctl_except except_b(except_a); + CHECK(std::strcmp(except_a.what(), except_b.what()) == 0); + } + + TEST(rpmctl_except_assignment_operator_should_copy_message_from_original_obj) + { + rpmctl::rpmctl_except except_a("foobar"); + rpmctl::rpmctl_except except_b("foobaz"); + except_b = except_a; + CHECK(std::strcmp(except_a.what(), except_b.what()) == 0); + } + +} diff --git a/pool/shard006/C++/0084248_coordinate_file.cc b/pool/shard006/C++/0084248_coordinate_file.cc new file mode 100644 index 0000000000000000000000000000000000000000..c010c75fa36e60a019c77db0ddaeca920a79ce4f --- /dev/null +++ b/pool/shard006/C++/0084248_coordinate_file.cc @@ -0,0 +1,180 @@ +// Author: Robert Davis + +#include "gmml/internal/coordinate_file.h" + +#include +#include +#include +#include +#include +#include + +#include "gmml/internal/environment.h" +#include "gmml/internal/geometry.h" +#include "utilities.h" + +using std::string; +using std::vector; + +namespace gmml { + +const char *CoordinateFile::kDefaultTitle = + "GENERATED BY GMML (http://code.google.com/p/gmml)"; + +struct CoordinateFile::Impl { + Impl() : title_(kDefaultTitle), noncoordinate_count_(0) {} + + ~Impl() { + cleanup(); + } + + void cleanup() { + std::for_each(coordinates_.begin(), coordinates_.end(), DeletePtr()); + } + + void read(std::istream& in); + bool process_coordinate_line(const string& line); + Coordinate *parse_coordinate(const string& str); + + void bad_file(const std::string& error) { + cleanup(); + throw std::invalid_argument(error); + } + + void write_coordinate_range(std::ostream& out, int start, int end) const; + void write_coordinate(std::ostream& out, + const Coordinate& coordinate) const; + void write_component(std::ostream& out, double component) const; + + string title_; + vector coordinates_; + int noncoordinate_count_; +}; + +CoordinateFile::CoordinateFile() : impl_(new Impl) { +} + +CoordinateFile::CoordinateFile(const string& file_name) : impl_(new Impl) { + Readable::read(file_name); +} + +CoordinateFile::~CoordinateFile() { +} + +void CoordinateFile::read(std::istream& in) { + impl_->read(in); +} + +void CoordinateFile::write(std::ostream& out) const { + out << impl_->title_ << std::endl; + int coordinates = coordinate_count(); + out << std::setw(kCountLabelWidth) << coordinates << std::endl; + impl_->write_coordinate_range(out, 0, coordinates - 1); + impl_->write_coordinate_range(out, coordinates, size() - 1); +} + +size_t CoordinateFile::size() const { + return impl_->coordinates_.size(); +} + +int CoordinateFile::noncoordinate_count() const { + return impl_->noncoordinate_count_; +} + +const Coordinate& CoordinateFile::operator[](int index) const { + if (0 <= index && index < size()) + return *impl_->coordinates_[index]; + string error = make_string() << "Invalid coordinate index: " << + index << "."; + throw std::range_error(error); +} + +void CoordinateFile::add_coordinate(const Coordinate& coordinate) { + impl_->coordinates_.push_back(new Coordinate(coordinate)); +} + +void CoordinateFile::add_noncoordinate(double x, double y, double z) { + impl_->coordinates_.push_back(new Coordinate(x, y, z)); + impl_->noncoordinate_count_++; +} + + +void CoordinateFile::Impl::read(std::istream& in) { + string line; + + if (!getline(in, line)) { + bad_file("Invalid coordinate file."); + } + trim(line); + title_ = line; + + if (!getline(in, line)) { + bad_file("Invalid coordinate file."); + } + int count_label = convert_string(line); + + int line_index = 2; + while (line_index++, getline(in, line)) { + if (!process_coordinate_line(line)) { + bad_file(make_string() << "Error on line " << line_index << "."); + } + } + + noncoordinate_count_ = coordinates_.size() - count_label; +} + +bool CoordinateFile::Impl::process_coordinate_line(const string& line) { + int coords_on_line = line.size()/kCoordinateWidth/3; + for (int i = 0; i < coords_on_line; i++) { + string crd = line.substr(i*kCoordinateWidth*3, kCoordinateWidth*3); + try { + Coordinate *coordinate = parse_coordinate(crd); + coordinates_.push_back(coordinate); + } catch (const ConversionException& e) { + return false; + } + } + return true; +} + +Coordinate *CoordinateFile::Impl::parse_coordinate(const string& str) { + double x = convert_string(str.substr(0, kCoordinateWidth)); + double y = convert_string(str.substr(kCoordinateWidth, + kCoordinateWidth)); + double z = convert_string(str.substr(2*kCoordinateWidth, + kCoordinateWidth)); + return new Coordinate(x, y, z); +} + +void CoordinateFile::Impl::write_coordinate_range(std::ostream& out, + int start, int end) const { + int count = end - start + 1; + bool is_odd = count & 1; + for (int i = start; i < end - is_odd + 1; i += 2) { + write_coordinate(out, *coordinates_[i]); + write_coordinate(out, *coordinates_[i + 1]); + out << std::endl; + } + if (is_odd) { + write_coordinate(out, *coordinates_[end]); + out << std::endl; + } +} + + +void CoordinateFile::Impl::write_coordinate( + std::ostream& out, const Coordinate& coordinate) const { + write_component(out, coordinate.x); + write_component(out, coordinate.y); + write_component(out, coordinate.z); +} + +void CoordinateFile::Impl::write_component(std::ostream& out, + double component) const { + out << std::setw(kCoordinateWidth) << + std::setprecision(kCoordinatePrecision) << + std::fixed << + component; +} + +} // namespace gmml diff --git a/pool/shard006/C++/0084252_TaskDlgTrajectoryCompound.cpp b/pool/shard006/C++/0084252_TaskDlgTrajectoryCompound.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d207952fb8f29b35a058360cfba86e4706a917a1 --- /dev/null +++ b/pool/shard006/C++/0084252_TaskDlgTrajectoryCompound.cpp @@ -0,0 +1,97 @@ +/*************************************************************************** + * Copyright (c) 2009 Jürgen Riegel * + * * + * This file is part of the FreeCAD CAx development system. * + * * + * This library is free software; you can redistribute it and/or * + * modify it under the terms of the GNU Library General Public * + * License as published by the Free Software Foundation; either * + * version 2 of the License, or (at your option) any later version. * + * * + * This library 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 Library General Public License for more details. * + * * + * You should have received a copy of the GNU Library General Public * + * License along with this library; see the file COPYING.LIB. If not, * + * write to the Free Software Foundation, Inc., 59 Temple Place, * + * Suite 330, Boston, MA 02111-1307, USA * + * * + ***************************************************************************/ + + +#include "PreCompiled.h" + +#ifndef _PreComp_ +# include +#endif + +#include "TaskDlgTrajectoryCompound.h" + +#include +#include +#include + + +using namespace RobotGui; + + +//************************************************************************** +//************************************************************************** +// TaskDialog +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +TaskDlgTrajectoryCompound::TaskDlgTrajectoryCompound(Robot::TrajectoryCompound *obj) + : TaskDialog(),TrajectoryCompound(obj) +{ + select = new Gui::TaskView::TaskSelectLinkProperty("SELECT Robot::TrajectoryObject COUNT 1..",&(obj->Source)); + + Content.push_back(select); +} + +TaskDlgTrajectoryCompound::~TaskDlgTrajectoryCompound() +{ + +} + +//==== calls from the TaskView =============================================================== + + +void TaskDlgTrajectoryCompound::open() +{ + select->activate(); + +} + + +bool TaskDlgTrajectoryCompound::accept() +{ + if(select->isSelectionValid()){ + select->accept(); + TrajectoryCompound->execute(); + Gui::Document* doc = Gui::Application::Instance->activeDocument(); + if(doc) doc->resetEdit(); + return true; + }else + QApplication::beep(); + + return false; +} + +bool TaskDlgTrajectoryCompound::reject() +{ + select->reject(); + TrajectoryCompound->execute(); + Gui::Document* doc = Gui::Application::Instance->activeDocument(); + if(doc) doc->resetEdit(); + return true; +} + +void TaskDlgTrajectoryCompound::helpRequested() +{ + +} + + +#include "moc_TaskDlgTrajectoryCompound.cpp" diff --git a/pool/shard006/C++/0084258_data.cpp b/pool/shard006/C++/0084258_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86e4972abc062c381bc5336a59eee49f3ace917b --- /dev/null +++ b/pool/shard006/C++/0084258_data.cpp @@ -0,0 +1,154 @@ +#include +#include +#include + +#include +#include "data.hpp" + + + +auto Data::Sensowna(int dzien, int miesiac, int rok) -> void +{ + bool kontrolaROK = false; + bool kontrolaMIESIAC = false; + bool kontrolaDZIEN = false; + + if (0 <= rok) + { + kontrolaROK = true; + } + + if(1 <= miesiac && miesiac <= 12) + { + kontrolaMIESIAC = true; + } + + if(miesiac == 2) + { + if(Przestepny(rok) && 1 <= dzien && dzien <= 29) kontrolaDZIEN = true; + if(!Przestepny(rok) && 1 <= dzien && dzien <= 28) kontrolaDZIEN = true; + } + else if(((miesiac % 2 == 1 && miesiac <= 7) + || (miesiac % 2 == 0 && miesiac >= 8)) + && (1 <= dzien && dzien <= 31)) + kontrolaDZIEN = true; + else if(1 <= dzien && dzien <= 31) kontrolaDZIEN = true; + + if(!kontrolaDZIEN) + throw zlyDZIEN{}; + if(!kontrolaMIESIAC) + throw zlyMIESIAC{}; + if(!kontrolaROK) + throw zlyROK{}; +} + + +auto Data::Dzien() -> int const +{ + return dzien_; +} + +auto Data::Miesiac() -> int const +{ + return miesiac_; +} + +auto Data::Rok() -> int const +{ + return rok_; +} + +auto Data::zlyD() -> bool const +{ + return zlyD_; +} + +auto Data::zlyM() -> bool const +{ + return zlyM_; +} + +auto Data::zlyR() -> bool const +{ + return zlyR_; +} + + +auto Data::Przestepny(int rok) -> bool +{ + rok = abs(rok); + return((rok%4 == 0 && rok%100 != 0) || rok%400 == 0); +} + +Data::Data() +{ + rok_ = miesiac_ = dzien_ = 1; +} + +Data::Data(int dzien, int miesiac, int rok) +{ + zlyD_ = false; + zlyM_ = false; + zlyR_ = false; + + + try + { + dzien_ = dzien; + miesiac_ = miesiac; + rok_ = rok; + + Sensowna(dzien, miesiac, rok); + } + + catch(zlyDZIEN& zd) + { + zlyD_ = true; + } + catch(zlyMIESIAC& zm) + { + zlyM_ = true; + } + catch(zlyROK& zr) + { + zlyR_ = true; + } +} + +std::istream& operator>>(std::istream& we, Data &D) +{ + int dzien, miesiac, rok; + we >> dzien >> miesiac >> rok; + if (we) + { + D = Data(dzien, miesiac, rok); + } + else + we.setstate(std::ios_base::failbit); + return we; +} + +Data pobieranieData(std::string polecenie) +{ + std::string wejscie; + Data wyjscie(1, 1, 1); + + std::cout << polecenie; + std::getline(std::cin, wejscie); + std::istringstream strumien(wejscie); + strumien >> std::skipws >> wyjscie; + + // while (!strumien || wyjscie.zlyR() || wyjscie.zlyM() || wyjscie.zlyD()) + while (!strumien) + { + strumien.ignore(1000, '\n'); + strumien.clear(); + std::cout << "Coś poszło nie tak, podaj date jeszcze raz (format DD MM YYYY): "; + std::cin.clear(); + std::getline(std::cin, wejscie); + strumien.str (wejscie); + strumien >> std::skipws >> wyjscie; + } + + return(wyjscie); +} diff --git a/pool/shard006/C++/0084264_main.cpp b/pool/shard006/C++/0084264_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ad139b9161ad8f50513eb9cd178426d25cb62f2 --- /dev/null +++ b/pool/shard006/C++/0084264_main.cpp @@ -0,0 +1,104 @@ +/** + Euclidean greatest common divisor for more than two numbers at compile time + Solution: + The GCD of three or more numbers equals the product of the prime factors common to all the numbers, + but it can also be calculated by repeatedly taking the GCDs of pairs of numbers. + + \see https://math.stackexchange.com/questions/1672249/greatest-common-divisor-of-more-than-two-numbers + \see https://github.com/nikolaAV/Modern-Cpp/tree/master/constexpr/greatest_common_divisor +*/ + +#include +#include +#include +#include + +namespace recursion +{ + +template +constexpr auto gcd(T m, T n) +{ + return std::gcd(m,n); +} + +template +constexpr auto gcd(T m, U... ns) +{ + return gcd(m,gcd(ns...)); +} + +template +constexpr auto gcd(const Container& c, std::index_sequence) +{ + return gcd(c[Idx]...); +} + +template +constexpr auto gcd(const T(&arr)[N]) +{ + return gcd(arr,std::make_index_sequence{}); +} + +} // end of namespace recursion + +namespace imperative +{ + +template +constexpr T accumulate(const Range& range, Func func, T init) { + for(auto&& elem:range) + init = func(init,elem); + return init; +} + +template +constexpr auto gcd(const Range& range) { + return accumulate(range + ,[](auto x, auto y){ return -1==x? y : std::gcd(x,y); } + ,-1 + ); +} + +} // end of namespace imperative + + +void test1() +{ + using namespace recursion; + + static_assert(8==gcd(48,16,24,96)); + static_assert(1==gcd(1,2,3)); + static_assert(2==gcd(8,6,4,2,10,12,100)); + + { constexpr long arr[] = {48,16,24,96}; + static_assert(8==gcd(arr)); + } + { constexpr unsigned short arr[] = {1,2,3}; + static_assert(1==gcd(arr)); + } + { constexpr int arr[] = {8,6,4,2,10,12,100}; + static_assert(2==gcd(arr)); + } +} + +void test2() +{ + using namespace imperative; + + { constexpr std::array arr{48,16,24,96}; + static_assert(8==gcd(arr)); + } + { constexpr unsigned short arr[] = {1,2,3}; + static_assert(1==gcd(arr)); + } + { constexpr int arr[] = {8,6,4,2,10,12,100}; + static_assert(2==gcd(arr)); + } +} + +int main() +{ + test1(); + test2(); +} diff --git a/pool/shard006/C++/0084265_xdg_user_dir_lookup.cc b/pool/shard006/C++/0084265_xdg_user_dir_lookup.cc new file mode 100644 index 0000000000000000000000000000000000000000..607ea3b468db6d8188b9b3cab48982cd1da0a7bd --- /dev/null +++ b/pool/shard006/C++/0084265_xdg_user_dir_lookup.cc @@ -0,0 +1,245 @@ +/* + This file is not licenced under the GPL like the rest of the code. + Its is under the MIT license, to encourage reuse by cut-and-paste. + + Copyright (c) 2007 Red Hat, inc + + 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 +#include +#include + +/** + * xdg_user_dir_lookup_with_fallback: + * @type: a string specifying the type of directory + * @fallback: value to use if the directory isn't specified by the user + * @returns: a newly allocated absolute pathname + * + * Looks up a XDG user directory of the specified type. + * Example of types are "DESKTOP" and "DOWNLOAD". + * + * In case the user hasn't specified any directory for the specified + * type the value returned is @fallback. + * + * The return value is newly allocated and must be freed with + * free(). The return value is never NULL if @fallback != NULL, unless + * out of memory. + **/ +static char * +xdg_user_dir_lookup_with_fallback (const char *type, const char *fallback) +{ + FILE *file; + char *home_dir, *config_home, *config_file; + char buffer[512]; + char *user_dir; + char *p, *d; + int len; + int relative; + + home_dir = getenv ("HOME"); + + if (home_dir == NULL) + goto error; + + config_home = getenv ("XDG_CONFIG_HOME"); + if (config_home == NULL || config_home[0] == 0) + { + config_file = (char*) malloc (strlen (home_dir) + strlen ("/.config/user-dirs.dirs") + 1); + if (config_file == NULL) + goto error; + + strcpy (config_file, home_dir); + strcat (config_file, "/.config/user-dirs.dirs"); + } + else + { + config_file = (char*) malloc (strlen (config_home) + strlen ("/user-dirs.dirs") + 1); + if (config_file == NULL) + goto error; + + strcpy (config_file, config_home); + strcat (config_file, "/user-dirs.dirs"); + } + + file = fopen (config_file, "r"); + free (config_file); + if (file == NULL) + goto error; + + user_dir = NULL; + while (fgets (buffer, sizeof (buffer), file)) + { + /* Remove newline at end */ + len = strlen (buffer); + if (len > 0 && buffer[len-1] == '\n') + buffer[len-1] = 0; + + p = buffer; + while (*p == ' ' || *p == '\t') + p++; + + if (strncmp (p, "XDG_", 4) != 0) + continue; + p += 4; + if (strncmp (p, type, strlen (type)) != 0) + continue; + p += strlen (type); + if (strncmp (p, "_DIR", 4) != 0) + continue; + p += 4; + + while (*p == ' ' || *p == '\t') + p++; + + if (*p != '=') + continue; + p++; + + while (*p == ' ' || *p == '\t') + p++; + + if (*p != '"') + continue; + p++; + + relative = 0; + if (strncmp (p, "$HOME/", 6) == 0) + { + p += 6; + relative = 1; + } + else if (*p != '/') + continue; + + if (relative) + { + user_dir = (char*) malloc (strlen (home_dir) + 1 + strlen (p) + 1); + if (user_dir == NULL) + goto error2; + + strcpy (user_dir, home_dir); + strcat (user_dir, "/"); + } + else + { + user_dir = (char*) malloc (strlen (p) + 1); + if (user_dir == NULL) + goto error2; + + *user_dir = 0; + } + + d = user_dir + strlen (user_dir); + while (*p && *p != '"') + { + if ((*p == '\\') && (*(p+1) != 0)) + p++; + *d++ = *p++; + } + *d = 0; + } +error2: + fclose (file); + + if (user_dir) + return user_dir; + + error: + if (fallback) + return strdup (fallback); + return NULL; +} + +/** + * xdg_user_dir_lookup: + * @type: a string specifying the type of directory + * @returns: a newly allocated absolute pathname + * + * Looks up a XDG user directory of the specified type. + * Example of types are "DESKTOP" and "DOWNLOAD". + * + * The return value is always != NULL (unless out of memory), + * and if a directory + * for the type is not specified by the user the default + * is the home directory. Except for DESKTOP which defaults + * to ~/Desktop. + * + * The return value is newly allocated and must be freed with + * free(). + **/ +char * +xdg_user_dir_lookup (const char *type) +{ + char *dir, *home_dir, *user_dir; + + dir = xdg_user_dir_lookup_with_fallback (type, NULL); + if (dir != NULL) + return dir; + + home_dir = getenv ("HOME"); + + if (home_dir == NULL) + return strdup ("/tmp"); + +#if defined(TOOLKIT_MEEGOTOUCH) + if (strcmp (type, ".local") == 0) + { + user_dir = (char*) malloc (strlen (home_dir) + strlen ("/.local/share/applications") + 1); + if (user_dir == NULL) + return NULL; + + strcpy (user_dir, home_dir); + strcat (user_dir, "/.local/share/applications"); + return user_dir; + } +#else + /* Special case desktop for historical compatibility */ + if (strcmp (type, "DESKTOP") == 0) + { + user_dir = (char*) malloc (strlen (home_dir) + strlen ("/Desktop") + 1); + if (user_dir == NULL) + return NULL; + + strcpy (user_dir, home_dir); + strcat (user_dir, "/Desktop"); + return user_dir; + } +#endif + + return strdup (home_dir); +} + +#ifdef STANDALONE_XDG_USER_DIR_LOOKUP +int +main (int argc, char *argv[]) +{ + if (argc != 2) + { + fprintf (stderr, "Usage %s \n", argv[0]); + exit (1); + } + + printf ("%s\n", xdg_user_dir_lookup (argv[1])); + return 0; +} +#endif diff --git a/pool/shard006/C++/0084267_tipc_connecter.cpp b/pool/shard006/C++/0084267_tipc_connecter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f27d4657efb2ab50768293c61a7ff11052353962 --- /dev/null +++ b/pool/shard006/C++/0084267_tipc_connecter.cpp @@ -0,0 +1,175 @@ +/* + Copyright (c) 2007-2016 Contributors as noted in the AUTHORS file + + This file is part of libzmq, the ZeroMQ core engine in C++. + + libzmq is free software; you can redistribute it and/or modify it under + the terms of the GNU Lesser General Public License (LGPL) as published + by the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + As a special exception, the Contributors give you permission to link + this library with independent modules to produce an executable, + regardless of the license terms of these independent modules, and to + copy and distribute the resulting executable under terms of your choice, + provided that you also meet, for each linked independent module, the + terms and conditions of the license of that module. An independent + module is a module which is not derived from or based on this library. + If you modify this library, you must extend this exception to your + version of the library. + + libzmq 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 Lesser General Public + License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program. If not, see . +*/ + +#include "precompiled.hpp" + +#include "tipc_connecter.hpp" + +#if defined ZMQ_HAVE_TIPC + +#include +#include + +#include "io_thread.hpp" +#include "platform.hpp" +#include "random.hpp" +#include "err.hpp" +#include "ip.hpp" +#include "address.hpp" +#include "tipc_address.hpp" +#include "session_base.hpp" + +#include +#include +#include +#ifdef ZMQ_HAVE_VXWORKS +#include +#endif + +zmq::tipc_connecter_t::tipc_connecter_t (class io_thread_t *io_thread_, + class session_base_t *session_, + const options_t &options_, + address_t *addr_, + bool delayed_start_) : + stream_connecter_base_t ( + io_thread_, session_, options_, addr_, delayed_start_) +{ + zmq_assert (_addr->protocol == "tipc"); +} + +void zmq::tipc_connecter_t::out_event () +{ + fd_t fd = connect (); + rm_handle (); + + // Handle the error condition by attempt to reconnect. + if (fd == retired_fd) { + close (); + add_reconnect_timer (); + return; + } + + create_engine (fd, get_socket_name (fd, socket_end_local)); +} + +void zmq::tipc_connecter_t::start_connecting () +{ + // Open the connecting socket. + int rc = open (); + + // Connect may succeed in synchronous manner. + if (rc == 0) { + _handle = add_fd (_s); + out_event (); + } + + // Connection establishment may be delayed. Poll for its completion. + else if (rc == -1 && errno == EINPROGRESS) { + _handle = add_fd (_s); + set_pollout (_handle); + _socket->event_connect_delayed ( + make_unconnected_connect_endpoint_pair (_endpoint), zmq_errno ()); + } + + // Handle any other error condition by eventual reconnect. + else { + if (_s != retired_fd) + close (); + add_reconnect_timer (); + } +} + +int zmq::tipc_connecter_t::open () +{ + zmq_assert (_s == retired_fd); + + // Cannot connect to random tipc addresses + if (_addr->resolved.tipc_addr->is_random ()) { + errno = EINVAL; + return -1; + } + // Create the socket. + _s = open_socket (AF_TIPC, SOCK_STREAM, 0); + if (_s == -1) + return -1; + + // Set the non-blocking flag. + unblock_socket (_s); + // Connect to the remote peer. +#ifdef ZMQ_HAVE_VXWORKS + int rc = ::connect (s, (sockaddr *) addr->resolved.tipc_addr->addr (), + addr->resolved.tipc_addr->addrlen ()); +#else + int rc = ::connect (_s, _addr->resolved.tipc_addr->addr (), + _addr->resolved.tipc_addr->addrlen ()); +#endif + // Connect was successful immediately. + if (rc == 0) + return 0; + + // Translate other error codes indicating asynchronous connect has been + // launched to a uniform EINPROGRESS. + if (rc == -1 && errno == EINTR) { + errno = EINPROGRESS; + return -1; + } + // Forward the error. + return -1; +} + +zmq::fd_t zmq::tipc_connecter_t::connect () +{ + // Following code should handle both Berkeley-derived socket + // implementations and Solaris. + int err = 0; +#ifdef ZMQ_HAVE_VXWORKS + int len = sizeof (err); +#else + socklen_t len = sizeof (err); +#endif + int rc = getsockopt (_s, SOL_SOCKET, SO_ERROR, + reinterpret_cast (&err), &len); + if (rc == -1) + err = errno; + if (err != 0) { + // Assert if the error was caused by 0MQ bug. + // Networking problems are OK. No need to assert. + errno = err; + errno_assert (errno == ECONNREFUSED || errno == ECONNRESET + || errno == ETIMEDOUT || errno == EHOSTUNREACH + || errno == ENETUNREACH || errno == ENETDOWN); + + return retired_fd; + } + fd_t result = _s; + _s = retired_fd; + return result; +} + +#endif diff --git a/pool/shard006/C++/0084268_boss_loatheb.cpp b/pool/shard006/C++/0084268_boss_loatheb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2db0ad726e7968e9e7ff3b2452cbdfbb24a1937d --- /dev/null +++ b/pool/shard006/C++/0084268_boss_loatheb.cpp @@ -0,0 +1,204 @@ +/* + * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ScriptMgr.h" +#include "InstanceScript.h" +#include "naxxramas.h" +#include "ScriptedCreature.h" +#include "SpellAuras.h" +#include "SpellScript.h" + +enum Spells +{ + SPELL_NECROTIC_AURA = 55593, + SPELL_SUMMON_SPORE = 29234, + SPELL_DEATHBLOOM = 29865, + SPELL_INEVITABLE_DOOM = 29204, + SPELL_FUNGAL_CREEP = 29232, + + SPELL_DEATHBLOOM_FINAL_DAMAGE = 55594, +}; + +enum Texts +{ + SAY_NECROTIC_AURA_APPLIED = 0, + SAY_NECROTIC_AURA_REMOVED = 1, + SAY_NECROTIC_AURA_FADING = 2, +}; + +enum Events +{ + EVENT_NECROTIC_AURA = 1, + EVENT_DEATHBLOOM, + EVENT_INEVITABLE_DOOM, + EVENT_SPORE, + EVENT_NECROTIC_AURA_FADING, + EVENT_NECROTIC_AURA_FADED +}; + +enum Achievement +{ + DATA_ACHIEVEMENT_SPORE_LOSER = 21822183, +}; + +class boss_loatheb : public CreatureScript +{ + public: + boss_loatheb() : CreatureScript("boss_loatheb") { } + + struct boss_loathebAI : public BossAI + { + boss_loathebAI(Creature* creature) : BossAI(creature, BOSS_LOATHEB), _doomCounter(0), _sporeLoser(true) { } + + void Reset() override + { + _Reset(); + instance->DoRemoveAurasDueToSpellOnPlayers(SPELL_FUNGAL_CREEP); + _doomCounter = 0; + _sporeLoser = true; + } + + void JustEngagedWith(Unit* who) override + { + BossAI::JustEngagedWith(who); + events.ScheduleEvent(EVENT_NECROTIC_AURA, 17s); + events.ScheduleEvent(EVENT_DEATHBLOOM, 5s); + events.ScheduleEvent(EVENT_SPORE, 18s); + events.ScheduleEvent(EVENT_INEVITABLE_DOOM, 2min); + } + + void SummonedCreatureDies(Creature* summon, Unit* /*killer*/) override + { + _sporeLoser = false; + summon->CastSpell(summon, SPELL_FUNGAL_CREEP, true); + } + + uint32 GetData(uint32 id) const override + { + return (_sporeLoser && id == DATA_ACHIEVEMENT_SPORE_LOSER) ? 1u : 0u; + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + events.Update(diff); + + while (uint32 eventId = events.ExecuteEvent()) + { + switch (eventId) + { + case EVENT_NECROTIC_AURA: + DoCastAOE(SPELL_NECROTIC_AURA); + Talk(SAY_NECROTIC_AURA_APPLIED); + events.ScheduleEvent(EVENT_NECROTIC_AURA_FADING, 14s); + events.ScheduleEvent(EVENT_NECROTIC_AURA_FADED, 17s); + events.Repeat(Seconds(20)); + break; + case EVENT_DEATHBLOOM: + DoCastAOE(SPELL_DEATHBLOOM); + events.Repeat(Seconds(30)); + break; + case EVENT_INEVITABLE_DOOM: + ++_doomCounter; + DoCastAOE(SPELL_INEVITABLE_DOOM); + if (_doomCounter > 6) + events.Repeat((_doomCounter & 1) ? Seconds(14) : Seconds(17)); + else + events.Repeat(Seconds(30)); + break; + case EVENT_SPORE: + DoCast(me, SPELL_SUMMON_SPORE, false); + events.Repeat(RAID_MODE(Seconds(36), Seconds(15))); + break; + case EVENT_NECROTIC_AURA_FADING: + Talk(SAY_NECROTIC_AURA_FADING); + break; + case EVENT_NECROTIC_AURA_FADED: + Talk(SAY_NECROTIC_AURA_REMOVED); + break; + default: + break; + } + } + + DoMeleeAttackIfReady(); + } + + private: + uint8 _doomCounter; + bool _sporeLoser; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return GetNaxxramasAI(creature); + } +}; + +class achievement_spore_loser : public AchievementCriteriaScript +{ + public: + achievement_spore_loser() : AchievementCriteriaScript("achievement_spore_loser") { } + + bool OnCheck(Player* /*source*/, Unit* target) override + { + return target && target->GetAI()->GetData(DATA_ACHIEVEMENT_SPORE_LOSER); + } +}; + +class spell_loatheb_deathbloom : public SpellScriptLoader +{ + public: + spell_loatheb_deathbloom() : SpellScriptLoader("spell_loatheb_deathbloom") { } + + class spell_loatheb_deathbloom_AuraScript : public AuraScript + { + PrepareAuraScript(spell_loatheb_deathbloom_AuraScript); + + bool Validate(SpellInfo const* /*spell*/) override + { + return ValidateSpellInfo({ SPELL_DEATHBLOOM_FINAL_DAMAGE }); + } + + void AfterRemove(AuraEffect const* eff, AuraEffectHandleModes /*mode*/) + { + if (GetTargetApplication()->GetRemoveMode() != AURA_REMOVE_BY_EXPIRE) + return; + + GetTarget()->CastSpell(nullptr, SPELL_DEATHBLOOM_FINAL_DAMAGE, CastSpellExtraArgs(eff).SetOriginalCaster(GetCasterGUID())); + } + + void Register() override + { + AfterEffectRemove += AuraEffectRemoveFn(spell_loatheb_deathbloom_AuraScript::AfterRemove, EFFECT_0, SPELL_AURA_PERIODIC_DAMAGE, AURA_EFFECT_HANDLE_REAL); + } + }; + + AuraScript* GetAuraScript() const override + { + return new spell_loatheb_deathbloom_AuraScript(); + } +}; + +void AddSC_boss_loatheb() +{ + new boss_loatheb(); + new achievement_spore_loser(); + new spell_loatheb_deathbloom(); +} diff --git a/pool/shard006/C++/0084271_BpmBlock.cpp b/pool/shard006/C++/0084271_BpmBlock.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1d9f0db94626b56199bdd51f40c3e83cff09116 --- /dev/null +++ b/pool/shard006/C++/0084271_BpmBlock.cpp @@ -0,0 +1,101 @@ +// Copyright (c) 2016 Electronic Theatre Controls, Inc., http://www.etcconnect.com +// +// 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 "BpmBlock.h" + +#include "core/Nodes.h" +#include "core/MainController.h" // for LuminosusConstants + +BpmBlock::BpmBlock(MainController* controller, QString uid) + : InOutBlock(controller, uid) + , m_bpm(120) + , m_lastBeats(BpmConstants::HISTORY_LENGTH) + , m_lastValue(0) + , m_factor(1) +{ + m_startTime = HighResTime::now(); + connect(m_inputNode, SIGNAL(dataChanged()), this, SLOT(onInputChanged())); + setBpm(120); +} + +void BpmBlock::getAdditionalState(QJsonObject& state) const { + state["bpm"] = getBpm(); + state["factor"] = getFactor(); +} + +void BpmBlock::setAdditionalState(const QJsonObject &state) { + setBpm(state["bpm"].toDouble()); + setFactor(state["factor"].toDouble()); +} + +void BpmBlock::triggerBeat() { + double beatTime = HighResTime::elapsedSecSince(m_startTime); + // check if history should be discarded: + if (!m_lastBeats.isEmpty()) { + double secSinceLast = beatTime - m_lastBeats.last(); + if (secSinceLast > 60. / BpmConstants::MIN_BPM) { + // yes last beat is too old -> discard history: + m_lastBeats.clear(); + } + } + m_lastBeats.append(beatTime); + updateBpm(); +} + +void BpmBlock::updateOutput() { + double realBpm = m_bpm * m_factor; + if (realBpm > 0) { + m_outputNode->setAbsoluteValue(60.0 / realBpm); + } +} + +void BpmBlock::setFactor(double value) { + m_factor = limit(0.1, value, 10); + emit factorChanged(); + updateOutput(); +} + +void BpmBlock::setBpm(qreal value) { + m_bpm = value; + emit bpmChanged(); + updateOutput(); +} + +void BpmBlock::updateBpm() { + // check if there are at least 2 values: + if (m_lastBeats.size() < 2) return; + + double sumBeatDuration = 0; // in sec + for (int i=1; igetValue(); + if (value >= LuminosusConstants::triggerThreshold && m_lastValue < LuminosusConstants::triggerThreshold) { + // this is a "beat" + triggerBeat(); + } + m_lastValue = value; +} diff --git a/pool/shard006/C++/0084273_RunLengthDecoderTest.cpp b/pool/shard006/C++/0084273_RunLengthDecoderTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b705796bb9e931e2f9ce2eecd1c7e58f40fe2a8c --- /dev/null +++ b/pool/shard006/C++/0084273_RunLengthDecoderTest.cpp @@ -0,0 +1,56 @@ +/* + * 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 Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + * RunLengthDecoderTest.cpp + * Test fixture for the RunLengthDecoder class + * Copyright (C) 2005-2008 Simon Newton + */ + +#include +#include +#include "plugins/espnet/RunLengthDecoder.h" + +class RunLengthDecoderTest: public CppUnit::TestFixture { + CPPUNIT_TEST_SUITE(RunLengthDecoderTest); + CPPUNIT_TEST(testDecode); + CPPUNIT_TEST_SUITE_END(); + + public: + void testDecode(); + private: +}; + + +CPPUNIT_TEST_SUITE_REGISTRATION(RunLengthDecoderTest); + + +/* + * Check that we can decode DMX data + */ +void RunLengthDecoderTest::testDecode() { + ola::plugin::espnet::RunLengthDecoder decoder; + uint8_t data[] = {0x78, 0x56, 0x74, 0xFE, 0x5, 0x10, 0x41, 0x78, 0xFD, 0xFE, + 0x36, 0xFD, 0xFD}; + uint8_t expected_data[] = {0x78, 0x56, 0x74, 0x10, 0x10, 0x10, 0x10, 0x10, + 0x41, 0x78, 0xFE, 0x36, 0xFD}; + ola::DmxBuffer buffer; + ola::DmxBuffer expected(expected_data, sizeof(expected_data)); + + buffer.Blackout(); + buffer.Reset(); + CPPUNIT_ASSERT_EQUAL((unsigned int) 0, buffer.Size()); + decoder.Decode(&buffer, data, sizeof(data)); + CPPUNIT_ASSERT(buffer == expected); +} diff --git a/pool/shard006/C++/0084283_download_crx_util.cc b/pool/shard006/C++/0084283_download_crx_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6edf37054d592679c50a79d8211510d2bb3633c --- /dev/null +++ b/pool/shard006/C++/0084283_download_crx_util.cc @@ -0,0 +1,153 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +// +// Download code which handles CRX files (extensions, themes, apps, ...). + +#include "chrome/browser/download/download_crx_util.h" + +#include "chrome/browser/chrome_notification_types.h" +#include "chrome/browser/extensions/crx_installer.h" +#include "chrome/browser/extensions/extension_install_prompt.h" +#include "chrome/browser/extensions/extension_service.h" +#include "chrome/browser/extensions/extension_system.h" +#include "chrome/browser/extensions/webstore_installer.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/host_desktop.h" +#include "chrome/browser/ui/tabs/tab_strip_model.h" +#include "content/public/browser/download_item.h" +#include "content/public/browser/notification_service.h" +#include "extensions/common/user_script.h" + +using content::BrowserThread; +using content::DownloadItem; +using extensions::WebstoreInstaller; + +namespace download_crx_util { + +namespace { + +// Hold a mock ExtensionInstallPrompt object that will be used when the +// download system opens a CRX. +ExtensionInstallPrompt* mock_install_prompt_for_testing = NULL; + +// Called to get an extension install UI object. In tests, will return +// a mock if the test calls download_util::SetMockInstallPromptForTesting() +// to set one. +scoped_ptr CreateExtensionInstallPrompt( + Profile* profile, + const DownloadItem& download_item) { + // Use a mock if one is present. Otherwise, create a real extensions + // install UI. + if (mock_install_prompt_for_testing) { + ExtensionInstallPrompt* result = mock_install_prompt_for_testing; + mock_install_prompt_for_testing = NULL; + return scoped_ptr(result); + } else { + content::WebContents* web_contents = download_item.GetWebContents(); + if (!web_contents) { + chrome::HostDesktopType active_desktop = chrome::GetActiveDesktop(); + Browser* browser = chrome::FindLastActiveWithProfile(profile, + active_desktop); + if (!browser) + browser = new Browser(Browser::CreateParams(Browser::TYPE_TABBED, + profile, active_desktop)); + web_contents = browser->tab_strip_model()->GetActiveWebContents(); + } + return scoped_ptr( + new ExtensionInstallPrompt(web_contents)); + } +} + +} // namespace + +// Tests can call this method to inject a mock ExtensionInstallPrompt +// to be used to confirm permissions on a downloaded CRX. +void SetMockInstallPromptForTesting( + scoped_ptr mock_prompt) { + mock_install_prompt_for_testing = mock_prompt.release(); +} + +scoped_refptr OpenChromeExtension( + Profile* profile, + const DownloadItem& download_item) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); + + ExtensionService* service = extensions::ExtensionSystem::Get(profile)-> + extension_service(); + CHECK(service); + + scoped_refptr installer( + extensions::CrxInstaller::Create( + service, + CreateExtensionInstallPrompt(profile, download_item), + WebstoreInstaller::GetAssociatedApproval(download_item))); + + installer->set_error_on_unsupported_requirements(true); + installer->set_delete_source(true); + installer->set_install_cause(extension_misc::INSTALL_CAUSE_USER_DOWNLOAD); + + if (OffStoreInstallAllowedByPrefs(profile, download_item)) { + installer->set_off_store_install_allow_reason( + extensions::CrxInstaller::OffStoreInstallAllowedBecausePref); + } + + if (extensions::UserScript::IsURLUserScript(download_item.GetURL(), + download_item.GetMimeType())) { + installer->InstallUserScript(download_item.GetFullPath(), + download_item.GetURL()); + } else { + bool is_gallery_download = + WebstoreInstaller::GetAssociatedApproval(download_item) != NULL; + installer->set_original_mime_type(download_item.GetOriginalMimeType()); + installer->set_apps_require_extension_mime_type(true); + installer->set_download_url(download_item.GetURL()); + installer->set_is_gallery_install(is_gallery_download); + if (is_gallery_download) + installer->set_original_download_url(download_item.GetOriginalUrl()); + installer->set_allow_silent_install(is_gallery_download); + installer->InstallCrx(download_item.GetFullPath()); + } + + return installer; +} + +bool IsExtensionDownload(const DownloadItem& download_item) { + if (download_item.GetTargetDisposition() == + DownloadItem::TARGET_DISPOSITION_PROMPT) + return false; + + if (download_item.GetMimeType() == extensions::Extension::kMimeType || + extensions::UserScript::IsURLUserScript(download_item.GetURL(), + download_item.GetMimeType())) { + return true; + } else { + return false; + } +} + +bool OffStoreInstallAllowedByPrefs(Profile* profile, const DownloadItem& item) { + ExtensionService* service = extensions::ExtensionSystem::Get( + profile)->extension_service(); + if (!service) + return false; + + extensions::ExtensionPrefs* prefs = service->extension_prefs(); + CHECK(prefs); + + extensions::URLPatternSet url_patterns = prefs->GetAllowedInstallSites(); + + if (!url_patterns.MatchesURL(item.GetURL())) + return false; + + // The referrer URL must also be whitelisted, unless the URL has the file + // scheme (there's no referrer for those URLs). + // TODO(aa): RefererURL is cleared in some cases, for example when going + // between secure and non-secure URLs. It would be better if DownloadItem + // tracked the initiating page explicitly. + return url_patterns.MatchesURL(item.GetReferrerUrl()) || + item.GetURL().SchemeIsFile(); +} + +} // namespace download_crx_util diff --git a/pool/shard006/C++/0084286_main.cpp b/pool/shard006/C++/0084286_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7ce5e3bd2fcb45611ef09c4d127949d6dc274b47 --- /dev/null +++ b/pool/shard006/C++/0084286_main.cpp @@ -0,0 +1,27 @@ +#include +#include +#include + +using namespace std; + +int main(int argc, char *argv[]) +{ + const float setengah = 0.5; + int alas; + int tinggi; + float luas; + + cout<<"Masukkan alas = "; + cin>>alas; + + cout<<"Masukkan tinggi = "; + cin>>tinggi; + + luas = setengah * alas * tinggi; + + cout< +#include +#include +#include + +namespace QS3 { + +S3::S3(const QString& hostName, QObject *parent) : + QObject(parent), _hostName(hostName) +{ +} + +S3::S3(const QString& hostName, const QString& proxy, QObject *parent) : + QObject(parent), _hostName(hostName), _proxy(proxy) +{ +} + +QString S3::hostName() const +{ + return _hostName; +} + +QString S3::proxy() const +{ + return _proxy; +} + +void S3::signV2(QNetworkRequest &request, const QString &accessKey, const QString &secretKey, const QString &method, const QString &pathString) const +{ + auto date = QDateTime::currentDateTimeUtc(); + QString dateString = date.toString("ddd, dd MMM yyyy hh:mm:ss +0000"); + request.setRawHeader("Date", dateString.toLocal8Bit()); + QString signature = this->signatureV2(accessKey, secretKey, method, dateString, pathString); + //qDebug() << signature; + request.setRawHeader("Authorization", signature.toLocal8Bit()); +} + +QString S3::signatureV2(const QString &accessKey, const QString &secretKey, const QString &method, const QString &dateString, const QString &pathString, const QString &contentType, const QString &md5) const +{ + QStringList inputs; + inputs << method << md5 << contentType << dateString << pathString; + + QString templateString = "AWS %1:%2"; + + return templateString.arg(accessKey, this->_hmacSha1(secretKey.toLocal8Bit(), inputs.join("\n").toLocal8Bit())); +} + +QS3::Bucket* S3::bucket(const QString &bucketName, const QString &accessKey, const QString &secretKey) const +{ + return new QS3::Bucket(bucketName, this, accessKey, secretKey); +} + +// http://qt-project.org/wiki/HMAC-SHA1 +QString S3::_hmacSha1(QByteArray key, QByteArray baseString) const +{ + int blockSize = 64; // HMAC-SHA-1 block size, defined in SHA-1 standard + if (key.length() > blockSize) { // if key is longer than block size (64), reduce key length with SHA-1 compression + key = QCryptographicHash::hash(key, QCryptographicHash::Sha1); + } + + QByteArray innerPadding(blockSize, char(0x36)); // initialize inner padding with char "6" + QByteArray outerPadding(blockSize, char(0x5c)); // initialize outer padding with char "\" + // ascii characters 0x36 ("6") and 0x5c ("\") are selected because they have large + // Hamming distance (http://en.wikipedia.org/wiki/Hamming_distance) + + for (int i = 0; i < key.length(); i++) { + innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length + outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length + } + + // result = hash ( outerPadding CONCAT hash ( innerPadding CONCAT baseString ) ).toBase64 + QByteArray total = outerPadding; + QByteArray part = innerPadding; + part.append(baseString); + total.append(QCryptographicHash::hash(part, QCryptographicHash::Sha1)); + QByteArray hashed = QCryptographicHash::hash(total, QCryptographicHash::Sha1); + return hashed.toBase64(); +} + +} diff --git a/pool/shard006/C++/0084299_Leaderboard.tests.cpp b/pool/shard006/C++/0084299_Leaderboard.tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a2a16b15f96ca42b48d9d9f6290c139853f0694 --- /dev/null +++ b/pool/shard006/C++/0084299_Leaderboard.tests.cpp @@ -0,0 +1,34 @@ +#include "TestData.hpp" +#include + +#include +#include + +using namespace ::testing; + +TEST(Leaderboard, SumThePoints) +{ + std::map results = TestData::sampleLeaderboard1.driverResults(); + ASSERT_NE(results.end(), results.find("Lewis Hamilton")); + ASSERT_EQ((18 + 18 + 25), results["Lewis Hamilton"]); +} + +TEST(Leaderboard, FindTheWinner) +{ + ASSERT_EQ(0, TestData::sampleLeaderboard1.driverRankings().front().compare("Lewis Hamilton")); +} + +TEST(Leaderboard, KeepAllDriversWhenSamePoints) +{ + // bug, drops drivers with same points + Race winDriver1("Australian Grand Prix", TestData::CreateDriverList(TestData::driver1, TestData::driver2, TestData::driver3)); + Race winDriver2("Malaysian Grand Prix", TestData::CreateDriverList(TestData::driver2, TestData::driver1, TestData::driver3)); + Leaderboard exEquoLeaderBoard(TestData::CreateRaceList(winDriver1, winDriver2)); + + std::list rankings = exEquoLeaderBoard.driverRankings(); + std::list::const_iterator r = rankings.begin(); + ASSERT_EQ(TestData::driver2.getName(), *r); ++r; + ASSERT_EQ(TestData::driver1.getName(), *r); ++r; + ASSERT_EQ(TestData::driver3.getName(), *r); ++r; + // note: the order of driver1 and driver2 is runtime/platform dependent +} \ No newline at end of file diff --git a/pool/shard006/C++/0084306_RunningObjectTableRegistrar.cpp b/pool/shard006/C++/0084306_RunningObjectTableRegistrar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe6cbb5ed54e22d4b1b41adb11934e350faa387b --- /dev/null +++ b/pool/shard006/C++/0084306_RunningObjectTableRegistrar.cpp @@ -0,0 +1,45 @@ +#include "pch.hpp" +#include "RunningObjectTableRegistrar.hpp" + +#include "HResultException.hpp" + +using namespace Mntone::DirectShowSupport; + +RunningObjectTableRegistrar::RunningObjectTableRegistrar() noexcept + : initialized_(false) + , registerID_(0) +{ } + +RunningObjectTableRegistrar::RunningObjectTableRegistrar(IGraphBuilder* graphBuilder) + : initialized_(false) + , registerID_(0) +{ + Initialize(graphBuilder); +} + +RunningObjectTableRegistrar::~RunningObjectTableRegistrar() noexcept +{ + if (!initialized_) return; + + HRESULT hr = runningObjectTable_->Revoke(registerID_); + assert(SUCCEEDED(hr)); +} + +void RunningObjectTableRegistrar::Initialize(IGraphBuilder* graphBuilder) +{ + HRESULT hr = S_OK; + + hr = GetRunningObjectTable(0, &runningObjectTable_); + if (FAILED(hr)) throw HResultException(hr); + + ::Microsoft::WRL::ComPtr moniker; + wchar_t wsz[128]; + wsprintfW(wsz, L"FilterGraph %08x pid %08x", graphBuilder, GetCurrentProcessId()); + hr = CreateItemMoniker(L"!", wsz, &moniker); + if (FAILED(hr)) throw HResultException(hr); + + hr = runningObjectTable_->Register(ROTFLAGS_REGISTRATIONKEEPSALIVE, graphBuilder, moniker.Get(), ®isterID_); + if (FAILED(hr)) throw HResultException(hr); + + initialized_ = true; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084307_geometry_string.cpp b/pool/shard006/C++/0084307_geometry_string.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5209460ec2323389c0f9a382aab9efc2a4023570 --- /dev/null +++ b/pool/shard006/C++/0084307_geometry_string.cpp @@ -0,0 +1,45 @@ +#include +#include + +#include "engine/polyline_compressor.hpp" +#include "util/coordinate_calculation.hpp" + +#include + +#include +#include + +BOOST_AUTO_TEST_SUITE(polyline) + +using namespace osrm; +using namespace osrm::engine; + +BOOST_AUTO_TEST_CASE(decode) +{ + // Polyline string for the 5 coordinates + const std::string polyline = "_c`|@_c`|@o}@_pRo}@_pRo}@_pRo}@_pR"; + const auto coords = decodePolyline(polyline); + + // Test coordinates; these would be the coordinates we give the loc parameter, + // e.g. loc=10.00,10.0&loc=10.01,10.1... + util::Coordinate coord1(util::FloatLongitude(10.0), util::FloatLatitude(10.00)); + util::Coordinate coord2(util::FloatLongitude(10.1), util::FloatLatitude(10.01)); + util::Coordinate coord3(util::FloatLongitude(10.2), util::FloatLatitude(10.02)); + util::Coordinate coord4(util::FloatLongitude(10.3), util::FloatLatitude(10.03)); + util::Coordinate coord5(util::FloatLongitude(10.4), util::FloatLatitude(10.04)); + + // Put the test coordinates into the vector for comparison + std::vector cmp_coords = {coord1, coord2, coord3, coord4, coord5}; + + BOOST_CHECK_EQUAL(cmp_coords.size(), coords.size()); + + for (unsigned i = 0; i < cmp_coords.size(); ++i) + { + BOOST_CHECK_CLOSE(static_cast(util::toFloating(coords[i].lat)), + static_cast(util::toFloating(cmp_coords[i].lat)), 0.0001); + BOOST_CHECK_CLOSE(static_cast(util::toFloating(coords[i].lon)), + static_cast(util::toFloating(cmp_coords[i].lon)), 0.0001); + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard006/C++/0084322_mman.cpp b/pool/shard006/C++/0084322_mman.cpp new file mode 100644 index 0000000000000000000000000000000000000000..baddc4f85c53f178a84cfc0315d111faf20f8109 --- /dev/null +++ b/pool/shard006/C++/0084322_mman.cpp @@ -0,0 +1,185 @@ +#include "mman.h" + +#include +#include +#include +#include + +#ifndef FILE_MAP_EXECUTE +#define FILE_MAP_EXECUTE 0x0020 +#endif /* FILE_MAP_EXECUTE */ + +static int __map_mman_error(const DWORD err, const int deferr) +{ + if (err == 0) + return 0; + //TODO: implement + return err; +} + +static DWORD __map_mmap_prot_page(const int prot) +{ + DWORD protect = 0; + + if (prot == PROT_NONE) + return protect; + + if ((prot & PROT_EXEC) != 0) + { + protect = ((prot & PROT_WRITE) != 0) ? + PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ; + } + else + { + protect = ((prot & PROT_WRITE) != 0) ? + PAGE_READWRITE : PAGE_READONLY; + } + + return protect; +} + +static DWORD __map_mmap_prot_file(const int prot) +{ + DWORD desiredAccess = 0; + + if (prot == PROT_NONE) + return desiredAccess; + + if ((prot & PROT_READ) != 0) + desiredAccess |= FILE_MAP_READ; + if ((prot & PROT_WRITE) != 0) + desiredAccess |= FILE_MAP_WRITE; + if ((prot & PROT_EXEC) != 0) + desiredAccess |= FILE_MAP_EXECUTE; + + return desiredAccess; +} + +int ftruncate(int fildes, size_t len) +{ + return _chsize(fildes, len); +} + +void* mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off) +{ + HANDLE fm, h; + + void * map = MAP_FAILED; + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable: 4293) +#endif + + const DWORD dwFileOffsetLow = (sizeof(off_t) <= sizeof(DWORD)) ? + (DWORD)off : (DWORD)(off & 0xFFFFFFFFL); + const DWORD dwFileOffsetHigh = (sizeof(off_t) <= sizeof(DWORD)) ? + (DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL); + const DWORD protect = __map_mmap_prot_page(prot); + const DWORD desiredAccess = __map_mmap_prot_file(prot); + + const off_t maxSize = off + (off_t)len; + + const DWORD dwMaxSizeLow = (sizeof(off_t) <= sizeof(DWORD)) ? + (DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL); + const DWORD dwMaxSizeHigh = (sizeof(off_t) <= sizeof(DWORD)) ? + (DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL); + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + + errno = 0; + + if (len == 0 + /* Unsupported flag combinations */ + || (flags & MAP_FIXED) != 0 + /* Usupported protection combinations */ + || prot == PROT_EXEC) + { + errno = EINVAL; + return MAP_FAILED; + } + + h = ((flags & MAP_ANONYMOUS) == 0) ? + (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE; + + if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE) + { + errno = EBADF; + return MAP_FAILED; + } + + fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL); + + if (fm == NULL) + { + errno = __map_mman_error(GetLastError(), EPERM); + return MAP_FAILED; + } + + map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len); + + CloseHandle(fm); + + if (map == NULL) + { + errno = __map_mman_error(GetLastError(), EPERM); + return MAP_FAILED; + } + + return map; +} + +int munmap(void *addr, size_t len) +{ + if (UnmapViewOfFile(addr)) + return 0; + + errno = __map_mman_error(GetLastError(), EPERM); + + return -1; +} + +int mprotect(void *addr, size_t len, int prot) +{ + DWORD newProtect = __map_mmap_prot_page(prot); + DWORD oldProtect = 0; + + if (VirtualProtect(addr, len, newProtect, &oldProtect)) + return 0; + + errno = __map_mman_error(GetLastError(), EPERM); + + return -1; +} + +int msync(void *addr, size_t len, int flags) +{ + if (FlushViewOfFile(addr, len)) + return 0; + + errno = __map_mman_error(GetLastError(), EPERM); + + return -1; +} + +int mlock(const void *addr, size_t len) +{ + if (VirtualLock((LPVOID)addr, len)) + return 0; + + errno = __map_mman_error(GetLastError(), EPERM); + + return -1; +} + +int munlock(const void *addr, size_t len) +{ + if (VirtualUnlock((LPVOID)addr, len)) + return 0; + + errno = __map_mman_error(GetLastError(), EPERM); + + return -1; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084324_perfMemory.cpp b/pool/shard006/C++/0084324_perfMemory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..794f7beb947893ca7e09d552de9305f379869b0d --- /dev/null +++ b/pool/shard006/C++/0084324_perfMemory.cpp @@ -0,0 +1,271 @@ +/* + * Copyright (c) 2001, 2015, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "memory/allocation.inline.hpp" +#include "runtime/arguments.hpp" +#include "runtime/java.hpp" +#include "runtime/mutex.hpp" +#include "runtime/mutexLocker.hpp" +#include "runtime/orderAccess.inline.hpp" +#include "runtime/os.hpp" +#include "runtime/perfData.hpp" +#include "runtime/perfMemory.hpp" +#include "runtime/safepoint.hpp" +#include "runtime/statSampler.hpp" +#include "utilities/globalDefinitions.hpp" + +// Prefix of performance data file. +const char PERFDATA_NAME[] = "hsperfdata"; + +// Add 1 for the '_' character between PERFDATA_NAME and pid. The '\0' terminating +// character will be included in the sizeof(PERFDATA_NAME) operation. +static const size_t PERFDATA_FILENAME_LEN = sizeof(PERFDATA_NAME) + + UINT_CHARS + 1; + +char* PerfMemory::_start = NULL; +char* PerfMemory::_end = NULL; +char* PerfMemory::_top = NULL; +size_t PerfMemory::_capacity = 0; +jint PerfMemory::_initialized = false; +PerfDataPrologue* PerfMemory::_prologue = NULL; + +void perfMemory_init() { + + if (!UsePerfData) return; + + PerfMemory::initialize(); +} + +void perfMemory_exit() { + + if (!UsePerfData) return; + if (!PerfMemory::is_initialized()) return; + + // Only destroy PerfData objects if we're at a safepoint and the + // StatSampler is not active. Otherwise, we risk removing PerfData + // objects that are currently being used by running JavaThreads + // or the StatSampler. This method is invoked while we are not at + // a safepoint during a VM abort so leaving the PerfData objects + // around may also help diagnose the failure. In rare cases, + // PerfData objects are used in parallel with a safepoint. See + // the work around in PerfDataManager::destroy(). + // + if (SafepointSynchronize::is_at_safepoint() && !StatSampler::is_active()) { + PerfDataManager::destroy(); + } + + // Remove the persistent external resources, if any. This method + // does not unmap or invalidate any virtual memory allocated during + // initialization. + // + PerfMemory::destroy(); +} + +void PerfMemory::initialize() { + + if (_prologue != NULL) + // initialization already performed + return; + + size_t capacity = align_size_up(PerfDataMemorySize, + os::vm_allocation_granularity()); + + if (PerfTraceMemOps) { + tty->print("PerfDataMemorySize = " SIZE_FORMAT "," + " os::vm_allocation_granularity = %d," + " adjusted size = " SIZE_FORMAT "\n", + PerfDataMemorySize, + os::vm_allocation_granularity(), + capacity); + } + + // allocate PerfData memory region + create_memory_region(capacity); + + if (_start == NULL) { + + // the PerfMemory region could not be created as desired. Rather + // than terminating the JVM, we revert to creating the instrumentation + // on the C heap. When running in this mode, external monitoring + // clients cannot attach to and monitor this JVM. + // + // the warning is issued only in debug mode in order to avoid + // additional output to the stdout or stderr output streams. + // + if (PrintMiscellaneous && Verbose) { + warning("Could not create PerfData Memory region, reverting to malloc"); + } + + _prologue = NEW_C_HEAP_OBJ(PerfDataPrologue, mtInternal); + } + else { + + // the PerfMemory region was created as expected. + + if (PerfTraceMemOps) { + tty->print("PerfMemory created: address = " INTPTR_FORMAT "," + " size = " SIZE_FORMAT "\n", + p2i(_start), + _capacity); + } + + _prologue = (PerfDataPrologue *)_start; + _end = _start + _capacity; + _top = _start + sizeof(PerfDataPrologue); + } + + assert(_prologue != NULL, "prologue pointer must be initialized"); + +#ifdef VM_LITTLE_ENDIAN + _prologue->magic = (jint)0xc0c0feca; + _prologue->byte_order = PERFDATA_LITTLE_ENDIAN; +#else + _prologue->magic = (jint)0xcafec0c0; + _prologue->byte_order = PERFDATA_BIG_ENDIAN; +#endif + + _prologue->major_version = PERFDATA_MAJOR_VERSION; + _prologue->minor_version = PERFDATA_MINOR_VERSION; + _prologue->accessible = 0; + + _prologue->entry_offset = sizeof(PerfDataPrologue); + _prologue->num_entries = 0; + _prologue->used = 0; + _prologue->overflow = 0; + _prologue->mod_time_stamp = 0; + + OrderAccess::release_store(&_initialized, 1); +} + +void PerfMemory::destroy() { + + if (_prologue == NULL) return; + + if (_start != NULL && _prologue->overflow != 0) { + + // This state indicates that the contiguous memory region exists and + // that it wasn't large enough to hold all the counters. In this case, + // we output a warning message to the user on exit if the -XX:+Verbose + // flag is set (a debug only flag). External monitoring tools can detect + // this condition by monitoring the _prologue->overflow word. + // + // There are two tunables that can help resolve this issue: + // - increase the size of the PerfMemory with -XX:PerfDataMemorySize= + // - decrease the maximum string constant length with + // -XX:PerfMaxStringConstLength= + // + if (PrintMiscellaneous && Verbose) { + warning("PerfMemory Overflow Occurred.\n" + "\tCapacity = " SIZE_FORMAT " bytes" + " Used = " SIZE_FORMAT " bytes" + " Overflow = " INT32_FORMAT " bytes" + "\n\tUse -XX:PerfDataMemorySize= to specify larger size.", + PerfMemory::capacity(), + PerfMemory::used(), + _prologue->overflow); + } + } + + if (_start != NULL) { + + // this state indicates that the contiguous memory region was successfully + // and that persistent resources may need to be cleaned up. This is + // expected to be the typical condition. + // + delete_memory_region(); + } + + _start = NULL; + _end = NULL; + _top = NULL; + _prologue = NULL; + _capacity = 0; +} + +// allocate an aligned block of memory from the PerfData memory +// region. This method assumes that the PerfData memory region +// was aligned on a double word boundary when created. +// +char* PerfMemory::alloc(size_t size) { + + if (!UsePerfData) return NULL; + + MutexLocker ml(PerfDataMemAlloc_lock); + + assert(_prologue != NULL, "called before initialization"); + + // check that there is enough memory for this request + if ((_top + size) >= _end) { + + _prologue->overflow += (jint)size; + + return NULL; + } + + char* result = _top; + + _top += size; + + assert(contains(result), "PerfData memory pointer out of range"); + + _prologue->used = (jint)used(); + _prologue->num_entries = _prologue->num_entries + 1; + + return result; +} + +void PerfMemory::mark_updated() { + if (!UsePerfData) return; + + _prologue->mod_time_stamp = os::elapsed_counter(); +} + +// Returns the complete path including the file name of performance data file. +// Caller is expected to release the allocated memory. +char* PerfMemory::get_perfdata_file_path() { + char* dest_file = NULL; + + if (PerfDataSaveFile != NULL) { + // dest_file_name stores the validated file name if file_name + // contains %p which will be replaced by pid. + dest_file = NEW_C_HEAP_ARRAY(char, JVM_MAXPATHLEN, mtInternal); + if(!Arguments::copy_expand_pid(PerfDataSaveFile, strlen(PerfDataSaveFile), + dest_file, JVM_MAXPATHLEN)) { + FREE_C_HEAP_ARRAY(char, dest_file); + if (PrintMiscellaneous && Verbose) { + warning("Invalid performance data file path name specified, "\ + "fall back to a default name"); + } + } else { + return dest_file; + } + } + // create the name of the file for retaining the instrumentation memory. + dest_file = NEW_C_HEAP_ARRAY(char, PERFDATA_FILENAME_LEN, mtInternal); + jio_snprintf(dest_file, PERFDATA_FILENAME_LEN, + "%s_%d", PERFDATA_NAME, os::current_process_id()); + + return dest_file; +} diff --git a/pool/shard006/C++/0084329_copy.cc b/pool/shard006/C++/0084329_copy.cc new file mode 100644 index 0000000000000000000000000000000000000000..dfa9d01effb0c6bb79bc1507ef2f71b95a0e08b1 --- /dev/null +++ b/pool/shard006/C++/0084329_copy.cc @@ -0,0 +1,132 @@ +// { dg-do run { target c++11 } } + +// Copyright (C) 2005-2017 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library 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 library; see the file COPYING3. If not see +// . + +// 20.6.6.2 Template class shared_ptr [util.smartptr.shared] + +#include +#include + +struct A +{ + A() { ++ctor_count; } + virtual ~A() { ++dtor_count; } + static long ctor_count; + static long dtor_count; +}; +long A::ctor_count = 0; +long A::dtor_count = 0; + +struct B : A +{ + B() { ++ctor_count; } + virtual ~B() { ++dtor_count; } + static long ctor_count; + static long dtor_count; +}; +long B::ctor_count = 0; +long B::dtor_count = 0; + +void deleter(A* p) { delete p; } + +struct reset_count_struct +{ + ~reset_count_struct() + { + A::ctor_count = 0; + A::dtor_count = 0; + B::ctor_count = 0; + B::dtor_count = 0; + } +}; + +// 20.6.6.2.1 shared_ptr constructors [util.smartptr.shared.const] + +// Copy construction +int test01() +{ + reset_count_struct __attribute__((unused)) reset; + + std::shared_ptr a1; + std::shared_ptr a2(a1); + VERIFY( a2.use_count() == 0 ); + VERIFY( A::ctor_count == 0 ); + VERIFY( A::dtor_count == 0 ); + VERIFY( B::ctor_count == 0 ); + VERIFY( B::dtor_count == 0 ); + + return 0; +} + +int +test02() +{ + reset_count_struct __attribute__((unused)) reset; + + std::shared_ptr a1(new A); + std::shared_ptr a2(a1); + VERIFY( a2.use_count() == 2 ); + VERIFY( A::ctor_count == 1 ); + VERIFY( A::dtor_count == 0 ); + VERIFY( B::ctor_count == 0 ); + VERIFY( B::dtor_count == 0 ); + + return 0; +} + +int +test03() +{ + reset_count_struct __attribute__((unused)) reset; + + std::shared_ptr b(new B); + std::shared_ptr a(b); + VERIFY( a.use_count() == 2 ); + VERIFY( A::ctor_count == 1 ); + VERIFY( A::dtor_count == 0 ); + VERIFY( B::ctor_count == 1 ); + VERIFY( B::dtor_count == 0 ); + + return 0; +} + +int +test04() +{ + reset_count_struct __attribute__((unused)) reset; + + std::shared_ptr b(new B, &deleter); + std::shared_ptr a(b); + VERIFY( a.use_count() == 2 ); + VERIFY( A::ctor_count == 1 ); + VERIFY( A::dtor_count == 0 ); + VERIFY( B::ctor_count == 1 ); + VERIFY( B::dtor_count == 0 ); + + return 0; +} + +int +main() +{ + test01(); + test02(); + test03(); + test04(); + return 0; +} diff --git a/pool/shard006/C++/0084330_V8AbstractEventListener.cpp b/pool/shard006/C++/0084330_V8AbstractEventListener.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a05e286150743b5a01a3682eaeb922fdaaea9b25 --- /dev/null +++ b/pool/shard006/C++/0084330_V8AbstractEventListener.cpp @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2006, 2007, 2008, 2009 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "bindings/core/v8/V8AbstractEventListener.h" + +#include "bindings/core/v8/V8Binding.h" +#include "bindings/core/v8/V8Event.h" +#include "bindings/core/v8/V8EventListenerList.h" +#include "bindings/core/v8/V8EventTarget.h" +#include "bindings/core/v8/V8HiddenValue.h" +#include "core/events/BeforeUnloadEvent.h" +#include "core/events/Event.h" +#include "core/inspector/InstanceCounters.h" +#include "core/workers/WorkerGlobalScope.h" + +namespace blink { + +V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, DOMWrapperWorld& world, v8::Isolate* isolate) + : EventListener(JSEventListenerType) + , m_isAttribute(isAttribute) + , m_world(world) + , m_isolate(isolate) +{ + if (isMainThread()) + InstanceCounters::incrementCounter(InstanceCounters::JSEventListenerCounter); +} + +V8AbstractEventListener::~V8AbstractEventListener() +{ + if (!m_listener.isEmpty()) { + v8::HandleScope scope(m_isolate); + V8EventListenerList::clearWrapper(m_listener.newLocal(isolate()), m_isAttribute, isolate()); + } + if (isMainThread()) + InstanceCounters::decrementCounter(InstanceCounters::JSEventListenerCounter); +} + +void V8AbstractEventListener::handleEvent(ExecutionContext* executionContext, Event* event) +{ + if (!executionContext) + return; + // Don't reenter V8 if execution was terminated in this instance of V8. + if (executionContext->isJSExecutionForbidden()) + return; + + // A ScriptState used by the event listener needs to be calculated based on + // the ExecutionContext that fired the the event listener and the world + // that installed the event listener. + ASSERT(event); + v8::HandleScope handleScope(toIsolate(executionContext)); + v8::Local v8Context = toV8Context(executionContext, world()); + if (v8Context.IsEmpty()) + return; + ScriptState* scriptState = ScriptState::from(v8Context); + if (!scriptState->contextIsValid()) + return; + handleEvent(scriptState, event); +} + +void V8AbstractEventListener::handleEvent(ScriptState* scriptState, Event* event) +{ + // The callback function on XMLHttpRequest can clear the event listener and destroys 'this' object. Keep a local reference to it. + // See issue 889829. + RefPtr protect(this); + + ScriptState::Scope scope(scriptState); + + // Get the V8 wrapper for the event object. + v8::Local jsEvent = toV8(event, scriptState->context()->Global(), isolate()); + if (jsEvent.IsEmpty()) + return; + invokeEventHandler(scriptState, event, v8::Local::New(isolate(), jsEvent)); +} + +void V8AbstractEventListener::setListenerObject(v8::Local listener) +{ + m_listener.set(isolate(), listener); + m_listener.setWeak(this, &setWeakCallback); +} + +void V8AbstractEventListener::invokeEventHandler(ScriptState* scriptState, Event* event, v8::Local jsEvent) +{ + if (!event->canBeDispatchedInWorld(world())) + return; + + v8::Local returnValue; + { + // Catch exceptions thrown in the event handler so they do not propagate to javascript code that caused the event to fire. + v8::TryCatch tryCatch(isolate()); + tryCatch.SetVerbose(true); + + // Save the old 'event' property so we can restore it later. + v8::Local savedEvent = V8HiddenValue::getHiddenValue(isolate(), scriptState->context()->Global(), V8HiddenValue::event(isolate())); + tryCatch.Reset(); + + // Make the event available in the global object, so LocalDOMWindow can expose it. + V8HiddenValue::setHiddenValue(isolate(), scriptState->context()->Global(), V8HiddenValue::event(isolate()), jsEvent); + tryCatch.Reset(); + + returnValue = callListenerFunction(scriptState, jsEvent, event); + if (tryCatch.HasCaught()) + event->target()->uncaughtExceptionInEventHandler(); + + if (!tryCatch.CanContinue()) { // Result of TerminateExecution(). + if (scriptState->executionContext()->isWorkerGlobalScope()) + toWorkerGlobalScope(scriptState->executionContext())->script()->forbidExecution(); + return; + } + tryCatch.Reset(); + + // Restore the old event. This must be done for all exit paths through this method. + if (savedEvent.IsEmpty()) + V8HiddenValue::setHiddenValue(isolate(), scriptState->context()->Global(), V8HiddenValue::event(isolate()), v8::Undefined(isolate())); + else + V8HiddenValue::setHiddenValue(isolate(), scriptState->context()->Global(), V8HiddenValue::event(isolate()), savedEvent); + tryCatch.Reset(); + } + + if (returnValue.IsEmpty()) + return; + + if (m_isAttribute && !returnValue->IsNull() && !returnValue->IsUndefined() && event->isBeforeUnloadEvent()) { + TOSTRING_VOID(V8StringResource<>, stringReturnValue, returnValue); + toBeforeUnloadEvent(event)->setReturnValue(stringReturnValue); + } + + if (m_isAttribute && shouldPreventDefault(returnValue)) + event->preventDefault(); +} + +bool V8AbstractEventListener::shouldPreventDefault(v8::Local returnValue) +{ + // Prevent default action if the return value is false in accord with the spec + // http://www.w3.org/TR/html5/webappapis.html#event-handler-attributes + return returnValue->IsBoolean() && !returnValue.As()->Value(); +} + +v8::Local V8AbstractEventListener::getReceiverObject(ScriptState* scriptState, Event* event) +{ + v8::Local listener = m_listener.newLocal(isolate()); + if (!m_listener.isEmpty() && !listener->IsFunction()) + return listener; + + EventTarget* target = event->currentTarget(); + v8::Local value = toV8(target, scriptState->context()->Global(), isolate()); + if (value.IsEmpty()) + return v8::Local(); + return v8::Local::New(isolate(), v8::Local::Cast(value)); +} + +bool V8AbstractEventListener::belongsToTheCurrentWorld() const +{ + return ScriptState::hasCurrentScriptState(isolate()) && &world() == &DOMWrapperWorld::current(isolate()); +} + +void V8AbstractEventListener::setWeakCallback(const v8::WeakCallbackInfo &data) +{ + data.GetParameter()->m_listener.clear(); +} + +} // namespace blink diff --git a/pool/shard006/C++/0084331_package.cc b/pool/shard006/C++/0084331_package.cc new file mode 100644 index 0000000000000000000000000000000000000000..f1f14fcbd9ffbb7bd4370ff26a8cc72abcfe321b --- /dev/null +++ b/pool/shard006/C++/0084331_package.cc @@ -0,0 +1,47 @@ +/****************************************************************************** + * * + * This file is a part of GeNa project / Franca IDL. * + * * + ******************************************************************************/ + +// self-include: +#include "package.hh" + +// local includes: +#include "ast.hh" +#include "tokeniser.hh" +#include "parse_error.hh" +#include "state/types_or_iface.hh" + +static const char s_package_name_expected_msg[] = "A package name is expected."; + +using namespace franca; + +void state::package_t::handle_token() +{ + tokeniser_t tkn(m_input); + + switch ( m_subst ) { + case subst_t::expect_package_keyword: + tkn.add_rule_assign("package", m_subst, subst_t::expect_package_name); + tkn.exec_rules(); + break; + + case subst_t::expect_package_name: + ast().set_active_package(tkn.read_fqn(s_package_name_expected_msg)); + transit(); + break; + } +} + +void state::package_t::handle_eof() +{ + switch ( m_subst ) { + case subst_t::expect_package_keyword: + /* FIDL file is empty. This is okay. */ + break; + case subst_t::expect_package_name: + raise_unexpected_eof(s_package_name_expected_msg); + break; + } +} diff --git a/pool/shard006/C++/0084332_OptExcel.cpp b/pool/shard006/C++/0084332_OptExcel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e8abcd0fdb0b717d0bd52d87044f953df1a6b01 --- /dev/null +++ b/pool/shard006/C++/0084332_OptExcel.cpp @@ -0,0 +1,245 @@ +#include "stdafx.h" +#include "OptExcel.h" + + +COptExcel::COptExcel() + : covOptional((long)DISP_E_PARAMNOTFOUND, VT_ERROR) { + +} + +COptExcel::~COptExcel() { + +} + +//////////////////////////////////////////////////////////////////////// +///Function: Init +///Description: ³õʼ»¯º¯Êý£¬³õʼ»¯Öи½¼ÓexcelÓ¦ÓóÌÐò +///Call: app.CreateDispatch(_T("Excel.Application") +//////////////////////////////////////////////////////////////////////// +BOOL COptExcel::Init() { + /*BOOL bRes = AfxOleInit(); + if (!bRes) { + AfxMessageBox(_T("OLE³õʼ»¯Ê§°Ü!")); + return FALSE; + }*/ + + COleException exception; + if (!app.CreateDispatch(_T("Excel.Application"), &exception)) { + CString err; + err.Format(_T("ÇëÈ·ÈÏExcelÊÇ·ñÕýÈ·°²×°! ´íÎóÂë: %ld"), exception.m_sc); + AfxMessageBox(err); + return FALSE; + } + return TRUE; +} + +//////////////////////////////////////////////////////////////////////// +///Function: Release +///Description: Îö¹¹º¯Êý£¬ÊͷŶÔÏ󣬷dz£ÖØÒª£¬²»È«²¿ÊÍ·Å£¬Õ¼ÓÃÄڴ棬Ï +/// Ò»´ÎʹÓôËÀàʱ»áÖÐ¶Ï +///Call: ReleaseDispatch() +//////////////////////////////////////////////////////////////////////// +void COptExcel::Release() { + books.ReleaseDispatch(); + book.ReleaseDispatch(); + sheets.ReleaseDispatch(); + sheet.ReleaseDispatch(); + range.ReleaseDispatch(); + font.ReleaseDispatch(); + cell.ReleaseDispatch(); + app.Quit(); + app.ReleaseDispatch(); +} + +//////////////////////////////////////////////////////////////////////// +///Function: OpenExcelBook +///Description: ´ò¿ª±íÃûΪfilenameµÄÎļþ£¬×¢Ò⣬Îļþ·¾¶·Ç×Ô¶¯Éú³É£¬ÒÔºó +/// ¿¼ÂÇ´ÓÏ´¦Àí·½·¨ +///Call: GetAppPath() +///Input: CString filename ÎļþÃû +//////////////////////////////////////////////////////////////////////// +BOOL COptExcel::OpenExcelBook(CString filename) { + CFileFind filefind; + if (!filefind.FindFile(filename)) { + AfxMessageBox(_T("Îļþ²»´æÔÚ!")); + return FALSE; + } + + LPDISPATCH lpDisp; + books = app.get_Workbooks(); + lpDisp = books.Open(filename, + covOptional, covOptional, covOptional, covOptional, + covOptional, covOptional, covOptional, covOptional, + covOptional, covOptional, covOptional, covOptional, + covOptional, covOptional); + book.AttachDispatch(lpDisp); + sheets = book.get_Sheets(); + sheet = sheets.get_Item(COleVariant((short)1)); + return TRUE; +} + +//////////////////////////////////////////////////////////////////////// +///Function: NewExcelBook +///Description: н¨Excel±í +//////////////////////////////////////////////////////////////////////// +void COptExcel::NewExcelBook() { + books = app.get_Workbooks(); + book = books.Add(covOptional); + sheets = book.get_Sheets(); + sheet = sheets.get_Item(COleVariant((short)1)); +} + +//////////////////////////////////////////////////////////////////////// +///Function: OpenExcelApp +///Description: ´ò¿ªÓ¦ÓóÌÐò£¨Òª×¢ÒâÒÔºóÈçºÎʶ±ðÓû§Òª´ò¿ªµÄÊÇÄĸöÎļþ£© +//////////////////////////////////////////////////////////////////////// +void COptExcel::OpenExcelApp() { + app.put_Visible(TRUE); + app.put_UserControl(TRUE); +} + +//////////////////////////////////////////////////////////////////////// +///Function: SaveExcel +///Description: ÓÃÓÚ´ò¿ªÊý¾ÝÎļþ£¬Ðø´æÊý¾ÝºóÖ±½Ó±£´æ +//////////////////////////////////////////////////////////////////////// +void COptExcel::SaveExcel() { + book.put_Saved(TRUE); +} + +//////////////////////////////////////////////////////////////////////// +///Function: SaveAsExcel +///Description: ±£´æexcelÎļþ +//////////////////////////////////////////////////////////////////////// +void COptExcel::SaveAsExcel(CString filename) { + book.SaveAs(COleVariant(filename), covOptional, + covOptional, covOptional,covOptional, covOptional, + (long)0, covOptional, covOptional, covOptional, + covOptional, covOptional); +} + +//////////////////////////////////////////////////////////////////////// +///Function: SetCellValue +///Description: Ð޸ĵ¥Ôª¸ñÄÚµÄÖµ +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int row µ¥Ôª¸ñËùÔÚÐÐ +/// int col µ¥Ôª¸ñËùÔÚÁÐ +/// int Align ¶ÔÆë·½Ê½Ä¬ÈÏΪ¾ÓÖÐ +//////////////////////////////////////////////////////////////////////// +void COptExcel::SetCellValue(int row, int col, int Align, CString value) { + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + range.put_Value2(COleVariant(value)); + cell.AttachDispatch((range.get_Item(COleVariant(long(1)), COleVariant(long(1)))).pdispVal); + cell.put_HorizontalAlignment(COleVariant((short)Align)); +} + +//////////////////////////////////////////////////////////////////////// +///Function: GetCellValue +///Description: µÃµ½µÄµ¥Ôª¸ñÖеÄÖµ +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int row µ¥Ôª¸ñËùÔÚÐÐ +/// int col µ¥Ôª¸ñËùÔÚÁÐ +///Return: CString µ¥Ôª¸ñÖеÄÖµ +//////////////////////////////////////////////////////////////////////// +CString COptExcel::GetCellValue(int row, int col) { + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + COleVariant rValue; + rValue = COleVariant(range.get_Value2()); + rValue.ChangeType(VT_BSTR); + return CString(rValue.bstrVal); +} + +//////////////////////////////////////////////////////////////////////// +///Function: SetRowHeight +///Description: ÉèÖÃÐÐ¸ß +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int row µ¥Ôª¸ñËùÔÚÐÐ +//////////////////////////////////////////////////////////////////////// +void COptExcel::SetRowHeight(int row, CString height) { + int col = 1; + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + range.put_RowHeight(COleVariant(height)); +} + +//////////////////////////////////////////////////////////////////////// +///Function: SetColumnWidth +///Description: ÉèÖÃÁпí +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int col ÒªÉèÖÃÁпíµÄÁÐ +/// CString ¿íÖµ +/////////////////////////////////////////////////////////////////////// +void COptExcel::SetColumnWidth(int col, CString width) { + int row = 1; + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + range.put_ColumnWidth(COleVariant(width)); +} + +//////////////////////////////////////////////////////////////////////// +///Function: GetColumnWidth +///Description: ÉèÖÃÁÐ¸ß +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int row µ¥Ôª¸ñËùÔÚÐÐ +//////////////////////////////////////////////////////////////////////// +CString COptExcel::GetColumnWidth(int col) { + int row = 1; + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + VARIANT width = range.get_ColumnWidth(); + CString strwidth; + strwidth.Format(CString((LPCSTR)(_bstr_t)(_variant_t)width)); + return strwidth; +} + +//////////////////////////////////////////////////////////////////////// +///Function: GetRowHeight +///Description: ÉèÖÃÐÐ¸ß +///Call: IndexToString() ´Ó(x,y)×ø±êÐÎʽת»¯Îª¡°A1¡±¸ñʽ×Ö·û´® +///Input: int row ÒªÉèÖÃÐиߵÄÐÐ +/// CString ¿íÖµ +//////////////////////////////////////////////////////////////////////// +CString COptExcel::GetRowHeight(int row) { + int col = 1; + range = sheet.get_Range(COleVariant(IndexToString(row, col)), COleVariant(IndexToString(row, col))); + VARIANT height = range.get_RowHeight(); + CString strheight; + strheight.Format(CString((LPCSTR)(_bstr_t)(_variant_t)height)); + return strheight; +} + +//////////////////////////////////////////////////////////////////////// +///Function: IndexToString +///Description: µÃµ½µÄµ¥Ôª¸ñÔÚEXCELÖеĶ¨Î»Ãû³Æ×Ö·û´® +///Input: int row µ¥Ôª¸ñËùÔÚÐÐ +/// int col µ¥Ôª¸ñËùÔÚÁÐ +///Return: CString µ¥Ôª¸ñÔÚEXCELÖеĶ¨Î»Ãû³Æ×Ö·û´® +//////////////////////////////////////////////////////////////////////// +CString COptExcel::IndexToString(int row, int col) { + CString strResult; + if (col > 26) { + strResult.Format(_T("%c%c%d"), 'A' + (col - 1) / 26 - 1, 'A' + (col - 1) % 26, row); + } else { + strResult.Format(_T("%c%d"), 'A' + (col - 1) % 26, row); + } + return strResult; +} + +//////////////////////////////////////////////////////////////////////// +///Function: LastLineIndex +///Description: µÃµ½±í¸ñ×ܵÚÒ»¸ö¿ÕÐеÄË÷Òý +///Return: int ¿ÕÐеÄË÷ÒýºÅ +//////////////////////////////////////////////////////////////////////// +unsigned int COptExcel::LastLineIndex() { + unsigned int i, j, flag = 0; + CString str; + for (i = 1;; i++) { + flag = 0; + //´ÖÂÔͳ¼Æ£¬ÈÏΪǰÁж¼Ã»ÓÐÊý¾Ý¼´Îª¿ÕÐÐ + for (j = 1; j <= 5; j++) { + str.Format(_T("%s"), GetCellValue(i, j).Trim()); + if (str.Compare(_T("")) != 0) { + flag = 1; + break; + } + } + if (flag == 0) + return i; + } +} diff --git a/pool/shard006/C++/0084341_qtextimagehandler.cpp b/pool/shard006/C++/0084341_qtextimagehandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe45fc47ec69e25fda17ca89db99904795fa9e0b --- /dev/null +++ b/pool/shard006/C++/0084341_qtextimagehandler.cpp @@ -0,0 +1,234 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include "qtextimagehandler_p.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +// set by the mime source factory in Qt3Compat +QTextImageHandler::ExternalImageLoaderFunction QTextImageHandler::externalLoader = 0; + +static QPixmap getPixmap(QTextDocument *doc, const QTextImageFormat &format) +{ + QPixmap pm; + + QString name = format.name(); + if (name.startsWith(QLatin1String(":/"))) // auto-detect resources + name.prepend(QLatin1String("qrc")); + QUrl url = QUrl::fromEncoded(name.toUtf8()); + const QVariant data = doc->resource(QTextDocument::ImageResource, url); + if (data.type() == QVariant::Pixmap || data.type() == QVariant::Image) { + pm = qvariant_cast(data); + } else if (data.type() == QVariant::ByteArray) { + pm.loadFromData(data.toByteArray()); + } + + if (pm.isNull()) { + QString context; +#ifndef QT_NO_TEXTBROWSER + QTextBrowser *browser = qobject_cast(doc->parent()); + if (browser) + context = browser->source().toString(); +#endif + QImage img; + if (QTextImageHandler::externalLoader) + img = QTextImageHandler::externalLoader(name, context); + + if (img.isNull()) { // try direct loading + name = format.name(); // remove qrc:/ prefix again + if (name.isEmpty() || !img.load(name)) + return QPixmap(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png")); + } + pm = QPixmap::fromImage(img); + doc->addResource(QTextDocument::ImageResource, url, pm); + } + + return pm; +} + +static QSize getPixmapSize(QTextDocument *doc, const QTextImageFormat &format) +{ + QPixmap pm; + + const bool hasWidth = format.hasProperty(QTextFormat::ImageWidth); + const int width = qRound(format.width()); + const bool hasHeight = format.hasProperty(QTextFormat::ImageHeight); + const int height = qRound(format.height()); + + QSize size(width, height); + if (!hasWidth || !hasHeight) { + pm = getPixmap(doc, format); + if (!hasWidth) { + if (!hasHeight) + size.setWidth(pm.width()); + else + size.setWidth(qRound(height * (pm.width() / (qreal) pm.height()))); + } + if (!hasHeight) { + if (!hasWidth) + size.setHeight(pm.height()); + else + size.setHeight(qRound(width * (pm.height() / (qreal) pm.width()))); + } + } + + qreal scale = 1.0; + QPaintDevice *pdev = doc->documentLayout()->paintDevice(); + if (pdev) { + Q_GUI_EXPORT extern int qt_defaultDpi(); + if (pm.isNull()) + pm = getPixmap(doc, format); + if (!pm.isNull()) + scale = qreal(pdev->logicalDpiY()) / qreal(qt_defaultDpi()); + } + size *= scale; + + return size; +} + +static QImage getImage(QTextDocument *doc, const QTextImageFormat &format) +{ + QImage image; + + QString name = format.name(); + if (name.startsWith(QLatin1String(":/"))) // auto-detect resources + name.prepend(QLatin1String("qrc")); + QUrl url = QUrl::fromEncoded(name.toUtf8()); + const QVariant data = doc->resource(QTextDocument::ImageResource, url); + if (data.type() == QVariant::Image) { + image = qvariant_cast(data); + } else if (data.type() == QVariant::ByteArray) { + image.loadFromData(data.toByteArray()); + } + + if (image.isNull()) { + QString context; +#ifndef QT_NO_TEXTBROWSER + QTextBrowser *browser = qobject_cast(doc->parent()); + if (browser) + context = browser->source().toString(); +#endif + if (QTextImageHandler::externalLoader) + image = QTextImageHandler::externalLoader(name, context); + + if (image.isNull()) { // try direct loading + name = format.name(); // remove qrc:/ prefix again + if (name.isEmpty() || !image.load(name)) + return QImage(QLatin1String(":/trolltech/styles/commonstyle/images/file-16.png")); + } + doc->addResource(QTextDocument::ImageResource, url, image); + } + + return image; +} + +static QSize getImageSize(QTextDocument *doc, const QTextImageFormat &format) +{ + QImage image; + + const bool hasWidth = format.hasProperty(QTextFormat::ImageWidth); + const int width = qRound(format.width()); + const bool hasHeight = format.hasProperty(QTextFormat::ImageHeight); + const int height = qRound(format.height()); + + QSize size(width, height); + if (!hasWidth || !hasHeight) { + image = getImage(doc, format); + if (!hasWidth) + size.setWidth(image.width()); + if (!hasHeight) + size.setHeight(image.height()); + } + + qreal scale = 1.0; + QPaintDevice *pdev = doc->documentLayout()->paintDevice(); + if (pdev) { + extern int qt_defaultDpi(); + if (image.isNull()) + image = getImage(doc, format); + if (!image.isNull()) + scale = qreal(pdev->logicalDpiY()) / qreal(qt_defaultDpi()); + } + size *= scale; + + return size; +} + +QTextImageHandler::QTextImageHandler(QObject *parent) + : QObject(parent) +{ +} + +QSizeF QTextImageHandler::intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format) +{ + Q_UNUSED(posInDocument) + const QTextImageFormat imageFormat = format.toImageFormat(); + + if (qApp->thread() != QThread::currentThread()) + return getImageSize(doc, imageFormat); + return getPixmapSize(doc, imageFormat); +} + +void QTextImageHandler::drawObject(QPainter *p, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format) +{ + Q_UNUSED(posInDocument) + const QTextImageFormat imageFormat = format.toImageFormat(); + + if (qApp->thread() != QThread::currentThread()) { + const QImage image = getImage(doc, imageFormat); + p->drawImage(rect, image, image.rect()); + } else { + const QPixmap pixmap = getPixmap(doc, imageFormat); + p->drawPixmap(rect, pixmap, pixmap.rect()); + } +} + +QT_END_NAMESPACE diff --git a/pool/shard006/C++/0084346_httpsocket.cpp b/pool/shard006/C++/0084346_httpsocket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ea42c43faadc5eac956ba16aba7ab3e3e7f9f73 --- /dev/null +++ b/pool/shard006/C++/0084346_httpsocket.cpp @@ -0,0 +1,125 @@ +/*************************************************************************** + * Copyright (C) 2010 by Etrnls * + * Etrnls@gmail.com * + * * + * This file is part of Evangel. * + * * + * Evangel is free software: you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation, either version 3 of the License, or * + * (at your option) any later version. * + * * + * Evangel 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 Evangel. If not, see . * + ***************************************************************************/ +#include "httpsocket.h" +#include "httpclient.h" + +#include +#include + +namespace Protocol +{ + +namespace HTTP +{ + +QWeakPointer HTTPSocket::accessManager; + +HTTPSocket::HTTPSocket(const QUrl &URL) : AbstractSocket(NormalPriority), URL(URL), manager(accessManager), reply(0) +{ + if (!manager) + { + manager = QSharedPointer(new QNetworkAccessManager()); + accessManager = manager; + } +} + +HTTPSocket::~HTTPSocket() +{ + detachTrafficControl(); + delete reply; +} + +void HTTPSocket::head() +{ +} + +void HTTPSocket::get(qint64 offset) +{ + Q_ASSERT_X(getState() == UnconnectedState, Q_FUNC_INFO, "Already started"); + + + attachTrafficControl(); +} + +HTTPSocket::State HTTPSocket::getState() const +{ + return reply ? ConnectedState : UnconnectedState; +} + +void HTTPSocket::setNetworkReadBufferSize(int size) +{ + Q_ASSERT_X(getState() == ConnectedState, Q_FUNC_INFO, "Not started yet"); + reply->setReadBufferSize(size); +} + +bool HTTPSocket::canDownload() const +{ + Q_ASSERT_X(getState() == ConnectedState, Q_FUNC_INFO, "Not started yet"); + return reply->bytesAvailable() > 0; +} + +bool HTTPSocket::canUpload() const +{ + return false; +} + +int HTTPSocket::download(int maxSize) +{ + Q_ASSERT_X(getState() == ConnectedState, Q_FUNC_INFO, "Not started yet"); + + maxSize = qMin(maxSize, reply->bytesAvailable()); + if (maxSize == 0) return 0; + + const int oldSize = incomingBuffer.size(); + incomingBuffer.resize(incomingBuffer.size() + maxSize); + + const int result = reply->read(incomingBuffer.data() + oldSize, maxSize); + incomingBuffer.resize(result > 0 ? oldSize + result : oldSize); + + if (result > 0) QMetaObject::invokeMethod(this, "autoProcessIncomingData", Qt::QueuedConnection); + + return result; +} + +int HTTPSocket::upload(int maxSize) +{ + Q_UNUSED(maxSize); + Q_ASSERT_X(false, Q_FUNC_INFO, "Invalid call"); + return 0; +} + +void HTTPSocket::processHead() const +{ +} + +void HTTPSocket::processIncomingData() +{ + static const int threshold = 4 * 1024; + if (incomingBuffer.size() >= threshold) + { + emit blockReceived(offset, incomingBuffer); + incomingBuffer.clear(); + } +} + + +} + +} diff --git a/pool/shard006/C++/0084357_main.cpp b/pool/shard006/C++/0084357_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07fb42a843b3719b8c00b9f10042b1d0b8c9fd21 --- /dev/null +++ b/pool/shard006/C++/0084357_main.cpp @@ -0,0 +1,65 @@ +#include +#include + +#include "thread_pool.hpp" +#include "command_line_parser.hpp" + +void task_one(int id) { + std::cout << id << " function\n"; +} + +void task_two(int id, int N) { + std::this_thread::sleep_for(std::chrono::milliseconds(N)); + std::cout << id << " function" << std::endl; +} + +int main(int argc, char **argv) +{ + std::ios_base::sync_with_stdio(false); + + CommandLineParser parser; + if (!parser.parse(argc, argv)) { + return 1; + } + + std_utils::thread_pool p(parser.count_threads); + + auto qw = p.submit(std::move(task_one)); + + auto output_flag = true; + auto command = 0; + auto N = 0; + std::string menu("0 - Exit\n" + "1 - To add a task with a duration of N seconds\n" + "2 - To remove a task from execution by its ID\n" + "3 - To request the status of the task\n" + "Your choice: " + ); + + while (output_flag) { + std::cout << menu; + std::cin >> command; + switch (command) { + case 0: + output_flag = false; + break; + case 1: + std::cin >> N; + p.submit(task_two, 1000 * N); + break; + case 2: + std::cin >> N; + p.interrupt(N); + break; + case 3: + std::cin >> N; + std::cout << p.get_id(N) << std::endl; + break; + default: + std::cout << "Error\n\n"; + break; + } + } + + return 0; +} diff --git a/pool/shard006/C++/0084364_D.cpp b/pool/shard006/C++/0084364_D.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0fe07ec61fbb88eca80caf269942c3a25a9cb3ba --- /dev/null +++ b/pool/shard006/C++/0084364_D.cpp @@ -0,0 +1,74 @@ +//#pragma comment(linker, "/STACK:1024000000,1024000000") +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define Msn(x,y) (memset((x),0,sizeof((x[0]))*(y+1))) +#define msn(x) (memset((x),0,sizeof((x)))) +#define msx(x,y) (memset((x),0x7f,sizeof((x[0]))*(y+3))) +#define fuck(x) cerr << #x << " <- " << x << endl +#define acer cout<<"sb"<=aa) + { + dp[j-aa][0]=max(dp[j-aa][0],dp[j][0]+v); + dp[j-aa][1]=max(dp[j-aa][1],dp[j][1]+v); + dp[j-aa][2]=max(dp[j-aa][2],dp[j][2]+v); + } + if(j>=a) + { + dp[j-a][1]=max(dp[j-a][1],dp[j][0]+v); + dp[j-a][2]=max(dp[j-a][2],dp[j][1]+v); + } + } + } + +// fuck(dp[2][0]); + for(int j=0;j<=m;j++) + { + for(int k=0;k<=2;k++)ans=max(ans,dp[j][k]); + } +// fuck(ans); + printf("Case #%d: %lld\n",_,ans); + } + return 0; +} diff --git a/pool/shard006/C++/0084390_RekognitionEndpoint.cpp b/pool/shard006/C++/0084390_RekognitionEndpoint.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13a1f48dda7bd5fe922f383499a820240a2c96ed --- /dev/null +++ b/pool/shard006/C++/0084390_RekognitionEndpoint.cpp @@ -0,0 +1,72 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include + +using namespace Aws; +using namespace Aws::Rekognition; + +namespace Aws +{ +namespace Rekognition +{ +namespace RekognitionEndpoint +{ + static const int CN_NORTH_1_HASH = Aws::Utils::HashingUtils::HashString("cn-north-1"); + static const int CN_NORTHWEST_1_HASH = Aws::Utils::HashingUtils::HashString("cn-northwest-1"); + static const int US_ISO_EAST_1_HASH = Aws::Utils::HashingUtils::HashString("us-iso-east-1"); + static const int US_ISOB_EAST_1_HASH = Aws::Utils::HashingUtils::HashString("us-isob-east-1"); + + + Aws::String ForRegion(const Aws::String& regionName, bool useDualStack) + { + auto hash = Aws::Utils::HashingUtils::HashString(regionName.c_str()); + + Aws::StringStream ss; + ss << "rekognition" << "."; + + if(useDualStack) + { + ss << "dualstack."; + } + + ss << regionName; + + if (hash == CN_NORTH_1_HASH || hash == CN_NORTHWEST_1_HASH) + { + ss << ".amazonaws.com.cn"; + } + else if (hash == US_ISO_EAST_1_HASH) + { + ss << ".c2s.ic.gov"; + } + else if (hash == US_ISOB_EAST_1_HASH) + { + ss << ".sc2s.sgov.gov"; + } + else + { + ss << ".amazonaws.com"; + } + + return ss.str(); + } + +} // namespace RekognitionEndpoint +} // namespace Rekognition +} // namespace Aws + diff --git a/pool/shard006/C++/0084396_decode_as_dialog.cpp b/pool/shard006/C++/0084396_decode_as_dialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..488cdab1f50792503009fdab776e58379fb5d614 --- /dev/null +++ b/pool/shard006/C++/0084396_decode_as_dialog.cpp @@ -0,0 +1,244 @@ +/* decode_as_dialog.cpp + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +#include "decode_as_dialog.h" +#include + +#include "epan/decode_as.h" +#include "epan/epan_dissect.h" + +#include "ui/decode_as_utils.h" +#include "ui/simple_dialog.h" +#include "wsutil/filesystem.h" +#include + +#include +#include +#include "wireshark_application.h" + +#include + +#include +#include +#include +#include +#include + +#include + +// To do: +// - Ranges +// - Add DCERPC support (or make DCERPC use a regular dissector table?) + +DecodeAsDialog::DecodeAsDialog(QWidget *parent, capture_file *cf, bool create_new) : + GeometryStateDialog(parent), + ui(new Ui::DecodeAsDialog), + model_(new DecodeAsModel(this, cf)), + delegate_(NULL) +{ + ui->setupUi(this); + loadGeometry(); + + delegate_ = new DecodeAsDelegate(ui->decodeAsTreeView, cf); + + ui->decodeAsTreeView->setModel(model_); + ui->decodeAsTreeView->setItemDelegate(delegate_); + + ui->newToolButton->setStockIcon("list-add"); + ui->deleteToolButton->setStockIcon("list-remove"); + ui->copyToolButton->setStockIcon("list-copy"); + ui->clearToolButton->setStockIcon("list-clear"); + +#ifdef Q_OS_MAC + ui->newToolButton->setAttribute(Qt::WA_MacSmallSize, true); + ui->deleteToolButton->setAttribute(Qt::WA_MacSmallSize, true); + ui->copyToolButton->setAttribute(Qt::WA_MacSmallSize, true); + ui->clearToolButton->setAttribute(Qt::WA_MacSmallSize, true); + ui->pathLabel->setAttribute(Qt::WA_MacSmallSize, true); +#endif + + setWindowTitle(wsApp->windowTitleString(tr("Decode As…"))); + + QString abs_path = gchar_free_to_qstring(get_persconffile_path(DECODE_AS_ENTRIES_FILE_NAME, TRUE)); + if (file_exists(abs_path.toUtf8().constData())) { + ui->pathLabel->setText(abs_path); + ui->pathLabel->setUrl(QUrl::fromLocalFile(abs_path).toString()); + ui->pathLabel->setToolTip(tr("Open ") + DECODE_AS_ENTRIES_FILE_NAME); + ui->pathLabel->setEnabled(true); + } + + CopyFromProfileButton *copy_button = new CopyFromProfileButton(this, DECODE_AS_ENTRIES_FILE_NAME); + ui->buttonBox->addButton(copy_button, QDialogButtonBox::ActionRole); + connect(copy_button, &CopyFromProfileButton::copyProfile, this, &DecodeAsDialog::copyFromProfile); + + fillTable(); + + connect(model_, SIGNAL(modelReset()), this, SLOT(modelRowsReset())); + ui->clearToolButton->setEnabled(model_->rowCount() > 0); + + if (create_new) + on_newToolButton_clicked(); +} + +DecodeAsDialog::~DecodeAsDialog() +{ + delete ui; + delete model_; + delete delegate_; +} + +void DecodeAsDialog::fillTable() +{ + model_->fillTable(); + + resizeColumns(); + + //set selection as first row + if (model_->rowCount() > 0) { + const QModelIndex &new_index = model_->index(0, 0); + ui->decodeAsTreeView->setCurrentIndex(new_index); + } +} + +void DecodeAsDialog::resizeColumns() +{ + if (model_->rowCount() > 0) { + for (int i = 0; i < model_->columnCount(); i++) { + ui->decodeAsTreeView->resizeColumnToContents(i); + } + } +} + +void DecodeAsDialog::modelRowsReset() +{ + ui->deleteToolButton->setEnabled(false); + ui->copyToolButton->setEnabled(false); + ui->clearToolButton->setEnabled(false); +} + +void DecodeAsDialog::on_decodeAsTreeView_currentItemChanged(const QModelIndex ¤t, const QModelIndex&) +{ + if (current.isValid()) { + ui->deleteToolButton->setEnabled(true); + ui->copyToolButton->setEnabled(true); + ui->clearToolButton->setEnabled(true); + } else { + ui->deleteToolButton->setEnabled(false); + ui->copyToolButton->setEnabled(false); + ui->clearToolButton->setEnabled(false); + } +} + +void DecodeAsDialog::copyFromProfile(QString filename) +{ + const gchar *err = NULL; + + if (!model_->copyFromProfile(filename, &err)) { + simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "Error while loading %s: %s", filename.toUtf8().constData(), err); + } + + resizeColumns(); + + ui->clearToolButton->setEnabled(model_->rowCount() > 0); +} + +void DecodeAsDialog::addRecord(bool copy_from_current) +{ + const QModelIndex ¤t = ui->decodeAsTreeView->currentIndex(); + if (copy_from_current && !current.isValid()) return; + +// XXX - This doesn't appear to work as intended to give "edit triggers on demand" + ui->decodeAsTreeView->setEditTriggers(ui->decodeAsTreeView->editTriggers() | QAbstractItemView::CurrentChanged | QAbstractItemView::AnyKeyPressed); + + // should not fail, but you never know. + if (!model_->insertRows(model_->rowCount(), 1)) { + qDebug() << "Failed to add a new record"; + return; + } + const QModelIndex &new_index = model_->index(model_->rowCount() - 1, 0); + if (copy_from_current) { + model_->copyRow(new_index.row(), current.row()); + } + + resizeColumns(); + + // due to an EditTrigger, this will also start editing. + ui->decodeAsTreeView->setCurrentIndex(new_index); +} + +void DecodeAsDialog::on_newToolButton_clicked() +{ + addRecord(); +} + +void DecodeAsDialog::on_deleteToolButton_clicked() +{ + const QModelIndex ¤t = ui->decodeAsTreeView->currentIndex(); + if (model_ && current.isValid()) { + if (!model_->removeRows(current.row(), 1)) { + qDebug() << "Failed to remove row"; + } + } +} + +void DecodeAsDialog::on_copyToolButton_clicked() +{ + addRecord(true); +} + +void DecodeAsDialog::on_clearToolButton_clicked() +{ + model_->clearAll(); +} + +void DecodeAsDialog::applyChanges() +{ + model_->applyChanges(); + wsApp->queueAppSignal(WiresharkApplication::PacketDissectionChanged); +} + +void DecodeAsDialog::on_buttonBox_clicked(QAbstractButton *button) +{ + ui->buttonBox->setFocus(); + + switch (ui->buttonBox->standardButton(button)) { + case QDialogButtonBox::Ok: + applyChanges(); + break; + case QDialogButtonBox::Save: + { + gchar* err = NULL; + + applyChanges(); + if (save_decode_as_entries(&err) < 0) { + simple_dialog(ESD_TYPE_ERROR, ESD_BTN_OK, "%s", err); + g_free(err); + } + } + break; + case QDialogButtonBox::Help: + wsApp->helpTopicAction(HELP_DECODE_AS_SHOW_DIALOG); + break; + default: + break; + } +} + +/* + * Editor modelines + * + * Local Variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard006/C++/0084401_sk.cpp b/pool/shard006/C++/0084401_sk.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84ec5032f4d79cc8138ce8c95be144dc74a012c3 --- /dev/null +++ b/pool/shard006/C++/0084401_sk.cpp @@ -0,0 +1,161 @@ +#include +#include + +using namespace Skuld; + +#if defined(SKULD_PLATFORM_IS_WINDOWS) + +#include +#include + +class StdoutWriter : public StringWriter +{ +private: + HANDLE handle; +public: + StdoutWriter() + { + handle = GetStdHandle(STD_OUTPUT_HANDLE); + } + virtual Raw Write(StringView str) override + { + DWORD dw; + std::wstring temp = str.ToStd(); + ::WriteConsoleW(handle, temp.c_str(), (DWORD)temp.size(), &dw, NULL); + return this; + } + + virtual Raw WriteLine() override + { + DWORD dw; + ::WriteConsoleW(handle, L"\n", 1, &dw, NULL); + return this; + } +}; + +class StdinReader : public StringReader +{ +private: + HANDLE handle; + std::array buffer; +public: + StdinReader() + : buffer{ 0 } + { + handle = GetStdHandle(STD_INPUT_HANDLE); + } + virtual String ReadLine() override + { + StringBuilder sb; + + auto append = [&sb, this](size_t _start, size_t _end) + { + if (_end != _start) + sb.Append(String::FromWString(std::wstring_view{ &buffer[_start], _end - _start })); + }; + + bool stop = false; + size_t start = 0; + while (!stop) + { + DWORD readSize = 0; + ::ReadConsoleW(handle, &buffer[0], (DWORD)buffer.size(), &readSize, NULL); + size_t end = start; + size_t bufferEnd = start + readSize; + while (end < start + readSize) + { + if (buffer[end] == L'\r') + { + stop = true; + break; + } + + end++; + } + append(start, end); + if (stop) + { + start = end + 2; + size_t shouldSkip = start - bufferEnd; + while (shouldSkip) + { + size_t shouldRead = std::min(shouldSkip, buffer.size()); + ::ReadConsoleW(handle, &buffer[0], (DWORD)shouldRead, &readSize, NULL); + shouldSkip -= readSize; + } + } + } + return sb.ToString(); + } +}; + +#else + +class StdoutWriter : public StringWriter +{ +public: + virtual Raw Write(StringView str) override + { + std::cout << str; + return this; + } + virtual Raw WriteLine() override + { + std::cout << std::endl; + return this; + } +}; + +class StdinReader : public StringReader +{ +public: + virtual String ReadLine() override + { + std::string str; + std::getline(std::cin, str); + + return String::FromUTF8(str); + } +}; + +#endif + +#include + +int SkuldApp_OnStart(const std::vector& args) +{ + Handle fs = CreateNativeFileSystem(); + Handle _stdout = NewHandle(); + + if (args.size() == 1) + { + Handle _stdin = NewHandle(); + Skuld::Tool::Shell(fs, _stdin, _stdout); + return 0; + } + else + { + std::vector args_(args.size() - 1); + for (size_t i = 0; i < args_.size(); i++) + args_[i] = args[i + 1]; + + return Skuld::Tool::Execute(fs, args, _stdout); + } +} + +int main(int _argc, char** _argv) +{ + int argc; +#if defined(SKULD_PLATFORM_IS_WINDOWS) + wchar_t** argv = CommandLineToArgvW(GetCommandLineW(), &argc); + std::vector args(argc); + for (int i = 0; i < argc; i++) args[i] = String::FromWString(argv[i]); + LocalFree(argv); +#else + argc = _argc; + std::vector args(argc); + for (int i = 0; i < argc; i++) args[i] = String::FromUTF8(_argv[i]); +#endif + + return SkuldApp_OnStart(args); +} \ No newline at end of file diff --git a/pool/shard006/C++/0084407_GlobalsTest.cpp b/pool/shard006/C++/0084407_GlobalsTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da9dabcf43375651331e751d07e803323747d370 --- /dev/null +++ b/pool/shard006/C++/0084407_GlobalsTest.cpp @@ -0,0 +1,59 @@ +//============================================================================ +// Project: Jabber Universal Document Objects (Judo) +// Filename: GlobalsTest.cpp +// Description: judo global function tests +// Created at: Tue Jul 3 13:06:11 2001 +// Modified at: Mon Jul 30 18:10:54 2001 +// +// License: +// +// The contents of this file are subject to the Jabber Open Source License +// Version 1.0 (the "License"). You may not copy or use this file, in either +// source code or executable form, except in compliance with the License. You +// may obtain a copy of the License at http://www.jabber.com/license/ or at +// http://www.opensource.org/. +// +// Software distributed under the License is distributed on an "AS IS" basis, +// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +// for the specific language governing rights and limitations under the +// License. +// +// Copyrights +// +// Portions created by or assigned to Jabber.com, Inc. are +// Copyright (c) 1999-2001 Jabber.com, Inc. All Rights Reserved. +// +// $Id: GlobalsTest.cpp,v 1.2 2002/07/13 19:30:22 temas Exp $ +//============================================================================ + +#include "judo.hpp" +#include "judo_test.hpp" +using namespace judo; +using namespace std; + +Test* GlobalsTest::getTestSuite() +{ + TestSuite* s = new TestSuite(); + s->addTest(new TestCaller("testing XML escaping", + &GlobalsTest::escape)); + s->addTest(new TestCaller("testing XML unescape", + &GlobalsTest::unescape)); + return s; +} + +const string G_escaped = "& me ' you " < 23 > 5"; +const string G_unescaped = "& me ' you \" < 23 > 5"; + +void GlobalsTest::escape() +{ + Assert(G_escaped == judo::escape(G_unescaped)); +} + +void GlobalsTest::unescape() +{ + string target; + + judo::unescape(G_escaped.c_str(), G_escaped.size(), target); + + Assert(G_unescaped == target); +} diff --git a/pool/shard006/C++/0084409_gltfWriter-Light.cpp b/pool/shard006/C++/0084409_gltfWriter-Light.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b77d4a63dfefab0a76ca5a3210573666d1d1fc19 --- /dev/null +++ b/pool/shard006/C++/0084409_gltfWriter-Light.cpp @@ -0,0 +1,135 @@ +// +// Copyright (c) Autodesk, Inc. All rights reserved +// +// C++ glTF FBX importer/exporter plug-in +// by Cyrille Fauvel - Autodesk Developer Network (ADN) +// January 2015 +// +// Permission to use, copy, modify, and distribute this software in +// object code form for any purpose and without fee is hereby granted, +// provided that the above copyright notice appears in all copies and +// that both that copyright notice and the limited warranty and +// restricted rights notice below appear in all supporting +// documentation. +// +// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. +// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF +// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. +// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE +// UNINTERRUPTED OR ERROR FREE. +// +#include "StdAfx.h" +#include "gltfWriter.h" + +namespace _IOglTF_NS_ { + +void gltfWriter::lightAttenuation (FbxLight *pLight, web::json::value &lightDef) { + float attenuation [3] = { + 1.f, // Constant + 0.f, // Linear + 0.f // Quadratic + } ; + switch ( pLight->DecayType.Get () ) { + case FbxLight::EDecayType::eLinear: + attenuation [0] =0.0f ; + attenuation [1] =1.0f ; + break ; + case FbxLight::EDecayType::eCubic: + attenuation [0] =0.0f ; + attenuation [2] =1.0f ; // OpenGL doesn't support cubicU( so default to quadratic + break ; + case FbxLight::EDecayType::eQuadratic: + attenuation [0] =0.0f ; + attenuation [2] =1.0f ; + break ; + case FbxLight::EDecayType::eNone: + default: + attenuation [0] =1.0f ; + break ; + } + if ( attenuation [0] != 1.0f ) + lightDef [U("constantAttenuation")] =web::json::value::number (attenuation [0]) ; + if ( attenuation [1] != 0.0f ) + lightDef [U("linearAttenuation")] =web::json::value::number (attenuation [1]) ; + if ( attenuation [2] != 0.0f ) + lightDef [U("quadraticAttenuation")] =web::json::value::number (attenuation [2]) ; +} + +web::json::value gltfWriter::WriteLight (FbxNode *pNode) { + web::json::value light =web::json::value::object () ; + web::json::value lightDef =web::json::value::object () ; + light [U("name")] =web::json::value::string (nodeId (pNode, true)) ; + + if ( isKnownId (pNode->GetNodeAttribute ()->GetUniqueID ()) ) { + // The light was already exported, create only the transform node + web::json::value node =WriteNode (pNode) ; + web::json::value ret =web::json::value::object ({ { U("nodes"), node } }) ; + return (ret) ; + } + + FbxLight *pLight =pNode->GetLight () ; //FbxCast(pNode->GetNodeAttribute ()) ; + static const FbxDouble3 defaultLightColor (1., 1., 1.) ; + auto color =pLight->Color ; + if ( _writeDefaults || color.Get () != defaultLightColor ) + lightDef [U("color")] =web::json::value::array ({{ + static_cast(color.Get () [0]), + static_cast(color.Get () [1]), + static_cast(color.Get () [2]) + }}) ; + switch ( pLight->LightType.Get () ) { + case FbxLight::EType::ePoint: + light [U("type")] =web::json::value::string (U("point")) ; + lightAttenuation (pLight, lightDef) ; + light [U("point")] =lightDef ; + break ; + case FbxLight::EType::eSpot: + light [U("type")] =web::json::value::string (U("spot")) ; + lightAttenuation (pLight, lightDef) ; + if ( pLight->OuterAngle.Get () != 180.0 ) // default is PI + lightDef [U("fallOffAngle")] =DEG2RAD (pLight->OuterAngle) ; + if ( _writeDefaults ) + lightDef [U("fallOffExponent")] =web::json::value::number ((double)0.) ; + light [U("spot")] =lightDef ; + break ; + case FbxLight::EType::eDirectional: + light [U("type")] =web::json::value::string (U("directional")) ; + light [U("directional")] =lightDef ; + break ; + case FbxLight::EType::eArea: + case FbxLight::EType::eVolume: + default: // ambient + _ASSERTE (false) ; + return (web::json::value::object ()) ; + break ; + } + + web::json::value lib =web::json::value::object ({ { nodeId (pNode, true, true), light } }) ; + web::json::value node =WriteNode (pNode) ; + + return (web::json::value::object ({ { U("lights"), lib }, { U("nodes"), node } })) ; +} + +web::json::value gltfWriter::WriteAmbientLight (FbxScene &pScene) { + web::json::value light =web::json::value::object () ; + web::json::value lightDef =web::json::value::object () ; + static const FbxDouble3 defaultLightColor (1., 1., 1.) ; + FbxColor color (pScene.GetGlobalSettings ().GetAmbientColor ()) ; + if ( !color.mRed && !color.mGreen && !color.mBlue ) + return (web::json::value::object ()) ; + if ( !_writeDefaults && color == defaultLightColor ) + return (web::json::value::object ()) ; + lightDef [U("color")] =web::json::value::array () ; + lightDef [U("color")] [0] =static_cast (color.mRed) ; + lightDef [U("color")] [1] =static_cast (color.mGreen) ; + lightDef [U("color")] [2] =static_cast (color.mBlue) ; + light [U("type")] =web::json::value::string (U("ambient")) ; + light [U("ambient")] =lightDef ; + + utility::string_t buffer =utility::conversions::to_string_t ((int)0) ; + utility::string_t uid (U("defaultambient")) ; + uid +=U("_") + buffer ; + return (web::json::value::object ({ { uid, light } })) ; + //return (web::json::value::object ({ { nodeId (U("defaultambient"), 0x00), light } })) ; +} + +} \ No newline at end of file diff --git a/pool/shard006/C++/0084411_Tcpserver.cc b/pool/shard006/C++/0084411_Tcpserver.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe7246a6c3862d76c304a598084e7e044b749eb5 --- /dev/null +++ b/pool/shard006/C++/0084411_Tcpserver.cc @@ -0,0 +1,110 @@ +#include + +#include +#include +#include +#include +#include + +#include + +#include // snprintf + +using namespace walle::sys; +namespace walle { +namespace net { + +TcpServer::TcpServer(EventLoop* loop, + AddrInet& listenAddr, + const string& nameArg, + Option option) + : _loop(loop), + _hostport(listenAddr.toString()), + _name(nameArg), + _acceptor(new Acceptor(loop, listenAddr, option == kReusePort)), + _threadPool(new EventLoopThreadPool(loop)), + _connectionCallback(defaultConnectionCallback), + _messageCallback(defaultMessageCallback), + _nextConnId(1) +{ + _acceptor->setNewConnectionCallback( + std::bind(&TcpServer::newConnection, this, std::_1, std::_2)); +} + +TcpServer::~TcpServer() +{ + _loop->assertInLoopThread(); + + for (ConnectionMap::iterator it(_connections.begin()); + it != _connections.end(); ++it) + { + TcpConnectionPtr conn = it->second; + it->second.reset(); + conn->getLoop()->runInLoop( + std::bind(&TcpConnection::connectDestroyed, conn)); + conn.reset(); + } +} + +void TcpServer::setThreadNum(int numThreads) +{ + assert(0 <= numThreads); + _threadPool->setThreadNum(numThreads); +} + +void TcpServer::start() +{ + if (_started.getAndSet(1) == 0) + { + _threadPool->start(_threadInitCallback); + + assert(!_acceptor->listenning()); + _loop->runInLoop( + std::bind(&Acceptor::listen, get_pointer(_acceptor))); + } +} + +void TcpServer::newConnection(int sockfd, const AddrInet& peerAddr) +{ + _loop->assertInLoopThread(); + EventLoop* ioLoop = _threadPool->getNextLoop(); + char buf[128]; + snprintf(buf, sizeof buf, "%s:%s#%d",_name.c_str(), _hostport.c_str(), _nextConnId); + ++_nextConnId; + string connName(buf); + AddrInet localAddr; + localAddr.upDateLocal(sockfd); + + TcpConnectionPtr conn(new TcpConnection(ioLoop, + connName, + sockfd, + localAddr, + peerAddr)); + _connections[connName] = conn; + conn->setConnectionCallback(_connectionCallback); + conn->setMessageCallback(_messageCallback); + conn->setWriteCompleteCallback(_writeCompleteCallback); + conn->setCloseCallback( + std::bind(&TcpServer::removeConnection, this, std::_1)); + ioLoop->runInLoop(std::bind(&TcpConnection::connectEstablished, conn)); +} + +void TcpServer::removeConnection(const TcpConnectionPtr& conn) +{ + + _loop->runInLoop(std::bind(&TcpServer::removeConnectionInLoop, this, conn) +); +} + +void TcpServer::removeConnectionInLoop(const TcpConnectionPtr& conn) +{ + _loop->assertInLoopThread(); + size_t n = _connections.erase(conn->name()); + (void)n; + assert(n == 1); + EventLoop* ioLoop = conn->getLoop(); + ioLoop->queueInLoop( + std::bind(&TcpConnection::connectDestroyed, conn)); +} +} +} diff --git a/pool/shard006/C++/0084413_duration.cpp b/pool/shard006/C++/0084413_duration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..592ff93069bd5d4033d434220cede51576e1c496 --- /dev/null +++ b/pool/shard006/C++/0084413_duration.cpp @@ -0,0 +1,66 @@ +/****************************************************************************** + * ____ _ _____ * + * / ___| / \ | ___| C++ * + * | | / _ \ | |_ Actor * + * | |___ / ___ \| _| Framework * + * \____/_/ \_|_| * + * * + * Copyright (C) 2011 - 2016 * + * Dominik Charousset * + * * + * Distributed under the terms and conditions of the BSD 3-Clause License or * + * (at your option) under the terms and conditions of the Boost Software * + * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. * + * * + * If you did not receive a copy of the license files, see * + * http://opensource.org/licenses/BSD-3-Clause and * + * http://www.boost.org/LICENSE_1_0.txt. * + ******************************************************************************/ + +#include + +#include "caf/duration.hpp" + +#include "caf/detail/enum_to_string.hpp" + +namespace caf { + +namespace { + +const char* time_unit_strings[] = { + "invalid", + "minutes", + "seconds", + "milliseconds", + "microseconds", + "nanoseconds" +}; + +const char* time_unit_short_strings[] = { + "?", + "min", + "s", + "ms", + "us", + "ns" +}; + +} // namespace + +std::string to_string(time_unit x) { + return detail::enum_to_string(x, time_unit_strings); +} + +std::string to_string(const duration& x) { + if (x.unit == time_unit::invalid) + return "infinite"; + auto result = std::to_string(x.count); + result += detail::enum_to_string(x.unit, time_unit_short_strings); + return result; +} + +bool operator==(const duration& lhs, const duration& rhs) { + return lhs.unit == rhs.unit && lhs.count == rhs.count; +} + +} // namespace caf diff --git a/pool/shard006/C++/0084425_HybridRSMAmbientOcclusionRenderPass.cpp b/pool/shard006/C++/0084425_HybridRSMAmbientOcclusionRenderPass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01796d4dec4b0b22c68851499365e1368c4b494e --- /dev/null +++ b/pool/shard006/C++/0084425_HybridRSMAmbientOcclusionRenderPass.cpp @@ -0,0 +1,183 @@ +#include "HybridRSMAmbientOcclusionRenderPass.h" + +#include "Resources/Resources.h" +#include "Renderer/RenderSystem.h" + +#include "Renderer/Pipeline.h" + +#include "RenderPasses/GBuffer.h" + +#include "Debug/Statistics/StatisticsManager.h" +#include "HGIStatisticsObject.h" + +#include "Utils/Extensions/MathExtend.h" + +void HybridRSMAmbientOcclusionRenderPass::Init (const RenderSettings& settings) +{ + /* + * Shader for not animated objects + */ + + Resource shader = Resources::LoadShader ({ + "Assets/Shaders/PostProcess/postProcessVertex.glsl", + "Assets/Shaders/HybridGlobalIllumination/hybridRSMAmbientOcclusionFragment.glsl" + }); + + _shaderView = RenderSystem::LoadShader (shader); +} + +void HybridRSMAmbientOcclusionRenderPass::Clear () +{ + /* + * Nothing + */ +} + +bool HybridRSMAmbientOcclusionRenderPass::IsAvailable (const RenderScene* renderScene, const Camera* camera, + const RenderSettings& settings, const RenderVolumeCollection* rvc) const +{ + return settings.hgi_ao_enabled && VolumetricLightRenderPassI::IsAvailable (renderScene, camera, settings, rvc); +} + +bool HybridRSMAmbientOcclusionRenderPass::IsAvailable (const RenderLightObject*) const +{ + return true; +} + +RenderVolumeCollection* HybridRSMAmbientOcclusionRenderPass::Execute (const RenderScene* renderScene, const Camera* camera, + const RenderSettings& settings, RenderVolumeCollection* rvc) +{ + /* + * Get volumetric light from render volume collection + */ + + RenderLightObject* renderLightObject = GetRenderLightObject (rvc); + + /* + * Bind framebuffer for writing + */ + + auto resultVolume = (FramebufferRenderVolume*) rvc->GetRenderVolume ("ambientOcclusionMap"); + + resultVolume->GetFramebufferView ()->Activate (); + + /* + * Update statistics object + */ + + auto hgiStatisticsObject = StatisticsManager::Instance ()->GetStatisticsObject (); + + hgiStatisticsObject->hgiRSMAmbientOcclusionMapVolume = resultVolume; + + /* + * Lock post-process shader + */ + + Pipeline::LockShader (_shaderView); + + /* + * Update matrices + */ + + Pipeline::CreateProjection (((GBuffer*) rvc->GetRenderVolume ("GBuffer"))->GetProjectionMatrix ()); + Pipeline::SendCamera (camera); + Pipeline::SetObjectTransform (Transform::Default ()); + + Pipeline::UpdateMatrices (nullptr); + + /* + * Set viewport + */ + + GL::Viewport (settings.viewport.x, settings.viewport.y, + settings.viewport.width, settings.viewport.height); + + /* + * Enable color blending + */ + + GL::Enable (GL_BLEND); + GL::BlendFunc (GL_ONE, GL_ONE); + + /* + * Disable depth test + */ + + GL::Disable (GL_DEPTH_TEST); + + /* + * Disable face culling + */ + + GL::Disable (GL_CULL_FACE); + + /* + * Send custom uniforms + */ + + Pipeline::SendCustomAttributes (nullptr, rvc->GetRenderVolume ("GBuffer")->GetCustomAttributes ()); + Pipeline::SendCustomAttributes (nullptr, rvc->GetRenderVolume ("ReflectiveShadowMapVolume")->GetCustomAttributes ()); + Pipeline::SendCustomAttributes (nullptr, rvc->GetRenderVolume ("NoiseMapVolume")->GetCustomAttributes ()); + Pipeline::SendCustomAttributes (nullptr, rvc->GetRenderVolume ("SSAOSamplesVolume")->GetCustomAttributes ()); + Pipeline::SendCustomAttributes (nullptr, GetCustomAttributes (camera, settings, renderLightObject)); + + /* + * Draw a screen covering triangle + */ + + GL::DrawArrays (GL_TRIANGLES, 0, 3); + + /* + * Unlock current shader + */ + + Pipeline::UnlockShader (); + + return rvc; +} + +std::vector HybridRSMAmbientOcclusionRenderPass::GetCustomAttributes (const Camera* camera, + const RenderSettings& settings, const RenderLightObject* renderLightObject) const +{ + /* + * Attach screen space ambient occlusion attributes to pipeline + */ + + std::vector attributes; + + PipelineAttribute ssaoRadius; + PipelineAttribute ssaoBias; + PipelineAttribute hgiAOBlend; + PipelineAttribute lightDirection; + PipelineAttribute temporalFilterEnabled; + + ssaoRadius.type = PipelineAttribute::AttrType::ATTR_1F; + ssaoBias.type = PipelineAttribute::AttrType::ATTR_1F; + hgiAOBlend.type = PipelineAttribute::AttrType::ATTR_1F; + lightDirection.type = PipelineAttribute::AttrType::ATTR_3F; + temporalFilterEnabled.type = PipelineAttribute::AttrType::ATTR_1I; + + ssaoRadius.name = "ssaoRadius"; + ssaoBias.name = "ssaoBias"; + hgiAOBlend.name = "hgiAOBlend"; + lightDirection.name = "lightDirection"; + temporalFilterEnabled.name = "temporalFilterEnabled"; + + glm::vec3 lightDir = renderLightObject->GetTransform ()->GetRotation () * glm::vec3 (0, 0, -1); + glm::mat3 viewMatrix = glm::mat3_cast (camera->GetRotation ()); + lightDir = glm::normalize (viewMatrix * lightDir); + + ssaoRadius.value.x = settings.hgi_ao_radius; + ssaoBias.value.x = settings.hgi_ao_bias; + hgiAOBlend.value.x = settings.hgi_ao_blend; + lightDirection.value = lightDir; + temporalFilterEnabled.value.x = settings.hgi_temporal_filter_enabled; + + attributes.push_back (ssaoRadius); + attributes.push_back (ssaoBias); + attributes.push_back (hgiAOBlend); + attributes.push_back (lightDirection); + attributes.push_back (temporalFilterEnabled); + + return attributes; +} diff --git a/pool/shard006/C++/0084431_svm_test.cpp b/pool/shard006/C++/0084431_svm_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61b1b215cd4c653efa51f3263b7f052740232e72 --- /dev/null +++ b/pool/shard006/C++/0084431_svm_test.cpp @@ -0,0 +1,63 @@ +/* +Author: Andrej Karpathy (http://cs.stanford.edu/~karpathy/) +1 May 2012 +BSD licence +*/ + +#include +#include +#include + +#include +#include +#include + +using namespace std; +using namespace esvm; + +// run from build folder of the project (see path below) +int main (int argc, char** argv) { + + Eigen::MatrixXf X; + Eigen::MatrixXf y; + eigen_extensions::loadASCII("../test/svmtestx.eig.txt", &X); + eigen_extensions::loadASCII("../test/svmtesty.eig.txt", &y); + + // Classify + cout << X.topRows(5) << endl; + cout << y.topRows(5) << endl; + vector yhat; + SVMClassifier svm; + svm.train(X, y); + svm.test(X, yhat); + + Eigen::MatrixXf w; + float b; + svm.getw(w, b); + Eigen::MatrixXf margin= ((X * w).array() + b).matrix(); // ahh eigen... + + // Evaluate accuracy and print results + int match=0; + for(int i=0;i +#include +#include +#include + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace CloudHSM + { + namespace Model + { + namespace HsmStatusMapper + { + + static const int PENDING_HASH = HashingUtils::HashString("PENDING"); + static const int RUNNING_HASH = HashingUtils::HashString("RUNNING"); + static const int UPDATING_HASH = HashingUtils::HashString("UPDATING"); + static const int SUSPENDED_HASH = HashingUtils::HashString("SUSPENDED"); + static const int TERMINATING_HASH = HashingUtils::HashString("TERMINATING"); + static const int TERMINATED_HASH = HashingUtils::HashString("TERMINATED"); + static const int DEGRADED_HASH = HashingUtils::HashString("DEGRADED"); + + + HsmStatus GetHsmStatusForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == PENDING_HASH) + { + return HsmStatus::PENDING; + } + else if (hashCode == RUNNING_HASH) + { + return HsmStatus::RUNNING; + } + else if (hashCode == UPDATING_HASH) + { + return HsmStatus::UPDATING; + } + else if (hashCode == SUSPENDED_HASH) + { + return HsmStatus::SUSPENDED; + } + else if (hashCode == TERMINATING_HASH) + { + return HsmStatus::TERMINATING; + } + else if (hashCode == TERMINATED_HASH) + { + return HsmStatus::TERMINATED; + } + else if (hashCode == DEGRADED_HASH) + { + return HsmStatus::DEGRADED; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast(hashCode); + } + + return HsmStatus::NOT_SET; + } + + Aws::String GetNameForHsmStatus(HsmStatus enumValue) + { + switch(enumValue) + { + case HsmStatus::PENDING: + return "PENDING"; + case HsmStatus::RUNNING: + return "RUNNING"; + case HsmStatus::UPDATING: + return "UPDATING"; + case HsmStatus::SUSPENDED: + return "SUSPENDED"; + case HsmStatus::TERMINATING: + return "TERMINATING"; + case HsmStatus::TERMINATED: + return "TERMINATED"; + case HsmStatus::DEGRADED: + return "DEGRADED"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast(enumValue)); + } + + return ""; + } + } + + } // namespace HsmStatusMapper + } // namespace Model + } // namespace CloudHSM +} // namespace Aws diff --git a/pool/shard006/C++/0084447_pair_ufm_omp.cpp b/pool/shard006/C++/0084447_pair_ufm_omp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2140de5546c479916122fcd5ad94b2d821524269 --- /dev/null +++ b/pool/shard006/C++/0084447_pair_ufm_omp.cpp @@ -0,0 +1,160 @@ +// clang-format off +/* ---------------------------------------------------------------------- + LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator + https://www.lammps.org/, Sandia National Laboratories + Steve Plimpton, sjplimp@sandia.gov + + This software is distributed under the GNU General Public License. + + See the README file in the top-level LAMMPS directory. +------------------------------------------------------------------------- */ + +/* ---------------------------------------------------------------------- + Contributing author: + Rodolfo Paula Leite (Unicamp/Brazil) - pl.rodolfo@gmail.com + Maurice de Koning (Unicamp/Brazil) - dekoning@ifi.unicamp.br + ------------------------------------------------------------------------- */ + +#include "pair_ufm_omp.h" + +#include "atom.h" +#include "comm.h" +#include "force.h" +#include "neigh_list.h" +#include "suffix.h" + +#include + +#include "omp_compat.h" +using namespace LAMMPS_NS; + +/* ---------------------------------------------------------------------- */ + +PairUFMOMP::PairUFMOMP(LAMMPS *lmp) : + PairUFM(lmp), ThrOMP(lmp, THR_PAIR) +{ + suffix_flag |= Suffix::OMP; + respa_enable = 0; +} + +/* ---------------------------------------------------------------------- */ + +void PairUFMOMP::compute(int eflag, int vflag) +{ + ev_init(eflag,vflag); + + const int nall = atom->nlocal + atom->nghost; + const int nthreads = comm->nthreads; + const int inum = list->inum; + +#if defined(_OPENMP) +#pragma omp parallel LMP_DEFAULT_NONE LMP_SHARED(eflag,vflag) +#endif + { + int ifrom, ito, tid; + + loop_setup_thr(ifrom, ito, tid, inum, nthreads); + ThrData *thr = fix->get_thr(tid); + thr->timer(Timer::START); + ev_setup_thr(eflag, vflag, nall, eatom, vatom, nullptr, thr); + + if (evflag) { + if (eflag) { + if (force->newton_pair) eval<1,1,1>(ifrom, ito, thr); + else eval<1,1,0>(ifrom, ito, thr); + } else { + if (force->newton_pair) eval<1,0,1>(ifrom, ito, thr); + else eval<1,0,0>(ifrom, ito, thr); + } + } else { + if (force->newton_pair) eval<0,0,1>(ifrom, ito, thr); + else eval<0,0,0>(ifrom, ito, thr); + } + + thr->timer(Timer::PAIR); + reduce_thr(this, eflag, vflag, thr); + } // end of omp parallel region +} + +template +void PairUFMOMP::eval(int iifrom, int iito, ThrData * const thr) +{ + int i,j,ii,jj,jnum,itype,jtype; + double xtmp,ytmp,ztmp,delx,dely,delz,evdwl,fpair; + double rsq,expuf,factor; + int *ilist,*jlist,*numneigh,**firstneigh; + + evdwl = 0.0; + + const dbl3_t * _noalias const x = (dbl3_t *) atom->x[0]; + dbl3_t * _noalias const f = (dbl3_t *) thr->get_f()[0]; + const int * _noalias const type = atom->type; + const int nlocal = atom->nlocal; + const double * _noalias const special_lj = force->special_lj; + double fxtmp,fytmp,fztmp; + + ilist = list->ilist; + numneigh = list->numneigh; + firstneigh = list->firstneigh; + + // loop over neighbors of my atoms + + for (ii = iifrom; ii < iito; ++ii) { + + i = ilist[ii]; + xtmp = x[i].x; + ytmp = x[i].y; + ztmp = x[i].z; + itype = type[i]; + jlist = firstneigh[i]; + jnum = numneigh[i]; + fxtmp=fytmp=fztmp=0.0; + + for (jj = 0; jj < jnum; jj++) { + j = jlist[jj]; + factor = special_lj[sbmask(j)]; + j &= NEIGHMASK; + + delx = xtmp - x[j].x; + dely = ytmp - x[j].y; + delz = ztmp - x[j].z; + rsq = delx*delx + dely*dely + delz*delz; + jtype = type[j]; + + if (rsq < cutsq[itype][jtype]) { + expuf = exp(- rsq * uf2[itype][jtype]); + fpair = factor * scale[itype][jtype] * uf1[itype][jtype] * expuf /(1.0 - expuf); + + fxtmp += delx*fpair; + fytmp += dely*fpair; + fztmp += delz*fpair; + if (NEWTON_PAIR || j < nlocal) { + f[j].x -= delx*fpair; + f[j].y -= dely*fpair; + f[j].z -= delz*fpair; + } + + if (EFLAG) { + evdwl = -uf3[itype][jtype] * log(1.0 - expuf) - offset[itype][jtype]; + evdwl *= factor; + } + + if (EVFLAG) ev_tally_thr(this,i,j,nlocal,NEWTON_PAIR, + evdwl,0.0,fpair,delx,dely,delz,thr); + } + } + f[i].x += fxtmp; + f[i].y += fytmp; + f[i].z += fztmp; + } +} + +/* ---------------------------------------------------------------------- */ + +double PairUFMOMP::memory_usage() +{ + double bytes = memory_usage_thr(); + bytes += PairUFM::memory_usage(); + + return bytes; +} diff --git a/pool/shard006/C++/0084455_Timer.cpp b/pool/shard006/C++/0084455_Timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c159fc2de6d5495dfdeb125f9517272dbcfc7d4 --- /dev/null +++ b/pool/shard006/C++/0084455_Timer.cpp @@ -0,0 +1,52 @@ +/* + * Timer.cpp + * + * Created on: Feb 8, 2009 + * Author: kupcu + */ +#include "Timer.h" + +#ifdef TIMER +#include "CashException.h" +#include +#include + +vector brownieTimerValue; +void startTimer() { + timeval t; + gettimeofday(&t, NULL); + brownieTimerValue.push_back(t); +} + +/* Determine the difference, in milliseconds, between two struct timevals. */ +#define TV_DIFF_MS(a, b) \ + (((b).tv_sec - (a).tv_sec) * 1000 + ((b).tv_usec - (a).tv_usec) / 1000) +/* Determine the difference, in microseconds, between two struct timevals. */ +#define TV_DIFF_US(a, b) \ + (((b).tv_sec - (a).tv_sec) * 1000000 + ((b).tv_usec - (a).tv_usec)) + +double printTimer(const string &msg) { + long long elapsed = elapsedTime(); + cout << msg << " [" << elapsed/1000.0 << " ms]" << endl; + return elapsed/1000.0; +} + +double printTimer(const int index, const string &msg) { + long long elapsed = elapsedTime(); + cout << index << ":" << msg << " [" << elapsed/1000.0 << " ms]" << endl; + return elapsed/1000.0; +} + +long long elapsedTime() { + timeval now; + gettimeofday(&now, NULL); + if (brownieTimerValue.size() == 0) + throw CashException(CashException::CE_TIMER_ERROR, + "[Timer::printTimer] No running timer found. " + "Maybe you forgot to start one?"); + long long elapsed = TV_DIFF_US(brownieTimerValue.back(), now); + brownieTimerValue.pop_back(); + return elapsed; +} + +#endif diff --git a/pool/shard006/C++/0084456_phase_chain.cpp b/pool/shard006/C++/0084456_phase_chain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..258c2f21d1e8a1d80f27f37a566ddf3cfde07e9e --- /dev/null +++ b/pool/shard006/C++/0084456_phase_chain.cpp @@ -0,0 +1,120 @@ +/* + * phase_chain.cpp + * + * Example of MPI parallelization with odeint + * + * Copyright 2013 Karsten Ahnert + * Copyright 2013 Mario Mulansky + * Copyright 2013 Pascal Germroth + * Distributed under the Boost Software License, Version 1.0. (See + * accompanying file LICENSE_1_0.txt or copy at + * http://www.boost.org/LICENSE_1_0.txt) + */ + +#include +#include +#include +#include +//[phase_chain_mpi_header +#include +#include +//] + +using namespace std; +using namespace boost::numeric::odeint; +using boost::timer::cpu_timer; +using boost::math::double_constants::pi; + +//[phase_chain_state +typedef mpi_state< vector > state_type; +//] + +//[phase_chain_mpi_rhs +struct phase_chain_mpi_state +{ + phase_chain_mpi_state( double gamma = 0.5 ) + : m_gamma( gamma ) { } + + void operator()( const state_type &x , state_type &dxdt , double /* t */ ) const + { + const size_t M = x().size(); + const bool have_left = x.world.rank() > 0, + have_right = x.world.rank() < x.world.size()-1; + double x_left, x_right; + boost::mpi::request r_left, r_right; + if( have_left ) + { + x.world.isend( x.world.rank()-1 , 0 , x().front() ); // send to x_right + r_left = x.world.irecv( x.world.rank()-1 , 0 , x_left ); // receive from x().back() + } + if( have_right ) + { + x.world.isend( x.world.rank()+1 , 0 , x().back() ); // send to x_left + r_right = x.world.irecv( x.world.rank()+1 , 0 , x_right ); // receive from x().front() + } + for(size_t m = 1 ; m < M-1 ; ++m) + { + dxdt()[m] = coupling_func( x()[m+1] - x()[m] ) + + coupling_func( x()[m-1] - x()[m] ); + } + dxdt()[0] = coupling_func( x()[1] - x()[0] ); + if( have_left ) + { + r_left.wait(); + dxdt()[0] += coupling_func( x_left - x().front() ); + } + dxdt()[M-1] = coupling_func( x()[M-2] - x()[M-1] ); + if( have_right ) + { + r_right.wait(); + dxdt()[M-1] += coupling_func( x_right - x().back() ); + } + } + + double coupling_func( double x ) const + { + return sin( x ) - m_gamma * ( 1.0 - cos( x ) ); + } + + double m_gamma; +}; +//] + + +int main( int argc , char **argv ) +{ + //[phase_chain_mpi_init + boost::mpi::environment env( argc , argv ); + boost::mpi::communicator world; + + const size_t N = 131101; + vector x; + if( world.rank() == 0 ) + { + x.resize( N ); + boost::random::uniform_real_distribution distribution( 0.0 , 2.0*pi ); + boost::random::mt19937 engine( 0 ); + generate( x.begin() , x.end() , boost::bind( distribution , engine ) ); + } + + state_type x_split( world ); + split( x , x_split ); + //] + + + cpu_timer timer; + //[phase_chain_mpi_integrate + integrate_n_steps( runge_kutta4() , phase_chain_mpi_state( 1.2 ) , + x_split , 0.0 , 0.01 , 100 ); + unsplit( x_split , x ); + //] + + if( world.rank() == 0 ) + { + double run_time = static_cast(timer.elapsed().wall) * 1.0e-9; + std::cerr << run_time << "s" << std::endl; + // copy(x.begin(), x.end(), ostream_iterator(cout, "\n")); + } + + return 0; +} diff --git a/pool/shard006/C++/0084460_SubchannelMask.cpp b/pool/shard006/C++/0084460_SubchannelMask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46c4877969cdda1f57a4d5d56c50f05ee9403be5 --- /dev/null +++ b/pool/shard006/C++/0084460_SubchannelMask.cpp @@ -0,0 +1,263 @@ +/******************************************************************************* + + File: SubchannelMask.cpp + Project: OpenSonATA + Authors: The OpenSonATA code is the result of many programmers + over many years + + Copyright 2011 The SETI Institute + + OpenSonATA is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + OpenSonATA 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 OpenSonATA. If not, see. + + Implementers of this code are requested to include the caption + "Licensed through SETI" with a link to setiQuest.org. + + For alternate licensing arrangements, please contact + The SETI Institute at www.seti.org or setiquest.org. + +*******************************************************************************/ + +// +// Subchannel mask class +// +// $Header: /home/cvs/nss/sonata-pkg/dx/lib/SubchannelMask.cpp,v 1.5 2009/05/24 23:44:26 kes Exp $ +// +#include +#include +#include "System.h" +#include "Activity.h" +#include "Err.h" +#include "State.h" +#include "SubchannelMask.h" + +namespace dx { + +SubchannelMask::SubchannelMask(SubchannelMaskBitset *mask_): + subchannels(0), subchannelBandwidth(0) +{ + if (mask_) + mask = *mask_; + else + mask.reset(); +} + +SubchannelMask::~SubchannelMask() +{ +} + +// +// createSubchannelMask: create the DSP subchannel mask +// +// Synopsis: +// void createSubchannelMask(subchannels_, birdieMask_, permRfiMask_, +// testSignalMask_); +// int32_t subchannels_; # of subchannels in use +// DxBirdieMask *birdieMask_; birdie mask +// DxPermRfIMask *permRfiMask_; permanent RFI mask +// DxTestSignalMask *testSignalMask_; test signal mask +// Notes: +// The active set of subchannels is specified by subchannels_; +// all DX subchannels which lie outside this range are +// masked. +// Masking is performed by setting the bit representing +// that subchannel to 1. +// The birdie mask is an IF mask, which means it is independent +// of RF frequency. +// The permanent RFI mask is an RF mask which requires that +// the center frequency be known. +// The test signal mask works in reverse: it resets any +// subchannel specified. +void +SubchannelMask::createSubchannelMask(Activity *act) +{ + Assert(act); + subchannels = act->getUsableSubchannels(); + subchannelBandwidth = act->getSubchannelWidthMHz(); + + Debug(DEBUG_SUBCHANNEL, act->getActivityId(), "actId"); + Debug(DEBUG_SUBCHANNEL, act->getSkyFreq(), "dxSkyFreq"); + Debug(DEBUG_SUBCHANNEL, act->getIfcSkyFreq(), "ifcSkyFreq"); + Debug(DEBUG_SUBCHANNEL, act->getRcvrSkyFreq(), "rcvrSkyFreq"); + float64_t dxSkyFreq = act->getSkyFreq(); + float64_t dxIfcFreq = dxSkyFreq - act->getIfcSkyFreq(); + float64_t dxRcvrFreq = dxSkyFreq - act->getRcvrSkyFreq(); + BirdieMask *birdieMask = act->getBirdieMask(); + BirdieMask *rcvrBirdieMask = act->getRcvrBirdieMask(); + PermRfiMask *permRfiMask = act->getPermRfiMask(); + TestSignalMask *testSignalMask = act->getTestSignalMask(); + uint32_t ops = act->getOperationsMask(); + Debug(DEBUG_SUBCHANNEL, (int32_t) ops, "operations"); + Debug(DEBUG_BIRDIE_MASK, act->getRcvrSkyFreq(), + "...act->getRcvrSkyFrequency()"); + DxOpsBitset operations(ops); + ops = operations.to_ulong(); + Debug(DEBUG_SUBCHANNEL, (int32_t) ops, "operations"); + + mask.reset(); + + Debug(DEBUG_SUBCHANNEL, 0, "birdieMask"); + if (operations.test(APPLY_BIRDIE_MASK)) + applyBirdieMask(birdieMask, dxIfcFreq); + Debug(DEBUG_SUBCHANNEL, 0, "rcvrBirdieMask"); + if (operations.test(APPLY_RCVR_BIRDIE_MASK)) + applyBirdieMask(rcvrBirdieMask, dxRcvrFreq); + Debug(DEBUG_SUBCHANNEL, 1, "permRfiMask"); + if (operations.test(APPLY_PERMANENT_RFI_MASK)) + applyPermRfiMask(permRfiMask, dxSkyFreq); + Debug(DEBUG_SUBCHANNEL, 2, "testSignalMask"); + if (operations.test(APPLY_TEST_SIGNAL_MASK)) + applyTestSignalMask(testSignalMask, dxSkyFreq); +} + +/** + * Return the subchannel mask. + */ +void +SubchannelMask::getSubchannelMask(SubchannelMaskBitset *mask_) +{ + Assert(mask_); + *mask_ = mask; +} + +/** + * Test whether the specified subchannel is masked. + */ +bool +SubchannelMask::isSubchannelMasked(int32_t subchannel) +{ + return (mask.test(subchannel)); +} + +// +// applyBirdieMask: apply the specified birdie mask to the subchannel mask +// +// Synopsis: +// void applyBirdieMask(birdieMask, dxIfcFreq); +// DxBirdieMask *birdieMask; active birdie mask +// float64_t dxIfcFreq; DX center freq relative to IFC ctr freq +// Notes: +// The birdie mask comes in two versions: an IF mask which is +// independent of the RF center frequency, and an RF mask which +// is used to mask birdies in the RF (receiver). +// Since the IF bandwidth is greater than the DX bandwidth, +// these values must be adjusted for the DX's center frequency +// relative to the IFC center frequency. +// +void +SubchannelMask::applyBirdieMask(BirdieMask *birdieMask, + float64_t dxIfcFreq) +{ + if (!birdieMask) + return; + Debug(DEBUG_BIRDIE_MASK, dxIfcFreq, "dx ctr freq ofs"); + for (const FrequencyBand *band = birdieMask->getFirst(); band; + band = birdieMask->getNext()) { + FrequencyBand freqBand = *band; + Debug(DEBUG_BIRDIE_MASK, freqBand.centerFreq, "ifc ctr freq"); + freqBand.centerFreq -= dxIfcFreq; + Debug(DEBUG_BIRDIE_MASK, freqBand.centerFreq, "dx ifc freq"); + int32_t first, last; + computeSubchannelRange(freqBand, first, last); + Debug(DEBUG_BIRDIE_MASK, first, "first subchannel"); + Debug(DEBUG_BIRDIE_MASK, last, "last subchannel"); + for (int32_t i = first; i <= last; ++i) + mask.set(i); + } +} + +void +SubchannelMask::applyPermRfiMask(PermRfiMask *permRfiMask, + float64_t centerFreq) +{ + if (!permRfiMask) + return; + for (FrequencyBand *band = permRfiMask->getFirst(); band; + band = permRfiMask->getNext()) { + FrequencyBand freqBand = *band; + Debug(DEBUG_SUBCHANNEL, centerFreq, "rf center freq"); + Debug(DEBUG_SUBCHANNEL, freqBand.centerFreq, "mask center freq"); + freqBand.centerFreq -= centerFreq; + int32_t first, last; + computeSubchannelRange(freqBand, first, last); + Debug(DEBUG_SUBCHANNEL, first, "first subchannel"); + Debug(DEBUG_SUBCHANNEL, last, "last subchannel"); + for (int32_t i = first; i <= last; ++i) + mask.set(i); + } +} + +void +SubchannelMask::applyTestSignalMask(TestSignalMask *testSignalMask, + float64_t centerFreq) +{ + if (!testSignalMask) + return; + for (FrequencyBand *band = testSignalMask->getFirst(); band; + band = testSignalMask->getNext()) { + FrequencyBand freqBand = *band; + freqBand.centerFreq -= centerFreq; + int32_t first, last; + computeSubchannelRange(freqBand, first, last); + for (int32_t i = first; i <= last; ++i) + mask.reset(i); + } +} + +// +// computeSubchannelRange: compute the set of subchannels covered by a +// frequency band +// +// Notes: +// Computes the entire set of subchannels covered by a +// frequency band. +// +void +SubchannelMask::computeSubchannelRange(FrequencyBand& band, + int32_t& first, int32_t& last) +{ + float64_t loFreq = band.centerFreq - band.bandwidth / 2; + float64_t hiFreq = band.centerFreq + band.bandwidth / 2; + + first = computeSubchannel(loFreq); + if (first < 0) + first = 0; + last = computeSubchannel(hiFreq); + if (last >= subchannels) + last = subchannels - 1; +} + +/** + * Compute the subchannel corresponding to the specified frequency. + * + * Description:\n + * Given an IF frequency relative to the DX center frequency, compute + * the subchannel in which the frequency lies.\n\n + * + * Notes:\n + * Since DC lies in the center of subchannel n/2, we have to adjust + * the frequency by half a subchannel to get the correct value. + */ +int32_t +SubchannelMask::computeSubchannel(float64_t freq_) +{ + Debug(DEBUG_SUBCHANNEL, freq_, "freq"); + freq_ += (freq_ < 0 ? -subchannelBandwidth / 2 : subchannelBandwidth / 2); + int32_t subchannel = (int32_t) (freq_ / subchannelBandwidth); + subchannel += subchannels / 2; + Debug(DEBUG_SUBCHANNEL, freq_, "freq"); + Debug(DEBUG_SUBCHANNEL, subchannel, "subchannel"); + return (subchannel); +} + +} diff --git a/pool/shard006/C++/0084476_pow.cpp b/pool/shard006/C++/0084476_pow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53726ca89323ebe6d8cdbf3c1c1ecc08e3a82bfb --- /dev/null +++ b/pool/shard006/C++/0084476_pow.cpp @@ -0,0 +1,84 @@ +// Copyright (c) 2020-2021 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +void initialize_pow() +{ + SelectParams(CBaseChainParams::MAIN); +} + +FUZZ_TARGET_INIT(pow, initialize_pow) +{ + FuzzedDataProvider fuzzed_data_provider(buffer.data(), buffer.size()); + const Consensus::Params& consensus_params = Params().GetConsensus(); + std::vector blocks; + const uint32_t fixed_time = fuzzed_data_provider.ConsumeIntegral(); + const uint32_t fixed_bits = fuzzed_data_provider.ConsumeIntegral(); + while (fuzzed_data_provider.remaining_bytes() > 0) { + const std::optional block_header = ConsumeDeserializable(fuzzed_data_provider); + if (!block_header) { + continue; + } + CBlockIndex current_block{*block_header}; + { + CBlockIndex* previous_block = !blocks.empty() ? &blocks[fuzzed_data_provider.ConsumeIntegralInRange(0, blocks.size() - 1)] : nullptr; + const int current_height = (previous_block != nullptr && previous_block->nHeight != std::numeric_limits::max()) ? previous_block->nHeight + 1 : 0; + if (fuzzed_data_provider.ConsumeBool()) { + current_block.pprev = previous_block; + } + if (fuzzed_data_provider.ConsumeBool()) { + current_block.nHeight = current_height; + } + if (fuzzed_data_provider.ConsumeBool()) { + const uint32_t seconds = current_height * consensus_params.nPowTargetSpacing; + if (!AdditionOverflow(fixed_time, seconds)) { + current_block.nTime = fixed_time + seconds; + } + } + if (fuzzed_data_provider.ConsumeBool()) { + current_block.nBits = fixed_bits; + } + if (fuzzed_data_provider.ConsumeBool()) { + current_block.nChainWork = previous_block != nullptr ? previous_block->nChainWork + GetBlockProof(*previous_block) : arith_uint256{0}; + } else { + current_block.nChainWork = ConsumeArithUInt256(fuzzed_data_provider); + } + blocks.push_back(current_block); + } + { + (void)GetBlockProof(current_block); + (void)CalculateNextWorkRequired(¤t_block, fuzzed_data_provider.ConsumeIntegralInRange(0, std::numeric_limits::max()), consensus_params); + if (current_block.nHeight != std::numeric_limits::max() && current_block.nHeight - (consensus_params.DifficultyAdjustmentInterval() - 1) >= 0) { + (void)GetNextWorkRequired(¤t_block, &(*block_header), consensus_params); + } + } + { + const CBlockIndex* to = &blocks[fuzzed_data_provider.ConsumeIntegralInRange(0, blocks.size() - 1)]; + const CBlockIndex* from = &blocks[fuzzed_data_provider.ConsumeIntegralInRange(0, blocks.size() - 1)]; + const CBlockIndex* tip = &blocks[fuzzed_data_provider.ConsumeIntegralInRange(0, blocks.size() - 1)]; + try { + (void)GetBlockProofEquivalentTime(*to, *from, *tip, consensus_params); + } catch (const uint_error&) { + } + } + { + const std::optional hash = ConsumeDeserializable(fuzzed_data_provider); + if (hash) { + (void)CheckProofOfWork(*hash, fuzzed_data_provider.ConsumeIntegral(), consensus_params); + } + } + } +} diff --git a/pool/shard006/C++/0084477_wait_for.cc b/pool/shard006/C++/0084477_wait_for.cc new file mode 100644 index 0000000000000000000000000000000000000000..63ec9b356d013fdf292648ae8889a65fc774867b --- /dev/null +++ b/pool/shard006/C++/0084477_wait_for.cc @@ -0,0 +1,53 @@ +// { dg-do run { target *-*-freebsd* *-*-dragonfly* *-*-netbsd* *-*-linux* *-*-gnu* *-*-solaris* *-*-cygwin *-*-darwin* powerpc-ibm-aix* } } +// { dg-options " -std=gnu++0x -pthread" { target *-*-freebsd* *-*-dragonfly* *-*-netbsd* *-*-linux* *-*-gnu* powerpc-ibm-aix* } } +// { dg-options " -std=gnu++0x -pthreads" { target *-*-solaris* } } +// { dg-options " -std=gnu++0x " { target *-*-cygwin *-*-darwin* } } +// { dg-require-cstdint "" } +// { dg-require-gthreads "" } +// { dg-require-atomic-builtins "" } + +// Copyright (C) 2009-2014 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library 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 library; see the file COPYING3. If not see +// . + + +#include +#include +#include + +void test01() +{ + bool test __attribute__((unused)) = true; + + std::promise p1; + std::future f1(p1.get_future()); + + std::chrono::milliseconds delay(100); + + VERIFY( f1.wait_for(delay) == std::future_status::timeout ); + + p1.set_value(1); + + auto before = std::chrono::system_clock::now(); + VERIFY( f1.wait_for(delay) == std::future_status::ready ); + VERIFY( std::chrono::system_clock::now() < (before + delay) ); +} + +int main() +{ + test01(); + return 0; +} diff --git a/pool/shard006/C++/0084486_loop.cpp b/pool/shard006/C++/0084486_loop.cpp new file mode 100644 index 0000000000000000000000000000000000000000..52c846d618314b7acdb53ad7443730264ae84903 --- /dev/null +++ b/pool/shard006/C++/0084486_loop.cpp @@ -0,0 +1,79 @@ +//===----------------------------------------------------------------------===// +// +// Peloton +// +// loop.cpp +// +// Identification: src/codegen/loop.cpp +// +// Copyright (c) 2015-17, Carnegie Mellon University Database Group +// +//===----------------------------------------------------------------------===// + +#include "codegen/loop.h" + +namespace peloton { +namespace codegen { + +// Constructor +Loop::Loop(CodeGen &cg, llvm::Value *start_condition, + const std::vector &loop_vars) + : cg_(cg), + fn_(cg_->GetInsertBlock()->getParent()), + pre_loop_bb_(cg_->GetInsertBlock()), + last_loop_bb_(nullptr) { + // Create the loop block and the end block (outside loop) + loop_bb_ = llvm::BasicBlock::Create(cg_.GetContext(), "loop", fn_); + end_bb_ = llvm::BasicBlock::Create(cg_.GetContext(), "afterLoop"); + + // Start loop only if condition is met + cg_->CreateCondBr(start_condition, loop_bb_, end_bb_); + cg_->SetInsertPoint(loop_bb_); + + // Create phi nodes for each loop variable + for (auto &loop_var : loop_vars) { + auto *phi_node = cg_->CreatePHI(loop_var.val->getType(), 2, loop_var.name); + phi_node->addIncoming(loop_var.val, pre_loop_bb_); + phi_nodes_.push_back(phi_node); + } +} + +llvm::Value *Loop::GetLoopVar(uint32_t id) const { + // Get a specific loop variable + return id < phi_nodes_.size() ? phi_nodes_[id] : nullptr; +} + +// Function to mark the end of the loop. It ties up all the PHI nodes with +// their new values. +void Loop::LoopEnd(llvm::Value *end_condition, + const std::vector &next) { + // We have the ending BB, use that to add incoming to each PHI loop + // variable + auto *loop_end_bb = cg_->GetInsertBlock(); + last_loop_bb_ = loop_end_bb; + cg_->CreateCondBr(end_condition, loop_bb_, end_bb_); + + for (uint32_t i = 0; i < phi_nodes_.size(); i++) { + phi_nodes_[i]->addIncoming(next[i], loop_end_bb); + } + + // Loop is complete, all new instructions go to the end BB + fn_->getBasicBlockList().push_back(end_bb_); + cg_->SetInsertPoint(end_bb_); +} + +// Collect all the final values of the loop variables after the loop is +// complete +void Loop::CollectFinalLoopVariables(std::vector &loop_vals) { + PL_ASSERT(last_loop_bb_ != nullptr); + for (const auto *phi_node : phi_nodes_) { + llvm::PHINode *end_phi = + cg_->CreatePHI(phi_node->getType(), 2, phi_node->getName() + "End"); + end_phi->addIncoming(phi_node->getIncomingValue(0), pre_loop_bb_); + end_phi->addIncoming(phi_node->getIncomingValue(1), last_loop_bb_); + loop_vals.push_back(end_phi); + } +} + +} // namespace codegen +} // namespace peloton \ No newline at end of file diff --git a/pool/shard006/C++/0084487_ObjCUnusedIVarsChecker.cpp b/pool/shard006/C++/0084487_ObjCUnusedIVarsChecker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb47704515723a38e4bf3bbc28f6b75d574f193c --- /dev/null +++ b/pool/shard006/C++/0084487_ObjCUnusedIVarsChecker.cpp @@ -0,0 +1,191 @@ +//==- ObjCUnusedIVarsChecker.cpp - Check for unused ivars --------*- C++ -*-==// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// +// This file defines a CheckObjCUnusedIvars, a checker that +// analyzes an Objective-C class's interface/implementation to determine if it +// has any ivars that are never accessed. +// +//===----------------------------------------------------------------------===// + +#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h" +#include "clang/Analysis/PathDiagnostic.h" +#include "clang/AST/Attr.h" +#include "clang/AST/DeclObjC.h" +#include "clang/AST/Expr.h" +#include "clang/AST/ExprObjC.h" +#include "clang/Basic/LangOptions.h" +#include "clang/Basic/SourceManager.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/Checker.h" + +using namespace clang; +using namespace ento; + +enum IVarState { Unused, Used }; +typedef llvm::DenseMap IvarUsageMap; + +static void Scan(IvarUsageMap& M, const Stmt *S) { + if (!S) + return; + + if (const ObjCIvarRefExpr *Ex = dyn_cast(S)) { + const ObjCIvarDecl *D = Ex->getDecl(); + IvarUsageMap::iterator I = M.find(D); + if (I != M.end()) + I->second = Used; + return; + } + + // Blocks can reference an instance variable of a class. + if (const BlockExpr *BE = dyn_cast(S)) { + Scan(M, BE->getBody()); + return; + } + + if (const PseudoObjectExpr *POE = dyn_cast(S)) + for (PseudoObjectExpr::const_semantics_iterator + i = POE->semantics_begin(), e = POE->semantics_end(); i != e; ++i) { + const Expr *sub = *i; + if (const OpaqueValueExpr *OVE = dyn_cast(sub)) + sub = OVE->getSourceExpr(); + Scan(M, sub); + } + + for (const Stmt *SubStmt : S->children()) + Scan(M, SubStmt); +} + +static void Scan(IvarUsageMap& M, const ObjCPropertyImplDecl *D) { + if (!D) + return; + + const ObjCIvarDecl *ID = D->getPropertyIvarDecl(); + + if (!ID) + return; + + IvarUsageMap::iterator I = M.find(ID); + if (I != M.end()) + I->second = Used; +} + +static void Scan(IvarUsageMap& M, const ObjCContainerDecl *D) { + // Scan the methods for accesses. + for (const auto *I : D->instance_methods()) + Scan(M, I->getBody()); + + if (const ObjCImplementationDecl *ID = dyn_cast(D)) { + // Scan for @synthesized property methods that act as setters/getters + // to an ivar. + for (const auto *I : ID->property_impls()) + Scan(M, I); + + // Scan the associated categories as well. + for (const auto *Cat : ID->getClassInterface()->visible_categories()) { + if (const ObjCCategoryImplDecl *CID = Cat->getImplementation()) + Scan(M, CID); + } + } +} + +static void Scan(IvarUsageMap &M, const DeclContext *C, const FileID FID, + const SourceManager &SM) { + for (const auto *I : C->decls()) + if (const auto *FD = dyn_cast(I)) { + SourceLocation L = FD->getBeginLoc(); + if (SM.getFileID(L) == FID) + Scan(M, FD->getBody()); + } +} + +static void checkObjCUnusedIvar(const ObjCImplementationDecl *D, + BugReporter &BR, + const CheckerBase *Checker) { + + const ObjCInterfaceDecl *ID = D->getClassInterface(); + IvarUsageMap M; + + // Iterate over the ivars. + for (const auto *Ivar : ID->ivars()) { + // Ignore ivars that... + // (a) aren't private + // (b) explicitly marked unused + // (c) are iboutlets + // (d) are unnamed bitfields + if (Ivar->getAccessControl() != ObjCIvarDecl::Private || + Ivar->hasAttr() || Ivar->hasAttr() || + Ivar->hasAttr() || + Ivar->isUnnamedBitfield()) + continue; + + M[Ivar] = Unused; + } + + if (M.empty()) + return; + + // Now scan the implementation declaration. + Scan(M, D); + + // Any potentially unused ivars? + bool hasUnused = false; + for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I) + if (I->second == Unused) { + hasUnused = true; + break; + } + + if (!hasUnused) + return; + + // We found some potentially unused ivars. Scan the entire translation unit + // for functions inside the @implementation that reference these ivars. + // FIXME: In the future hopefully we can just use the lexical DeclContext + // to go from the ObjCImplementationDecl to the lexically "nested" + // C functions. + const SourceManager &SM = BR.getSourceManager(); + Scan(M, D->getDeclContext(), SM.getFileID(D->getLocation()), SM); + + // Find ivars that are unused. + for (IvarUsageMap::iterator I = M.begin(), E = M.end(); I!=E; ++I) + if (I->second == Unused) { + std::string sbuf; + llvm::raw_string_ostream os(sbuf); + os << "Instance variable '" << *I->first << "' in class '" << *ID + << "' is never used by the methods in its @implementation " + "(although it may be used by category methods)."; + + PathDiagnosticLocation L = + PathDiagnosticLocation::create(I->first, BR.getSourceManager()); + BR.EmitBasicReport(D, Checker, "Unused instance variable", "Optimization", + os.str(), L); + } +} + +//===----------------------------------------------------------------------===// +// ObjCUnusedIvarsChecker +//===----------------------------------------------------------------------===// + +namespace { +class ObjCUnusedIvarsChecker : public Checker< + check::ASTDecl > { +public: + void checkASTDecl(const ObjCImplementationDecl *D, AnalysisManager& mgr, + BugReporter &BR) const { + checkObjCUnusedIvar(D, BR, this); + } +}; +} + +void ento::registerObjCUnusedIvarsChecker(CheckerManager &mgr) { + mgr.registerChecker(); +} + +bool ento::shouldRegisterObjCUnusedIvarsChecker(const LangOptions &LO) { + return true; +} diff --git a/pool/shard006/C++/0084493_UpdateJobQueueResult.cpp b/pool/shard006/C++/0084493_UpdateJobQueueResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..171c3e2f62a817ce3b983467cac6cf9d0bb450ef --- /dev/null +++ b/pool/shard006/C++/0084493_UpdateJobQueueResult.cpp @@ -0,0 +1,46 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::Batch::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +UpdateJobQueueResult::UpdateJobQueueResult() +{ +} + +UpdateJobQueueResult::UpdateJobQueueResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +UpdateJobQueueResult& UpdateJobQueueResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("jobQueueName")) + { + m_jobQueueName = jsonValue.GetString("jobQueueName"); + + } + + if(jsonValue.ValueExists("jobQueueArn")) + { + m_jobQueueArn = jsonValue.GetString("jobQueueArn"); + + } + + + + return *this; +} diff --git a/pool/shard006/C++/0084500_compiledIC_sparc.cpp b/pool/shard006/C++/0084500_compiledIC_sparc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ea9ccc6579b29b5d693da584ab41e437b36c8834 --- /dev/null +++ b/pool/shard006/C++/0084500_compiledIC_sparc.cpp @@ -0,0 +1,165 @@ +/* + * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "asm/macroAssembler.inline.hpp" +#include "code/compiledIC.hpp" +#include "code/icBuffer.hpp" +#include "code/nmethod.hpp" +#include "memory/resourceArea.hpp" +#include "runtime/mutexLocker.hpp" +#include "runtime/safepoint.hpp" +#ifdef COMPILER2 +#include "opto/matcher.hpp" +#endif + +// Release the CompiledICHolder* associated with this call site is there is one. +void CompiledIC::cleanup_call_site(virtual_call_Relocation* call_site) { + // This call site might have become stale so inspect it carefully. + NativeCall* call = nativeCall_at(call_site->addr()); + if (is_icholder_entry(call->destination())) { + NativeMovConstReg* value = nativeMovConstReg_at(call_site->cached_value()); + InlineCacheBuffer::queue_for_release((CompiledICHolder*)value->data()); + } +} + +bool CompiledIC::is_icholder_call_site(virtual_call_Relocation* call_site) { + // This call site might have become stale so inspect it carefully. + NativeCall* call = nativeCall_at(call_site->addr()); + return is_icholder_entry(call->destination()); +} + +// ---------------------------------------------------------------------------- + +#define __ _masm. +void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf, address mark) { + // Stub is fixed up when the corresponding call is converted from calling + // compiled code to calling interpreted code. + // set (empty), G5 + // jmp -1 + + if (mark == NULL) { + mark = cbuf.insts_mark(); // Get mark within main instrs section. + } + + MacroAssembler _masm(&cbuf); + + address base = + __ start_a_stub(to_interp_stub_size()); + guarantee(base != NULL, "out of space"); + + // Static stub relocation stores the instruction address of the call. + __ relocate(static_stub_Relocation::spec(mark)); + + __ set_metadata(NULL, G5); + + __ set_inst_mark(); + AddressLiteral addrlit(-1); + __ JUMP(addrlit, G3, 0); + + __ delayed()->nop(); + + assert(__ pc() - base <= to_interp_stub_size(), "wrong stub size"); + + // Update current stubs pointer and restore code_end. + __ end_a_stub(); +} +#undef __ + +int CompiledStaticCall::to_interp_stub_size() { + // This doesn't need to be accurate but it must be larger or equal to + // the real size of the stub. + return (NativeMovConstReg::instruction_size + // sethi/setlo; + NativeJump::instruction_size + // sethi; jmp; nop + (TraceJumps ? 20 * BytesPerInstWord : 0) ); +} + +// Relocation entries for call stub, compiled java to interpreter. +int CompiledStaticCall::reloc_to_interp_stub() { + return 10; // 4 in emit_java_to_interp + 1 in Java_Static_Call +} + +void CompiledStaticCall::set_to_interpreted(methodHandle callee, address entry) { + address stub = find_stub(); + guarantee(stub != NULL, "stub not found"); + + if (TraceICs) { + ResourceMark rm; + tty->print_cr("CompiledStaticCall@" INTPTR_FORMAT ": set_to_interpreted %s", + instruction_address(), + callee->name_and_sig_as_C_string()); + } + + // Creation also verifies the object. + NativeMovConstReg* method_holder = nativeMovConstReg_at(stub); + NativeJump* jump = nativeJump_at(method_holder->next_instruction_address()); + + assert(method_holder->data() == 0 || method_holder->data() == (intptr_t)callee(), + "a) MT-unsafe modification of inline cache"); + assert(jump->jump_destination() == (address)-1 || jump->jump_destination() == entry, + "b) MT-unsafe modification of inline cache"); + + // Update stub. + method_holder->set_data((intptr_t)callee()); + jump->set_jump_destination(entry); + + // Update jump to call. + set_destination_mt_safe(stub); +} + +void CompiledStaticCall::set_stub_to_clean(static_stub_Relocation* static_stub) { + assert (CompiledIC_lock->is_locked() || SafepointSynchronize::is_at_safepoint(), "mt unsafe call"); + // Reset stub. + address stub = static_stub->addr(); + assert(stub != NULL, "stub not found"); + // Creation also verifies the object. + NativeMovConstReg* method_holder = nativeMovConstReg_at(stub); + NativeJump* jump = nativeJump_at(method_holder->next_instruction_address()); + method_holder->set_data(0); + jump->set_jump_destination((address)-1); +} + +//----------------------------------------------------------------------------- +// Non-product mode code +#ifndef PRODUCT + +void CompiledStaticCall::verify() { + // Verify call. + NativeCall::verify(); + if (os::is_MP()) { + verify_alignment(); + } + + // Verify stub. + address stub = find_stub(); + assert(stub != NULL, "no stub found for static call"); + // Creation also verifies the object. + NativeMovConstReg* method_holder = nativeMovConstReg_at(stub); + NativeJump* jump = nativeJump_at(method_holder->next_instruction_address()); + + // Verify state. + assert(is_clean() || is_call_to_compiled() || is_call_to_interpreted(), "sanity check"); +} + +#endif // !PRODUCT diff --git a/pool/shard006/C++/0084501_2.cpp b/pool/shard006/C++/0084501_2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..624f440901d5ecfad902fc657beb194db8fe63a6 --- /dev/null +++ b/pool/shard006/C++/0084501_2.cpp @@ -0,0 +1,43 @@ +#include +#include +#include +//#include +#include + +#define U_DEBUG +#define L_JUDGE + +#ifdef L_JUDGE +#pragma warning(disable:4996) +#endif + +using namespace std; +const int MAXN=1005; +const int MAXM=6; +const int MAXS=1025; +const int MOD=1e9+7; + +int dp[MAXN][MAXM][MAXS]; + + +int main(){ + #ifdef L_JUDGE + freopen("in.txt","r",stdin); +// freopen("out.txt","w",stdout); + #endif + int ans=0; + for(int i=1;i<=1000;i++){ + if(i%3==0||0==i%5){ + ans+=i; + } + } + cout< + * Copyright (C) 2004, 2005, 2007, 2008 Rob Buis + * Copyright (C) 2007 Eric Seidel + * Copyright (C) 2009 Google, Inc. All rights reserved. + * Copyright (C) 2009 Dirk Schulze + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "core/layout/svg/LayoutSVGContainer.h" + +#include "core/layout/HitTestResult.h" +#include "core/layout/LayoutAnalyzer.h" +#include "core/layout/svg/SVGLayoutSupport.h" +#include "core/layout/svg/SVGResources.h" +#include "core/layout/svg/SVGResourcesCache.h" +#include "core/paint/SVGContainerPainter.h" + +namespace blink { + +LayoutSVGContainer::LayoutSVGContainer(SVGElement* node) + : LayoutSVGModelObject(node) + , m_objectBoundingBoxValid(false) + , m_needsBoundariesUpdate(true) + , m_hasNonIsolatedBlendingDescendants(false) + , m_hasNonIsolatedBlendingDescendantsDirty(false) +{ +} + +LayoutSVGContainer::~LayoutSVGContainer() +{ +} + +void LayoutSVGContainer::layout() +{ + ASSERT(needsLayout()); + LayoutAnalyzer::Scope analyzer(*this); + + // Allow LayoutSVGViewportContainer to update its viewport. + calcViewport(); + + // Allow LayoutSVGTransformableContainer to update its transform. + bool updatedTransform = calculateLocalTransform(); + + // LayoutSVGViewportContainer needs to set the 'layout size changed' flag. + determineIfLayoutSizeChanged(); + + SVGLayoutSupport::layoutChildren(this, selfNeedsLayout() || SVGLayoutSupport::filtersForceContainerLayout(this)); + + // Invalidate all resources of this client if our layout changed. + if (everHadLayout() && needsLayout()) + SVGResourcesCache::clientLayoutChanged(this); + + if (m_needsBoundariesUpdate || updatedTransform) { + updateCachedBoundaries(); + m_needsBoundariesUpdate = false; + + // If our bounds changed, notify the parents. + LayoutSVGModelObject::setNeedsBoundariesUpdate(); + } + + clearNeedsLayout(); +} + +void LayoutSVGContainer::addChild(LayoutObject* child, LayoutObject* beforeChild) +{ + LayoutSVGModelObject::addChild(child, beforeChild); + SVGResourcesCache::clientWasAddedToTree(child, child->styleRef()); + + bool shouldIsolateDescendants = (child->isBlendingAllowed() && child->style()->hasBlendMode()) || child->hasNonIsolatedBlendingDescendants(); + if (shouldIsolateDescendants) + descendantIsolationRequirementsChanged(DescendantIsolationRequired); +} + +void LayoutSVGContainer::removeChild(LayoutObject* child) +{ + SVGResourcesCache::clientWillBeRemovedFromTree(child); + LayoutSVGModelObject::removeChild(child); + + bool hadNonIsolatedDescendants = (child->isBlendingAllowed() && child->style()->hasBlendMode()) || child->hasNonIsolatedBlendingDescendants(); + if (hadNonIsolatedDescendants) + descendantIsolationRequirementsChanged(DescendantIsolationNeedsUpdate); +} + +bool LayoutSVGContainer::selfWillPaint() const +{ + SVGResources* resources = SVGResourcesCache::cachedResourcesForLayoutObject(this); + return resources && resources->filter(); +} + +void LayoutSVGContainer::styleDidChange(StyleDifference diff, const ComputedStyle* oldStyle) +{ + LayoutSVGModelObject::styleDidChange(diff, oldStyle); + + bool hadIsolation = oldStyle && !isSVGHiddenContainer() && SVGLayoutSupport::willIsolateBlendingDescendantsForStyle(*oldStyle); + bool isolationChanged = hadIsolation == !SVGLayoutSupport::willIsolateBlendingDescendantsForObject(this); + + if (!parent() || !isolationChanged) + return; + + if (hasNonIsolatedBlendingDescendants()) + parent()->descendantIsolationRequirementsChanged(SVGLayoutSupport::willIsolateBlendingDescendantsForObject(this) ? DescendantIsolationNeedsUpdate : DescendantIsolationRequired); +} + +bool LayoutSVGContainer::hasNonIsolatedBlendingDescendants() const +{ + if (m_hasNonIsolatedBlendingDescendantsDirty) { + m_hasNonIsolatedBlendingDescendants = SVGLayoutSupport::computeHasNonIsolatedBlendingDescendants(this); + m_hasNonIsolatedBlendingDescendantsDirty = false; + } + return m_hasNonIsolatedBlendingDescendants; +} + +void LayoutSVGContainer::descendantIsolationRequirementsChanged(DescendantIsolationState state) +{ + switch (state) { + case DescendantIsolationRequired: + m_hasNonIsolatedBlendingDescendants = true; + m_hasNonIsolatedBlendingDescendantsDirty = false; + break; + case DescendantIsolationNeedsUpdate: + if (m_hasNonIsolatedBlendingDescendantsDirty) + return; + m_hasNonIsolatedBlendingDescendantsDirty = true; + break; + } + if (SVGLayoutSupport::willIsolateBlendingDescendantsForObject(this)) + return; + if (parent()) + parent()->descendantIsolationRequirementsChanged(state); +} + +void LayoutSVGContainer::paint(const PaintInfo& paintInfo, const LayoutPoint&) const +{ + SVGContainerPainter(*this).paint(paintInfo); +} + +void LayoutSVGContainer::addOutlineRects(Vector& rects, const LayoutPoint&, IncludeBlockVisualOverflowOrNot) const +{ + rects.append(LayoutRect(paintInvalidationRectInLocalCoordinates())); +} + +void LayoutSVGContainer::updateCachedBoundaries() +{ + SVGLayoutSupport::computeContainerBoundingBoxes(this, m_objectBoundingBox, m_objectBoundingBoxValid, m_strokeBoundingBox, m_paintInvalidationBoundingBox); + SVGLayoutSupport::intersectPaintInvalidationRectWithResources(this, m_paintInvalidationBoundingBox); +} + +bool LayoutSVGContainer::nodeAtFloatPoint(HitTestResult& result, const FloatPoint& pointInParent, HitTestAction hitTestAction) +{ + // Give LayoutSVGViewportContainer a chance to apply its viewport clip + if (!pointIsInsideViewportClip(pointInParent)) + return false; + + FloatPoint localPoint; + if (!SVGLayoutSupport::transformToUserSpaceAndCheckClipping(this, localToParentTransform(), pointInParent, localPoint)) + return false; + + for (LayoutObject* child = lastChild(); child; child = child->previousSibling()) { + if (child->nodeAtFloatPoint(result, localPoint, hitTestAction)) { + const LayoutPoint& localLayoutPoint = roundedLayoutPoint(localPoint); + updateHitTestResult(result, localLayoutPoint); + if (result.addNodeToListBasedTestResult(child->node(), localLayoutPoint) == StopHitTesting) + return true; + } + } + + // pointer-events=boundingBox makes it possible for containers to be direct targets + if (style()->pointerEvents() == PE_BOUNDINGBOX) { + ASSERT(isObjectBoundingBoxValid()); + if (objectBoundingBox().contains(localPoint)) { + const LayoutPoint& localLayoutPoint = roundedLayoutPoint(localPoint); + updateHitTestResult(result, localLayoutPoint); + if (result.addNodeToListBasedTestResult(element(), localLayoutPoint) == StopHitTesting) + return true; + } + } + // 16.4: "If there are no graphics elements whose relevant graphics content is under the pointer (i.e., there is no target element), the event is not dispatched." + return false; +} + +} // namespace blink diff --git a/pool/shard006/C++/0084526_strid.cpp b/pool/shard006/C++/0084526_strid.cpp new file mode 100644 index 0000000000000000000000000000000000000000..41daf101156c921af8fb823bc5600d59b7cef78a --- /dev/null +++ b/pool/shard006/C++/0084526_strid.cpp @@ -0,0 +1,48 @@ +/* -*- mode:C++ -*- +/////////////////////////////////////////////////////////////////////////////// +// +// Copyright (C) 2012-2013, Markus Schütz +// +// This library is free software. You can redistribute and/or modify it under +// the terms of the GNU Lesser General Public License as published by the Free +// Software Foundation. Either version 2.1 of the License, or (at your option) +// any later version. +// +// This library 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 Lesser General Public License +// for more details. +// +// You should have received a copy of the GNU Lesser General Public License +// along with this library. If not, write to the Free Software Foundation, Inc, +// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, or consult URL +// http://www.gnu.org/licenses/lgpl.html. +// +/////////////////////////////////////////////////////////////////////////////// +*/ +#include "test.h" +#include + +using namespace lisle; + +#ifdef _MSC_VER +#pragma warning (disable:4512) +#endif + +TEST (Strid, success) +{ + bool done = false; + class Thread : public strand + { + public: + Thread (bool& done) : base(), done(done) {} + void main () { done = true; } + private: + typedef strand base; + bool& done; + }; + ASSERT_FALSE(done); + strid thr(new Thread(done)); + thr.join(); + ASSERT_TRUE(done); +} diff --git a/pool/shard006/C++/0084528_sched_rsjf.cpp b/pool/shard006/C++/0084528_sched_rsjf.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fceab593a575ab3a61f60a46ee30c68ae788159f --- /dev/null +++ b/pool/shard006/C++/0084528_sched_rsjf.cpp @@ -0,0 +1,73 @@ +#include "sched_rsjf.h" +#include + +using namespace std; +#define DBG(x) cerr << #x << " = " << (x) << endl + +SchedRSJF::SchedRSJF(vector argn) { + // Recibe por parámetro la cantidad de cores, sus cpu_quantum y los tiempos de ejecución de cada tarea en el lote + quantums = vector (argn[0]); // quantums por core + ticksleft = vector (argn[0]); // ticks que le quedan al proceso en ese core + timeleft = vector (argn.size()-1-argn[0]); // tiempo que le queda al proceso en total + for (int i = 0; i < argn[0]; ++i) { + quantums[i] = ticksleft[i] = argn[i+1]-1; + } + for (unsigned int i = 0; i < argn.size()-1-argn[0]; ++i) { + timeleft[i] = argn[i+argn[0]+1]; + } +} + +SchedRSJF::~SchedRSJF() { +} + +void SchedRSJF::load(int pid) { + proc p; + p.pid = pid; + p.time = timeleft[pid]; + q.push(p); +} + +void SchedRSJF::unblock(int pid) { +} + +int SchedRSJF::tick(int core, const enum Motivo m) { + if (m == EXIT){ + // Si el proceso terminó, lo saco de la cola y sigo. + if (q.empty()) return IDLE_TASK; + else{ + int sig = q.top().pid; q.pop(); + ticksleft[core] = quantums[core]; + return sig; + } + + } else { + //Si estaba idle y hay tarea, correla + if (current_pid(core) == IDLE_TASK && !q.empty()){ + int sig = q.top().pid; + q.pop(); + return sig; + } else if (current_pid(core) == IDLE_TASK) { + return IDLE_TASK; + } + // Si hay una tarea corriendo: + if (ticksleft[core] == 0 && !q.empty()) { + // si no le quedan ticks, lo meto en la cola y saco el minimo (puede ser el mismo). + proc p; + p.pid = current_pid(core); + p.time = --timeleft[current_pid(core)]; + q.push(p); + int sig = q.top().pid; + q.pop(); + ticksleft[core] = quantums[core]; + return sig; + } else if (ticksleft[core] == 0) { + // no le quedan ticks pero la cola está vacía. + return current_pid(core); + } else { + // le quedan ticks: descuento 1 y sigue el mismo. + ticksleft[core]--; + timeleft[current_pid(core)]--; + return current_pid(core); + } + } +} diff --git a/pool/shard006/C++/0084529_general_names.cc b/pool/shard006/C++/0084529_general_names.cc new file mode 100644 index 0000000000000000000000000000000000000000..f8bd9875deb093d57fc9dea01db1733c6125b675 --- /dev/null +++ b/pool/shard006/C++/0084529_general_names.cc @@ -0,0 +1,237 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/cert/internal/general_names.h" + +#include "base/check_op.h" +#include "base/strings/string_util.h" +#include "net/cert/internal/cert_error_params.h" +#include "net/cert/internal/cert_errors.h" +#include "net/der/input.h" +#include "net/der/parser.h" +#include "net/der/tag.h" + +namespace net { + +DEFINE_CERT_ERROR_ID(kFailedParsingGeneralName, "Failed parsing GeneralName"); + +namespace { + +DEFINE_CERT_ERROR_ID(kRFC822NameNotAscii, "rfc822Name is not ASCII"); +DEFINE_CERT_ERROR_ID(kDnsNameNotAscii, "dNSName is not ASCII"); +DEFINE_CERT_ERROR_ID(kURINotAscii, "uniformResourceIdentifier is not ASCII"); +DEFINE_CERT_ERROR_ID(kFailedParsingIp, "Failed parsing iPAddress"); +DEFINE_CERT_ERROR_ID(kUnknownGeneralNameType, "Unknown GeneralName type"); +DEFINE_CERT_ERROR_ID(kFailedReadingGeneralNames, + "Failed reading GeneralNames SEQUENCE"); +DEFINE_CERT_ERROR_ID(kGeneralNamesTrailingData, + "GeneralNames contains trailing data after the sequence"); +DEFINE_CERT_ERROR_ID(kGeneralNamesEmpty, + "GeneralNames is a sequence of 0 elements"); +DEFINE_CERT_ERROR_ID(kFailedReadingGeneralName, + "Failed reading GeneralName TLV"); + +// Return true if the bitmask |mask| contains only zeros after the first +// |prefix_length| bits. +bool IsSuffixZero(const IPAddressBytes& mask, unsigned prefix_length) { + size_t zero_bits = mask.size() * CHAR_BIT - prefix_length; + size_t zero_bytes = zero_bits / CHAR_BIT; + std::vector zeros(zero_bytes, 0); + if (memcmp(zeros.data(), mask.data() + mask.size() - zero_bytes, zero_bytes)) + return false; + size_t leftover_bits = zero_bits % CHAR_BIT; + if (leftover_bits) { + uint8_t b = mask[mask.size() - zero_bytes - 1]; + for (size_t i = 0; i < leftover_bits; ++i) { + if (b & (1 << i)) + return false; + } + } + return true; +} + +} // namespace + +GeneralNames::GeneralNames() = default; + +GeneralNames::~GeneralNames() = default; + +// static +std::unique_ptr GeneralNames::Create( + const der::Input& general_names_tlv, + CertErrors* errors) { + DCHECK(errors); + + // RFC 5280 section 4.2.1.6: + // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + der::Parser parser(general_names_tlv); + der::Input sequence_value; + if (!parser.ReadTag(der::kSequence, &sequence_value)) { + errors->AddError(kFailedReadingGeneralNames); + return nullptr; + } + // Should not have trailing data after GeneralNames sequence. + if (parser.HasMore()) { + errors->AddError(kGeneralNamesTrailingData); + return nullptr; + } + return CreateFromValue(sequence_value, errors); +} + +// static +std::unique_ptr GeneralNames::CreateFromValue( + const der::Input& general_names_value, + CertErrors* errors) { + DCHECK(errors); + + std::unique_ptr general_names(new GeneralNames()); + + der::Parser sequence_parser(general_names_value); + // The GeneralNames sequence should have at least 1 element. + if (!sequence_parser.HasMore()) { + errors->AddError(kGeneralNamesEmpty); + return nullptr; + } + + while (sequence_parser.HasMore()) { + der::Input raw_general_name; + if (!sequence_parser.ReadRawTLV(&raw_general_name)) { + errors->AddError(kFailedReadingGeneralName); + return nullptr; + } + + if (!ParseGeneralName(raw_general_name, IP_ADDRESS_ONLY, + general_names.get(), errors)) { + errors->AddError(kFailedParsingGeneralName); + return nullptr; + } + } + + return general_names; +} + +WARN_UNUSED_RESULT bool ParseGeneralName( + const der::Input& input, + GeneralNames::ParseGeneralNameIPAddressType ip_address_type, + GeneralNames* subtrees, + CertErrors* errors) { + DCHECK(errors); + der::Parser parser(input); + der::Tag tag; + der::Input value; + if (!parser.ReadTagAndValue(&tag, &value)) + return false; + GeneralNameTypes name_type = GENERAL_NAME_NONE; + if (tag == der::ContextSpecificConstructed(0)) { + // otherName [0] OtherName, + name_type = GENERAL_NAME_OTHER_NAME; + subtrees->other_names.push_back(value); + } else if (tag == der::ContextSpecificPrimitive(1)) { + // rfc822Name [1] IA5String, + name_type = GENERAL_NAME_RFC822_NAME; + const base::StringPiece s = value.AsStringPiece(); + if (!base::IsStringASCII(s)) { + errors->AddError(kRFC822NameNotAscii); + return false; + } + subtrees->rfc822_names.push_back(s); + } else if (tag == der::ContextSpecificPrimitive(2)) { + // dNSName [2] IA5String, + name_type = GENERAL_NAME_DNS_NAME; + const base::StringPiece s = value.AsStringPiece(); + if (!base::IsStringASCII(s)) { + errors->AddError(kDnsNameNotAscii); + return false; + } + subtrees->dns_names.push_back(s); + } else if (tag == der::ContextSpecificConstructed(3)) { + // x400Address [3] ORAddress, + name_type = GENERAL_NAME_X400_ADDRESS; + subtrees->x400_addresses.push_back(value); + } else if (tag == der::ContextSpecificConstructed(4)) { + // directoryName [4] Name, + name_type = GENERAL_NAME_DIRECTORY_NAME; + // Name is a CHOICE { rdnSequence RDNSequence }, therefore the SEQUENCE + // tag is explicit. Remove it, since the name matching functions expect + // only the value portion. + der::Parser name_parser(value); + der::Input name_value; + if (!name_parser.ReadTag(der::kSequence, &name_value) || parser.HasMore()) + return false; + subtrees->directory_names.push_back(name_value); + } else if (tag == der::ContextSpecificConstructed(5)) { + // ediPartyName [5] EDIPartyName, + name_type = GENERAL_NAME_EDI_PARTY_NAME; + subtrees->edi_party_names.push_back(value); + } else if (tag == der::ContextSpecificPrimitive(6)) { + // uniformResourceIdentifier [6] IA5String, + name_type = GENERAL_NAME_UNIFORM_RESOURCE_IDENTIFIER; + const base::StringPiece s = value.AsStringPiece(); + if (!base::IsStringASCII(s)) { + errors->AddError(kURINotAscii); + return false; + } + subtrees->uniform_resource_identifiers.push_back(s); + } else if (tag == der::ContextSpecificPrimitive(7)) { + // iPAddress [7] OCTET STRING, + name_type = GENERAL_NAME_IP_ADDRESS; + if (ip_address_type == GeneralNames::IP_ADDRESS_ONLY) { + // RFC 5280 section 4.2.1.6: + // When the subjectAltName extension contains an iPAddress, the address + // MUST be stored in the octet string in "network byte order", as + // specified in [RFC791]. The least significant bit (LSB) of each octet + // is the LSB of the corresponding byte in the network address. For IP + // version 4, as specified in [RFC791], the octet string MUST contain + // exactly four octets. For IP version 6, as specified in [RFC2460], + // the octet string MUST contain exactly sixteen octets. + if ((value.Length() != IPAddress::kIPv4AddressSize && + value.Length() != IPAddress::kIPv6AddressSize)) { + errors->AddError(kFailedParsingIp); + return false; + } + subtrees->ip_addresses.push_back( + IPAddress(value.UnsafeData(), value.Length())); + } else { + DCHECK_EQ(ip_address_type, GeneralNames::IP_ADDRESS_AND_NETMASK); + // RFC 5280 section 4.2.1.10: + // The syntax of iPAddress MUST be as described in Section 4.2.1.6 with + // the following additions specifically for name constraints. For IPv4 + // addresses, the iPAddress field of GeneralName MUST contain eight (8) + // octets, encoded in the style of RFC 4632 (CIDR) to represent an + // address range [RFC4632]. For IPv6 addresses, the iPAddress field + // MUST contain 32 octets similarly encoded. For example, a name + // constraint for "class C" subnet 192.0.2.0 is represented as the + // octets C0 00 02 00 FF FF FF 00, representing the CIDR notation + // 192.0.2.0/24 (mask 255.255.255.0). + if (value.Length() != IPAddress::kIPv4AddressSize * 2 && + value.Length() != IPAddress::kIPv6AddressSize * 2) { + errors->AddError(kFailedParsingIp); + return false; + } + const IPAddress mask(value.UnsafeData() + value.Length() / 2, + value.Length() / 2); + const unsigned mask_prefix_length = MaskPrefixLength(mask); + if (!IsSuffixZero(mask.bytes(), mask_prefix_length)) { + errors->AddError(kFailedParsingIp); + return false; + } + subtrees->ip_address_ranges.push_back( + std::make_pair(IPAddress(value.UnsafeData(), value.Length() / 2), + mask_prefix_length)); + } + } else if (tag == der::ContextSpecificPrimitive(8)) { + // registeredID [8] OBJECT IDENTIFIER } + name_type = GENERAL_NAME_REGISTERED_ID; + subtrees->registered_ids.push_back(value); + } else { + errors->AddError(kUnknownGeneralNameType, + CreateCertErrorParams1SizeT("tag", tag)); + return false; + } + DCHECK_NE(GENERAL_NAME_NONE, name_type); + subtrees->present_name_types |= name_type; + return true; +} + +} // namespace net diff --git a/pool/shard006/C++/0084535_Init_from_image.cpp b/pool/shard006/C++/0084535_Init_from_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd08e945b55199dda05840f723ed4f529db270fd --- /dev/null +++ b/pool/shard006/C++/0084535_Init_from_image.cpp @@ -0,0 +1,64 @@ + +/*copyright 2010 Simon Graeser*/ + +/* +This file is part of Pina. + +Pina is free software: you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +Pina 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 Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with Pina. If not, see . +*/ + +#include "Init_from_image.h" +#include "../Templates/Ordering.h" + +#include "Ref.h" +#include "Hex.h" + + +#define THIS Init_from_image +namespace PINA_NAMESPACE{ + + + + +THIS::THIS(XmlElement* h):Element(h){ + + /* attributes */ + createAttribute(attrib_mips_generate,"mips_generate"); + + /* children */ + buildChildren(Types()); + + /* data */ + +} + +std::string THIS::getName() const { + return Name; +} + +void THIS::order(){ + children.sort(Ordering()); +} + +const std::string THIS::Name = "init_from"; + +THIS::~THIS(){ +} + + + + +}/*PINA_NAMESPACE*/ +#undef THIS + diff --git a/pool/shard006/C++/0084536_cenumpins.cpp b/pool/shard006/C++/0084536_cenumpins.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25d3c6c950392afecba0e41a62f58f4cb1973e34 --- /dev/null +++ b/pool/shard006/C++/0084536_cenumpins.cpp @@ -0,0 +1,111 @@ +// Copyright (c) 2010 The WebM project authors. All Rights Reserved. +// +// Use of this source code is governed by a BSD-style license +// that can be found in the LICENSE file in the root of the source +// tree. An additional intellectual property rights grant can be found +// in the file PATENTS. All contributing project authors may +// be found in the AUTHORS file in the root of the source tree. + +#include +#include "cenumpins.hpp" +#include + +CEnumPins::CEnumPins(IPin* const* a, ULONG n) +{ + m_pins.reserve(n); + + for (ULONG i = 0; i < n; ++i) + { + IPin* const p = a[i]; + p->AddRef(); + + m_pins.push_back(p); + } +} + + +CEnumPins::~CEnumPins() +{ + while (!m_pins.empty()) + { + IPin* const p = m_pins.back(); + m_pins.pop_back(); + + p->Release(); + } +} + + +CEnumPins::CEnumPins(const CEnumPins& rhs) +{ + const pins_t::size_type n = rhs.m_pins.size(); + + m_pins.reserve(n); + + for (ULONG i = 0; i < n; ++i) + { + IPin* const p = rhs.m_pins[i]; + p->AddRef(); + + m_pins.push_back(p); + } +} + + +HRESULT CEnumPins::Clone(IEnumPins** pp) +{ + if (pp == 0) + return E_POINTER; + + IEnumPins*& p = *pp; + + p = new (std::nothrow) CEnumPins(*this); + + return p ? S_OK : E_OUTOFMEMORY; +} + + +HRESULT CEnumPins::GetCount(ULONG& n) const +{ + const pins_t::size_type size = m_pins.size(); + n = static_cast(size); + + return S_OK; +} + + +HRESULT CEnumPins::GetItem(ULONG i, IPin*& p) +{ + p = m_pins[i]; + p->AddRef(); + + return S_OK; +} + + +void CEnumPins::ReleaseItems(IPin** a, ULONG n) +{ + for (ULONG i = 0; i < n; ++i) + { + IPin* const p = a[i]; + p->Release(); + } +} + + +HRESULT CEnumPins::CreateInstance( + IPin* const* a, + ULONG n, + IEnumPins** pp) +{ + if (pp == 0) + return E_POINTER; + + IEnumPins*& p = *pp; + + p = new (std::nothrow) CEnumPins(a, n); + + return p ? S_OK : E_OUTOFMEMORY; +} + + diff --git a/pool/shard006/C++/0084539_FastqcWorker.cpp b/pool/shard006/C++/0084539_FastqcWorker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..27fe8bb8897db66e30dbbdcca16cbb6908b20e2f --- /dev/null +++ b/pool/shard006/C++/0084539_FastqcWorker.cpp @@ -0,0 +1,243 @@ +/** + * UGENE - Integrated Bioinformatics Tools. + * Copyright (C) 2008-2017 UniPro + * http://ugene.net + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "FastqcSupport.h" +#include "FastqcTask.h" +#include "FastqcWorker.h" +#include "java/JavaSupport.h" +#include "perl/PerlSupport.h" + +namespace U2 { +namespace LocalWorkflow { + + +const QString FastQCWorker::BASE_FASTQC_SUBDIR = "FastQC"; +const QString FastQCWorker::INPUT_PORT = "in-file"; +const QString FastQCWorker::OUT_MODE_ID = "out-mode"; +const QString FastQCWorker::CUSTOM_DIR_ID = "custom-dir"; + +const QString FastQCWorker::ADAPTERS = "adapter"; +const QString FastQCWorker::CONTAMINANTS = "contaminants"; + +const QString FastQCFactory::ACTOR_ID("fastqc"); + +//////////////////////////////////////////////// +// FastQCPrompter + +QString FastQCPrompter::composeRichDoc() { + IntegralBusPort* input = qobject_cast(target->getPort(FastQCWorker::INPUT_PORT)); + const Actor* producer = input->getProducer(BaseSlots::URL_SLOT().getId()); + QString unsetStr = ""+tr("unset")+""; + QString producerName = tr(" from %1").arg(producer ? producer->getLabel() : unsetStr); + + QString doc = tr("Builds FastQC report for file(s) %1.").arg(producerName); + return doc; +} + +//////////////////////////////////////// +//FastQCFactory +void FastQCFactory::init() { + Descriptor desc( ACTOR_ID, FastQCWorker::tr("FastQC Quality Control"), + FastQCWorker::tr("Builds quality control reports.") ); + + QList p; + { + Descriptor inD(FastQCWorker::INPUT_PORT, FastQCWorker::tr("Short reads"), + FastQCWorker::tr("Short read data")); + + QMap inM; + inM[BaseSlots::URL_SLOT()] = BaseTypes::STRING_TYPE(); + p << new PortDescriptor(inD, DataTypePtr(new MapDataType("fastqc.input-url", inM)), true); + + } + + QList a; + { + + Descriptor outDir(FastQCWorker::OUT_MODE_ID, FastQCWorker::tr("Output directory"), + FastQCWorker::tr("Select an output directory. Custom - specify the output directory in the 'Custom directory' parameter. " + "Workflow - internal workflow directory. " + "Input file - the directory of the input file.")); + + Descriptor customDir(FastQCWorker::CUSTOM_DIR_ID, FastQCWorker::tr("Custom directory"), + FastQCWorker::tr("Select the custom output directory.")); + + Descriptor adapters(FastQCWorker::ADAPTERS, FastQCWorker::tr("List of adapters"), + FastQCWorker::tr("Specifies a non-default file which contains the list of adapter sequences which will be explicity searched against " + "the library. The file must contain sets of named adapters " + "in the form name[tab]sequence. Lines prefixed with a hash " + "will be ignored.")); + + Descriptor conts(FastQCWorker::CONTAMINANTS, FastQCWorker::tr("List of contaminants"), + FastQCWorker::tr("Specifies a non-default file which contains the list of " + "contaminants to screen overrepresented sequences against. " + "The file must contain sets of named contaminants in the " + "form name[tab]sequence. Lines prefixed with a hash will " + "be ignored.")); + + + a << new Attribute(outDir, BaseTypes::NUM_TYPE(), false, QVariant(FileAndDirectoryUtils::WORKFLOW_INTERNAL)); + Attribute* customDirAttr = new Attribute(customDir, BaseTypes::STRING_TYPE(), false, QVariant("")); + customDirAttr->addRelation(new VisibilityRelation(FastQCWorker::OUT_MODE_ID, FileAndDirectoryUtils::CUSTOM)); + a << customDirAttr; + + a << new Attribute( adapters, BaseTypes::STRING_TYPE(), false, ""); + a << new Attribute( conts, BaseTypes::STRING_TYPE(), false, ""); + } + + QMap delegates; + { + + QVariantMap directoryMap; + QString fileDir = FastQCWorker::tr("Input file"); + QString workflowDir = FastQCWorker::tr("Workflow"); + QString customD = FastQCWorker::tr("Custom"); + directoryMap[fileDir] = FileAndDirectoryUtils::FILE_DIRECTORY; + directoryMap[workflowDir] = FileAndDirectoryUtils::WORKFLOW_INTERNAL; + directoryMap[customD] = FileAndDirectoryUtils::CUSTOM; + delegates[FastQCWorker::OUT_MODE_ID] = new ComboBoxDelegate(directoryMap); + + delegates[FastQCWorker::CUSTOM_DIR_ID] = new URLDelegate("", "", false, true); + + delegates[FastQCWorker::ADAPTERS] = new URLDelegate("", "", false, false, false); + delegates[FastQCWorker::CONTAMINANTS] = new URLDelegate("", "", false, false, false); + } + + ActorPrototype* proto = new IntegralBusActorPrototype(desc, p, a); + proto->setEditor(new DelegateEditor(delegates)); + proto->setPrompter(new FastQCPrompter()); + proto->addExternalTool(ET_JAVA); + proto->addExternalTool(ET_FASTQC); + proto->addExternalTool(ET_PERL); + + WorkflowEnv::getProtoRegistry()->registerProto(BaseActorCategories::CATEGORY_NGS_BASIC(), proto); + DomainFactory *localDomain = WorkflowEnv::getDomainRegistry()->getById(LocalDomainFactory::ID); + localDomain->registerEntry(new FastQCFactory()); +} + +////////////////////////////////////////////////////////////////////////// +//FastQCWorker +FastQCWorker::FastQCWorker(Actor *a) +:BaseWorker(a) +,inputUrlPort(NULL) +{ + +} + +void FastQCWorker::init() { + inputUrlPort = ports.value(INPUT_PORT); +} + +Task * FastQCWorker::tick() { + if (inputUrlPort->hasMessage()) { + const QString url = takeUrl(); + CHECK(!url.isEmpty(), NULL); + + QString outputDir = FileAndDirectoryUtils::createWorkingDir(url, getValue(OUT_MODE_ID), getValue(CUSTOM_DIR_ID), context->workingDir()); + U2OpStatusImpl os; + outputDir = GUrlUtils::createDirectory(outputDir + FastQCWorker::BASE_FASTQC_SUBDIR, "_", os); + + FastQCSetting setting; + setting.inputUrl = url; + setting.outDir = outputDir; + setting.adapters = getValue(ADAPTERS); + setting.conts = getValue(CONTAMINANTS); + + FastQCTask *t = new FastQCTask (setting); + t->addListeners(createLogListeners()); + connect(new TaskSignalMapper(t), SIGNAL(si_taskFinished(Task*)), SLOT(sl_taskFinished(Task*))); + return t; + } + + if (inputUrlPort->isEnded()) { + setDone(); + } + return NULL; +} + +void FastQCWorker::cleanup(){ + +} + +namespace { + QString getTargetTaskUrl(Task * task) { + FastQCTask *curtask = dynamic_cast(task); + if (NULL != curtask) { + return curtask->getResult(); + } + return ""; + } + +} + +void FastQCWorker::sl_taskFinished(Task *task) { + CHECK(!task->hasError(), ); + CHECK(!task->isCanceled(), ); + + QString url = getTargetTaskUrl(task); + CHECK(!url.isEmpty(), ); + + monitor()->addOutputFile(url, getActorId(), true); +} + +QString FastQCWorker::takeUrl() { + const Message inputMessage = getMessageAndSetupScriptValues(inputUrlPort); + if (inputMessage.isEmpty()) { + return ""; + } + + const QVariantMap data = inputMessage.getData().toMap(); + return data[BaseSlots::URL_SLOT().getId()].toString(); +} + +} //LocalWorkflow +} //U2 + diff --git a/pool/shard006/C++/0084552_json_rpc_websocket_server.cpp b/pool/shard006/C++/0084552_json_rpc_websocket_server.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ddf102e1cdb36e7153642957d77526cf3804de60 --- /dev/null +++ b/pool/shard006/C++/0084552_json_rpc_websocket_server.cpp @@ -0,0 +1,119 @@ +#include "json_rpc_websocket_server.h" +#include "json_rpc_websocket.h" +#include "jcon_assert.h" + +#include +#include + +namespace jcon { + +JsonRpcWebSocketServer::JsonRpcWebSocketServer( + QObject* parent, + std::shared_ptr logger) + : JsonRpcServer(parent, logger) + , m_server(new QWebSocketServer("JSON RPC WebSocket server", + QWebSocketServer::NonSecureMode, + this)) +{ + m_server->connect(m_server, &QWebSocketServer::newConnection, + this, &JsonRpcWebSocketServer::newConnection); +} + +JsonRpcWebSocketServer::~JsonRpcWebSocketServer() +{ + m_server->disconnect(this); + close(); + delete m_server; + m_server = nullptr; +} + +bool JsonRpcWebSocketServer::listen(int port) +{ + logInfo(QString("listening on port %2").arg(port)); + return m_server->listen(QHostAddress::AnyIPv4, port); +} + + +bool JsonRpcWebSocketServer::listen(const QHostAddress& addr, int port) +{ + logInfo(QString("listening on port %2").arg(port)); + return m_server->listen(addr, port); +} + +void JsonRpcWebSocketServer::close() +{ + m_server->close(); +} + +JsonRpcEndpoint* JsonRpcWebSocketServer::findClient(QObject* socket) +{ + QWebSocket* web_socket = qobject_cast(socket); + auto it = m_client_endpoints.find(web_socket); + return (it != m_client_endpoints.end()) ? it->second.get() : nullptr; +} + +QVector JsonRpcWebSocketServer::getAllClients() +{ + int size = static_cast(m_client_endpoints.size()); + QVector rpc_endpoints(size, nullptr); + + for (auto const& client_endpoint : m_client_endpoints) + rpc_endpoints.append(client_endpoint.second.get()); + + return rpc_endpoints; +} + +void JsonRpcWebSocketServer::newConnection() +{ + JCON_ASSERT(m_server->hasPendingConnections()); + if (m_server->hasPendingConnections()) { + QWebSocket* web_socket = m_server->nextPendingConnection(); + + JCON_ASSERT(web_socket); + if (!web_socket) { + logError("pending socket was null"); + return; + } + + logInfo("client connected: " + web_socket->peerAddress().toString()); + + // TODO: maybe move this to base class? + // { + auto rpc_socket = std::make_shared(web_socket); + + auto endpoint = + std::make_shared(rpc_socket, log(), this); + + connect(endpoint.get(), &JsonRpcEndpoint::socketDisconnected, + this, &JsonRpcWebSocketServer::disconnectClient); + + connect(endpoint.get(), &JsonRpcEndpoint::jsonObjectReceived, + this, &JsonRpcServer::jsonRequestReceived); + + m_client_endpoints[web_socket] = endpoint; + emit(clientConnected(web_socket)); + // } + } +} + +void JsonRpcWebSocketServer::disconnectClient(QObject* client_socket) +{ + QWebSocket* socket = qobject_cast(client_socket); + JCON_ASSERT(socket); + if (!socket) { + logError("client disconnected, but socket is null"); + return; + } + + logInfo("client disconnected: " + socket->peerAddress().toString()); + auto it = m_client_endpoints.find(socket); + JCON_ASSERT(it != m_client_endpoints.end()); + if (it == m_client_endpoints.end()) { + logError("unknown client disconnected"); + return; + } + m_client_endpoints.erase(it); + emit(clientDisconnected(client_socket)); +} + +} diff --git a/pool/shard006/C++/0084559_CancelSpotInstanceRequestsResponse.cpp b/pool/shard006/C++/0084559_CancelSpotInstanceRequestsResponse.cpp new file mode 100644 index 0000000000000000000000000000000000000000..39b806742e0ed195ca3fcd5d1a33b0aaa50d3390 --- /dev/null +++ b/pool/shard006/C++/0084559_CancelSpotInstanceRequestsResponse.cpp @@ -0,0 +1,69 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::EC2::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +CancelSpotInstanceRequestsResponse::CancelSpotInstanceRequestsResponse() +{ +} + +CancelSpotInstanceRequestsResponse::CancelSpotInstanceRequestsResponse(const AmazonWebServiceResult& result) +{ + *this = result; +} + +CancelSpotInstanceRequestsResponse& CancelSpotInstanceRequestsResponse::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "CancelSpotInstanceRequestsResponse") + { + resultNode = rootNode.FirstChild("CancelSpotInstanceRequestsResponse"); + } + + if(!resultNode.IsNull()) + { + XmlNode cancelledSpotInstanceRequestsNode = resultNode.FirstChild("spotInstanceRequestSet"); + if(!cancelledSpotInstanceRequestsNode.IsNull()) + { + XmlNode cancelledSpotInstanceRequestsMember = cancelledSpotInstanceRequestsNode.FirstChild("item"); + while(!cancelledSpotInstanceRequestsMember.IsNull()) + { + m_cancelledSpotInstanceRequests.push_back(cancelledSpotInstanceRequestsMember); + cancelledSpotInstanceRequestsMember = cancelledSpotInstanceRequestsMember.NextNode("item"); + } + + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::EC2::Model::CancelSpotInstanceRequestsResponse", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + + return *this; +} diff --git a/pool/shard006/C++/0084561_RenardPlugin.cpp b/pool/shard006/C++/0084561_RenardPlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04f8e32d29ba94ab0ceec7669d24a577cb70bce0 --- /dev/null +++ b/pool/shard006/C++/0084561_RenardPlugin.cpp @@ -0,0 +1,192 @@ +/* + * 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 Library 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. + * + * RenardPlugin.cpp + * The Renard plugin for ola + * Copyright (C) 2013 Hakan Lindestaf + */ + +#include +#include + +#include "ola/Logging.h" +#include "olad/PluginAdaptor.h" +#include "olad/Preferences.h" +#include "plugins/renard/RenardDevice.h" +#include "plugins/renard/RenardPlugin.h" + +namespace ola { +namespace plugin { +namespace renard { + +using ola::io::ConnectedDescriptor; +using std::string; +using std::vector; + +// Blank default path, so we don't start using a serial port without being asked +const char RenardPlugin::RENARD_DEVICE_PATH[] = ""; +const char RenardPlugin::PLUGIN_NAME[] = "Renard"; +const char RenardPlugin::PLUGIN_PREFIX[] = "renard"; +const char RenardPlugin::DEVICE_KEY[] = "device"; + +/* + * Start the plugin + */ +bool RenardPlugin::StartHook() { + vector device_names; + vector::iterator it; + RenardDevice *device; + + // fetch device listing + device_names = m_preferences->GetMultipleValue(DEVICE_KEY); + + for (it = device_names.begin(); it != device_names.end(); ++it) { + if (it->empty()) { + OLA_DEBUG << "No path configured for device, please set one in " + "ola-renard.conf"; + continue; + } + + device = new RenardDevice(this, m_preferences, *it); + OLA_DEBUG << "Adding device " << *it; + + if (!device->Start()) { + delete device; + continue; + } + + OLA_DEBUG << "Started device " << *it; + + m_plugin_adaptor->AddReadDescriptor(device->GetSocket()); + m_plugin_adaptor->RegisterDevice(device); + m_devices.push_back(device); + } + return true; +} + + +/* + * Stop the plugin + * @return true on success, false on failure + */ +bool RenardPlugin::StopHook() { + vector::iterator iter; + for (iter = m_devices.begin(); iter != m_devices.end(); ++iter) { + m_plugin_adaptor->RemoveReadDescriptor((*iter)->GetSocket()); + DeleteDevice(*iter); + } + m_devices.clear(); + return true; +} + + +/* + * Return the description for this plugin + */ +string RenardPlugin::Description() const { + return +"Renard Plugin\n" +"----------------------------\n" +"\n" +"This plugin creates devices with one output port. It supports multiple " +"Renard SS boards directly connected, or daisy-chained. See this link " +"for more information: " +"http://www.doityourselfchristmas.com/wiki/index.php?title=Renard\n" +"\n" +"--- Config file : ola-renard.conf ---\n" +"\n" +"device = /dev/ttyUSB0\n" +"The device to use as a path for the serial port or USB-Serial adapter. " +"Renard boards don't have a built-in USB port, you will need an adapter (" +"USB->RS232 or USB->RS485). Multiple devices are supported.\n" +"\n" +"--- Per Device Settings (using above device name without /dev/) ---\n" +"-baudrate = \n" +"The speed of the serial port, options are 9600, 19200, 38400, 57600, " +"115200. Default is 57600.\n" +"\n" +"-channels = \n" +"The number of channels connected to this device. Default 64.\n" +"Note that the max number of channels vary by baud rate and " +"the encoding.\n" +"\n" +"-dmx-offset = \n" +"Which starting point in the DMX universe this device is mapped to. " +"The default is 0, which means the first channel on Renard address " +"128 (0x80) will be mapped to DMX channel 1.\n" +"\n"; +} + + +/* + * Called when the file descriptor is closed. + */ +int RenardPlugin::SocketClosed(ConnectedDescriptor *socket) { + vector::iterator iter; + + for (iter = m_devices.begin(); iter != m_devices.end(); ++iter) { + if ((*iter)->GetSocket() == socket) { + break; + } + } + + if (iter == m_devices.end()) { + OLA_WARN << "unknown fd"; + return -1; + } + + DeleteDevice(*iter); + m_devices.erase(iter); + return 0; +} + + +/* + * load the plugin prefs and default to sensible values + * + */ +bool RenardPlugin::SetDefaultPreferences() { + if (!m_preferences) { + return false; + } + + bool save = false; + + save |= m_preferences->SetDefaultValue(DEVICE_KEY, StringValidator(), + RENARD_DEVICE_PATH); + + if (save) { + m_preferences->Save(); + } + + // Just check key exists, as we've set it to "" + if (!m_preferences->HasKey(DEVICE_KEY)) { + return false; + } + return true; +} + + +/* + * Cleanup a single device + */ +void RenardPlugin::DeleteDevice(RenardDevice *device) { + m_plugin_adaptor->UnregisterDevice(device); + device->Stop(); + delete device; +} +} // namespace renard +} // namespace plugin +} // namespace ola diff --git a/pool/shard006/C++/0084565_TextDropShadowCache.cpp b/pool/shard006/C++/0084565_TextDropShadowCache.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b1d4cb2196c4caafd50879ec7f57964f2c50729 --- /dev/null +++ b/pool/shard006/C++/0084565_TextDropShadowCache.cpp @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define LOG_TAG "OpenGLRenderer" + +#include + +#include "Caches.h" +#include "Debug.h" +#include "FontRenderer.h" +#include "TextDropShadowCache.h" +#include "Properties.h" + +namespace android { +namespace uirenderer { + +/////////////////////////////////////////////////////////////////////////////// +// Cache support +/////////////////////////////////////////////////////////////////////////////// + +hash_t ShadowText::hash() const { + uint32_t charCount = len / sizeof(char16_t); + uint32_t hash = JenkinsHashMix(0, len); + hash = JenkinsHashMix(hash, android::hash_type(radius)); + hash = JenkinsHashMix(hash, android::hash_type(textSize)); + hash = JenkinsHashMix(hash, android::hash_type(typeface)); + hash = JenkinsHashMix(hash, flags); + hash = JenkinsHashMix(hash, android::hash_type(italicStyle)); + hash = JenkinsHashMix(hash, android::hash_type(scaleX)); + if (text) { + hash = JenkinsHashMixShorts( + hash, reinterpret_cast(text), charCount); + } + if (positions) { + for (uint32_t i = 0; i < charCount * 2; i++) { + hash = JenkinsHashMix(hash, android::hash_type(positions[i])); + } + } + return JenkinsHashWhiten(hash); +} + +int ShadowText::compare(const ShadowText& lhs, const ShadowText& rhs) { + int deltaInt = int(lhs.len) - int(rhs.len); + if (deltaInt != 0) return deltaInt; + + deltaInt = lhs.flags - rhs.flags; + if (deltaInt != 0) return deltaInt; + + if (lhs.radius < rhs.radius) return -1; + if (lhs.radius > rhs.radius) return +1; + + if (lhs.typeface < rhs.typeface) return -1; + if (lhs.typeface > rhs.typeface) return +1; + + if (lhs.textSize < rhs.textSize) return -1; + if (lhs.textSize > rhs.textSize) return +1; + + if (lhs.italicStyle < rhs.italicStyle) return -1; + if (lhs.italicStyle > rhs.italicStyle) return +1; + + if (lhs.scaleX < rhs.scaleX) return -1; + if (lhs.scaleX > rhs.scaleX) return +1; + + if (lhs.text != rhs.text) { + if (!lhs.text) return -1; + if (!rhs.text) return +1; + + deltaInt = memcmp(lhs.text, rhs.text, lhs.len); + if (deltaInt != 0) return deltaInt; + } + + if (lhs.positions != rhs.positions) { + if (!lhs.positions) return -1; + if (!rhs.positions) return +1; + + return memcmp(lhs.positions, rhs.positions, lhs.len << 2); + } + + return 0; +} + +/////////////////////////////////////////////////////////////////////////////// +// Constructors/destructor +/////////////////////////////////////////////////////////////////////////////// + +TextDropShadowCache::TextDropShadowCache(): + mCache(LruCache::kUnlimitedCapacity), + mSize(0), mMaxSize(MB(DEFAULT_DROP_SHADOW_CACHE_SIZE)) { + char property[PROPERTY_VALUE_MAX]; + if (property_get(PROPERTY_DROP_SHADOW_CACHE_SIZE, property, nullptr) > 0) { + INIT_LOGD(" Setting drop shadow cache size to %sMB", property); + setMaxSize(MB(atof(property))); + } else { + INIT_LOGD(" Using default drop shadow cache size of %.2fMB", + DEFAULT_DROP_SHADOW_CACHE_SIZE); + } + + init(); +} + +TextDropShadowCache::TextDropShadowCache(uint32_t maxByteSize): + mCache(LruCache::kUnlimitedCapacity), + mSize(0), mMaxSize(maxByteSize) { + init(); +} + +TextDropShadowCache::~TextDropShadowCache() { + mCache.clear(); +} + +void TextDropShadowCache::init() { + mCache.setOnEntryRemovedListener(this); + mDebugEnabled = Properties::debugLevel & kDebugMoreCaches; +} + +/////////////////////////////////////////////////////////////////////////////// +// Size management +/////////////////////////////////////////////////////////////////////////////// + +uint32_t TextDropShadowCache::getSize() { + return mSize; +} + +uint32_t TextDropShadowCache::getMaxSize() { + return mMaxSize; +} + +void TextDropShadowCache::setMaxSize(uint32_t maxSize) { + mMaxSize = maxSize; + while (mSize > mMaxSize) { + mCache.removeOldest(); + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Callbacks +/////////////////////////////////////////////////////////////////////////////// + +void TextDropShadowCache::operator()(ShadowText&, ShadowTexture*& texture) { + if (texture) { + mSize -= texture->bitmapSize; + + if (mDebugEnabled) { + ALOGD("Shadow texture deleted, size = %d", texture->bitmapSize); + } + + texture->deleteTexture(); + delete texture; + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Caching +/////////////////////////////////////////////////////////////////////////////// + +void TextDropShadowCache::clear() { + mCache.clear(); +} + +ShadowTexture* TextDropShadowCache::get(const SkPaint* paint, const char* text, uint32_t len, + int numGlyphs, float radius, const float* positions) { + ShadowText entry(paint, radius, len, text, positions); + ShadowTexture* texture = mCache.get(entry); + + if (!texture) { + SkPaint paintCopy(*paint); + paintCopy.setTextAlign(SkPaint::kLeft_Align); + FontRenderer::DropShadow shadow = mRenderer->renderDropShadow(&paintCopy, text, 0, + len, numGlyphs, radius, positions); + + if (!shadow.image) { + return nullptr; + } + + Caches& caches = Caches::getInstance(); + + texture = new ShadowTexture(caches); + texture->left = shadow.penX; + texture->top = shadow.penY; + texture->width = shadow.width; + texture->height = shadow.height; + texture->generation = 0; + texture->blend = true; + + const uint32_t size = shadow.width * shadow.height; + texture->bitmapSize = size; + + // Don't even try to cache a bitmap that's bigger than the cache + if (size < mMaxSize) { + while (mSize + size > mMaxSize) { + mCache.removeOldest(); + } + } + + glGenTextures(1, &texture->id); + + caches.textureState().bindTexture(texture->id); + // Textures are Alpha8 + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texture->width, texture->height, 0, + GL_ALPHA, GL_UNSIGNED_BYTE, shadow.image); + + texture->setFilter(GL_LINEAR); + texture->setWrap(GL_CLAMP_TO_EDGE); + + if (size < mMaxSize) { + if (mDebugEnabled) { + ALOGD("Shadow texture created, size = %d", texture->bitmapSize); + } + + entry.copyTextLocally(); + + mSize += size; + mCache.put(entry, texture); + } else { + texture->cleanup = true; + } + + // Cleanup shadow + free(shadow.image); + } + + return texture; +} + +}; // namespace uirenderer +}; // namespace android diff --git a/pool/shard006/C++/0084567_unittest.cpp b/pool/shard006/C++/0084567_unittest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a03b64625e9f1a8cdbc68fc91a86ae9164816734 --- /dev/null +++ b/pool/shard006/C++/0084567_unittest.cpp @@ -0,0 +1,48 @@ +#include +#include +#include +#include "../include/otus/app.hpp" +#include "../include/otus/server.hpp" +#include "../include/otus/render.hpp" +using namespace std; + +int main() { + // initialize + ots::otus app = ots::otus(); + + // set static folder + app.set_static_folder("static"); + // set template folder + app.set_template_folder("templates"); + + // routing + //app.route("/", "GET", [](ots::request req)->string{ + // cout << req.method << endl; + // cout << req.path << endl; + // cout << req.source << endl; + // cout << req.destination << endl; + // cout << req.body << endl; + // for (auto header : req.headers) { + // cout << header.name << ":" << header.value << endl; + // } + // return ots::render_template("test.html"); + //}); + + app.route("/", "POST", [](ots::request req)->string{ + cout << req.method << endl; + cout << req.path << endl; + cout << req.source << endl; + cout << req.destination << endl; + cout << req.body << endl; + return "OK"; + }); + + app.route("", "GET", [](ots::request req){ + return "Hello"; + }); + + + app.run("localhost", "9000"); + + return 0; +} diff --git a/pool/shard006/C++/0084571_Intl.cpp b/pool/shard006/C++/0084571_Intl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fdae0b1aba144b5bc1471e0749830fba66d0f7ea --- /dev/null +++ b/pool/shard006/C++/0084571_Intl.cpp @@ -0,0 +1,98 @@ +/** + * \file Intl.h + * This file is part of LyX, the document processor. + * Licence details can be found in the file COPYING. + * + * \author unknown + * \author Lars Gullik Bjønnes + * \author Angus Leeming + * \author John Levon + * + * Full author contact details are available in file CREDITS. + */ + +#include + +#include "Intl.h" +#include "LyXRC.h" + +#include "support/debug.h" + +namespace lyx { + + +Intl::Intl() + : keymap(Intl::PRIMARY), keymapon(lyxrc.use_kbmap), + prim_lang(lyxrc.primary_kbmap), sec_lang(lyxrc.secondary_kbmap) +{ +} + + +void Intl::keyMapOn(bool on) +{ + keymapon = on; + + if (on) { + if (keymap == PRIMARY) + keyMapPrim(); + else + keyMapSec(); + } else { + trans.disableKeymap(); + } +} + + +void Intl::toggleKeyMap() +{ + if (keymapon && (keymap == PRIMARY)) + keyMapSec(); + else if (keymapon) + keyMapOn(false); + else + keyMapPrim(); +} + + +void Intl::keyMapPrim() +{ + if (!trans.setPrimary(prim_lang)) + trans.enablePrimary(); + + keymapon = true; + keymap = PRIMARY; +} + + +void Intl::keyMapSec() +{ + if (!trans.setSecondary(sec_lang)) + trans.enableSecondary(); + + keymapon = true; + keymap = SECONDARY; +} + + +void Intl::initKeyMapper(bool on) +{ + LYXERR(Debug::INIT, "Initializing key mappings..."); + + if (trans.setPrimary(prim_lang) == -1) + prim_lang.erase(); + if (trans.setSecondary(sec_lang) == -1) + sec_lang.erase(); + + if (prim_lang.empty() && sec_lang.empty()) + keymapon = false; + else + keymapon = on; + + keyMapOn(keymapon); + + if (keymapon) + keyMapPrim(); +} + + +} // namespace lyx diff --git a/pool/shard006/C++/0084575_particle.cpp b/pool/shard006/C++/0084575_particle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2ae64a2d451f36b336829981c014772d1df9051 --- /dev/null +++ b/pool/shard006/C++/0084575_particle.cpp @@ -0,0 +1,78 @@ +/* + Particle. + Copyright (C) 2015 Denis BOURGE + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 + USA +*/ + +#include "hx3d/graphics/particle.hpp" + +#include "hx3d/math/interpolation.hpp" + +namespace hx3d { +namespace graphics { + +Particle::Particle() { + reset(); +} + +void Particle::reset() { + life = baseLife = 0.f; + dead = false; + rotation = 0.f; + rotationSpeed = 0.f; + color = Color::White; +} + +void Particle::setTexture(const Ptr& texture) { + sprite.setTexture(texture); +} + +void Particle::update(const float delta) { + life -= delta; + + if (life <= 0.f) { + dead = true; + return; + } + + else { + float percentage = life / baseLife; + color.a = math::interpolate(0, 255, percentage, math::Interpolation::Linear); + float z_pos = color.a / 255.f; // between 0 && 1 + sprite.setTint(color); + + position.x -= velocity.x * delta; + position.y -= velocity.y * delta; + position.z = z_pos; + + velocity.x -= gravity.x * delta; + velocity.y -= gravity.y * delta; + + rotation += rotationSpeed * delta; + } +} + +void Particle::draw(Batch& batch) { + sprite.transform.position = position; + sprite.transform.size = size; + sprite.transform.rotation.z = rotation; + + batch.draw(sprite); +} + +} /* graphics */ +} /* hx3d */ diff --git a/pool/shard006/C++/0084580_PcapInput.cpp b/pool/shard006/C++/0084580_PcapInput.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b040108bcab63a985d3355b596398b5d7ea1df6c --- /dev/null +++ b/pool/shard006/C++/0084580_PcapInput.cpp @@ -0,0 +1,118 @@ +#include "stdafx.h" +#include "PcapInput.h" +#include +#include "Prefs.h" +#include "Trace.h" +#include "Sector.h" + +PcapInput::PcapInput(const char * name):NetInputer(name) +{ + mFromFile = FALSE; +} + +PcapInput::~PcapInput(void) +{ + Shutdown(); + if(mHandle) pcap_close((pcap_t *)mHandle); +} +BOOL PcapInput::Create( ) +{ + + char errbuf[PCAP_ERRBUF_SIZE]; + + if(!mWriter){ + Trace::traceEvent(TRACE_NORMAL, "Not define outer!"); + return FALSE; + } + Trace::traceEvent(TRACE_NORMAL, "Use outputer: %s",mWriter->Name()); + packets_captured = packets_discard= 0; + mHandle= pcap_open_live(mName, // name of the device + gPrefs->getSnaplen(), // portion of the packet to capture. + // 65536 grants that the whole packet will be captured on all the MACs. + 0, // promiscuous mode (nonzero means promiscuous) + 500, // read timeout + errbuf // error buffer + ); + if( !mHandle ){ + Trace::traceEvent(TRACE_ERROR,"could not open pcap file: %s", errbuf); + return FALSE; + } + Trace::traceEvent(TRACE_NORMAL, "Reading packets from interface %s...", mName); + + mType = pcap_datalink((pcap_t *)mHandle); + Trace::traceEvent(TRACE_NORMAL,"%s , data link[%s]",pcap_lib_version(),pcap_datalink_val_to_name(mType)); + //pcap_setbuff((pcap_t *)mHandle,6144000); + return TRUE; +} + +void PcapInput::StartPolling() +{ + Trace::traceEvent(TRACE_NORMAL, "Started packet polling on interface %s...", mName); + set_status_run(); + + pcap_t *pd = (pcap_t *) mHandle; + /* Wait until the initialization competes */ + while( isRunning() ) { + const u_char *pkt; + struct pcap_pkthdr hdr; + NetPacket packet; + + if((pkt = pcap_next(pd, &hdr)) != NULL) { + packets_captured++; + if((hdr.caplen > 0) && (hdr.len > 0)){ + memset(&packet,0,sizeof(NetPacket)); + packet.tv_sec = hdr.ts.tv_sec; + if( CSector::dissector(packet,pkt,hdr.len,hdr.caplen) ) mWriter->Write(packet); + else packets_discard++; + } else packets_discard++; + } else { + if(mFromFile) break; +#ifndef HAVE_PTHREAD_H + mWriter->doIdle(); +#endif + } + } /* while */ + set_status_down(); + Trace::traceEvent(TRACE_NORMAL, "Terminated packet polling for %s", mName); + +} +void PcapInput::Shutdown() +{ + if( isRunning() ) { + set_status_signed(); + printStat(); + if(mHandle) pcap_breakloop((pcap_t *)mHandle); + } +} + +int PcapInput::SetFilter(char *filter) +{ + struct bpf_program fcode; + struct in_addr netmask; + + netmask.s_addr = htonl(0xFFFFFF00); + + if((pcap_compile((pcap_t *)mHandle, &fcode, filter, 1, netmask.s_addr) < 0) + || (pcap_setfilter((pcap_t *)mHandle, &fcode) < 0)) { + Trace::traceEvent(TRACE_ERROR, "Unable to set filter %s. Filter ignored.", filter); + return 0; + } else { + Trace::traceEvent(TRACE_NORMAL, "Packet capture filter set to \"%s\"", filter); + return 1; + } +} + +void PcapInput::printStat() +{ + struct pcap_stat stat; + if( pcap_stats((pcap_t *)mHandle,&stat)==0){ + //ps_ifdrop = stat.ps_ifdrop; /* drops by interface XXX not yet supported */ + Trace::traceEvent(TRACE_NORMAL, "%u packets captured, %u packets discard", packets_captured,packets_discard); + Trace::traceEvent(TRACE_NORMAL, "%d packets received by filter", stat.ps_recv /* number of packets received */); + Trace::traceEvent(TRACE_NORMAL, "%d packets dropped by kernel", stat.ps_drop /* number of packets dropped */); + //Trace::traceEvent(TRACE_NORMAL, "%d packets dropped by interface", stat.ps_ifdrop /* drops by interface XXX not yet supported */); + } + +} + + diff --git a/pool/shard006/C++/0084583_polygon_test.cc b/pool/shard006/C++/0084583_polygon_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ba41133934d6bca6ae0ec3e2f8c6f8423b9909ff --- /dev/null +++ b/pool/shard006/C++/0084583_polygon_test.cc @@ -0,0 +1,178 @@ +/* +Copyright 2017 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS-IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include +#include +#include + +#include "ion/math/vector.h" +#include "gtest/gtest.h" +#include "seurat/base/util.h" +#include "seurat/geometry/convex_hull2d.h" +#include "seurat/geometry/polygon.h" +#include "seurat/geometry/quad.h" +#include "seurat/image/image.h" + +using ion::math::Point2f; +using ion::math::Range2f; +using ion::math::Vector2f; +using seurat::image::Image4f; + +namespace { + +const float kEpsilon = 1.0e-5f; + +} // namespace + +namespace seurat { +namespace geometry { + +std::unique_ptr TextureSetup() { + std::unique_ptr texture(new Image4f(100, 200)); + int x_c = (texture->Width() >> 1), y_c = (texture->Height() >> 1); + for (int y = 0; y < texture->Height(); ++y) { + for (int x = 0; x < texture->Width(); ++x) { + float* pixel = texture->At(x, y).Data(); + pixel[0] = pixel[1] = pixel[2] = pixel[3] = 0.0f; + int dx = x - x_c, dy = y - y_c; + if (dx * dx + 2 * dy * dy < 500) pixel[1] = pixel[3] = 1.0f; + } + } + return texture; +} + +TEST(PolygonTest, TestExtent) { + std::vector poly; + poly.emplace_back(12.0f, 3.0f); + poly.emplace_back(6.0f, 6.0f); + poly.emplace_back(0.0f, 3.0f); + poly.emplace_back(6.0f, 0.0f); + const auto& extent = + Extent(poly, {{{1.0f, 0.0f}, {0.0f, 1.0f}}}, {0.0f, 0.0f}); + EXPECT_NEAR(12.0f, (extent.GetSize())[0], kEpsilon); + EXPECT_NEAR(6.0f, (extent.GetSize())[1], kEpsilon); + EXPECT_NEAR(0.0f, (extent.GetMinPoint())[0], kEpsilon); + EXPECT_NEAR(0.0f, (extent.GetMinPoint())[1], kEpsilon); + EXPECT_NEAR(12.0f, (extent.GetMaxPoint())[0], kEpsilon); + EXPECT_NEAR(6.0f, (extent.GetMaxPoint())[1], kEpsilon); +} + +TEST(PolygonTest, TestExtent2) { + std::vector poly; + poly.emplace_back(12.0f, 3.0f); + poly.emplace_back(6.0f, 6.0f); + poly.emplace_back(0.0f, 3.0f); + poly.emplace_back(6.0f, 0.0f); + std::array dirs; + dirs[0] = ion::math::Normalized(poly[2] - poly[1]); + dirs[1] = ion::math::Orthogonal(dirs[0]); + const auto& extent = Extent(poly, dirs, poly[1]); + EXPECT_NEAR(10.73313f, (extent.GetSize())[0], kEpsilon); + EXPECT_NEAR(5.36656f, (extent.GetSize())[1], kEpsilon); + EXPECT_NEAR(-4.02492f, (extent.GetMinPoint())[0], kEpsilon); + EXPECT_NEAR(0.0f, (extent.GetMinPoint())[1], kEpsilon); + EXPECT_NEAR(6.70820f, (extent.GetMaxPoint())[0], kEpsilon); + EXPECT_NEAR(5.36656f, (extent.GetMaxPoint())[1], kEpsilon); +} + +TEST(PolygonTest, TestPolygonArea) { + std::vector points; + points.emplace_back(0.0f, 0.0f); + points.emplace_back(1.0f, 0.0f); + points.emplace_back(0.0f, 1.0f); + float area = PolygonArea(points); + EXPECT_NEAR(0.5f, area, kEpsilon); +} + +TEST(PolygonTest, TestComputeCPolyOBB) { + std::vector cpoly; + cpoly.emplace_back(12.0f, 3.0f); + cpoly.emplace_back(6.0f, 6.0f); + cpoly.emplace_back(0.0f, 3.0f); + cpoly.emplace_back(6.0f, 0.0f); + float obb_area; + const auto& obb = ComputeConvexPolygonOBB(cpoly, &obb_area); + EXPECT_EQ(4, obb.size()); + EXPECT_NEAR(57.6f, obb_area, kEpsilon); +} + +TEST(PolygonTest, TestTextureBoundary) { + const auto texture = TextureSetup(); + int opaque_texel_count; + const auto& tex_bnd = ComputeTextureBoundary(*texture, &opaque_texel_count); + EXPECT_EQ(1115, opaque_texel_count); + EXPECT_EQ(132, tex_bnd.size()); +} + +TEST(PolygonTest, TestComputeTextureConvexHull) { + auto texture = TextureSetup(); + int opaque_texel_count; + const auto& boundary = ComputeTextureBoundary(*texture, &opaque_texel_count); + const auto& hull = ComputeConvexHull(boundary); + int hull_triangle_count = hull.size() - 2; + float hull_area = PolygonArea(hull); + EXPECT_EQ(1115, opaque_texel_count); + EXPECT_EQ(24, hull.size()); + EXPECT_EQ(22, hull_triangle_count); + EXPECT_NEAR(1151, hull_area, kEpsilon); +} + +TEST(PolygonTest, TestComputeOBBTilt) { + std::vector cpoly; + cpoly.emplace_back(12.0f, 3.0f); + cpoly.emplace_back(6.0f, 6.0f); + cpoly.emplace_back(0.0f, 3.0f); + cpoly.emplace_back(6.0f, 0.0f); + float obb_area; + const auto& obb = ComputeConvexPolygonOBB(cpoly, &obb_area); + int pivot_index; + float phi = ComputeOBBTilt(obb, &pivot_index); + EXPECT_NEAR(2.03444f, phi, kEpsilon); + EXPECT_EQ(1, pivot_index); +} + +TEST(PolygonTest, TestIsCounterClockwise) { + std::vector convex_ccw; + convex_ccw.push_back({0.0f, 0.0f}); + convex_ccw.push_back({1.0f, 0.0f}); + convex_ccw.push_back({1.0f, 1.0f}); + convex_ccw.push_back({0.0f, 1.0f}); + EXPECT_TRUE(IsConvexCounterClockwise(convex_ccw)); + + std::vector nonconvex_ccw; + nonconvex_ccw.push_back({0.0f, 0.0f}); + nonconvex_ccw.push_back({1.0f, 0.0f}); + nonconvex_ccw.push_back({0.1f, 0.1f}); + nonconvex_ccw.push_back({0.0f, 1.0f}); + EXPECT_FALSE(IsConvexCounterClockwise(nonconvex_ccw)); + + std::vector convex_cw; + convex_cw.push_back({0.0f, 0.0f}); + convex_cw.push_back({0.0f, 1.0f}); + convex_cw.push_back({1.0f, 1.0f}); + convex_cw.push_back({1.0f, 0.0f}); + EXPECT_FALSE(IsConvexCounterClockwise(convex_cw)); + + std::vector nonconvex_cw; + nonconvex_cw.push_back({0.0f, 0.0f}); + nonconvex_cw.push_back({0.0f, 1.0f}); + nonconvex_cw.push_back({0.1f, 0.1f}); + nonconvex_cw.push_back({1.0f, 0.0f}); + EXPECT_FALSE(IsConvexCounterClockwise(nonconvex_cw)); +} + +} // namespace geometry +} // namespace seurat diff --git a/pool/shard006/C++/0084586_TcpCommunicator.cpp b/pool/shard006/C++/0084586_TcpCommunicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f126e9d038edb06c1ee706e041dc9ed59671e773 --- /dev/null +++ b/pool/shard006/C++/0084586_TcpCommunicator.cpp @@ -0,0 +1,195 @@ +/* + * gVirtuS -- A GPGPU transparent virtualization component. + * + * Copyright (C) 2009-2010 The University of Napoli Parthenope at Naples. + * + * This file is part of gVirtuS. + * + * gVirtuS 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. + * + * gVirtuS 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with gVirtuS; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + * Written by: Giuseppe Coviello , + * Department of Applied Science + */ + +/** + * @file TcpCommunicator.cpp + * @author Giuseppe Coviello + * @date Thu Oct 8 12:08:33 2009 + * + * @brief + * + * + */ + +#include "TcpCommunicator.h" + +#ifndef _WIN32 +#include +#include +#include +#include +#include +#else +#include +static bool initialized = false; +#endif + +#include +#include + +using namespace std; + +TcpCommunicator::TcpCommunicator(const std::string& communicator) { +#ifdef _WIN32 + if(!initialized) { + WSADATA data; + if(WSAStartup(MAKEWORD(2, 2), &data) != 0) + throw "Cannot initialized WinSock."; + initialized = true; + } +#endif + const char *valueptr = strstr(communicator.c_str(), "://") + 3; + const char *portptr = strchr(valueptr, ':'); + if (portptr == NULL) + throw "Port not specified."; + mPort = (short) strtol(portptr + 1, NULL, 10); +#ifdef _WIN32 + char *hostname = _strdup(valueptr); +#else + char *hostname = strdup(valueptr); +#endif + hostname[portptr - valueptr] = 0; + mHostname = string(hostname); + struct hostent *ent = gethostbyname(hostname); + free(hostname); + if (ent == NULL) + throw "TcpCommunicator: Can't resolve hostname '" + mHostname + "'."; + mInAddrSize = ent->h_length; + mInAddr = new char[mInAddrSize]; + memcpy(mInAddr, *ent->h_addr_list, mInAddrSize); +} + +TcpCommunicator::TcpCommunicator(const char *hostname, short port) { + mHostname = string(hostname); + struct hostent *ent = gethostbyname(hostname); + if (ent == NULL) + throw "TcpCommunicator: Can't resolve hostname '" + mHostname + "'."; + mInAddrSize = ent->h_length; + mInAddr = new char[mInAddrSize]; + memcpy(mInAddr, *ent->h_addr_list, mInAddrSize); + mPort = port; +} + +TcpCommunicator::TcpCommunicator(int fd, const char *hostname) { + mSocketFd = fd; + InitializeStream(); +} + +TcpCommunicator::~TcpCommunicator() { + delete[] mInAddr; +} + +void TcpCommunicator::Serve() { + struct sockaddr_in socket_addr; + + + if ((mSocketFd = socket(AF_INET, SOCK_STREAM, 0)) == 0) + throw "TcpCommunicator: Can't create socket."; + + memset((char *) &socket_addr, 0, sizeof(struct sockaddr_in)); + + socket_addr.sin_family = AF_INET; + socket_addr.sin_port = htons(mPort); + socket_addr.sin_addr.s_addr = INADDR_ANY; + + char on = 1; + setsockopt(mSocketFd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)); + + int result = bind(mSocketFd, (struct sockaddr *) & socket_addr, + sizeof (struct sockaddr_in)); + if( result != 0) + throw "TcpCommunicator: Can't bind socket."; + + if (listen(mSocketFd, 5) != 0) + throw "AfUnixCommunicator: Can't listen from socket."; +} + +const Communicator * const TcpCommunicator::Accept() const { + unsigned client_socket_fd; + struct sockaddr_in client_socket_addr; +#ifndef _WIN32 + unsigned client_socket_addr_size; +#else + int client_socket_addr_size; +#endif + client_socket_addr_size = sizeof (struct sockaddr_in); + if ((client_socket_fd = accept(mSocketFd, + (sockaddr *) & client_socket_addr, + &client_socket_addr_size)) == 0) + throw "TcpCommunicator: Error while accepting connection."; + + return new TcpCommunicator(client_socket_fd, + inet_ntoa(client_socket_addr.sin_addr)); +} + +void TcpCommunicator::Connect() { + struct sockaddr_in remote; + + if ((mSocketFd = socket(AF_INET, SOCK_STREAM, 0)) == 0) + throw "TcpCommunicator: Can't create socket."; + + remote.sin_family = AF_INET; + remote.sin_port = htons(mPort); + memcpy(&remote.sin_addr, mInAddr, mInAddrSize); + + if (connect(mSocketFd, (struct sockaddr *) & remote, + sizeof (struct sockaddr_in)) != 0) + throw "TcpCommunicator: Can't connect to socket."; + InitializeStream(); +} + +void TcpCommunicator::Close() { +} + +size_t TcpCommunicator::Read(char* buffer, size_t size) { + mpInput->read(buffer, size); + if (mpInput->bad() || mpInput->eof()) + return 0; + return size; +} + +size_t TcpCommunicator::Write(const char* buffer, size_t size) { + mpOutput->write(buffer, size); + return size; +} + +void TcpCommunicator::Sync() { + mpOutput->flush(); +} + +void TcpCommunicator::InitializeStream() { +#ifdef _WIN32 + FILE *i = _fdopen(mSocketFd, "r"); + FILE *o = _fdopen(mSocketFd, "w"); + mpInputBuf = new filebuf(i); + mpOutputBuf = new filebuf(o); +#else + mpInputBuf = new __gnu_cxx::stdio_filebuf(mSocketFd, ios_base::in); + mpOutputBuf = new __gnu_cxx::stdio_filebuf(mSocketFd, ios_base::out); +#endif + mpInput = new istream(mpInputBuf); + mpOutput = new ostream(mpOutputBuf); +} + diff --git a/pool/shard006/C++/0084593_editaddressdialog.cpp b/pool/shard006/C++/0084593_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c8fcba7412bdefdb60ce28d9728ce95ba47ba80 --- /dev/null +++ b/pool/shard006/C++/0084593_editaddressdialog.cpp @@ -0,0 +1,145 @@ +// Copyright (c) 2011-2014 The Bitcoin developers +// Copyright (c) 2014-2015 The Dash developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" + +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), + mapper(0), + mode(mode), + model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setEnabled(false); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + if(!model) + return; + + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + case AddressTableModel::NO_CHANGES: + // No changes were made during edit operation. Just reject. + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid Flaxscript address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + + } + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard006/C++/0084598_CitationRecord.cpp b/pool/shard006/C++/0084598_CitationRecord.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f9d9e634c913349399f7ad0e8720bb512604d1d --- /dev/null +++ b/pool/shard006/C++/0084598_CitationRecord.cpp @@ -0,0 +1,75 @@ +/* Citation record class implementation. + + Copyright (C) 2010 rel-eng + + This file is part of QWinHelp. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include "CitationRecord.h" + +#include "SystemRecordHeader.h" + +#include "Utils/IOUtils.h" +#include "Utils/DebugUtils.h" + +CitationRecord::CitationRecord() : + citation() +{ + PRINT_DBG("Citation record default constructor"); +} + +CitationRecord::CitationRecord(const QString &citation) : + citation(citation) +{ + PRINT_DBG("Citation record constructor"); +} + +CitationRecord::CitationRecord(QFile &file, qint64 off, QTextCodec *codec) +{ + PRINT_DBG("Reading Citation record at %lld", off); + seekFile(file, off); + SystemRecordHeader hdr(file, off); + this->citation = + readFixedLengthString(file, + static_cast(hdr.getRecordSize()), codec); + PRINT_DBG(" Citation: %s", this->citation.toLocal8Bit().data()); + PRINT_DBG("Citation record loaded successfully"); +} + +CitationRecord::CitationRecord(const CitationRecord& rhs) : + citation(rhs.citation) +{ + PRINT_DBG("Citation record copy constructor"); +} + +CitationRecord & CitationRecord::operator=(const CitationRecord & rhs) +{ + PRINT_DBG("Citation record assignment operator"); + if (this != &rhs) + { + this->citation = rhs.citation; + } + return *this; +} + +CitationRecord::~CitationRecord() +{ + PRINT_DBG("Citation record destructor"); +} + +QString CitationRecord::getCitation() const +{ + return this->citation; +} diff --git a/pool/shard006/C++/0084601_test_chtable.cpp b/pool/shard006/C++/0084601_test_chtable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dfb9b4047e1f256c478eeb8e1be3f88b00772874 --- /dev/null +++ b/pool/shard006/C++/0084601_test_chtable.cpp @@ -0,0 +1,142 @@ +// Copyright (c) 2014, ultramailman +// This file is licensed under the MIT License. + +#include +#include +#include +#include "chtable.hpp" +#include "hash_mixer.hpp" + +static inline unsigned random(unsigned x) +{ + return (x * 16807) % ((2 << 31) - 1); +} + + + +template +struct TableTester{ + std::vector data; + std::vector membership; + cuckoo::Table t; + double maxLoad; + double count; + double capacity; + double totalLoad; + TableTester() + : + data(LENGTH), + membership(LENGTH), + t(LENGTH) + { + unsigned seed = 10; + for(int i = 0; i < LENGTH; i++) + { + seed = random(seed); + data[i] = seed; + membership[i] = 0; + } + + maxLoad = 0; + totalLoad = 0; + } + + clock_t testInsert() + { + clock_t t1 = clock(); + for(unsigned i = 0; i < LENGTH; i++) { + t.Set(data[i], i); + + bool found; + unsigned val; + std::tie(val, found) = t.Get(data[i]); + assert(found); + assert(val == i); + + count = t.count(); + capacity = t.capacity(); + double load = count / capacity; + totalLoad += load; + if(load > maxLoad) + maxLoad = load; + } + clock_t t2 = clock(); + return t2 - t1; + } + clock_t testFind() + { + clock_t t1 = clock(); + for(unsigned i = 0; i < LENGTH; i++) + { + bool found; + unsigned val; + std::tie(val, found) = t.Get(data[i]); + if( !found ) + fputs("find error\n", stderr); + else if( val != i) + fputs("data error 3\n", stderr); + } + clock_t t2 = clock(); + return t2 - t1; + } + + clock_t testDelete() + { + clock_t t1 = clock(); + for(unsigned i = 0; i < LENGTH; i++) + { + bool found; + unsigned val; + std::tie(val, found) = t.Get(data[i]); + if( found ) + { + bool good = t.Delete(data[i]); + assert(good); + std::tie(val, found) = t.Get(data[i]); + if( found ) + puts("removal error"); + } + } + clock_t t2 = clock(); + return t2 - t1; + } + clock_t testIterator() + { + unsigned count = 0; + clock_t t1 = clock(); + for(auto pair : t) + { + unsigned i = pair.val; + if(data[i] != pair.key) + fputs("iterator error\n", stderr); + count++; + } + clock_t t2 = clock(); + assert(count == LENGTH); + return t2 - t1; + } +}; +int main(void) +{ + + TableTester<300000> t; + clock_t insertTime = t.testInsert(); + + std::cout << "count: " << t.count << std::endl << + "capacity: " << t.capacity << std::endl << + "max load: " << t.maxLoad << std::endl << + "current load: " << t.count / t.capacity << std::endl << + "average load: " << t.totalLoad / t.count << std::endl << + "insert time: " << insertTime << std::endl; + + clock_t findTime = t.testFind(); + std::cout << "find time: " << findTime << std::endl; + + clock_t iterTime = t.testIterator(); + std::cout << "iter time: " << iterTime << std::endl; + + clock_t deleteTime = t.testDelete(); + std::cout << "delete time: " << deleteTime << std::endl; + + return 0; + } diff --git a/pool/shard006/C++/0084608_SceneryScatter.cpp b/pool/shard006/C++/0084608_SceneryScatter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b19ec342ce36a97d914436d9929cf6413fda9f53 --- /dev/null +++ b/pool/shard006/C++/0084608_SceneryScatter.cpp @@ -0,0 +1,243 @@ +/***************************************************************************** + * Copyright (c) 2014-2019 OpenRCT2 developers + * + * For a complete list of all authors, please refer to contributors.md + * Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2 + * + * OpenRCT2 is licensed under the GNU General Public License version 3. + *****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include + +enum WINDOW_CLEAR_SCENERY_WIDGET_IDX +{ + WIDX_BACKGROUND, + WIDX_TITLE, + WIDX_CLOSE, + WIDX_PREVIEW, + WIDX_DECREMENT, + WIDX_INCREMENT, + WIDX_DENSITY, + WIDX_DENSITY_LOW, + WIDX_DENSITY_MEDIUM, + WIDX_DENSITY_HIGH +}; + +bool gWindowSceneryScatterEnabled = false; +uint16_t gWindowSceneryScatterSize; +ScatterToolDensity gWindowSceneryScatterDensity; + +// clang-format off +static rct_widget window_scenery_scatter_widgets[] = { + { WWT_FRAME, 1, 0, 85, 0, 99, 0xFFFFFFFF, STR_NONE }, // panel / background + { WWT_CAPTION, 0, 1, 84, 1, 14, STR_SCENERY_SCATTER, STR_WINDOW_TITLE_TIP }, // title bar + { WWT_CLOSEBOX, 0, 73, 83, 2, 13, STR_CLOSE_X, STR_CLOSE_WINDOW_TIP }, // close x button + + { WWT_IMGBTN, 1, 20, 63, 17, 48, SPR_LAND_TOOL_SIZE_0, STR_NONE }, // preview box + { WWT_TRNBTN, 1, 21, 36, 18, 33, IMAGE_TYPE_REMAP | SPR_LAND_TOOL_DECREASE, STR_ADJUST_SMALLER_LAND_TIP }, // decrement size + { WWT_TRNBTN, 1, 47, 62, 32, 47, IMAGE_TYPE_REMAP | SPR_LAND_TOOL_INCREASE, STR_ADJUST_LARGER_LAND_TIP }, // increment size + + { WWT_GROUPBOX, 1, 3, 82, 55, 96, STR_SCATTER_TOOL_DENSITY, STR_NONE }, + { WWT_FLATBTN, 1, 7, 30, 68, 91, IMAGE_TYPE_REMAP | SPR_G2_SCENERY_SCATTER_LOW, STR_SCATTER_TOOL_DENSITY_LOW }, // low amount + { WWT_FLATBTN, 1, 31, 54, 68, 91, IMAGE_TYPE_REMAP | SPR_G2_SCENERY_SCATTER_MEDIUM, STR_SCATTER_TOOL_DENSITY_MEDIUM }, // medium amount + { WWT_FLATBTN, 1, 55, 78, 68, 91, IMAGE_TYPE_REMAP | SPR_G2_SCENERY_SCATTER_HIGH, STR_SCATTER_TOOL_DENSITY_HIGH }, // high amount + { WIDGETS_END }, +}; +// clang-format on + +static void window_scenery_scatter_close(rct_window* w); +static void window_scenery_scatter_mouseup(rct_window* w, rct_widgetindex widgetIndex); +static void window_scenery_scatter_mousedown(rct_window* w, rct_widgetindex widgetIndex, rct_widget* widget); +static void window_scenery_scatter_invalidate(rct_window* w); +static void window_scenery_scatter_paint(rct_window* w, rct_drawpixelinfo* dpi); +static void window_scenery_scatter_textinput(rct_window* w, rct_widgetindex widgetIndex, char* text); +static void window_scenery_scatter_inputsize(rct_window* w, rct_widgetindex widgetindex); + +// clang-format off +static rct_window_event_list window_clear_scenery_events = { + window_scenery_scatter_close, + window_scenery_scatter_mouseup, + nullptr, + window_scenery_scatter_mousedown, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + window_scenery_scatter_textinput, + nullptr, + nullptr, + nullptr, + nullptr, + nullptr, + window_scenery_scatter_invalidate, + window_scenery_scatter_paint, + nullptr +}; +// clang-format on + +rct_window* window_scenery_scatter_open() +{ + rct_window* window; + + // Check if window is already open + window = window_find_by_class(WC_SCENERY_SCATTER); + if (window != nullptr) + return window; + + window = window_create_auto_pos(86, 100, &window_clear_scenery_events, WC_SCENERY_SCATTER, 0); + + window->widgets = window_scenery_scatter_widgets; + window->enabled_widgets = (1 << WIDX_CLOSE) | (1 << WIDX_INCREMENT) | (1 << WIDX_DECREMENT) | (1 << WIDX_PREVIEW) + | (1 << WIDX_DENSITY_LOW) | (1 << WIDX_DENSITY_MEDIUM) | (1 << WIDX_DENSITY_HIGH); + window->hold_down_widgets = (1 << WIDX_INCREMENT) | (1 << WIDX_DECREMENT); + window_init_scroll_widgets(window); + window_push_others_below(window); + + gWindowSceneryScatterEnabled = true; + gWindowSceneryScatterSize = 16; + gWindowSceneryScatterDensity = ScatterToolDensity::MediumDensity; + + return window; +} + +static void window_scenery_scatter_close([[maybe_unused]] rct_window* w) +{ + gWindowSceneryScatterEnabled = false; +} + +static void window_scenery_scatter_mouseup(rct_window* w, rct_widgetindex widgetIndex) +{ + switch (widgetIndex) + { + case WIDX_CLOSE: + window_close(w); + break; + + case WIDX_PREVIEW: + window_scenery_scatter_inputsize(w, widgetIndex); + break; + + case WIDX_DENSITY_LOW: + gWindowSceneryScatterDensity = ScatterToolDensity::LowDensity; + break; + + case WIDX_DENSITY_MEDIUM: + gWindowSceneryScatterDensity = ScatterToolDensity::MediumDensity; + break; + + case WIDX_DENSITY_HIGH: + gWindowSceneryScatterDensity = ScatterToolDensity::HighDensity; + break; + } +} + +static void window_scenery_scatter_mousedown(rct_window* w, rct_widgetindex widgetIndex, [[maybe_unused]] rct_widget* widget) +{ + switch (widgetIndex) + { + case WIDX_DECREMENT: + // Decrement land tool size, if it stays within the limit + gWindowSceneryScatterSize = std::max(MINIMUM_TOOL_SIZE, gWindowSceneryScatterSize - 1); + w->Invalidate(); + break; + + case WIDX_INCREMENT: + // Increment land tool size, if it stays within the limit + gWindowSceneryScatterSize = std::min(MAXIMUM_TOOL_SIZE, gWindowSceneryScatterSize + 1); + w->Invalidate(); + break; + } +} + +static void window_scenery_scatter_textinput(rct_window* w, rct_widgetindex widgetIndex, char* text) +{ + int32_t size; + char* end; + + if (widgetIndex != WIDX_PREVIEW || text == nullptr) + return; + + size = strtol(text, &end, 10); + if (*end == '\0') + { + switch (widgetIndex) + { + case WIDX_PREVIEW: + size = std::max(MINIMUM_TOOL_SIZE, size); + size = std::min(MAXIMUM_TOOL_SIZE, size); + gWindowSceneryScatterSize = size; + break; + } + w->Invalidate(); + } +} + +static void window_scenery_scatter_inputsize(rct_window* w, rct_widgetindex widgetindex) +{ + uint8_t maxlen = 0; + switch (widgetindex) + { + case WIDX_PREVIEW: + TextInputDescriptionArgs[0] = MINIMUM_TOOL_SIZE; + TextInputDescriptionArgs[1] = MAXIMUM_TOOL_SIZE; + maxlen = 3; + break; + } + window_text_input_open(w, widgetindex, STR_SELECTION_SIZE, STR_ENTER_SELECTION_SIZE, STR_NONE, STR_NONE, maxlen); +} + +static void window_scenery_scatter_invalidate(rct_window* w) +{ + // Set the preview image button to be pressed down + w->pressed_widgets = (1 << WIDX_PREVIEW); + + // Set density buttons' pressed state. + switch (gWindowSceneryScatterDensity) + { + case ScatterToolDensity::LowDensity: + w->pressed_widgets |= (1 << WIDX_DENSITY_LOW); + break; + + case ScatterToolDensity::MediumDensity: + w->pressed_widgets |= (1 << WIDX_DENSITY_MEDIUM); + break; + + case ScatterToolDensity::HighDensity: + w->pressed_widgets |= (1 << WIDX_DENSITY_HIGH); + break; + } + + // Update the preview image (for tool sizes up to 7) + window_scenery_scatter_widgets[WIDX_PREVIEW].image = land_tool_size_to_sprite_index(gWindowSceneryScatterSize); +} + +static void window_scenery_scatter_paint(rct_window* w, rct_drawpixelinfo* dpi) +{ + window_draw_widgets(w, dpi); + + // Draw area as a number for tool sizes bigger than 7 + if (gWindowSceneryScatterSize > MAX_TOOL_SIZE_WITH_SPRITE) + { + auto preview = window_scenery_scatter_widgets[WIDX_PREVIEW]; + int32_t x = w->x + (preview.left + preview.right) / 2; + int32_t y = w->y + (preview.top + preview.bottom) / 2; + gfx_draw_string_centred(dpi, STR_LAND_TOOL_SIZE_VALUE, x, y - 2, COLOUR_BLACK, &gWindowSceneryScatterSize); + } +} diff --git a/pool/shard006/C++/0084610_knn_simple.cpp b/pool/shard006/C++/0084610_knn_simple.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f029f6e3965eef9ac0ad94ad15364066f3d6c992 --- /dev/null +++ b/pool/shard006/C++/0084610_knn_simple.cpp @@ -0,0 +1,99 @@ +/*************************************************************************** + * Copyright (C) 2010, 2011, 2012 by Leandro Graciá Gil * + * leandro.gracia.gil@gmail.com * + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License * + * along with this program; if not, write to the * + * Free Software Foundation, Inc., * + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * + ***************************************************************************/ + +/** + * \file knn_simple.cpp + * \brief Example program to show how to perform a simple K-Nearest Neighbour search using kche-tree. + * \author Leandro Graciá Gil + */ + +// C and C++ Standard Library includes. +#include +#include +#include +#include + +// Include the kche-tree templates. +#include "kche-tree/kche-tree.h" + +using namespace kche_tree; +using namespace std; + +// Data type and number of dimensions to use in this example. +typedef float Type; +const unsigned int Dimensions = 24; + +// Alias for the specific KDTree and data set types being used. +typedef KDTree KDTreeTest; +typedef DataSet DataSetTest; + +int main(int argc, char *argv[]) { + + // Initialize the random seed. + DefaultRandomEngine random_engine; + random_engine.seed(time(NULL)); + + // Create a uniform distribution between -100 and 100. + typedef Traits::UniformDistribution UniformDistribution; + UniformDistribution value_distribution(-100.0f, 100.0f); + + // Bind them together into a random number generator. Use operator () to get random numbers. + RandomGenerator generator(random_engine, value_distribution); + + // Generate 500000 random feature vectors for training. + DataSetTest train_set(500000); + train_set.set_random_values(generator); + + // Create and build a new kd-tree with the training set. + KDTreeTest kdtree; + kdtree.build(train_set); + + // Generate 5 random feature vectors for testing. + DataSetTest test_set(5); + test_set.set_random_values(generator); + + // Set the number of neighbours to retrieve. + const unsigned int K = 3; + + // For each test case... + for (unsigned int i=0; i(test_set[i], K, neighbors, EuclideanMetric()); + #else + kdtree.knn(test_set[i], K, neighbors); + #endif + + // Print distances to the K nearest neighbours. + cout << "Distance to the " << K << " nearest neighbours in test case " << (i + 1) << ": "; + cout << fixed; + for (unsigned int k=0; k +#include +#include +#include +#include +#include +#include + +using namespace std; + +struct Edge { + int v, w; + int weight; +}; + +struct Graph { + + Graph(int v): adjList(v), degree(v, 0) { + nV = v; + } + + void addEdge(Edge *e) { + adjList[e->v].push_back(e); + adjList[e->w].push_back(e); + + degree[e->v] += e->weight; + degree[e->w] += e->weight; + } + + int nV; + vector> adjList; + vector degree; +}; + +struct DFS { + + DFS(Graph *g) { + this->g = g; + isVisited = new bool[g->nV]; + memset(isVisited, 0, sizeof(bool) * g->nV); + + for (int i=0; inV; ++i) { + if (!isVisited[i]) { + set comp; + dfs(i, comp); + components.push_back(comp); + } + } + } + + void dfs(int v, set &comp) { + comp.insert(v); + isVisited[v] = true; + vector &adj = g->adjList[v]; + for (int i=0; iv == v ? e->w : e->v; + if (!isVisited[w]) { + dfs(w, comp); + } + } + } + + Graph *g; + vector> components; + bool *isVisited; +}; + +int main(int argc, const char * argv[]) +{ + int nRecord, threshold; + scanf("%d %d", &nRecord, &threshold); + + map nameTable; + vector names; + vector edges; + for (int i=0; i> a >> b >> e->weight; + + map::iterator it = nameTable.find(a); + if (it == nameTable.end()) { + e->v = static_cast(names.size()); + nameTable.insert(pair(a, e->v)); + names.push_back(a); + } else { + e->v = it->second; + } + it = nameTable.find(b); + if (it == nameTable.end()) { + e->w = static_cast(names.size()); + nameTable.insert(pair(b, e->w)); + names.push_back(b); + } else { + e->w = it->second; + } + + edges.push_back(e); + } + + Graph *g = new Graph(static_cast(names.size())); + for (int i=0; iaddEdge(edges[i]); + } + + DFS dfs(g); + vector> result; + for (int i=0; i &comp = dfs.components[i]; + if (comp.size() <= 2) continue; + int sum = 0; + int maxPos = -1; + int max = INT32_MIN; + for (set::iterator it=comp.begin(); it!=comp.end(); ++it) { + int degree = g->degree[*it]; + sum += degree; + if (degree > max) { + max = degree; + maxPos = *it; + } + } + sum /= 2; + if (sum > threshold) { + result.push_back(pair(names[maxPos], comp.size())); + } + } + + printf("%ld\n", result.size()); + sort(result.begin(), result.end()); + for (int i=0; i + +// Copyright (C) 2001-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library 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 library; see the file COPYING3. If not see +// . + +// 22.2.6.1.1 money_get members + +#include +#include +#include + +// test double version +void test03() +{ + using namespace std; + typedef istreambuf_iterator iterator_type; + + // basic construction + locale loc_c = locale::classic(); + locale loc_de = locale(ISO_8859(15,de_DE)); + VERIFY( loc_c != loc_de ); + + // total EPA budget FY 2002 + const long double digits1 = 720000000000.0; + + iterator_type end; + wistringstream iss; + iss.imbue(loc_de); + // cache the money_get facet + const money_get& mon_get = use_facet >(iss.getloc()); + + iss.str(L"7.200.000.000,00 "); + iterator_type is_it01(iss); + long double result1; + ios_base::iostate err01 = ios_base::goodbit; + mon_get.get(is_it01, end, true, iss, err01, result1); + VERIFY( result1 == digits1 ); + VERIFY( err01 == ios_base::eofbit ); + + iss.str(L"7.200.000.000,00 "); + iterator_type is_it02(iss); + long double result2; + ios_base::iostate err02 = ios_base::goodbit; + mon_get.get(is_it02, end, false, iss, err02, result2); + VERIFY( result2 == digits1 ); + VERIFY( err02 == ios_base::eofbit ); +} + +int main() +{ + test03(); + return 0; +} diff --git a/pool/shard006/C++/0084625_qdocumentfn.cpp b/pool/shard006/C++/0084625_qdocumentfn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c7dd82e651fcbadb76c792c2eb355928bd822d7 --- /dev/null +++ b/pool/shard006/C++/0084625_qdocumentfn.cpp @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the QtXmlPatterns module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the Technology Preview License Agreement accompanying +** this package. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +** +** +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qforclause_p.h" +#include "qfunctionfactory_p.h" +#include "qrangevariablereference_p.h" + +#include "qdocumentfn_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +Expression::Ptr DocumentFN::typeCheck(const StaticContext::Ptr &context, + const SequenceType::Ptr &reqType) +{ + /* See the class documentation for the rewrite that we're doing here. */ + + /* Generate type checking code for our operands such that they match. */ + typeCheckOperands(context); + + const QSourceLocation myLocation(context->locationFor(this)); + const FunctionFactory::Ptr functions(context->functionSignatures()); + + Expression::Ptr uriSource; + + { + Expression::List distinctValuesArgs; + distinctValuesArgs.append(m_operands.first()); + + uriSource = functions->createFunctionCall(QXmlName(StandardNamespaces::fn, StandardLocalNames::distinct_values), + distinctValuesArgs, + context, + this); + context->addLocation(uriSource.data(), myLocation); + } + + const VariableSlotID rangeSlot = context->allocateRangeSlot(); + const Expression::Ptr uriReference(new RangeVariableReference(uriSource, rangeSlot)); + context->addLocation(uriReference.data(), myLocation); + + Expression::List docArgs; + + if(m_operands.count() == 2) + { + Expression::List baseUriArgs; + baseUriArgs.append(uriReference); + baseUriArgs.append(m_operands.at(1)); + + const Expression::Ptr fnBaseUri(functions->createFunctionCall(QXmlName(StandardNamespaces::fn, StandardLocalNames::resolve_uri), + baseUriArgs, + context, + this)); + context->addLocation(fnBaseUri.data(), myLocation); + docArgs.append(fnBaseUri); + } + else + docArgs.append(uriReference); + + const Expression::Ptr fnDoc(functions->createFunctionCall(QXmlName(StandardNamespaces::fn, StandardLocalNames::doc), + docArgs, + context, + this)); + context->addLocation(fnDoc.data(), myLocation); + + + Expression::Ptr newMe(new ForClause(rangeSlot, + uriSource, + fnDoc, + -1 /* We have no position variable. */)); + + Expression::Ptr oldMe(this); + rewrite(oldMe, newMe, context); + return newMe->typeCheck(context, reqType); +} + +QT_END_NAMESPACE diff --git a/pool/shard006/C++/0084629_function.cpp b/pool/shard006/C++/0084629_function.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dcca9eb1729b02300d33c8be81699021fbe437cf --- /dev/null +++ b/pool/shard006/C++/0084629_function.cpp @@ -0,0 +1,133 @@ +#include +#include +#include "defs.h" +#include "function.h" +#include "colorspace.h" + +extern uint32_t g_target; +extern uint32_t g_global; +extern uint32_t g_ticks_per_frame; +extern uint32_t g_random_seed; +void set_led(uint8_t index, color_t *col); +void get_led(uint8_t index, color_t *col); +void adjust_led_brightness(uint8_t delta); +uint32_t ticks_to_ms(uint32_t ticks); +uint32_t ms_to_ticks(uint32_t ms); + +void p_error(int32_t t, uint8_t *data, uint8_t len) +{ + color_t col; + + col.r = col.g = col.b = 0; + if ((t / 2) % 2 == 0) + { + col.r = 128; + set_led(1, &col); + set_led(2, &col); + } + else + { + set_led(1, &col); + set_led(2, &col); + } +} + +void p_fade_to(int32_t t, uint8_t *data, uint8_t len) +{ + static color_t start_cols[NUM_LEDS], r_target; + int32_t delta_r, delta_g, delta_b; + uint8_t i; + color_t target, col, first_col; + + first_col.r = first_col.g = first_col.b = 0; + + // Save the current color if we're starting + if (t == 0) + { + for(i = 0; i < NUM_LEDS; i++) + get_led(i, &start_cols[i]); + + if (len == sizeof(uint16_t)) + hsv_to_rgb(rand() % SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR, &r_target); + + return; + } + + int32_t duration_ms = *((uint16_t *)data); + int32_t duration = ms_to_ticks(duration_ms); + data += sizeof(uint16_t); + + // If we're at the end of the pattern, bail + if (t > duration) + { + g_target = 0; + return; + } + + for(i = 0; i < NUM_LEDS; i++) + { + if (len == sizeof(uint16_t)) + target = r_target; + else + if ((i * 3) < (len - sizeof(uint16_t))) + { + target.r = *((uint8_t *)data); + data += sizeof(uint8_t); + target.g = *((uint8_t *)data); + data += sizeof(uint8_t); + target.b = *((uint8_t *)data); + data += sizeof(uint8_t); + } + else + target = first_col; + + if (i == 0) + first_col = target; + + delta_r = (target.r - start_cols[i].r); + delta_g = (target.g - start_cols[i].g); + delta_b = (target.b - start_cols[i].b); + + int32_t step = t * SCALE_FACTOR / duration; + col.r = start_cols[i].r + (delta_r * step) / SCALE_FACTOR; + col.g = start_cols[i].g + (delta_g * step) / SCALE_FACTOR; + col.b = start_cols[i].b + (delta_b * step) / SCALE_FACTOR; + + set_led(i, &col); + } +} + +void p_rainbow(int32_t t, uint8_t *data, uint8_t len) +{ + int8_t divisor = *data, i; + int32_t offset = t / divisor; + color_t col; + + for(i = 0; i < NUM_LEDS; i++) + { + hsv_to_rgb((offset + (250 * i) + (g_random_seed % SCALE_FACTOR)) % SCALE_FACTOR, SCALE_FACTOR, SCALE_FACTOR, &col); + set_led(i, &col); + } +} + +void p_decay(int32_t t, uint8_t *data, uint8_t len) +{ + int8_t decr = *data; + adjust_led_brightness(decr); +} + +void apply_pattern(int32_t t, uint8_t *data, uint8_t len) +{ + switch(*data) + { + case 0: + p_fade_to(t, data + 1, len - 1); + break; + case 1: + p_rainbow(t, data + 1, len - 1); + break; + case 2: + p_decay(t, data + 1, len - 1); + break; + } +} diff --git a/pool/shard006/C++/0084631_zone_hinterlands.cpp b/pool/shard006/C++/0084631_zone_hinterlands.cpp new file mode 100644 index 0000000000000000000000000000000000000000..811a05655f60524cc88dc49d9f229b54139bf37b --- /dev/null +++ b/pool/shard006/C++/0084631_zone_hinterlands.cpp @@ -0,0 +1,154 @@ +/* + * Copyright (C) 2011-2015 Project SkyFire + * Copyright (C) 2008-2015 TrinityCore + * Copyright (C) 2005-2015 MaNGOS + * Copyright (C) 2006-2014 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 3 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +/* ScriptData +SDName: Hinterlands +SD%Complete: 100 +SDComment: Quest support: 836 +SDCategory: The Hinterlands +EndScriptData */ + +/* ContentData +npc_00x09hl +EndContentData */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "ScriptedEscortAI.h" +#include "Player.h" + +/*###### +## npc_00x09hl +######*/ + +enum eOOX +{ + SAY_OOX_START = 0, + SAY_OOX_AGGRO = 1, + SAY_OOX_AMBUSH = 3, + SAY_OOX_AMBUSH_REPLY = 4, + SAY_OOX_END = 5, + + QUEST_RESQUE_OOX_09 = 836, + + NPC_MARAUDING_OWL = 7808, + NPC_VILE_AMBUSHER = 7809, + + FACTION_ESCORTEE_A = 774, + FACTION_ESCORTEE_H = 775 +}; + +class npc_00x09hl : public CreatureScript +{ +public: + npc_00x09hl() : CreatureScript("npc_00x09hl") { } + + bool OnQuestAccept(Player* player, Creature* creature, const Quest* quest) + { + if (quest->GetQuestId() == QUEST_RESQUE_OOX_09) + { + creature->SetStandState(UNIT_STAND_STATE_STAND); + + if (player->GetTeam() == ALLIANCE) + creature->setFaction(FACTION_ESCORTEE_A); + else if (player->GetTeam() == HORDE) + creature->setFaction(FACTION_ESCORTEE_H); + + creature->AI()->Talk(SAY_OOX_START, player); + + if (npc_00x09hlAI* pEscortAI = CAST_AI(npc_00x09hl::npc_00x09hlAI, creature->AI())) + pEscortAI->Start(false, false, player->GetGUID(), quest); + } + return true; + } + + CreatureAI* GetAI(Creature* creature) const OVERRIDE + { + return new npc_00x09hlAI(creature); + } + + struct npc_00x09hlAI : public npc_escortAI + { + npc_00x09hlAI(Creature* creature) : npc_escortAI(creature) { } + + void Reset() OVERRIDE { } + + void WaypointReached(uint32 waypointId) + { + switch (waypointId) + { + case 26: + Talk(SAY_OOX_AMBUSH); + break; + case 43: + Talk(SAY_OOX_AMBUSH); + break; + case 64: + Talk(SAY_OOX_END); + if (Player* player = GetPlayerForEscort()) + player->GroupEventHappens(QUEST_RESQUE_OOX_09, me); + break; + } + } + + void WaypointStart(uint32 uiPointId) + { + switch (uiPointId) + { + case 27: + for (uint8 i = 0; i < 3; ++i) + { + const Position src = {147.927444f, -3851.513428f, 130.893f, 0}; + Position dst; + me->GetRandomPoint(src, 7.0f, dst); + DoSummon(NPC_MARAUDING_OWL, dst, 25000, TEMPSUMMON_CORPSE_TIMED_DESPAWN); + } + break; + case 44: + for (uint8 i = 0; i < 3; ++i) + { + const Position src = {-141.151581f, -4291.213867f, 120.130f, 0}; + Position dst; + me->GetRandomPoint(src, 7.0f, dst); + me->SummonCreature(NPC_VILE_AMBUSHER, dst, TEMPSUMMON_CORPSE_TIMED_DESPAWN, 25000); + } + break; + } + } + + void EnterCombat(Unit* who) + { + if (who->GetEntry() == NPC_MARAUDING_OWL || who->GetEntry() == NPC_VILE_AMBUSHER) + return; + + Talk(SAY_OOX_AGGRO); + } + + void JustSummoned(Creature* summoned) OVERRIDE + { + summoned->GetMotionMaster()->MovePoint(0, me->GetPositionX(), me->GetPositionY(), me->GetPositionZ()); + } + }; +}; + +void AddSC_hinterlands() +{ + new npc_00x09hl(); +} diff --git a/pool/shard006/C++/0084634_TableComments.cc b/pool/shard006/C++/0084634_TableComments.cc new file mode 100644 index 0000000000000000000000000000000000000000..eb4f40cdd8938bc8c75c40e4046e84a094ae6ec1 --- /dev/null +++ b/pool/shard006/C++/0084634_TableComments.cc @@ -0,0 +1,119 @@ +// +------------------------------------------------------------------+ +// | ____ _ _ __ __ _ __ | +// | / ___| |__ ___ ___| | __ | \/ | |/ / | +// | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | +// | | |___| | | | __/ (__| < | | | | . \ | +// | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | +// | | +// | Copyright Mathias Kettner 2014 mk@mathias-kettner.de | +// +------------------------------------------------------------------+ +// +// This file is part of Check_MK. +// The official homepage is at http://mathias-kettner.de/check_mk. +// +// check_mk 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 in version 2. check_mk is distributed +// in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- +// out even the implied warranty of MERCHANTABILITY or FITNESS FOR A +// PARTICULAR PURPOSE. See the GNU General Public License for more de- +// tails. You should have received a copy of the GNU General Public +// License along with GNU Make; see the file COPYING. If not, write +// to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, +// Boston, MA 02110-1301 USA. + +#include "TableComments.h" +#include +#include +#include "DowntimeOrComment.h" +#include "DowntimesOrComments.h" // IWYU pragma: keep +#include "OffsetIntColumn.h" +#include "OffsetSStringColumn.h" +#include "OffsetTimeColumn.h" +#include "Query.h" +#include "TableHosts.h" +#include "TableServices.h" +#include "auth.h" + +using std::string; + +// TODO(sp): the dynamic data in this table must be locked with a mutex + +TableComments::TableComments(const DowntimesOrComments &downtimes_holder, + const DowntimesOrComments &comments_holder, + Logger *logger) + : Table(logger), _holder(comments_holder) { + Comment *ref = nullptr; + addColumn(new OffsetSStringColumn( + "author", "The contact that entered the comment", + reinterpret_cast(&(ref->_author_name)) - + reinterpret_cast(ref))); + addColumn( + new OffsetSStringColumn("comment", "A comment text", + reinterpret_cast(&(ref->_comment)) - + reinterpret_cast(ref))); + addColumn(new OffsetIntColumn( + "id", "The id of the comment", + reinterpret_cast(&(ref->_id)) - reinterpret_cast(ref))); + addColumn(new OffsetTimeColumn( + "entry_time", "The time the entry was made as UNIX timestamp", + reinterpret_cast(&(ref->_entry_time)) - + reinterpret_cast(ref))); + addColumn(new OffsetIntColumn( + "type", "The type of the comment: 1 is host, 2 is service", + reinterpret_cast(&(ref->_type)) - + reinterpret_cast(ref))); + addColumn(new OffsetIntColumn( + "is_service", + "0, if this entry is for a host, 1 if it is for a service", + reinterpret_cast(&(ref->_is_service)) - + reinterpret_cast(ref))); + + addColumn(new OffsetIntColumn( + "persistent", "Whether this comment is persistent (0/1)", + reinterpret_cast(&(ref->_persistent)) - + reinterpret_cast(ref))); + addColumn(new OffsetIntColumn( + "source", "The source of the comment (0 is internal and 1 is external)", + reinterpret_cast(&(ref->_source)) - + reinterpret_cast(ref))); + addColumn( + new OffsetIntColumn("entry_type", + "The type of the comment: 1 is user, 2 is " + "downtime, 3 is flap and 4 is acknowledgement", + reinterpret_cast(&(ref->_entry_type)) - + reinterpret_cast(ref))); + addColumn(new OffsetIntColumn("expires", "Whether this comment expires", + reinterpret_cast(&(ref->_expires)) - + reinterpret_cast(ref))); + addColumn(new OffsetTimeColumn( + "expire_time", "The time of expiry of this comment as a UNIX timestamp", + reinterpret_cast(&(ref->_expire_time)) - + reinterpret_cast(ref))); + + TableHosts::addColumns( + this, "host_", + reinterpret_cast(&(ref->_host)) - reinterpret_cast(ref), + -1, downtimes_holder, comments_holder); + TableServices::addColumns( + this, "service_", reinterpret_cast(&(ref->_service)) - + reinterpret_cast(ref), + false /* no hosts table */, downtimes_holder, comments_holder); +} + +string TableComments::name() const { return "comments"; } + +string TableComments::namePrefix() const { return "comment_"; } + +void TableComments::answerQuery(Query *query) { + for (const auto &entry : _holder) { + if (!query->processDataset(entry.second.get())) { + break; + } + } +} + +bool TableComments::isAuthorized(contact *ctc, void *data) { + DowntimeOrComment *dtc = static_cast(data); + return is_authorized_for(ctc, dtc->_host, dtc->_service); +} diff --git a/pool/shard006/C++/0084635_qgsscalecombobox.cpp b/pool/shard006/C++/0084635_qgsscalecombobox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0a17eea4e9444046a5af97137200004cde0af9a --- /dev/null +++ b/pool/shard006/C++/0084635_qgsscalecombobox.cpp @@ -0,0 +1,96 @@ +/*************************************************************************** + qgsscalecombobox.h + ------------------------ + begin : January 7, 2012 + copyright : (C) 2012 by Alexander Bruy + email : alexander dot bruy at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgis.h" +#include "qgsscalecombobox.h" + +#include +#include + +QgsScaleComboBox::QgsScaleComboBox( QWidget* parent ) : QComboBox( parent ) +{ + updateScales(); + + setEditable( true ); + setInsertPolicy( QComboBox::NoInsert ); + setCompleter( 0 ); +} + +QgsScaleComboBox::~QgsScaleComboBox() +{ +} + +void QgsScaleComboBox::updateScales( const QStringList &scales ) +{ + QStringList myScalesList; + QString oldScale = currentText(); + + if ( scales.isEmpty() ) + { + QSettings settings; + QString myScales = settings.value( "Map/scales", PROJECT_SCALES ).toString(); + if ( !myScales.isEmpty() ) + { + myScalesList = myScales.split( "," ); + } + } + else + { + QStringList::const_iterator scaleIt = scales.constBegin(); + for ( ; scaleIt != scales.constEnd(); ++scaleIt ) + { + myScalesList.append( *scaleIt ); + } + } + + blockSignals( true ); + clear(); + addItems( myScalesList ); + setEditText( oldScale ); + blockSignals( false ); +} + +void QgsScaleComboBox::showPopup() +{ + QComboBox::showPopup(); + + if ( !currentText().contains( ':' ) ) + { + return; + } + QStringList parts = currentText().split( ':' ); + bool ok; + int idx = 0; + int min = 999999; + long currScale = parts.at( 1 ).toLong( &ok ); + long nextScale, delta; + for ( int i = 0; i < count(); i++ ) + { + parts = itemText( i ).split( ':' ); + nextScale = parts.at( 1 ).toLong( &ok ); + delta = qAbs( currScale - nextScale ); + if ( delta < min ) + { + min = delta; + idx = i; + } + } + + blockSignals( true ); + view()->setCurrentIndex( model()->index( idx, 0 ) ); + blockSignals( false ); +} diff --git a/pool/shard006/C++/0084638_framestackitem.cpp b/pool/shard006/C++/0084638_framestackitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e4e22f1d1684f32eb596493d2b8709946c45e4d2 --- /dev/null +++ b/pool/shard006/C++/0084638_framestackitem.cpp @@ -0,0 +1,136 @@ +/* + * GDB Debugger Support + * + * Copyright 1999 John Birch + * Copyright 2006 Vladimir Prus + * Copyright 2007 Hamish Rodda + * + * 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 "framestackitem.h" + +#include + +#include "threaditem.h" +#include "stackmanager.h" + +using namespace GDBMI; +using namespace GDBDebugger; + +FrameStackItem::FrameStackItem(ThreadItem* thread, int frame) + : QObject(thread) + , m_frame(frame) + , m_dirty(true) + , m_refreshRequested(false) + , m_level(-1) + , m_function(i18n("")) + , m_sourceLine(-1) +{ +} + +ThreadItem* FrameStackItem::thread() const +{ + return static_cast(const_cast(parent())); +} + +int FrameStackItem::frame() const +{ + return m_frame; +} + +void FrameStackItem::parseFrame(const GDBMI::Value& frame) +{ + m_dirty = false; + m_refreshRequested = false; + + m_level = frame["level"].literal().toInt(); + + if (frame.hasField("func")) + m_function = frame["func"].literal(); + + if (frame.hasField("address")) + m_address = frame["address"].literal().toULongLong(); + + if (frame.hasField("file")) + { + m_source = frame["file"].literal(); + + if (frame.hasField("line")) + { + m_sourceLine = frame["line"].literal().toInt(); + } + } + else if (frame.hasField("from")) + { + m_source = frame["from"].literal(); + } + + stackManager()->dataChanged(this); +} + +QString GDBDebugger::FrameStackItem::function() const +{ + return m_function; +} + +QString GDBDebugger::FrameStackItem::sourceString() const +{ + if (m_sourceLine != -1) + return QString("%1:%2").arg(m_source).arg(m_sourceLine); + + return m_source; +} + +int GDBDebugger::FrameStackItem::sourceLine() const +{ + return m_sourceLine; +} + +StackManager* FrameStackItem::stackManager() const +{ + return thread()->stackManager(); +} + +bool GDBDebugger::FrameStackItem::isDirty() const +{ + return m_dirty; +} + +bool GDBDebugger::FrameStackItem::isRefreshRequested() const +{ + return m_refreshRequested; +} + +void GDBDebugger::FrameStackItem::setRefreshRequested() +{ + m_refreshRequested = true; +} + +void FrameStackItem::refresh() +{ + if (m_refreshRequested) + return; + + // Refresh in 5 frame blocks + int from = frame() - (frame() % 5); + int to = from + 4; + thread()->refreshFrames(from, to); + + Q_ASSERT(m_refreshRequested); +} + +#include "framestackitem.moc" diff --git a/pool/shard006/C++/0084639_AP_RCProtocol_FPort2.cpp b/pool/shard006/C++/0084639_AP_RCProtocol_FPort2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..955e1464d84a824ecbc8fe67fe28932926bda587 --- /dev/null +++ b/pool/shard006/C++/0084639_AP_RCProtocol_FPort2.cpp @@ -0,0 +1,296 @@ +/* + * This file is free software: you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This file is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ +/* + FRSky FPort2 implementation, with thanks to FrSky for + specification + */ + +#include "AP_RCProtocol_FPort2.h" +#include +#include +#include +#include +#include +#include + +extern const AP_HAL::HAL& hal; + +#define FRAME_LEN_16 0x18 +#define FRAME_LEN_8 0x0D +#define FRAME_LEN_24 0x23 +#define FRAME_LEN_DOWNLINK 0x08 + +#define FRAME_TYPE_CHANNEL 0xFF +#define FRAME_TYPE_FC 0x1B + +#define MAX_CHANNELS 24 + +#define FLAGS_FAILSAFE_BIT 3 +#define FLAGS_FRAMELOST_BIT 2 + +#define CHAN_SCALE_FACTOR1 1000U +#define CHAN_SCALE_FACTOR2 1600U +#define CHAN_SCALE_OFFSET 875U + +#define FPORT2_PRIM_NULL 0x00 +#define FPORT2_PRIM_READ 0x30 +#define FPORT2_PRIM_WRITE 0x31 + +struct PACKED FPort2_Frame { + uint8_t len; + uint8_t type; + union { + uint8_t data[36]; + struct PACKED { + uint8_t prim; + uint16_t appid; + uint8_t data[4]; + uint8_t crc; + } downlink; + }; +}; + +static_assert(sizeof(FPort2_Frame) == FPORT2_CONTROL_FRAME_SIZE, "FPort2_Frame incorrect size"); + +// constructor +AP_RCProtocol_FPort2::AP_RCProtocol_FPort2(AP_RCProtocol &_frontend, bool _inverted) : + AP_RCProtocol_Backend(_frontend), + inverted(_inverted) +{} + +// decode a full FPort2 control frame +void AP_RCProtocol_FPort2::decode_control(const FPort2_Frame &frame) +{ + uint16_t values[MAX_CHANNELS]; + + decode_11bit_channels(frame.data, chan_count, values, CHAN_SCALE_FACTOR1, CHAN_SCALE_FACTOR2, CHAN_SCALE_OFFSET); + + const uint8_t b_flags = frame.data[byte_input.control_len-5]; + const uint8_t b_rssi = frame.data[byte_input.control_len-4]; + + bool failsafe = ((b_flags & (1 << FLAGS_FAILSAFE_BIT)) != 0); + + // fport2 rssi 0-50, ardupilot rssi 0-255, scale factor 255/50=5.1 + const uint8_t scaled_rssi = MIN(b_rssi * 5.1f, 255); + + add_input(chan_count, values, failsafe, scaled_rssi); +} + +/* + decode a full FPort2 downlink frame +*/ +void AP_RCProtocol_FPort2::decode_downlink(const FPort2_Frame &frame) +{ +#if !APM_BUILD_TYPE(APM_BUILD_iofirmware) + /* + if we are getting FPORT2 over a UART then we can ask the FrSky + telem library for some passthrough data to send back, enabling + telemetry on the receiver via the same uart pin as we use for + incoming RC frames + */ + + AP_HAL::UARTDriver *uart = get_UART(); + if (!uart) { + return; + } + + // no telemetry for 24ch fport2, timing is too tight + if (chan_count > 16) { + return; + } + +#if HAL_WITH_FRSKY_TELEM_BIDIRECTIONAL + // 0x30,0x31 read/write frames + // allowed reply prim: 0x00,0x32 + if (frame.downlink.prim == FPORT2_PRIM_READ || frame.downlink.prim == FPORT2_PRIM_WRITE) { + AP_Frsky_Telem::set_telem_data(frame.downlink.prim, frame.downlink.appid, le32toh_ptr(frame.downlink.data)); + } +#endif //HAL_WITH_FRSKY_TELEM_BIDIRECTIONAL + + /* + we're only interested in "flight controller" requests i.e. 0x1B + Notes: + need to check how to handle multiple sensor IDs (we probably should respond to 0x1E as well) + with fport2 we need to account for the IDs we send sensor data from + if we respond to multiple sensors like we do for sport we need to make sure GPS data + is always sent with the same sensor ID or else OpenTX will see multiple sensor instances (one for each sensor we respond to) + (need to double check on OpenTX if fport2 carries sensor IDs up to the OpenTX sensor tables) + */ + if (frame.type != FRAME_TYPE_FC) { + /* + get SPort data from FRSky_Telem + when we are not polled for data we prepare telemetry data for the next poll + we save the data to a variable so in case we're late we'll + send it in the next call, this prevents corruption of status text messages + */ + if (!telem_data.available) { + uint8_t packet_count; + if (!AP_Frsky_Telem::get_telem_data(&telem_data.packet, packet_count, 1)) { + telem_data.packet.frame = 0x00; + telem_data.packet.appid = 0x00; + telem_data.packet.data = 0x00; + } + telem_data.available = true; + } + return; + } + + /* + check that we haven't been too slow in responding to the new + UART data. If we respond too late then we will corrupt the next + incoming control frame. + 16ch fport2: 4.5ms window before next control frame + specs require to release the bus at least 1.5ms before next control frame (uplink frame takes 0.851ms) + */ + uint64_t tend = uart->receive_time_constraint_us(1); + uint64_t now = AP_HAL::micros64(); + uint64_t tdelay = now - tend; + if (tdelay > 2500) { + // we've been too slow in responding + return; + } + + // we initialize to a default null frame + uint8_t buf[10] {}; + + buf[0] = 0x08; + buf[1] = frame.type; + // do not consume telemetry data for invalid downlink frames, i.e. incoming prim == 0x00 + if (frame.downlink.prim != FPORT2_PRIM_NULL) { + buf[2] = telem_data.packet.frame; + buf[3] = telem_data.packet.appid & 0xFF; + buf[4] = telem_data.packet.appid >> 8; + memcpy(&buf[5], &telem_data.packet.data, 4); + // get fresh telem_data in the next call + telem_data.available = false; + } + buf[9] = crc_sum8(&buf[1], 8); + + uart->write(buf, sizeof(buf)); +#endif +} + +/* + process a FPort2 input pulse of the given width + */ +void AP_RCProtocol_FPort2::process_pulse(uint32_t width_s0, uint32_t width_s1) +{ + if (have_UART()) { + // if we can use a UART we would much prefer to, as it allows + // us to send SPORT data out + return; + } + uint32_t w0 = width_s0; + uint32_t w1 = width_s1; + if (inverted) { + w0 = saved_width; + w1 = width_s0; + saved_width = width_s1; + } + uint8_t b; + if (ss.process_pulse(w0, w1, b)) { + _process_byte(ss.get_byte_timestamp_us(), b); + } +} + +// support byte input +void AP_RCProtocol_FPort2::_process_byte(uint32_t timestamp_us, uint8_t b) +{ + const bool have_frame_gap = (timestamp_us - byte_input.last_byte_us >= 2000U); + + byte_input.last_byte_us = timestamp_us; + + if (have_frame_gap) { + // if we have a frame gap then this must be the start of a new + // frame + byte_input.ofs = 0; + } + + if (byte_input.ofs == 0) { + switch (b) { + case FRAME_LEN_8: + byte_input.control_len = 16; + chan_count = 8; + byte_input.is_downlink = false; + break; + case FRAME_LEN_16: + byte_input.control_len = 27; + chan_count = 16; + byte_input.is_downlink = false; + break; + case FRAME_LEN_24: + byte_input.control_len = 38; + chan_count = 24; + byte_input.is_downlink = false; + break; + case FRAME_LEN_DOWNLINK: + byte_input.control_len = 10; + byte_input.is_downlink = true; + break; + default: + // definately not FPort2, missing header byte + return; + } + } + + if (byte_input.ofs == 1) { + if (!byte_input.is_downlink && b != FRAME_TYPE_CHANNEL) { + // not channel data + byte_input.ofs = 0; + return; + } + } + + byte_input.buf[byte_input.ofs++] = b; + + const FPort2_Frame *frame = (const FPort2_Frame *)&byte_input.buf[0]; + + if (byte_input.control_len > 2 && byte_input.ofs == byte_input.control_len) { + if (!byte_input.is_downlink) { + log_data(AP_RCProtocol::FPORT2, timestamp_us, byte_input.buf, byte_input.ofs); + if (check_checksum()) { + decode_control(*frame); + } + } else { + // downlink packet + if (check_checksum()) { + decode_downlink(*frame); + } + } + goto reset; + } + if (byte_input.ofs >= sizeof(byte_input.buf)) { + goto reset; + } + return; + +reset: + byte_input.ofs = 0; +} + +// check checksum byte +bool AP_RCProtocol_FPort2::check_checksum(void) +{ + return crc_sum8(&byte_input.buf[1], byte_input.control_len-1) == 0; +} + +// support byte input +void AP_RCProtocol_FPort2::process_byte(uint8_t b, uint32_t baudrate) +{ + if (baudrate != 115200) { + return; + } + _process_byte(AP_HAL::micros(), b); +} diff --git a/pool/shard006/C++/0084647_manual_constructor.cc b/pool/shard006/C++/0084647_manual_constructor.cc new file mode 100644 index 0000000000000000000000000000000000000000..de6f51b38680aa5e02b0604a2ce3084107015146 --- /dev/null +++ b/pool/shard006/C++/0084647_manual_constructor.cc @@ -0,0 +1,125 @@ +/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + http://www.apache.org/licenses/LICENSE-2.0 +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// tensorflow/tensorflow/core/lib/gtl/manual_constructor_test.cc + +#include "utils/manual_constructor.h" +#include +#include "platform/logging.h" +#include "platform/test.h" + +namespace bubblefs { +namespace { // namespace anonymous + +static int constructor_count_ = 0; + +template +struct TestN { + TestN() { ++constructor_count_; } + ~TestN() { --constructor_count_; } + char a[kSize]; +}; + +typedef TestN<1> Test1; +typedef TestN<2> Test2; +typedef TestN<3> Test3; +typedef TestN<4> Test4; +typedef TestN<5> Test5; +typedef TestN<9> Test9; +typedef TestN<15> Test15; + +} // namespace + +namespace { + +TEST(ManualConstructorTest, Sizeof) { + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test1)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test2)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test3)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test4)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test5)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test9)); + CHECK_EQ(sizeof(ManualConstructor), sizeof(Test15)); + + CHECK_EQ(constructor_count_, 0); + ManualConstructor mt[4]; + CHECK_EQ(sizeof(mt), 4); + CHECK_EQ(constructor_count_, 0); + mt[0].Init(); + CHECK_EQ(constructor_count_, 1); + mt[0].Destroy(); +} + +TEST(ManualConstructorTest, Alignment) { + // We want to make sure that ManualConstructor aligns its memory properly + // on a word barrier. Otherwise, it might be unexpectedly slow, since + // memory access will be unaligned. + + struct { + char a; + ManualConstructor b; + } test1; + struct { + char a; + void* b; + } control1; + + // TODO(bww): Make these tests more direct with C++11 alignment_of::value. + EXPECT_EQ(reinterpret_cast(test1.b.get()) - &test1.a, + reinterpret_cast(&control1.b) - &control1.a); + EXPECT_EQ(reinterpret_cast(test1.b.get()) % sizeof(control1.b), 0); + + struct { + char a; + ManualConstructor b; + } test2; + struct { + char a; + long double b; + } control2; + + EXPECT_EQ(reinterpret_cast(test2.b.get()) - &test2.a, + reinterpret_cast(&control2.b) - &control2.a); +#ifdef ARCH_K8 + EXPECT_EQ(reinterpret_cast(test2.b.get()) % 16, 0); +#endif +#ifdef ARCH_PIII + EXPECT_EQ(reinterpret_cast(test2.b.get()) % 4, 0); +#endif +} + +TEST(ManualConstructorTest, DefaultInitialize) { + struct X { + X() : x(123) {} + int x; + }; + union { + ManualConstructor x; + ManualConstructor y; + } u; + *u.y = -1; + u.x.Init(); // should default-initialize u.x + EXPECT_EQ(123, u.x->x); +} + +TEST(ManualConstructorTest, ZeroInitializePOD) { + union { + ManualConstructor x; + ManualConstructor y; + } u; + *u.y = -1; + u.x.Init(); // should not zero-initialize u.x + EXPECT_EQ(-1, *u.y); +} + +} // namespace anonymous +} // namespace bubblefs \ No newline at end of file diff --git a/pool/shard006/C++/0084667_FaceRecognizer.cpp b/pool/shard006/C++/0084667_FaceRecognizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bce2dfb96467466f55d9f770e03fe25231cbc683 --- /dev/null +++ b/pool/shard006/C++/0084667_FaceRecognizer.cpp @@ -0,0 +1,50 @@ +#include "FaceRecognizer.h" + +FaceRecognizer::FaceRecognizer(Mat _testImg, Mat _avgVec, Mat _eigenVec, Mat _facesInEigen, vector& _loadedFacesID) { + prepareFace(_testImg); + projectFace(testVec, _avgVec, _eigenVec); + recognize(testPrjFace, _facesInEigen, _loadedFacesID); + +} + +void FaceRecognizer::prepareFace(Mat _testImg) +{ + _testImg.convertTo(_testImg, CV_32FC1); + _testImg.reshape(0, _testImg.rows*_testImg.cols).copyTo(testVec); +} + +void FaceRecognizer::projectFace(Mat testVec, Mat _avgVec, Mat _eigenVec){ + Mat tmpData; + + subtract(testVec, _avgVec, tmpData); + testPrjFace = _eigenVec * tmpData; +} +//Find the closet Euclidean Distance between input and database +void FaceRecognizer::recognize(Mat testPrjFace, Mat _facesInEigen, vector& _loadedFacesID) +{ + for (int i =0; i < _loadedFacesID.size(); i++) { + Mat src1 = _facesInEigen.col(i); + Mat src2 = testPrjFace; + + double dist = norm(src1, src2, NORM_L2); + //cout << "Dist " < +#include <2geom/transforms.h> +#include +#include +using std::vector; + + +/** + * Called by sp_guide_moveto to indicate that the guide line corresponding to g has been moved, and + * that consequently this item should move with it. + * + * \pre exist [cn in item.constraints] g eq cn.g. + */ +void sp_item_notify_moveto(SPItem &item, SPGuide const &mv_g, int const snappoint_ix, + double const position, bool const commit) +{ + g_return_if_fail(SP_IS_ITEM(&item)); + g_return_if_fail( unsigned(snappoint_ix) < 8 ); + Geom::Point const dir( mv_g.normal_to_line ); + double const dir_lensq(dot(dir, dir)); + g_return_if_fail( dir_lensq != 0 ); + + std::vector snappoints; + sp_item_snappoints(&item, SnapPointsIter(snappoints), NULL); + g_return_if_fail( snappoint_ix < int(snappoints.size()) ); + + double const pos0 = dot(dir, snappoints[snappoint_ix]); + /// \todo effic: skip if mv_g is already satisfied. + + /* Translate along dir to make dot(dir, snappoints(item)[snappoint_ix]) == position. */ + + /* Calculation: + dot(dir, snappoints[snappoint_ix] + s * dir) = position. + dot(dir, snappoints[snappoint_ix]) + dot(dir, s * dir) = position. + pos0 + s * dot(dir, dir) = position. + s * lensq(dir) = position - pos0. + s = (position - pos0) / dot(dir, dir). */ + Geom::Translate const tr( ( position - pos0 ) + * ( dir / dir_lensq ) ); + sp_item_set_i2d_affine(&item, sp_item_i2d_affine(&item) * tr); + /// \todo Reget snappoints, check satisfied. + + if (commit) { + /// \todo Consider maintaining a set of dirty items. + + /* Commit repr. */ + { + sp_item_write_transform(&item, SP_OBJECT_REPR(&item), item.transform); + } + + sp_item_rm_unsatisfied_cns(item); +#if 0 /* nyi */ + move_cn_to_front(mv_g, snappoint_ix, item.constraints); + /** \note If the guideline is connected to multiple snappoints of + * this item, then keeping those cns in order requires that the + * guide send notifications in order of increasing importance. + */ +#endif + } +} + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/pool/shard006/C++/0084673_commit.cc b/pool/shard006/C++/0084673_commit.cc new file mode 100644 index 0000000000000000000000000000000000000000..0561e9b58367d284a7b4470f782c0598dab8f5c4 --- /dev/null +++ b/pool/shard006/C++/0084673_commit.cc @@ -0,0 +1,182 @@ +// Copyright 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "sync/engine/commit.h" + +#include "base/trace_event/trace_event.h" +#include "sync/engine/commit_contribution.h" +#include "sync/engine/commit_processor.h" +#include "sync/engine/commit_util.h" +#include "sync/engine/syncer.h" +#include "sync/engine/syncer_proto_util.h" +#include "sync/internal_api/public/events/commit_request_event.h" +#include "sync/internal_api/public/events/commit_response_event.h" +#include "sync/sessions/sync_session.h" + +namespace syncer { + +Commit::Commit( + const std::map& contributions, + const sync_pb::ClientToServerMessage& message, + ExtensionsActivity::Records extensions_activity_buffer) + : contributions_(contributions), + deleter_(&contributions_), + message_(message), + extensions_activity_buffer_(extensions_activity_buffer), + cleaned_up_(false) { +} + +Commit::~Commit() { + DCHECK(cleaned_up_); +} + +Commit* Commit::Init( + ModelTypeSet requested_types, + ModelTypeSet enabled_types, + size_t max_entries, + const std::string& account_name, + const std::string& cache_guid, + CommitProcessor* commit_processor, + ExtensionsActivity* extensions_activity) { + // Gather per-type contributions. + ContributionMap contributions; + commit_processor->GatherCommitContributions( + requested_types, + max_entries, + &contributions); + + // Give up if no one had anything to commit. + if (contributions.empty()) + return NULL; + + sync_pb::ClientToServerMessage message; + message.set_message_contents(sync_pb::ClientToServerMessage::COMMIT); + message.set_share(account_name); + + sync_pb::CommitMessage* commit_message = message.mutable_commit(); + commit_message->set_cache_guid(cache_guid); + + // Set extensions activity if bookmark commits are present. + ExtensionsActivity::Records extensions_activity_buffer; + ContributionMap::iterator it = contributions.find(syncer::BOOKMARKS); + if (it != contributions.end() && it->second->GetNumEntries() != 0) { + commit_util::AddExtensionsActivityToMessage( + extensions_activity, + &extensions_activity_buffer, + commit_message); + } + + // Set the client config params. + commit_util::AddClientConfigParamsToMessage( + enabled_types, + commit_message); + + // Finally, serialize all our contributions. + for (std::map::iterator it = + contributions.begin(); it != contributions.end(); ++it) { + it->second->AddToCommitMessage(&message); + } + + // If we made it this far, then we've successfully prepared a commit message. + return new Commit(contributions, message, extensions_activity_buffer); +} + +SyncerError Commit::PostAndProcessResponse( + sessions::NudgeTracker* nudge_tracker, + sessions::SyncSession* session, + sessions::StatusController* status, + ExtensionsActivity* extensions_activity) { + ModelTypeSet request_types; + for (ContributionMap::const_iterator it = contributions_.begin(); + it != contributions_.end(); ++it) { + request_types.Put(it->first); + } + session->mutable_status_controller()->set_commit_request_types(request_types); + + if (session->context()->debug_info_getter()) { + sync_pb::DebugInfo* debug_info = message_.mutable_debug_info(); + session->context()->debug_info_getter()->GetDebugInfo(debug_info); + } + + DVLOG(1) << "Sending commit message."; + + CommitRequestEvent request_event( + base::Time::Now(), + message_.commit().entries_size(), + request_types, + message_); + session->SendProtocolEvent(request_event); + + TRACE_EVENT_BEGIN0("sync", "PostCommit"); + const SyncerError post_result = SyncerProtoUtil::PostClientToServerMessage( + &message_, &response_, session); + TRACE_EVENT_END0("sync", "PostCommit"); + + // TODO(rlarocque): Use result that includes errors captured later? + CommitResponseEvent response_event( + base::Time::Now(), + post_result, + response_); + session->SendProtocolEvent(response_event); + + if (post_result != SYNCER_OK) { + LOG(WARNING) << "Post commit failed"; + return post_result; + } + + if (!response_.has_commit()) { + LOG(WARNING) << "Commit response has no commit body!"; + return SERVER_RESPONSE_VALIDATION_FAILED; + } + + size_t message_entries = message_.commit().entries_size(); + size_t response_entries = response_.commit().entryresponse_size(); + if (message_entries != response_entries) { + LOG(ERROR) + << "Commit response has wrong number of entries! " + << "Expected: " << message_entries << ", " + << "Got: " << response_entries; + return SERVER_RESPONSE_VALIDATION_FAILED; + } + + if (session->context()->debug_info_getter()) { + // Clear debug info now that we have successfully sent it to the server. + DVLOG(1) << "Clearing client debug info."; + session->context()->debug_info_getter()->ClearDebugInfo(); + } + + // Let the contributors process the responses to each of their requests. + SyncerError processing_result = SYNCER_OK; + for (std::map::iterator it = + contributions_.begin(); it != contributions_.end(); ++it) { + TRACE_EVENT1("sync", "ProcessCommitResponse", + "type", ModelTypeToString(it->first)); + SyncerError type_result = + it->second->ProcessCommitResponse(response_, status); + if (type_result == SERVER_RETURN_CONFLICT) { + nudge_tracker->RecordCommitConflict(it->first); + } + if (processing_result == SYNCER_OK && type_result != SYNCER_OK) { + processing_result = type_result; + } + } + + // Handle bookmarks' special extensions activity stats. + if (session->status_controller(). + model_neutral_state().num_successful_bookmark_commits == 0) { + extensions_activity->PutRecords(extensions_activity_buffer_); + } + + return processing_result; +} + +void Commit::CleanUp() { + for (ContributionMap::iterator it = contributions_.begin(); + it != contributions_.end(); ++it) { + it->second->CleanUp(); + } + cleaned_up_ = true; +} + +} // namespace syncer diff --git a/pool/shard006/C++/0084691_FacSupervisor.cpp b/pool/shard006/C++/0084691_FacSupervisor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2318f5e37bcfe58ae5b2bbdf15c16e1114b03663 --- /dev/null +++ b/pool/shard006/C++/0084691_FacSupervisor.cpp @@ -0,0 +1,112 @@ +// ////////////////////////////////////////////////////////////////////// +// Import section +// ////////////////////////////////////////////////////////////////////// +// OpenTREP +#include +#include +#include +#include +#include + +namespace OPENTREP { + + FacSupervisor* FacSupervisor::_instance = NULL; + + // ////////////////////////////////////////////////////////////////////// + FacSupervisor::FacSupervisor () : + _facXapianDB (NULL), _logger (NULL) { + } + + // ////////////////////////////////////////////////////////////////////// + FacSupervisor& FacSupervisor::instance() { + if (_instance == NULL) { + _instance = new FacSupervisor(); + } + assert (_instance != NULL); + return *_instance; + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor:: + registerBomFactory (FacBomAbstract* ioFacBomAbstract_ptr) { + _bomPool.push_back (ioFacBomAbstract_ptr); + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor:: + registerServiceFactory (FacServiceAbstract* ioFacServiceAbstract_ptr) { + _svcPool.push_back (ioFacServiceAbstract_ptr); + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::registerXapianDBFactory (FacXapianDB* ioFacXapianDB_ptr) { + _facXapianDB = ioFacXapianDB_ptr; + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::registerLoggerService (Logger* ioLogger_ptr) { + _logger = ioLogger_ptr; + } + + // ////////////////////////////////////////////////////////////////////// + FacSupervisor::~FacSupervisor() { + // For the underlying instance, if existing + cleanFactory(); + + // For the instance level + cleanBomLayer(); + cleanServiceLayer(); + cleanFacXapianDB(); + cleanLoggerService(); + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::cleanBomLayer() { + for (BomFactoryPool_T::const_iterator itFactory = _bomPool.begin(); + itFactory != _bomPool.end(); itFactory++) { + const FacBomAbstract* currentFactory_ptr = *itFactory; + assert (currentFactory_ptr != NULL); + + delete currentFactory_ptr; currentFactory_ptr = NULL; + } + + // Now that all the objects have been deleted, empty the underlying pool + _bomPool.clear(); + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::cleanServiceLayer() { + for (ServiceFactoryPool_T::const_iterator itFactory = _svcPool.begin(); + itFactory != _svcPool.end(); itFactory++) { + const FacServiceAbstract* currentFactory_ptr = *itFactory; + assert (currentFactory_ptr != NULL); + + delete currentFactory_ptr; currentFactory_ptr = NULL; + } + + // Now that all the objects have been deleted, empty the underlying pool + _svcPool.clear(); + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::cleanFacXapianDB() { + delete _facXapianDB; _facXapianDB = NULL; + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::cleanLoggerService() { + delete _logger; _logger = NULL; + } + + // ////////////////////////////////////////////////////////////////////// + void FacSupervisor::cleanFactory () { + if (_instance != NULL) { + _instance->cleanBomLayer(); + _instance->cleanServiceLayer(); + _instance->cleanFacXapianDB(); + _instance->cleanLoggerService(); + } + delete _instance; _instance = NULL; + } + +} diff --git a/pool/shard006/C++/0084698_cpu-trampoline-x64.cc b/pool/shard006/C++/0084698_cpu-trampoline-x64.cc new file mode 100644 index 0000000000000000000000000000000000000000..86184e95dd6119dbbfe3038988e3f58b4efce060 --- /dev/null +++ b/pool/shard006/C++/0084698_cpu-trampoline-x64.cc @@ -0,0 +1,49 @@ +// Copyright 2014 Runtime.JS project authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "cpu-trampoline-x64.h" +#include + +// located at 64 bit code location +extern "C" uint8_t _ap_startup_location; + +// located at 16 bit start and finish of code +extern "C" uint8_t _ap_startup_start; +extern "C" uint8_t _ap_startup_finish; + +// other +extern "C" volatile uint16_t _cpus_counter; + +namespace rt { + +CpuTrampolineX64::CpuTrampolineX64() { + RT_ASSERT(reinterpret_cast(&_ap_startup_finish) + > reinterpret_cast(&_ap_startup_start)); + + const void* ap_startup_loc = &_ap_startup_location; + uint16_t ap_startup_len = reinterpret_cast(&_ap_startup_finish) + - reinterpret_cast(&_ap_startup_start); + RT_ASSERT(ap_startup_loc); + RT_ASSERT(ap_startup_len); + + memcpy((void*)kLoadAddress, ap_startup_loc, ap_startup_len); + + printf("AP loader embedded at 0x%x, len = %d\n", ap_startup_loc, ap_startup_len); +} + +uint16_t CpuTrampolineX64::cpus_counter_value() { + return _cpus_counter; +} + +} // namespace rt diff --git a/pool/shard006/C++/0084705_analyzerutils.cpp b/pool/shard006/C++/0084705_analyzerutils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c26d4fa8ecabbeef4a420c792af8660259a966af --- /dev/null +++ b/pool/shard006/C++/0084705_analyzerutils.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "analyzerutils.h" + +#include "analyzerconstants.h" + +#include +#include + +#include + +#include +#include +#include + +#include + +using namespace Analyzer; +using namespace Core; + +static void moveCursorToEndOfName(QTextCursor *tc) +{ + QTextDocument *doc = tc->document(); + if (!doc) + return; + + QChar ch = doc->characterAt(tc->position()); + while (ch.isLetterOrNumber() || ch == QLatin1Char('_')) { + tc->movePosition(QTextCursor::NextCharacter); + ch = doc->characterAt(tc->position()); + } +} + +// TODO: Can this be improved? This code is ripped from CppEditor, especially CppElementEvaluater +// We cannot depend on this since CppEditor plugin code is internal and requires building the implementation files ourselves +CPlusPlus::Symbol *AnalyzerUtils::findSymbolUnderCursor() +{ + TextEditor::BaseTextEditor *editor = TextEditor::BaseTextEditor::currentTextEditor(); + if (!editor) + return 0; + + QTextCursor tc = editor->textCursor(); + int line = 0; + int column = 0; + const int pos = tc.position(); + editor->convertPosition(pos, &line, &column); + + const CPlusPlus::Snapshot &snapshot = CppTools::CppModelManagerInterface::instance()->snapshot(); + CPlusPlus::Document::Ptr doc = snapshot.document(editor->document()->filePath()); + QTC_ASSERT(doc, return 0); + + // fetch the expression's code + CPlusPlus::ExpressionUnderCursor expressionUnderCursor; + moveCursorToEndOfName(&tc); + const QString &expression = expressionUnderCursor(tc); + CPlusPlus::Scope *scope = doc->scopeAt(line, column); + + CPlusPlus::TypeOfExpression typeOfExpression; + typeOfExpression.init(doc, snapshot); + const QList &lookupItems = typeOfExpression(expression.toUtf8(), scope); + if (lookupItems.isEmpty()) + return 0; + + const CPlusPlus::LookupItem &lookupItem = lookupItems.first(); // ### TODO: select best candidate. + return lookupItem.declaration(); +} diff --git a/pool/shard006/C++/0084709_listsockets.cpp b/pool/shard006/C++/0084709_listsockets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cba6e037f2edf1efacd1a951e45f2c14a12f210 --- /dev/null +++ b/pool/shard006/C++/0084709_listsockets.cpp @@ -0,0 +1,256 @@ +/* + * Copyright (C) 2004-2017 ZNC, see the NOTICE file for details. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +class CSocketSorter { + public: + CSocketSorter(Csock* p) { m_pSock = p; } + bool operator<(const CSocketSorter& other) const { + // The 'biggest' item is displayed first. + // return false: this is first + // return true: other is first + + // Listeners go to the top + if (m_pSock->GetType() != other.m_pSock->GetType()) { + if (m_pSock->GetType() == Csock::LISTENER) return false; + if (other.m_pSock->GetType() == Csock::LISTENER) return true; + } + const CString& sMyName = m_pSock->GetSockName(); + const CString& sMyName2 = sMyName.Token(1, true, "::"); + bool bMyEmpty = sMyName2.empty(); + const CString& sHisName = other.GetSock()->GetSockName(); + const CString& sHisName2 = sHisName.Token(1, true, "::"); + bool bHisEmpty = sHisName2.empty(); + + // Then sort by first token after "::" + if (bMyEmpty && !bHisEmpty) return false; + if (bHisEmpty && !bMyEmpty) return true; + + if (!bMyEmpty && !bHisEmpty) { + int c = sMyName2.StrCmp(sHisName2); + if (c < 0) return false; + if (c > 0) return true; + } + // and finally sort by the whole socket name + return sMyName.StrCmp(sHisName) > 0; + } + Csock* GetSock() const { return m_pSock; } + + private: + Csock* m_pSock; +}; + +class CListSockets : public CModule { + public: + MODCONSTRUCTOR(CListSockets) { + AddHelpCommand(); + AddCommand( + "List", + static_cast(&CListSockets::OnListCommand), + "[-n]", + "Show the list of active sockets. Pass -n to show IP addresses"); + } + + bool OnLoad(const CString& sArgs, CString& sMessage) override { +#ifndef MOD_LISTSOCKETS_ALLOW_EVERYONE + if (!GetUser()->IsAdmin()) { + sMessage = "You must be admin to use this module"; + return false; + } +#endif + + return true; + } + + std::priority_queue GetSockets() { + CSockManager& m = CZNC::Get().GetManager(); + std::priority_queue ret; + + for (unsigned int a = 0; a < m.size(); a++) { + Csock* pSock = m[a]; + // These sockets went through SwapSockByAddr. That means + // another socket took over the connection from this + // socket. So ignore this to avoid listing the + // connection twice. + if (pSock->GetCloseType() == Csock::CLT_DEREFERENCE) continue; + ret.push(pSock); + } + + return ret; + } + + bool WebRequiresAdmin() override { return true; } + CString GetWebMenuTitle() override { return "List sockets"; } + + bool OnWebRequest(CWebSock& WebSock, const CString& sPageName, + CTemplate& Tmpl) override { + if (sPageName == "index") { + if (CZNC::Get().GetManager().empty()) { + return false; + } + + std::priority_queue socks = GetSockets(); + + while (!socks.empty()) { + Csock* pSocket = socks.top().GetSock(); + socks.pop(); + + CTemplate& Row = Tmpl.AddRow("SocketsLoop"); + Row["Name"] = pSocket->GetSockName(); + Row["Created"] = GetCreatedTime(pSocket); + Row["State"] = GetSocketState(pSocket); + Row["SSL"] = pSocket->GetSSL() ? "Yes" : "No"; + Row["Local"] = GetLocalHost(pSocket, true); + Row["Remote"] = GetRemoteHost(pSocket, true); + Row["In"] = CString::ToByteStr(pSocket->GetBytesRead()); + Row["Out"] = CString::ToByteStr(pSocket->GetBytesWritten()); + } + + return true; + } + + return false; + } + + void OnListCommand(const CString& sLine) { + CString sArg = sLine.Token(1, true); + + bool bShowHosts = true; + if (sArg.Equals("-n")) { + bShowHosts = false; + } + ShowSocks(bShowHosts); + } + + CString GetSocketState(Csock* pSocket) { + switch (pSocket->GetType()) { + case Csock::LISTENER: + return "Listener"; + case Csock::INBOUND: + return "Inbound"; + case Csock::OUTBOUND: + if (pSocket->IsConnected()) + return "Outbound"; + else + return "Connecting"; + } + + return "UNKNOWN"; + } + + CString GetCreatedTime(Csock* pSocket) { + unsigned long long iStartTime = pSocket->GetStartTime(); + time_t iTime = iStartTime / 1000; + return CUtils::FormatTime(iTime, "%Y-%m-%d %H:%M:%S", + GetUser()->GetTimezone()); + } + + CString GetLocalHost(Csock* pSocket, bool bShowHosts) { + CString sBindHost; + + if (bShowHosts) { + sBindHost = pSocket->GetBindHost(); + } + + if (sBindHost.empty()) { + sBindHost = pSocket->GetLocalIP(); + } + + return sBindHost + " " + CString(pSocket->GetLocalPort()); + } + + CString GetRemoteHost(Csock* pSocket, bool bShowHosts) { + CString sHost; + u_short uPort; + + if (!bShowHosts) { + sHost = pSocket->GetRemoteIP(); + } + + // While connecting, there might be no ip available + if (sHost.empty()) { + sHost = pSocket->GetHostName(); + } + + // While connecting, GetRemotePort() would return 0 + if (pSocket->GetType() == Csock::OUTBOUND) { + uPort = pSocket->GetPort(); + } else { + uPort = pSocket->GetRemotePort(); + } + + if (uPort != 0) { + return sHost + " " + CString(uPort); + } + + return sHost; + } + + void ShowSocks(bool bShowHosts) { + if (CZNC::Get().GetManager().empty()) { + PutStatus("You have no open sockets."); + return; + } + + std::priority_queue socks = GetSockets(); + + CTable Table; + Table.AddColumn("Name"); + Table.AddColumn("Created"); + Table.AddColumn("State"); +#ifdef HAVE_LIBSSL + Table.AddColumn("SSL"); +#endif + Table.AddColumn("Local"); + Table.AddColumn("Remote"); + Table.AddColumn("In"); + Table.AddColumn("Out"); + + while (!socks.empty()) { + Csock* pSocket = socks.top().GetSock(); + socks.pop(); + + Table.AddRow(); + Table.SetCell("Name", pSocket->GetSockName()); + Table.SetCell("Created", GetCreatedTime(pSocket)); + Table.SetCell("State", GetSocketState(pSocket)); + +#ifdef HAVE_LIBSSL + Table.SetCell("SSL", pSocket->GetSSL() ? "Yes" : "No"); +#endif + + Table.SetCell("Local", GetLocalHost(pSocket, bShowHosts)); + Table.SetCell("Remote", GetRemoteHost(pSocket, bShowHosts)); + Table.SetCell("In", CString::ToByteStr(pSocket->GetBytesRead())); + Table.SetCell("Out", + CString::ToByteStr(pSocket->GetBytesWritten())); + } + + PutModule(Table); + return; + } + + ~CListSockets() override {} +}; + +template <> +void TModInfo(CModInfo& Info) { + Info.SetWikiPage("listsockets"); +} + +USERMODULEDEFS(CListSockets, "List active sockets") diff --git a/pool/shard006/C++/0084715_video_metrics.cc b/pool/shard006/C++/0084715_video_metrics.cc new file mode 100644 index 0000000000000000000000000000000000000000..f537e03925aad80ff4bae7c0578ba75cd8d743cd --- /dev/null +++ b/pool/shard006/C++/0084715_video_metrics.cc @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "webrtc/test/testsupport/metrics/video_metrics.h" + +#include +#include + +#include // min_element, max_element + +#include "webrtc/common_video/interface/i420_video_frame.h" +#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h" + +namespace webrtc { +namespace test { + +// Copy here so our callers won't need to include libyuv for this constant. +double kMetricsPerfectPSNR = kPerfectPSNR; + +// Used for calculating min and max values. +static bool LessForFrameResultValue(const FrameResult& s1, + const FrameResult& s2) { + return s1.value < s2.value; +} + +enum VideoMetricsType { kPSNR, kSSIM, kBoth }; + +// Calculates metrics for a frame and adds statistics to the result for it. +void CalculateFrame(VideoMetricsType video_metrics_type, + const I420VideoFrame* ref, + const I420VideoFrame* test, + int frame_number, + QualityMetricsResult* result) { + FrameResult frame_result = {0, 0}; + frame_result.frame_number = frame_number; + switch (video_metrics_type) { + case kPSNR: + frame_result.value = I420PSNR(ref, test); + break; + case kSSIM: + frame_result.value = I420SSIM(ref, test); + break; + default: + assert(false); + } + result->frames.push_back(frame_result); +} + +// Calculates average, min and max values for the supplied struct, if non-NULL. +void CalculateStats(QualityMetricsResult* result) { + if (result == NULL || result->frames.size() == 0) { + return; + } + // Calculate average. + std::vector::iterator iter; + double metrics_values_sum = 0.0; + for (iter = result->frames.begin(); iter != result->frames.end(); ++iter) { + metrics_values_sum += iter->value; + } + result->average = metrics_values_sum / result->frames.size(); + + // Calculate min/max statistics. + iter = std::min_element(result->frames.begin(), result->frames.end(), + LessForFrameResultValue); + result->min = iter->value; + result->min_frame_number = iter->frame_number; + iter = std::max_element(result->frames.begin(), result->frames.end(), + LessForFrameResultValue); + result->max = iter->value; + result->max_frame_number = iter->frame_number; +} + +// Single method that handles all combinations of video metrics calculation, to +// minimize code duplication. Either psnr_result or ssim_result may be NULL, +// depending on which VideoMetricsType is targeted. +int CalculateMetrics(VideoMetricsType video_metrics_type, + const char* ref_filename, + const char* test_filename, + int width, + int height, + QualityMetricsResult* psnr_result, + QualityMetricsResult* ssim_result) { + assert(ref_filename != NULL); + assert(test_filename != NULL); + assert(width > 0); + assert(height > 0); + + FILE* ref_fp = fopen(ref_filename, "rb"); + if (ref_fp == NULL) { + // Cannot open reference file. + fprintf(stderr, "Cannot open file %s\n", ref_filename); + return -1; + } + FILE* test_fp = fopen(test_filename, "rb"); + if (test_fp == NULL) { + // Cannot open test file. + fprintf(stderr, "Cannot open file %s\n", test_filename); + fclose(ref_fp); + return -2; + } + int frame_number = 0; + + // Read reference and test frames. + const size_t frame_length = 3 * width * height >> 1; + I420VideoFrame ref_frame; + I420VideoFrame test_frame; + scoped_array ref_buffer(new uint8_t[frame_length]); + scoped_array test_buffer(new uint8_t[frame_length]); + + // Set decoded image parameters. + int half_width = (width + 1) / 2; + ref_frame.CreateEmptyFrame(width, height, width, half_width, half_width); + test_frame.CreateEmptyFrame(width, height, width, half_width, half_width); + + size_t ref_bytes = fread(ref_buffer.get(), 1, frame_length, ref_fp); + size_t test_bytes = fread(test_buffer.get(), 1, frame_length, test_fp); + while (ref_bytes == frame_length && test_bytes == frame_length) { + // Converting from buffer to plane representation. + ConvertToI420(kI420, ref_buffer.get(), 0, 0, width, height, 0, + kRotateNone, &ref_frame); + ConvertToI420(kI420, test_buffer.get(), 0, 0, width, height, 0, + kRotateNone, &test_frame); + switch (video_metrics_type) { + case kPSNR: + CalculateFrame(kPSNR, &ref_frame, &test_frame, frame_number, + psnr_result); + break; + case kSSIM: + CalculateFrame(kSSIM, &ref_frame, &test_frame, frame_number, + ssim_result); + break; + case kBoth: + CalculateFrame(kPSNR, &ref_frame, &test_frame, frame_number, + psnr_result); + CalculateFrame(kSSIM, &ref_frame, &test_frame, frame_number, + ssim_result); + break; + } + frame_number++; + ref_bytes = fread(ref_buffer.get(), 1, frame_length, ref_fp); + test_bytes = fread(test_buffer.get(), 1, frame_length, test_fp); + } + int return_code = 0; + if (frame_number == 0) { + fprintf(stderr, "Tried to measure video metrics from empty files " + "(reference file: %s test file: %s)\n", ref_filename, + test_filename); + return_code = -3; + } else { + CalculateStats(psnr_result); + CalculateStats(ssim_result); + } + fclose(ref_fp); + fclose(test_fp); + return return_code; +} + +int I420MetricsFromFiles(const char* ref_filename, + const char* test_filename, + int width, + int height, + QualityMetricsResult* psnr_result, + QualityMetricsResult* ssim_result) { + assert(psnr_result != NULL); + assert(ssim_result != NULL); + return CalculateMetrics(kBoth, ref_filename, test_filename, width, height, + psnr_result, ssim_result); +} + +int I420PSNRFromFiles(const char* ref_filename, + const char* test_filename, + int width, + int height, + QualityMetricsResult* result) { + assert(result != NULL); + return CalculateMetrics(kPSNR, ref_filename, test_filename, width, height, + result, NULL); +} + +int I420SSIMFromFiles(const char* ref_filename, + const char* test_filename, + int width, + int height, + QualityMetricsResult* result) { + assert(result != NULL); + return CalculateMetrics(kSSIM, ref_filename, test_filename, width, height, + NULL, result); +} + +} // namespace test +} // namespace webrtc diff --git a/pool/shard006/C++/0084725_FeatureSummary.cpp b/pool/shard006/C++/0084725_FeatureSummary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ffd34dfe5102c2f331d0c1b29c59fb35aed3524 --- /dev/null +++ b/pool/shard006/C++/0084725_FeatureSummary.cpp @@ -0,0 +1,210 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace CloudWatchEvidently +{ +namespace Model +{ + +FeatureSummary::FeatureSummary() : + m_arnHasBeenSet(false), + m_createdTimeHasBeenSet(false), + m_defaultVariationHasBeenSet(false), + m_evaluationRulesHasBeenSet(false), + m_evaluationStrategy(FeatureEvaluationStrategy::NOT_SET), + m_evaluationStrategyHasBeenSet(false), + m_lastUpdatedTimeHasBeenSet(false), + m_nameHasBeenSet(false), + m_projectHasBeenSet(false), + m_status(FeatureStatus::NOT_SET), + m_statusHasBeenSet(false), + m_tagsHasBeenSet(false) +{ +} + +FeatureSummary::FeatureSummary(JsonView jsonValue) : + m_arnHasBeenSet(false), + m_createdTimeHasBeenSet(false), + m_defaultVariationHasBeenSet(false), + m_evaluationRulesHasBeenSet(false), + m_evaluationStrategy(FeatureEvaluationStrategy::NOT_SET), + m_evaluationStrategyHasBeenSet(false), + m_lastUpdatedTimeHasBeenSet(false), + m_nameHasBeenSet(false), + m_projectHasBeenSet(false), + m_status(FeatureStatus::NOT_SET), + m_statusHasBeenSet(false), + m_tagsHasBeenSet(false) +{ + *this = jsonValue; +} + +FeatureSummary& FeatureSummary::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("arn")) + { + m_arn = jsonValue.GetString("arn"); + + m_arnHasBeenSet = true; + } + + if(jsonValue.ValueExists("createdTime")) + { + m_createdTime = jsonValue.GetDouble("createdTime"); + + m_createdTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("defaultVariation")) + { + m_defaultVariation = jsonValue.GetString("defaultVariation"); + + m_defaultVariationHasBeenSet = true; + } + + if(jsonValue.ValueExists("evaluationRules")) + { + Array evaluationRulesJsonList = jsonValue.GetArray("evaluationRules"); + for(unsigned evaluationRulesIndex = 0; evaluationRulesIndex < evaluationRulesJsonList.GetLength(); ++evaluationRulesIndex) + { + m_evaluationRules.push_back(evaluationRulesJsonList[evaluationRulesIndex].AsObject()); + } + m_evaluationRulesHasBeenSet = true; + } + + if(jsonValue.ValueExists("evaluationStrategy")) + { + m_evaluationStrategy = FeatureEvaluationStrategyMapper::GetFeatureEvaluationStrategyForName(jsonValue.GetString("evaluationStrategy")); + + m_evaluationStrategyHasBeenSet = true; + } + + if(jsonValue.ValueExists("lastUpdatedTime")) + { + m_lastUpdatedTime = jsonValue.GetDouble("lastUpdatedTime"); + + m_lastUpdatedTimeHasBeenSet = true; + } + + if(jsonValue.ValueExists("name")) + { + m_name = jsonValue.GetString("name"); + + m_nameHasBeenSet = true; + } + + if(jsonValue.ValueExists("project")) + { + m_project = jsonValue.GetString("project"); + + m_projectHasBeenSet = true; + } + + if(jsonValue.ValueExists("status")) + { + m_status = FeatureStatusMapper::GetFeatureStatusForName(jsonValue.GetString("status")); + + m_statusHasBeenSet = true; + } + + if(jsonValue.ValueExists("tags")) + { + Aws::Map tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); + for(auto& tagsItem : tagsJsonMap) + { + m_tags[tagsItem.first] = tagsItem.second.AsString(); + } + m_tagsHasBeenSet = true; + } + + return *this; +} + +JsonValue FeatureSummary::Jsonize() const +{ + JsonValue payload; + + if(m_arnHasBeenSet) + { + payload.WithString("arn", m_arn); + + } + + if(m_createdTimeHasBeenSet) + { + payload.WithDouble("createdTime", m_createdTime.SecondsWithMSPrecision()); + } + + if(m_defaultVariationHasBeenSet) + { + payload.WithString("defaultVariation", m_defaultVariation); + + } + + if(m_evaluationRulesHasBeenSet) + { + Array evaluationRulesJsonList(m_evaluationRules.size()); + for(unsigned evaluationRulesIndex = 0; evaluationRulesIndex < evaluationRulesJsonList.GetLength(); ++evaluationRulesIndex) + { + evaluationRulesJsonList[evaluationRulesIndex].AsObject(m_evaluationRules[evaluationRulesIndex].Jsonize()); + } + payload.WithArray("evaluationRules", std::move(evaluationRulesJsonList)); + + } + + if(m_evaluationStrategyHasBeenSet) + { + payload.WithString("evaluationStrategy", FeatureEvaluationStrategyMapper::GetNameForFeatureEvaluationStrategy(m_evaluationStrategy)); + } + + if(m_lastUpdatedTimeHasBeenSet) + { + payload.WithDouble("lastUpdatedTime", m_lastUpdatedTime.SecondsWithMSPrecision()); + } + + if(m_nameHasBeenSet) + { + payload.WithString("name", m_name); + + } + + if(m_projectHasBeenSet) + { + payload.WithString("project", m_project); + + } + + if(m_statusHasBeenSet) + { + payload.WithString("status", FeatureStatusMapper::GetNameForFeatureStatus(m_status)); + } + + if(m_tagsHasBeenSet) + { + JsonValue tagsJsonMap; + for(auto& tagsItem : m_tags) + { + tagsJsonMap.WithString(tagsItem.first, tagsItem.second); + } + payload.WithObject("tags", std::move(tagsJsonMap)); + + } + + return payload; +} + +} // namespace Model +} // namespace CloudWatchEvidently +} // namespace Aws diff --git a/pool/shard006/C++/0084729_AttachmentBase.cpp b/pool/shard006/C++/0084729_AttachmentBase.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a2d95880a64c78f481837df135fd5a9434e5c531 --- /dev/null +++ b/pool/shard006/C++/0084729_AttachmentBase.cpp @@ -0,0 +1,98 @@ +/* + Copyright (C) 2009 Erik Hjortsberg + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "AttachmentBase.h" + +#include "domain/EmberEntity.h" +#include "domain/IGraphicalRepresentation.h" + +namespace Ember +{ +namespace OgreView +{ + +AttachmentBase::AttachmentBase(EmberEntity& parentEntity, EmberEntity& childEntity) : + mParentEntity(parentEntity), mChildEntity(childEntity) +{ +} + +AttachmentBase::~AttachmentBase() +{ +} + +IGraphicalRepresentation* AttachmentBase::getGraphicalRepresentation() const +{ + return 0; +} + +EmberEntity& AttachmentBase::getAttachedEntity() const +{ + return mChildEntity; +} + +EmberEntity* AttachmentBase::getParentEntity() const +{ + return &mParentEntity; +} + +void AttachmentBase::setControlDelegate(IEntityControlDelegate* controllerDelegate) +{ +} + +IEntityControlDelegate* AttachmentBase::getControlDelegate() const +{ + return 0; +} + +void AttachmentBase::updateScale() +{ +} + +void AttachmentBase::updatePosition() +{ +} + +void AttachmentBase::getOffsetForContainedNode(const IEntityAttachment& attachment, const WFMath::Point<3>& localPosition, WFMath::Vector<3>& offset) +{ + if (mParentEntity.getAttachment()) { + WFMath::Vector<3> localPositionShift(mChildEntity.getPredictedPos()); + if (!localPositionShift.isValid()) { + localPositionShift = WFMath::Vector<3>::ZERO(); + } + WFMath::Point<3> adjustedLocalPosition = localPosition + localPositionShift; + mParentEntity.getAttachment()->getOffsetForContainedNode(attachment, adjustedLocalPosition, offset); + } +} + +void AttachmentBase::setVisualize(const std::string& visualization, bool visualize) +{ + if (getGraphicalRepresentation()) { + getGraphicalRepresentation()->setVisualize(visualization, visualize); + } +} + +bool AttachmentBase::getVisualize(const std::string& visualization) const +{ + if (getGraphicalRepresentation()) { + return getGraphicalRepresentation()->getVisualize(visualization); + } + return false; +} + +} +} diff --git a/pool/shard006/C++/0084731_WhitespacePingLayer.cpp b/pool/shard006/C++/0084731_WhitespacePingLayer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b14f3a2b116f78c1af01c02d9bc37bccf4ac5225 --- /dev/null +++ b/pool/shard006/C++/0084731_WhitespacePingLayer.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2010 Remko Tronçon + * Licensed under the GNU General Public License v3. + * See Documentation/Licenses/GPLv3.txt for more information. + */ + +#include + +#include + +#include +#include + +namespace Swift { + +static const int TIMEOUT_MILLISECONDS = 60000; + +WhitespacePingLayer::WhitespacePingLayer(TimerFactory* timerFactory) : isActive(false) { + timer = timerFactory->createTimer(TIMEOUT_MILLISECONDS); + timer->onTick.connect(boost::bind(&WhitespacePingLayer::handleTimerTick, this)); +} + +void WhitespacePingLayer::writeData(const SafeByteArray& data) { + writeDataToChildLayer(data); +} + +void WhitespacePingLayer::handleDataRead(const SafeByteArray& data) { + writeDataToParentLayer(data); +} + +void WhitespacePingLayer::handleTimerTick() { + timer->stop(); + writeDataToChildLayer(createSafeByteArray(" ")); + timer->start(); +} + +void WhitespacePingLayer::setActive() { + isActive = true; + timer->start(); +} + +void WhitespacePingLayer::setInactive() { + timer->stop(); + isActive = false; +} + +} diff --git a/pool/shard006/C++/0084735_bOSSQLSmartConnection.cpp b/pool/shard006/C++/0084735_bOSSQLSmartConnection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..611c3cf565338b225a92100231e9e4cc181a21b2 --- /dev/null +++ b/pool/shard006/C++/0084735_bOSSQLSmartConnection.cpp @@ -0,0 +1,54 @@ +#include "CommonDefines.h" + +#include "bOSSQLSmartConnection.h" +#include "bOSSQLConnectionManager.h" +#include "bOSSQLConnection.h" +using namespace bOS::SQL; + +SQLSmartConnection::SQLSmartConnection() +{ + manager = NULL; + connection = NULL; + + bConnectionOwner = false; +} + +SQLSmartConnection::SQLSmartConnection(SQLConnectionManager* _manager, SQLConnection* _connection) +{ + assert(_manager != NULL); + assert(_connection != NULL ); + + manager = _manager; + connection = _connection; + + bConnectionOwner = true; +} + +SQLSmartConnection::~SQLSmartConnection() +{ + if ( connection != NULL ) + { + try + { + manager->release(connection); + } + catch ( SQLException&) + { + //TODO + //TRC_TRACES(2, "impossible to free connection.Err[" << sqlErr << "]") + } + } +} + +void SQLSmartConnection::init(SQLConnectionManager* _manager, SQLConnection* _connection) +{ + assert(manager == NULL); + assert(connection == NULL); + assert(_manager != NULL); + assert(_connection != NULL ); + + manager = _manager; + connection = _connection; + + bConnectionOwner = true; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084736_drawRectBlockGenerator.cpp b/pool/shard006/C++/0084736_drawRectBlockGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7792f54ab4c1c5bca6e005733e5c5e33b0521c00 --- /dev/null +++ b/pool/shard006/C++/0084736_drawRectBlockGenerator.cpp @@ -0,0 +1,35 @@ +/* Copyright 2007-2015 QReal Research Group + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + +#include "drawRectBlockGenerator.h" + +using namespace nxt::simple; + +DrawRectBlockGenerator::DrawRectBlockGenerator(const qrRepo::RepoApi &repo + , generatorBase::GeneratorCustomizer &customizer + , const qReal::Id &id + , QObject *parent) + : DrawBlockGenerator(repo, customizer, id, parent) +{ +} + +void DrawRectBlockGenerator::drawBmp(QPainter *painter) +{ + const int x = mRepo.property(mId, "XCoordinateRect").toInt(); + const int y = mRepo.property(mId, "YCoordinateRect").toInt(); + const int width = mRepo.property(mId, "WidthRect").toInt(); + const int height = mRepo.property(mId, "HeightRect").toInt(); + + painter->drawRect(x, y, width, height); +} diff --git a/pool/shard006/C++/0084738_CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad.cpp b/pool/shard006/C++/0084738_CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8ff4703a8b142aca8d32017b8d3f8227a004444c --- /dev/null +++ b/pool/shard006/C++/0084738_CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad.cpp @@ -0,0 +1,150 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad.cpp +Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml +Template File: sources-sink-84_bad.tmpl.cpp +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sinks: popen + * BadSink : Execute command in data using popen() + * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use + * + * */ +#ifndef OMITBAD + +#include "std_testcase.h" +#include "CWE78_OS_Command_Injection__char_listen_socket_popen_84.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +/* define POPEN as _popen on Windows and popen otherwise */ +#ifdef _WIN32 +#define POPEN _popen +#define PCLOSE _pclose +#else /* NOT _WIN32 */ +#define POPEN popen +#define PCLOSE pclose +#endif + +namespace CWE78_OS_Command_Injection__char_listen_socket_popen_84 +{ +CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad::CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad(char * dataCopy) +{ + data = dataCopy; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } +} + +CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad::~CWE78_OS_Command_Injection__char_listen_socket_popen_84_bad() +{ + { + FILE *pipe; + /* POTENTIAL FLAW: Execute command in data possibly leading to command injection */ + pipe = POPEN(data, "wb"); + if (pipe != NULL) + { + PCLOSE(pipe); + } + } +} +} +#endif /* OMITBAD */ diff --git a/pool/shard006/C++/0084739_main.cpp b/pool/shard006/C++/0084739_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a4516ad57d75b51334ea5966ba427e04fb574fd --- /dev/null +++ b/pool/shard006/C++/0084739_main.cpp @@ -0,0 +1,215 @@ +#include +#include +#include +#include + +// To DO: +// read through the file +// count up the symbols +// create our HuffmanNodes +// build the tree +// build our dictionary +// write out the comrpessed file + +struct HuffmanNode +{ + HuffmanNode* parent; + HuffmanNode* zeroBitChild; + HuffmanNode* oneBitChild; + + int iFrequency; + unsigned char value; +}; + +struct DictionaryEntry +{ + unsigned char uiBitfield[32]; // absolute maximum worst case bitfield size + unsigned int uiBitCount; +}; + +void FillDictionary(DictionaryEntry* Dictionary, HuffmanNode* node, DictionaryEntry entry) +{ + if (node->oneBitChild) + { + // one bit branch + DictionaryEntry oneBitEntry = entry; + oneBitEntry.uiBitCount++; + unsigned int uiBitToSet = oneBitEntry.uiBitCount % 8; + unsigned int uiIntToSet = oneBitEntry.uiBitCount / 8; + + oneBitEntry.uiBitfield[uiIntToSet] |= 1 << uiBitToSet; + + FillDictionary(Dictionary, node->oneBitChild, oneBitEntry); + } + if (node->zeroBitChild) + { + // zero bit child + DictionaryEntry zeroBitEntry = entry; + zeroBitEntry.uiBitCount++; + + FillDictionary(Dictionary, node->zeroBitChild, zeroBitEntry); + } + if (!node->zeroBitChild && !node->oneBitChild) + { + // this is a leaf node + Dictionary[node->value] = entry; + } +} + + + +int main(int argc, char**argv) +{ + // usage: + // huffman + + if (argc != 3) + { + printf("Usage:\nhuffman \n"); + return 0; + } + + const char* inputFileName = argv[1]; + const char* outputFileName = argv[2]; + + if (strcmp(inputFileName, outputFileName) == 0) + { + // file names are the same + printf("Input and Output file names are the same, please use different file names!\n"); + printf("Usage:\nhuffman \n"); + return 0; + } + // should probably also do a check to see if the output (and input) file already exists + + FILE* inputFile = fopen(inputFileName, "rb"); + unsigned int uiByteCounts[256] = {}; // set the array to all zeros + + while (!feof(inputFile)) + { + unsigned char byte; + fread(&byte, 1, 1, inputFile); + + uiByteCounts[byte]++; + } + + HuffmanNode huffmanPool[512] = {}; + + unsigned int iNodesUsed = 0; + + std::vector aSymbolTree; + + for (unsigned int i = 0; i < 256; ++i) + { + if (uiByteCounts[i] != 0) + { + HuffmanNode* node = &huffmanPool[iNodesUsed++]; + node->iFrequency = uiByteCounts[i]; + node->value = (unsigned char)i; + + aSymbolTree.push_back(node); + } + } + + while (aSymbolTree.size() != 1) + { + std::sort(aSymbolTree.begin(), aSymbolTree.end(), + [](HuffmanNode *a, HuffmanNode* b) + { + return (a->iFrequency > b->iFrequency); + } + ); + + unsigned int uiLastIndex = aSymbolTree.size() - 1; + HuffmanNode* first = aSymbolTree[uiLastIndex]; + HuffmanNode* second = aSymbolTree[uiLastIndex - 1]; + + HuffmanNode* newNode = &huffmanPool[iNodesUsed++]; + newNode->iFrequency = first->iFrequency + second->iFrequency; + newNode->oneBitChild = first; + newNode->zeroBitChild = second; + + first->parent = newNode; + second->parent = newNode; + + aSymbolTree.pop_back(); + aSymbolTree.pop_back(); + + aSymbolTree.push_back(newNode); + } + + DictionaryEntry aDictionary[256]; + DictionaryEntry emptyEntry = {}; + FillDictionary(aDictionary, aSymbolTree[0], emptyEntry); + + FILE* outputFile = fopen(outputFileName, "wb"); + + fseek(inputFile, 0, SEEK_SET); + + fwrite(aDictionary, sizeof (aDictionary), 1, outputFile); + + unsigned char byteBuffer = 0; + unsigned int bitWriteCursor = 0; + + unsigned char maskLookup[9] = + { + 0, // 0000 0000 + 1, // 0000 0001 + 3, // 0000 0011 + 7, // 0000 0111 + 15, // 0000 1111 + 31, // 0001 1111 + 63, // 0011 1111 + 127, // 0111 1111 + 255 // 1111 1111 + }; + + while (!feof(inputFile)) + { + unsigned char byte; + fread(&byte, 1, 1, inputFile); + DictionaryEntry* entry = &aDictionary[byte]; + unsigned int bitReadCursor = 0; + + while (bitReadCursor < entry->uiBitCount) + { + unsigned int currReadBit = (bitReadCursor % 8); + unsigned int currReadByte = (bitReadCursor / 8); + + unsigned int bitsLeftInReadByte = 8 - currReadBit; + unsigned int bitsLeftInWriteByte = 8 - bitWriteCursor; + unsigned int bitsLeftInRead = entry->uiBitCount - bitReadCursor; + + unsigned int readBound = std::min(bitsLeftInReadByte, bitsLeftInRead); + unsigned int bitsToCopy = std::min(readBound, bitsLeftInWriteByte); + + unsigned char mask = maskLookup[bitsToCopy] << currReadBit; + + int shiftAmount = bitWriteCursor - currReadBit; + + if (shiftAmount >= 0) + { + // actual write + byteBuffer |= (entry->uiBitfield[currReadByte] & mask) << shiftAmount; + } + else + { + // actual write + byteBuffer |= (entry->uiBitfield[currReadByte] & mask) >> (-shiftAmount); + } + + bitWriteCursor += bitsToCopy; + bitReadCursor += bitsToCopy; + + if (bitWriteCursor == 8) + { + fwrite(&byteBuffer, 1, 1, outputFile); + byteBuffer = 0; + bitWriteCursor = 0; + } + } + } + fclose(inputFile); + fclose(outputFile); + + return 0; +} diff --git a/pool/shard006/C++/0084744_fake_permission_broker_client.cc b/pool/shard006/C++/0084744_fake_permission_broker_client.cc new file mode 100644 index 0000000000000000000000000000000000000000..73cc3645dbe771a8fe6536a37d11ae96487846dd --- /dev/null +++ b/pool/shard006/C++/0084744_fake_permission_broker_client.cc @@ -0,0 +1,214 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromeos/dbus/permission_broker/fake_permission_broker_client.h" + +#include +#include + +#include "base/bind.h" +#include "base/callback.h" +#include "base/check_op.h" +#include "base/location.h" +#include "base/posix/eintr_wrapper.h" +#include "base/strings/stringprintf.h" +#include "base/task/post_task.h" +#include "base/task/thread_pool.h" +#include "base/threading/thread_task_runner_handle.h" + +namespace chromeos { + +namespace { + +const char kOpenFailedError[] = "open_failed"; + +FakePermissionBrokerClient* g_instance = nullptr; + +// So that real devices can be accessed by tests and "Chromium OS on Linux" this +// function implements a simplified version of the method implemented by the +// permission broker by opening the path specified and returning the resulting +// file descriptor. +void OpenPath(const std::string& path, + PermissionBrokerClient::OpenPathCallback callback, + PermissionBrokerClient::ErrorCallback error_callback, + scoped_refptr task_runner) { + base::ScopedFD fd(HANDLE_EINTR(open(path.c_str(), O_RDWR))); + if (!fd.is_valid()) { + int error_code = logging::GetLastSystemErrorCode(); + task_runner->PostTask( + FROM_HERE, + base::BindOnce( + std::move(error_callback), kOpenFailedError, + base::StringPrintf( + "Failed to open '%s': %s", path.c_str(), + logging::SystemErrorCodeToString(error_code).c_str()))); + return; + } + + task_runner->PostTask(FROM_HERE, + base::BindOnce(std::move(callback), std::move(fd))); +} + +} // namespace + +FakePermissionBrokerClient::FakePermissionBrokerClient() { + DCHECK(!g_instance); + g_instance = this; +} + +FakePermissionBrokerClient::~FakePermissionBrokerClient() { + DCHECK_EQ(this, g_instance); + g_instance = nullptr; +} + +// static +FakePermissionBrokerClient* FakePermissionBrokerClient::Get() { + DCHECK(g_instance); + return g_instance; +} + +void FakePermissionBrokerClient::CheckPathAccess(const std::string& path, + ResultCallback callback) { + std::move(callback).Run(true); +} + +void FakePermissionBrokerClient::OpenPath(const std::string& path, + OpenPathCallback callback, + ErrorCallback error_callback) { + base::ThreadPool::PostTask( + FROM_HERE, + {base::MayBlock(), base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN}, + base::BindOnce(&chromeos::OpenPath, path, std::move(callback), + std::move(error_callback), + base::ThreadTaskRunnerHandle::Get())); +} + +void FakePermissionBrokerClient::RequestTcpPortAccess( + uint16_t port, + const std::string& interface, + int lifeline_fd, + ResultCallback callback) { + std::move(callback).Run( + RequestPortImpl(port, interface, tcp_deny_rule_set_, &tcp_hole_set_)); +} + +void FakePermissionBrokerClient::RequestUdpPortAccess( + uint16_t port, + const std::string& interface, + int lifeline_fd, + ResultCallback callback) { + std::move(callback).Run( + RequestPortImpl(port, interface, udp_deny_rule_set_, &udp_hole_set_)); +} + +void FakePermissionBrokerClient::ReleaseTcpPort(uint16_t port, + const std::string& interface, + ResultCallback callback) { + std::move(callback).Run(tcp_hole_set_.erase(std::make_pair(port, interface))); +} + +void FakePermissionBrokerClient::ReleaseUdpPort(uint16_t port, + const std::string& interface, + ResultCallback callback) { + std::move(callback).Run(udp_hole_set_.erase(std::make_pair(port, interface))); +} + +void FakePermissionBrokerClient::AddTcpDenyRule(uint16_t port, + const std::string& interface) { + tcp_deny_rule_set_.insert(std::make_pair(port, interface)); +} + +void FakePermissionBrokerClient::AddUdpDenyRule(uint16_t port, + const std::string& interface) { + udp_deny_rule_set_.insert(std::make_pair(port, interface)); +} + +bool FakePermissionBrokerClient::HasTcpHole(uint16_t port, + const std::string& interface) { + auto rule = std::make_pair(port, interface); + return tcp_hole_set_.find(rule) != tcp_hole_set_.end(); +} + +bool FakePermissionBrokerClient::HasUdpHole(uint16_t port, + const std::string& interface) { + auto rule = std::make_pair(port, interface); + return udp_hole_set_.find(rule) != udp_hole_set_.end(); +} + +bool FakePermissionBrokerClient::HasTcpPortForward( + uint16_t port, + const std::string& interface) { + auto rule = std::make_pair(port, interface); + return tcp_forwarding_set_.find(rule) != tcp_forwarding_set_.end(); +} + +bool FakePermissionBrokerClient::HasUdpPortForward( + uint16_t port, + const std::string& interface) { + auto rule = std::make_pair(port, interface); + return udp_forwarding_set_.find(rule) != udp_forwarding_set_.end(); +} + +void FakePermissionBrokerClient::RequestTcpPortForward( + uint16_t in_port, + const std::string& in_interface, + const std::string& dst_ip, + uint16_t dst_port, + int lifeline_fd, + ResultCallback callback) { + // TODO(matterchen): Increase logic for adding duplicate ports. + auto rule = std::make_pair(in_port, in_interface); + tcp_forwarding_set_.insert(rule); + std::move(callback).Run(true); +} + +void FakePermissionBrokerClient::RequestUdpPortForward( + uint16_t in_port, + const std::string& in_interface, + const std::string& dst_ip, + uint16_t dst_port, + int lifeline_fd, + ResultCallback callback) { + auto rule = std::make_pair(in_port, in_interface); + udp_forwarding_set_.insert(rule); + std::move(callback).Run(true); +} + +void FakePermissionBrokerClient::ReleaseTcpPortForward( + uint16_t in_port, + const std::string& in_interface, + ResultCallback callback) { + auto rule = std::make_pair(in_port, in_interface); + tcp_forwarding_set_.erase(rule); + std::move(callback).Run(true); +} + +void FakePermissionBrokerClient::ReleaseUdpPortForward( + uint16_t in_port, + const std::string& in_interface, + ResultCallback callback) { + auto rule = std::make_pair(in_port, in_interface); + udp_forwarding_set_.erase(rule); + std::move(callback).Run(true); +} + +bool FakePermissionBrokerClient::RequestPortImpl(uint16_t port, + const std::string& interface, + const RuleSet& deny_rule_set, + RuleSet* hole_set) { + auto rule = std::make_pair(port, interface); + + // If there is already a hole, returns true. + if (hole_set->find(rule) != hole_set->end()) + return true; + + // If it is denied to make a hole, returns false. + if (deny_rule_set.find(rule) != deny_rule_set.end()) + return false; + + hole_set->insert(rule); + return true; +} + +} // namespace chromeos diff --git a/pool/shard006/C++/0084753_Sets.cpp b/pool/shard006/C++/0084753_Sets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4e3436abeddf4cb45dee87b3fd15654ccec64a5 --- /dev/null +++ b/pool/shard006/C++/0084753_Sets.cpp @@ -0,0 +1,121 @@ +#include "ace/OS_Memory.h" +#include "ace/Log_Msg.h" +#include "ace/Containers.h" +#include "DataElement.h" + +class SetExample +{ +public: + // Illustrate all ACE set types. + int run (void); + +private: + // Illustrate the ACE Bounded Sets. + int runBoundedSet (void); + + // Illustrate the ACE Unbounded sets. + int runUnboundedSet (void); +}; + +int SetExample::run (void) +{ + ACE_TRACE ("SetExample::run"); + + ACE_ASSERT (!this->runBoundedSet ()); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n# of live objects %d\n"), + DataElement::numOfActiveObjects ())); + + ACE_ASSERT (!this->runUnboundedSet ()); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("\n# of live objects %d\n"), + DataElement::numOfActiveObjects ())); + + return 0; +} +// Listing 1 code/ch05 +int SetExample::runBoundedSet () +{ + ACE_TRACE ("SetExample::runBoundedSet"); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Using a bounded set\n"))); + ACE_Bounded_Set bset (100); + + DataElement elem[100]; + for (int i = 0; i < 100; i++) + { + elem[i].setData (i); + + // Inserting two copies of the same element isn't allowed. + bset.insert (elem[i]); + if (bset.insert (elem[i]) == -1) + { + ACE_DEBUG ((LM_ERROR, ACE_TEXT ("%p\n"), + ACE_TEXT ("insert set"))); + } + } + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d\n"), + DataElement::numOfActiveObjects ())); + + DataElement elem1 (10), elem2 (99); + if (!bset.find (elem1) && !bset.find (elem2)) + { + ACE_DEBUG ((LM_INFO, + ACE_TEXT ("The elements %d and %d are ") + ACE_TEXT ("in the set!\n"), + elem1.getData (), elem2.getData ())); + } + + for (int j = 0; j < 50; j++) + { + bset.remove (elem[j]); // Remove the element from the set. + ACE_DEBUG + ((LM_DEBUG, ACE_TEXT ("%d:"), elem[j].getData ())); + } + + if ((bset.find (elem[0]) == -1) && (bset.find (elem[49]) == -1)) + { + ACE_DEBUG ((LM_INFO, + ACE_TEXT ("The elements %d and %d are ") + ACE_TEXT ("NOT in the set!\n"), + elem[0].getData (), elem[99].getData ())); + } + + return 0; +} +// Listing 1 +// Listing 2 code/ch05 +int SetExample::runUnboundedSet () +{ + ACE_TRACE ("SetExample::runUnboundedSet"); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Using an unbounded set.\n"))); + ACE_Unbounded_Set uset; + for (int m = 0; m < 100; m++) + { + DataElement *elem; + ACE_NEW_RETURN (elem, DataElement (m), -1); + uset.insert (elem); + } + DataElement deBegin (0), deEnd (99); + if (!uset.find (&deBegin) && !uset.find (&deEnd)) + { + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Found the elements\n"))); + } + + // Iterate and destroy the elements in the set. + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("Deleting the elements\n"))); + ACE_Unbounded_Set_Iterator iter (uset); + for (iter = uset.begin (); iter != uset.end (); iter++) + { + DataElement* elem = (*iter); + ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("%d:"), elem->getData ())); + delete elem; + } + + return 0; +} +// Listing 2 + +int ACE_TMAIN (int, ACE_TCHAR *[]) +{ + SetExample se; + se.run (); + return 0; +} diff --git a/pool/shard006/C++/0084760_main.cpp b/pool/shard006/C++/0084760_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac57c465ec8b1bc1919da61fef63bcdff6a79e6d --- /dev/null +++ b/pool/shard006/C++/0084760_main.cpp @@ -0,0 +1,154 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +QTM_USE_NAMESPACE + + +#define NO_DISCOVERED_CONFIGURATIONS_ERROR 1 +#define SESSION_OPEN_ERROR 2 + + +int main(int argc, char** argv) +{ + QCoreApplication app(argc, argv); + + // Update configurations so that everything is up to date for this process too. + // Event loop is used to wait for awhile. + QNetworkConfigurationManager manager; + manager.updateConfigurations(); + QEventLoop iIgnoreEventLoop; + QTimer::singleShot(3000, &iIgnoreEventLoop, SLOT(quit())); + iIgnoreEventLoop.exec(); + + QList discovered = + manager.allConfigurations(QNetworkConfiguration::Discovered); + + foreach(QNetworkConfiguration config, discovered) { + qDebug() << "Lackey: Name of the config enumerated: " << config.name(); + qDebug() << "Lackey: State of the config enumerated: " << config.state(); + } + + if (discovered.isEmpty()) { + qDebug("Lackey: no discovered configurations, returning empty error."); + return NO_DISCOVERED_CONFIGURATIONS_ERROR; + } + + // Cannot read/write to processes on WinCE or Symbian. + // Easiest alternative is to use sockets for IPC. + QLocalSocket oopSocket; + + oopSocket.connectToServer("tst_qnetworksession"); + oopSocket.waitForConnected(-1); + + qDebug() << "Lackey started"; + + QNetworkSession *session = 0; + do { + if (session) { + delete session; + session = 0; + } + + qDebug() << "Discovered configurations:" << discovered.count(); + + if (discovered.isEmpty()) { + qDebug() << "No more discovered configurations"; + break; + } + + qDebug() << "Taking first configuration"; + + QNetworkConfiguration config = discovered.takeFirst(); + + if ((config.state() & QNetworkConfiguration::Active) == QNetworkConfiguration::Active) { + qDebug() << config.name() << " is active, therefore skipping it (looking for configs in 'discovered' state)."; + continue; + } + + qDebug() << "Creating session for" << config.name() << config.identifier(); + + session = new QNetworkSession(config); + + QString output = QString("Starting session for %1\n").arg(config.identifier()); + oopSocket.write(output.toAscii()); + oopSocket.waitForBytesWritten(); + session->open(); + session->waitForOpened(); + } while (!(session && session->isOpen())); + + qDebug() << "lackey: loop done"; + + if (!session) { + qDebug() << "Could not start session"; + + oopSocket.disconnectFromServer(); + oopSocket.waitForDisconnected(-1); + + return SESSION_OPEN_ERROR; + } + + QString output = QString("Started session for %1\n").arg(session->configuration().identifier()); + oopSocket.write(output.toAscii()); + oopSocket.waitForBytesWritten(); + + oopSocket.waitForReadyRead(); + oopSocket.readLine(); + + session->stop(); + + delete session; + + oopSocket.disconnectFromServer(); + oopSocket.waitForDisconnected(-1); + + return 0; +} diff --git a/pool/shard006/C++/0084768_RouteController.cpp b/pool/shard006/C++/0084768_RouteController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9a58090dc7d37d07862540775c1c38509e8e3d9 --- /dev/null +++ b/pool/shard006/C++/0084768_RouteController.cpp @@ -0,0 +1,35 @@ +// +// Created by Pedro Soares on 23/03/17. +// + +#include "RouteController.h" + +RouteController::RouteController() { + +} + +void RouteController::boot(int argc, char * argv[]) { + + if(argc < 2){ + return; + } + + vector paramns; + + for (int i = 2; i < argc; ++i) { + paramns.push_back(string(argv[i])); + } + + string nome = argv[1]; + for (auto& item: routes) { + if(nome == item.first){ + Console * console = item.second; + console->setParamns(paramns); + console->Execute(); + return; + } + } + + cout << "Não encontrado!" << endl; + +} \ No newline at end of file diff --git a/pool/shard006/C++/0084775_gstSite.cpp b/pool/shard006/C++/0084775_gstSite.cpp new file mode 100644 index 0000000000000000000000000000000000000000..134f1ef39e2afba01eb0e6df6c3ec8804340b03d --- /dev/null +++ b/pool/shard006/C++/0084775_gstSite.cpp @@ -0,0 +1,157 @@ +// Copyright 2017 Google Inc. +// Copyright 2020 The Open GEE Contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +#include +#include +#include +#include + +gstSite::gstSite(const FuseSiteConfig& cfg, + const gstSitePreviewConfig &preview_cfg) + : config(cfg), + preview_config(preview_cfg) { + offset_x_ = offset_y_ = 0.0; + + label_format_ = NULL; + popup_text_format_ = NULL; + custom_height_format_ = NULL; + + site_header_ = gstHeaderImpl::Create(); + site_header_->addSpec("label", gstTagUnicode); + site_header_->addSpec("outline_label", gstTagUnicode); + site_header_->addSpec("address", gstTagUnicode); + site_header_->addSpec("customHeight", gstTagDouble); +} + +gstSite::~gstSite() { + delete label_format_; + delete popup_text_format_; + delete custom_height_format_; +} + +gstVertex gstSite::Location(const gstGeodeHandle &feature) const { + if (feature->IsDegenerate()) { + notify(NFY_WARN, + "Can't build a site without a feature to get coords from!"); + return gstVertex(); + } + + // find the vertex coordinate + if (feature->PrimType() == gstPoint) { + return feature->Center(); + } else { + switch (config.position) { + case VectorDefs::AreaCenter: + { + gstVertex center = feature->Center(); + if (center != gstVertex()) { + return center; + } else { + return gstVertex(feature->BoundingBox().CenterX() + offset_x_, + feature->BoundingBox().CenterY() + offset_y_); + } + } + break; + + case VectorDefs::LineCenter: { + // TODO: feature can contain no one polyline here! + // Where should be the line center in this case? + return feature->Center(); + } + break; + } + } + + return gstVertex(); +} + + +gstRecordHandle gstSite::Expand(gstRecordHandle srcrec, + bool label_only, + JSDisplayBundle &jsbundle, + unsigned int filterId) const { + gstHeaderHandle srchdr = srcrec->Header(); + gstRecordHandle new_rec = site_header_->NewRecord(); + bool setJSRec = false; + + if (label().length()) { + QString outval; + if (jsbundle.displayJS[filterId].labelScript) { + jsbundle.cx->SetRecord(srcrec); + setJSRec = true; + QString error; + if (!jsbundle.cx->TryExecuteScript + (jsbundle.displayJS[filterId].labelScript, outval, error)) { + notify(NFY_WARN, "Error executing JS: %s", (const char *)error.utf8()); + outval = QString(); + return gstRecordHandle(); + } + } else { + if (label_format_ == NULL) + label_format_ = new gstRecordFormatter(label(), srchdr); + outval = label_format_->out(srcrec); + } + if (!outval.isEmpty()) + new_rec->Field(0)->set(outval); + } + + if (label_only) + return new_rec; + + if (config.popupText.length()) { + QString outval; + if (jsbundle.displayJS[filterId].popupTextScript) { + if (!setJSRec) { + jsbundle.cx->SetRecord(srcrec); + setJSRec = true; + } + QString error; + if (!jsbundle.cx->TryExecuteScript + (jsbundle.displayJS[filterId].popupTextScript, outval, error)) { + notify(NFY_WARN, "Error executing JS: %s", (const char *)error.utf8()); + outval = QString(); + return gstRecordHandle(); + } + } else { + if (popup_text_format_ == NULL) + popup_text_format_ = new gstRecordFormatter(config.popupText, srchdr); + outval = popup_text_format_->out(srcrec); + } + if (!outval.isEmpty()) + new_rec->Field(1)->set(outval); + } + + + // get the custom height variable field + if (config.style.altitudeMode != StyleConfig::ClampToGround && + config.style.enableCustomHeight && + config.style.customHeightVariableName.length()) { + if (custom_height_format_ == NULL) + custom_height_format_ = + new gstRecordFormatter(config.style.customHeightVariableName, + srchdr); + QString outval = custom_height_format_->out(srcrec); + if (outval.isEmpty()) { + new_rec->Field(2)->set(QString("0")); + } else { + new_rec->Field(2)->set(outval); + } + } else { + new_rec->Field(2)->set(QString("0")); + } + + return new_rec; +} diff --git a/pool/shard006/C++/0084785_s2_updateanddeletewithapi.xaml.cpp b/pool/shard006/C++/0084785_s2_updateanddeletewithapi.xaml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..530e1d0ff983e0a8ddbdb37a511d3bcb298b8cf3 --- /dev/null +++ b/pool/shard006/C++/0084785_s2_updateanddeletewithapi.xaml.cpp @@ -0,0 +1,167 @@ +//********************************************************* +// +// Copyright (c) Microsoft. All rights reserved. +// This code is licensed under the MIT License (MIT). +// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF +// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY +// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR +// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. +// +//********************************************************* + +// +// S2_UpdateAndDeleteWithAPI.xaml.cpp +// Implementation of the S2_UpdateAndDeleteWithAPI class +// + +#include "pch.h" +#include "S2_UpdateAndDeleteWithAPI.xaml.h" +#include "MainPage.xaml.h" +#include "Helpers.h" + +using namespace SDKTemplate; + +using namespace concurrency; +using namespace Platform; +using namespace Platform::Collections; +using namespace Windows::UI::Xaml; +using namespace Windows::UI::Xaml::Controls; +using namespace Windows::Foundation; +using namespace Windows::Foundation::Collections; + +S2_UpdateAndDeleteWithAPI::S2_UpdateAndDeleteWithAPI() +{ + InitializeComponent(); + InitializeRevisionNumber(); +} + +void Indexer::S2_UpdateAndDeleteWithAPI::AddToIndex_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer(); + AddItemsToIndex(indexer); +} + +void Indexer::S2_UpdateAndDeleteWithAPI::UpdatePropertyHelper(String^ itemKey, String^ propertyKey, String^ propertyName, Object^ newValue) +{ + auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer(); + auto propertyKeys = ref new Vector(); + propertyKeys->Append(propertyKey); + auto outputStrings = ref new Vector(); + create_task(indexer->RetrievePropertiesAsync(itemKey, propertyKeys)).then( + [outputStrings, indexer, this, itemKey, propertyKey, newValue, propertyName](IMapView^ retrievedProperties) mutable + { + // Log the original value of the property + outputStrings->Append(L"Original " + propertyName + L": " + StringifyProperty(retrievedProperties->Lookup(propertyKey))); + + // Create an indexable content item to update the property + auto content = ref new Windows::Storage::Search::IndexableContent(); + content->Id = itemKey; + content->Properties->Insert(propertyKey, newValue); + + // Update the indexer + OnIndexerOperationBegin(); + return indexer->UpdateAsync(content); + }).then([indexer, itemKey, propertyKeys]() + { + OnIndexerOperationComplete(indexer); + return indexer->RetrievePropertiesAsync(itemKey, propertyKeys); + }).then([outputStrings, propertyKey, propertyName](IMapView^ retrievedProperties) mutable + { + // Log the new value of the property + outputStrings->Append(L"\nNew " + propertyName + L": " + StringifyProperty(retrievedProperties->Lookup(propertyKey))); + auto outputString = ref new String(L""); + for (const auto& str : outputStrings) + { + outputString += str; + } + return outputString; + }).then([](task outputStringTask) + { + try + { + MainPage::Current->NotifyUser(outputStringTask.get(), NotifyType::StatusMessage); + } + catch (Platform::InvalidArgumentException^ e) + { + MainPage::Current->NotifyUser(L"Exception thrown! Did you try to retrieve or update a property on a non-existent item?" + + L"\nMessage: " + e->Message + + L"\nHRESULT: " + HResultToString(e->HResult), + NotifyType::ErrorMessage); + } + }); +} + +// This function updates the ItemNameDisplay property for the indexed item with the key "Sample 0." The +// updated ItemNameDisplay property comes from the itemNameInput text box. +void Indexer::S2_UpdateAndDeleteWithAPI::UpdateName_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + UpdatePropertyHelper(L"SampleKey0", Windows::Storage::SystemProperties::ItemNameDisplay, L"item name", ItemNameInput->Text); +} + +// This function deletes the Keywords property for the indexed item with the key "Sample0." +void Indexer::S2_UpdateAndDeleteWithAPI::DeleteKeywords_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + UpdatePropertyHelper(L"SampleKey0", Windows::Storage::SystemProperties::Keywords, L"keywords", nullptr); +} + +void Indexer::S2_UpdateAndDeleteWithAPI::DeleteItemsHelper(std::function deleteFunction) +{ + auto indexer = Windows::Storage::Search::ContentIndexer::GetIndexer(); + auto propertiesToRetrieve = ref new Vector(); + propertiesToRetrieve->Append(Windows::Storage::SystemProperties::ItemNameDisplay); + auto query = indexer->CreateQuery(L"*", propertiesToRetrieve); + auto outputStrings = ref new Vector(); + create_task(query->GetCountAsync()).then([outputStrings, indexer, deleteFunction](unsigned int count) + { + outputStrings->Append(L"Original number of items: " + count); + OnIndexerOperationBegin(); + return deleteFunction(indexer); + }).then([propertiesToRetrieve, indexer]() + { + OnIndexerOperationComplete(indexer); + auto query = indexer->CreateQuery(L"*", propertiesToRetrieve); + return query->GetCountAsync(); + }).then([outputStrings](unsigned int count) + { + outputStrings->Append(L"\nNew number of items: " + count); + auto outputString = ref new String(L""); + for (const auto& str : outputStrings) + { + outputString += str; + } + MainPage::Current->NotifyUser(outputString, NotifyType::StatusMessage); + }); +} + +// This function deletes the indexed item with the key "SampleKey0" added to the index by this app via the ContentIndexer +void Indexer::S2_UpdateAndDeleteWithAPI::DeleteSingleItem_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + return DeleteItemsHelper(std::function( + [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^ + { + return indexer->DeleteAsync(L"SampleKey0"); + })); +} + +// This function deletes the indexed items with the keys "SampleKey1" and "SampleKey2" added to the index by this app via the ContentIndexer +void Indexer::S2_UpdateAndDeleteWithAPI::DeleteMultipleItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + return DeleteItemsHelper(std::function( + [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^ + { + auto documentKeys = ref new Vector(); + documentKeys->Append(L"SampleKey1"); + documentKeys->Append(L"SampleKey2"); + return indexer->DeleteMultipleAsync(documentKeys); + })); +} + +// This function deletes all items added to the index by this app via the ContentIndexer +void Indexer::S2_UpdateAndDeleteWithAPI::DeleteAllItems_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e) +{ + return DeleteItemsHelper(std::function( + [](Windows::Storage::Search::ContentIndexer^ indexer) -> IAsyncAction^ + { + return indexer->DeleteAllAsync(); + })); +} diff --git a/pool/shard006/C++/0084790_knmusicffmpeganalysiser.cpp b/pool/shard006/C++/0084790_knmusicffmpeganalysiser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a8c1eab8bf770ccc8156a4a44f3df955d77584f --- /dev/null +++ b/pool/shard006/C++/0084790_knmusicffmpeganalysiser.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (C) Kreogist Dev Team + * + * 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 + +extern "C" +{ +#include +#include +} + +#include "knmusicffmpeganalysiser.h" + +KNMusicFfmpegAnalysiser::KNMusicFfmpegAnalysiser(QObject *parent) : + KNMusicAnalysiser(parent) +{ + //Register all the the muxers, demuxers and protocols. + av_register_all(); +} + +bool KNMusicFfmpegAnalysiser::analysis(KNMusicDetailInfo &detailInfo) +{ + //Generate the format context pointer. + AVFormatContext *formatContext=NULL; + //Open the file with ffmpeg. + if(avformat_open_input( + &formatContext, + QDir::toNativeSeparators( + detailInfo.filePath).toLocal8Bit().data(), + NULL, + NULL)) + { + //If return any negative AVERROR on failure, then failed to analysis the + //file. + return false; + } + //Check the formatContext. + if(!formatContext) + { + //Something wrong happened. + //Close the format context. + avformat_close_input(&formatContext); + //Failed to analysis the file. + return false; + } + //Find the stream info from the context. + if(avformat_find_stream_info(formatContext, NULL)<0) + { + //We can't find even one stream in the file. + //Close the format context. + avformat_close_input(&formatContext); + //Failed to analysis the file. + return false; + } + //Check whether the codec parameter is defined, if so, then it will use the + //latest version code of FFMpeg. + //Here we use the FF_API_OLD_BSF as the tester, the version later should + //contains AVCodecParameters. +#if (defined FF_API_COPY_CONTENT) || (defined Q_OS_MACX) + //Initial the audio stream context. + AVCodecParameters *codecParameters=NULL; + //Find the audio stream. + for(unsigned int i=0; inb_streams; ++i) + { + //Get the stream; + AVStream *stream=formatContext->streams[i]; + //Check the validation of the stream. + if(stream) + { + //Get the codec context of the stream. + AVCodecParameters *parameters=stream->codecpar; + //Check the context of the stream. + if(parameters && parameters->codec_type==AVMEDIA_TYPE_AUDIO) + { + //Save the context. + codecParameters=parameters; + //Get the sample rate. + detailInfo.samplingRate=codecParameters->sample_rate; + //Break. + break; + } + } + } +#else + //Use the old codec parameter of the stream. It is not recommend in the + //latest ffmpeg. + //Initial the audio stream context. + AVCodecContext *codecParameters=NULL; + //Find the audio stream. + for(unsigned int i=0; inb_streams; ++i) + { + //Get the stream; + AVStream *stream=formatContext->streams[i]; + //Check the validation of the stream. + if(stream) + { + //Get the codec context of the stream. + AVCodecContext *context=stream->codec; + //Check the context of the stream. + if(context && context->codec_type==AVMEDIA_TYPE_AUDIO) + { + //Save the context. + codecParameters=context; + //Break. + break; + } + } + } +#endif + //Check the audio stream index. + if(!codecParameters) + { + //We can't find any audio stream in the file. + //Close the format context. + avformat_close_input(&formatContext); + //Failed to analysis the file. + return false; + } + //Now, everything is ready. + //The duration which AVFormatContext providec is the duration of the stream, + //in AV_TIME_BASE fractional seconds. We need to change it to ms. + detailInfo.duration=formatContext->duration/(AV_TIME_BASE/1000); + //Calculate the bit rate. + detailInfo.bitRate=(double)detailInfo.size/detailInfo.duration*8+0.5; + //Close the format context. + avformat_close_input(&formatContext); + //Analysis complete. + return true; +} diff --git a/pool/shard006/C++/0084794_pr2_softness_sorter.cpp b/pool/shard006/C++/0084794_pr2_softness_sorter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3129669a7f690e437fe18286d3b986e6ad19de8f --- /dev/null +++ b/pool/shard006/C++/0084794_pr2_softness_sorter.cpp @@ -0,0 +1,47 @@ +/** + * @file pr2_softness_sorter.cpp + * @brief Launches grasp manager code + * @author Daniel Angelov + * @date 2016-06-08 + * @copyright (MIT) 2015 RAD-UoE Informatics + */ + +#include + +#include + +int main(int argc, char** argv) { + ros::init(argc, argv, "pr2_softness_sorter"); + ros::NodeHandle nh("~"); + + GraspManager grasp_manager(nh); + + ros::Rate r(10); + + while (ros::ok()) { + ros::spinOnce(); + if (grasp_manager.getGrasp()) { + ROS_INFO("Attempting to pick up object!"); + if (grasp_manager.sendPick()) { + ROS_INFO("Placing the object!"); + double hardness = grasp_manager.isSoft(); + ROS_WARN_STREAM("hardness: " << hardness); + if (hardness > 0.17) { + ROS_WARN("It is HARD!"); + grasp_manager.sendPlace(PLACE_LOCATION::HARD); + } else { + ROS_WARN("It is soft"); + grasp_manager.sendPlace(PLACE_LOCATION::SOFT); + } + } else { + ROS_INFO("Moving out of the way!"); + grasp_manager.sendMoveTo(); + } + } + r.sleep(); + } + + ros::shutdown(); + + return 0; +} diff --git a/pool/shard006/C++/0084802_SwingCLI.cpp b/pool/shard006/C++/0084802_SwingCLI.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dedf4faa3127b012ac6d161bb5e78968e05c0380 --- /dev/null +++ b/pool/shard006/C++/0084802_SwingCLI.cpp @@ -0,0 +1,86 @@ +#include "SwingCLI.h" + +#include "SwingCompiler.h" +//#include "crefile.hpp" +//#include "Debugger.h" +#include + +namespace swing +{ + + SwingCLI::SwingCLI(int argc, char* argv[]) : _args(), _commandLines(nullptr) + { + //_outPath = crefile::dirname(argv[0]); + std::string exe(argv[0]); + auto iter = exe.rbegin(); + for (; iter != exe.rend(); ++iter) + { + if (*iter == '\\') + break; + } + exe = std::string(exe.begin(), iter.base()); + + g_SwingCompiler->_swingPath = exe; + /// char* array -> string vector + for (int i = 1; i < argc; i++) + { + _args.push_back(std::string(argv[i])); + } + } + + SwingCLI::~SwingCLI() + { + } + + void SwingCLI::InitProgram() + { + /// Environment variable Setting. + /*if (std::getenv("SWING_PATH") == nullptr) + { +#ifdef _WINDOWS + _putenv_s("SWING_PATH", _outPath.c_str()); +#else + std::setenv("SWING_PATH", _outPath.c_str()); +#endif + }*/ + + /// Command Line + if (_args.empty()) + { + _commandLines = new HelpCommand(); + } + else if (_args[0] == "-build") + { + _commandLines = new BuildCommand(); + } + else if (_args[0] == "-compile") + { + _commandLines = new CompileCommand(); + } + else if (_args[0] == "-link") + { + _commandLines = new LinkCommand(); + } + /*else if (_args[0] == "-debug") + { + _commandLines = new DebugCommand(); + } + else if (_args[0] == "-create") + { + _commandLines = new CreateCommand(); + }*/ + else + { + _commandLines = new HelpCommand(); + } + } + + int SwingCLI::RunProgram() + { + if (!_commandLines->VerifierCommand(_args)) + return -1; + + return _commandLines->RunCommand(); + } + +} \ No newline at end of file diff --git a/pool/shard006/C++/0084803_gputer.cc b/pool/shard006/C++/0084803_gputer.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd042c7750c01a10ca4fe5f4b74cd30e312c6fb8 --- /dev/null +++ b/pool/shard006/C++/0084803_gputer.cc @@ -0,0 +1,89 @@ +#ifndef _WIN32 + +#include +#include +#include + +#include "llvm/Target/TargetOptions.h" +#include "llvm/Support/TargetRegistry.h" +#include "llvm/Target/TargetMachine.h" +#include "llvm/IR/LegacyPassManager.h" +#include "llvm/Transforms/IPO/PassManagerBuilder.h" + +#include "gputer.h" + +namespace Exys +{ + +Gputer::Gputer(std::unique_ptr jitter) +:mJitter(std::move(jitter)) +{ +} + +Gputer::~Gputer() +{ +} + +std::string Gputer::GetDOTGraph() +{ + return mJitter->GetDOTGraph(); +} + +void Gputer::CompleteBuild() +{ + LLVMInitializeNVPTXTarget(); + LLVMInitializeNVPTXAsmPrinter(); + LLVMInitializeNVPTXTargetInfo(); + LLVMInitializeNVPTXTargetMC(); + + auto module = mJitter->BuildModule(); + auto* M = module.get(); + + std::string Err; + std::string PTXTriple("nvptx64-unknown-cuda"); + std::string PTXCPU = "sm_35"; + + const llvm::Target *ptxTarget = llvm::TargetRegistry::lookupTarget(PTXTriple, Err); + if (!ptxTarget) + { + std::cout << Err; + assert(false && "no nvptx target is available"); + } + + if(!ptxTarget->hasTargetMachine()) + { + assert(false && "no backend for ptx gen available"); + } + + llvm::TargetOptions PTXTargetOptions = llvm::TargetOptions(); + auto* ptxTargetMachine = ptxTarget->createTargetMachine(PTXTriple, PTXCPU, "", PTXTargetOptions, + llvm::Reloc::PIC_, llvm::CodeModel::Default, llvm::CodeGenOpt::Aggressive); + + // 64-bit + M->setDataLayout(llvm::StringRef("e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-" + "f64:64:64-v16:16:16-v32:32:32-v64:64:64-v128:128:128-n16:32:64")); + + // Generate PTX assembly + llvm::raw_string_ostream OS(mPtxBuf); + { + // TODO: put these in the constructor + // + llvm::legacy::PassManager *PM2 = new llvm::legacy::PassManager(); + llvm::buffer_ostream FOS(OS); + ptxTargetMachine->addPassesToEmitFile(*PM2, FOS, llvm::TargetMachine::CGFT_AssemblyFile); + PM2->run(*M); + delete PM2; + } +} + +std::unique_ptr Gputer::Build(const std::string& text) +{ + auto jitter = Jitter::Build(text); + auto engine = std::unique_ptr(new Gputer(std::move(jitter))); + engine->CompleteBuild(); + return engine; +} + +} + +#endif diff --git a/pool/shard006/C++/0084807_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18.cpp b/pool/shard006/C++/0084807_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af6fdd9c943a9fc3b73567f8ffd923b724e16c6d --- /dev/null +++ b/pool/shard006/C++/0084807_CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18.cpp @@ -0,0 +1,116 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18.cpp +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805.string.label.xml +Template File: sources-sink-18.tmpl.cpp +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using new[] and set data pointer to a small buffer + * GoodSource: Allocate using new[] and set data pointer to a large buffer + * Sink: loop + * BadSink : Copy string to data using a loop + * Flow Variant: 18 Control flow: goto statements + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18 +{ + +#ifndef OMITBAD + +void bad() +{ + wchar_t * data; + data = NULL; + goto source; +source: + /* FLAW: Allocate using new[] and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = new wchar_t[50]; + data[0] = L'\0'; /* null terminate */ + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + delete [] data; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by reversing the blocks on the goto statement */ +static void goodG2B() +{ + wchar_t * data; + data = NULL; + goto source; +source: + /* FIX: Allocate using new[] and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = new wchar_t[100]; + data[0] = L'\0'; /* null terminate */ + { + size_t i; + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if source is larger than data */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + delete [] data; + } +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE805_wchar_t_loop_18; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard006/C++/0084810_vstcomponent.cpp b/pool/shard006/C++/0084810_vstcomponent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e0dee587cd7f4304957463d82aa53e56c1dbc21b --- /dev/null +++ b/pool/shard006/C++/0084810_vstcomponent.cpp @@ -0,0 +1,202 @@ +//----------------------------------------------------------------------------- +// Project : VST SDK +// Version : 3.6.0 +// +// Category : Helpers +// Filename : public.sdk/source/vst/vstcomponent.cpp +// Created by : Steinberg, 04/2005 +// Description : Basic VST Plug-in Implementation +// +//----------------------------------------------------------------------------- +// LICENSE +// (c) 2013, Steinberg Media Technologies GmbH, All Rights Reserved +//----------------------------------------------------------------------------- +// This Software Development Kit may not be distributed in parts or its entirety +// without prior written agreement by Steinberg Media Technologies GmbH. +// This SDK must not be used to re-engineer or manipulate any technology used +// in any Steinberg or Third-party application or software module, +// unless permitted by law. +// Neither the name of the Steinberg Media Technologies nor the names of its +// contributors may be used to endorse or promote products derived from this +// software without specific prior written permission. +// +// THIS SDK IS PROVIDED BY STEINBERG MEDIA TECHNOLOGIES GMBH "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 STEINBERG MEDIA TECHNOLOGIES GMBH BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. +//---------------------------------------------------------------------------------- + +#include "vstcomponent.h" + +namespace Steinberg { +namespace Vst { + + +//------------------------------------------------------------------------ +// Component Implementation +//------------------------------------------------------------------------ +Component::Component () +: audioInputs (kAudio, kInput) +, audioOutputs (kAudio, kOutput) +, eventInputs (kEvent, kInput) +, eventOutputs (kEvent, kOutput) +{} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::initialize (FUnknown* context) +{ + return ComponentBase::initialize (context); +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::terminate () +{ + // remove all buses + removeAllBusses (); + + return ComponentBase::terminate (); +} + +//------------------------------------------------------------------------ +BusList* Component::getBusList (MediaType type, BusDirection dir) +{ + if (type == kAudio) + return dir == kInput ? &audioInputs : &audioOutputs; + else if (type == kEvent) + return dir == kInput ? &eventInputs : &eventOutputs; + return 0; +} + +//------------------------------------------------------------------------ +tresult Component::removeAudioBusses () +{ + audioInputs.removeAll (); + audioOutputs.removeAll (); + + return kResultOk; +} + +//------------------------------------------------------------------------ +tresult Component::removeEventBusses () +{ + eventInputs.removeAll (); + eventOutputs.removeAll (); + + return kResultOk; +} + +//------------------------------------------------------------------------ +tresult Component::removeAllBusses () +{ + removeAudioBusses (); + removeEventBusses (); + + return kResultOk; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::getControllerClassId (TUID classID) +{ + if (controllerClass.isValid ()) + { + controllerClass.toTUID (classID); + return kResultTrue; + } + return kResultFalse; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::setIoMode (IoMode /*mode*/) +{ + return kNotImplemented; +} + +//------------------------------------------------------------------------ +int32 PLUGIN_API Component::getBusCount (MediaType type, BusDirection dir) +{ + BusList* busList = getBusList (type, dir); + return busList ? busList->total () : 0; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::getBusInfo (MediaType type, BusDirection dir, int32 index, BusInfo& info) +{ + BusList* busList = getBusList (type, dir); + Bus* bus = busList ? busList->at (index) : 0; + if (bus) + { + info.mediaType = type; + info.direction = dir; + if (bus->getInfo (info)) + return kResultTrue; + } + return kResultFalse; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::getRoutingInfo (RoutingInfo& /*inInfo*/, RoutingInfo& /*outInfo*/) +{ + return kNotImplemented; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::activateBus (MediaType type, BusDirection dir, int32 index, TBool state) +{ + BusList* busList = getBusList (type, dir); + Bus* bus = busList ? busList->at (index) : 0; + if (bus) + { + bus->setActive (state); + return kResultTrue; + } + return kResultFalse; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::setActive (TBool /*state*/) +{ + return kResultOk; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::setState (IBStream* /*state*/) +{ + return kNotImplemented; +} + +//------------------------------------------------------------------------ +tresult PLUGIN_API Component::getState (IBStream* /*state*/) +{ + return kNotImplemented; +} + +//------------------------------------------------------------------------ +tresult Component::renameBus (MediaType type, BusDirection dir, int32 index, const String128 newName) +{ + BusList* busList = getBusList (type, dir); + Bus* bus = busList ? busList->at (index) : 0; + if (bus) + { + bus->setName (newName); + return kResultTrue; + } + return kResultFalse; +} + + +//------------------------------------------------------------------------ +// Helpers Implementation +//------------------------------------------------------------------------ +tresult getSpeakerChannelIndex (SpeakerArrangement arrangement, uint64 speaker, int32& channel) +{ + channel = SpeakerArr::getSpeakerIndex (speaker, arrangement); + return channel < 0 ? kResultFalse : kResultTrue; +} +} // namespace Vst +} // namespace Steinberg diff --git a/pool/shard006/C++/0084812_ListCustomMetricsResult.cpp b/pool/shard006/C++/0084812_ListCustomMetricsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3fcae4a54bcd6ea3e836cb36c39a52a267e85bb8 --- /dev/null +++ b/pool/shard006/C++/0084812_ListCustomMetricsResult.cpp @@ -0,0 +1,49 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::IoT::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListCustomMetricsResult::ListCustomMetricsResult() +{ +} + +ListCustomMetricsResult::ListCustomMetricsResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +ListCustomMetricsResult& ListCustomMetricsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("metricNames")) + { + Array metricNamesJsonList = jsonValue.GetArray("metricNames"); + for(unsigned metricNamesIndex = 0; metricNamesIndex < metricNamesJsonList.GetLength(); ++metricNamesIndex) + { + m_metricNames.push_back(metricNamesJsonList[metricNamesIndex].AsString()); + } + } + + if(jsonValue.ValueExists("nextToken")) + { + m_nextToken = jsonValue.GetString("nextToken"); + + } + + + + return *this; +} diff --git a/pool/shard006/C++/0084814_AnimateVisitor.cpp b/pool/shard006/C++/0084814_AnimateVisitor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1124ca7871dd6f2216b68e6dc8a7ecb9a65a62c --- /dev/null +++ b/pool/shard006/C++/0084814_AnimateVisitor.cpp @@ -0,0 +1,244 @@ +/****************************************************************************** +* SOFA, Simulation Open-Framework Architecture, development version * +* (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * +* * +* This program is free software; you can redistribute it and/or modify it * +* under the terms of the GNU Lesser General Public License as published by * +* the Free Software Foundation; either version 2.1 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 Lesser General Public License * +* for more details. * +* * +* You should have received a copy of the GNU Lesser General Public License * +* along with this program. If not, see . * +******************************************************************************* +* Authors: The SOFA Team and external contributors (see Authors.txt) * +* * +* Contact information: contact@sofa-framework.org * +******************************************************************************/ +#include +#include +#include + +#include +#include +#include +#include +#include +#include + + +#include + +//#include "MechanicalIntegration.h" + +using namespace sofa::core; + +namespace sofa +{ + +namespace simulation +{ + + +AnimateVisitor::AnimateVisitor(const core::ExecParams* params, SReal dt) + : Visitor(params) + , dt(dt) + , firstNodeVisited(false) +{ +} + +AnimateVisitor::AnimateVisitor(const core::ExecParams* params) + : Visitor(params) + , dt(0) + , firstNodeVisited(false) +{ +} + +void AnimateVisitor::processBehaviorModel(simulation::Node*, core::BehaviorModel* obj) +{ + sofa::helper::AdvancedTimer::stepBegin("BehaviorModel",obj); + + obj->updatePosition(getDt()); + sofa::helper::AdvancedTimer::stepEnd("BehaviorModel",obj); +} + +void AnimateVisitor::fwdInteractionForceField(simulation::Node*, core::behavior::BaseInteractionForceField* obj) +{ + //cerr<<"AnimateVisitor::IFF "<getName()<dt); + obj->addForce(&mparams, ffId); + + sofa::helper::AdvancedTimer::stepEnd("InteractionFF",obj); +} + +void AnimateVisitor::processCollisionPipeline(simulation::Node* node, core::collision::Pipeline* obj) +{ + sofa::helper::AdvancedTimer::stepBegin("Collision",obj); + + sofa::helper::AdvancedTimer::stepBegin("begin collision",obj); + { + CollisionBeginEvent evBegin; + PropagateEventVisitor eventPropagation( params, &evBegin); + eventPropagation.execute(node->getContext()); + } + sofa::helper::AdvancedTimer::stepEnd("begin collision",obj); + + CollisionVisitor act(this->params); + node->execute(&act); + + sofa::helper::AdvancedTimer::stepBegin("end collision",obj); + { + CollisionEndEvent evEnd; + PropagateEventVisitor eventPropagation( params, &evEnd); + eventPropagation.execute(node->getContext()); + } + sofa::helper::AdvancedTimer::stepEnd("end collision",obj); + + sofa::helper::AdvancedTimer::stepEnd("Collision",obj); +} + +void AnimateVisitor::processOdeSolver(simulation::Node* node, core::behavior::OdeSolver* solver) +{ + sofa::helper::AdvancedTimer::stepBegin("Mechanical",node); + /* MechanicalIntegrationVisitor act(getDt()); + node->execute(&act);*/ +// cerr<<"AnimateVisitor::processOdeSolver "<getName()<solve(params, getDt()); + sofa::helper::AdvancedTimer::stepEnd("Mechanical",node); +} + +Visitor::Result AnimateVisitor::processNodeTopDown(simulation::Node* node) +{ + + static const bool use_constraints = false; + + //cerr<<"AnimateVisitor::process Node "<getName()<isActive()) return Visitor::RESULT_PRUNE; + if (node->isSleeping()) return Visitor::RESULT_PRUNE; + if (!firstNodeVisited) + { + firstNodeVisited=true; + +// core::behavior::BaseAnimationLoop* presenceAnimationManager; +// node->get(presenceAnimationManager, core::objectmodel::BaseContext::SearchDown); +// if (!presenceAnimationManager) +// { +// std::cerr << "AnimateVisitor::processNodeTopDown, ERROR: no BaseAnimationLoop found while searching down from node: " << node->getName() << std::endl; + +// } + + if(use_constraints) { + sofa::core::MechanicalParams mparams(*this->params); + mparams.setDt(dt); + MechanicalResetConstraintVisitor resetConstraint(&mparams); + node->execute(&resetConstraint); + } + } + + if (dt == 0) setDt(node->getDt()); + else node->setDt(dt); + + if (node->collisionPipeline != NULL) + { + + //ctime_t t0 = begin(node, node->collisionPipeline); +#ifndef SOFA_SMP + processCollisionPipeline(node, node->collisionPipeline); +#endif + //end(node, node->collisionPipeline, t0); + } + /* if (node->solver != NULL) + { + ctime_t t0 = begin(node, node->solver); + processOdeSolver(node, node->solver); + end(node, node->solver, t0); + return RESULT_PRUNE; + }*/ + if (!node->solver.empty() ) + { + sofa::helper::AdvancedTimer::StepVar timer("Mechanical",node); + SReal nextTime = node->getTime() + dt; + + + { + IntegrateBeginEvent evBegin; + PropagateEventVisitor eventPropagation( this->params, &evBegin); + eventPropagation.execute(node); + } + + MechanicalBeginIntegrationVisitor beginVisitor(this->params, dt); + node->execute(&beginVisitor); + + sofa::core::MechanicalParams m_mparams(*this->params); + m_mparams.setDt(dt); + + if(use_constraints){ + unsigned int constraintId=0; + core::ConstraintParams cparams; + //MechanicalAccumulateConstraint(&m_mparams, constraintId, VecCoordId::position()).execute(node); + simulation::MechanicalAccumulateConstraint(&cparams, core::MatrixDerivId::constraintJacobian(),constraintId).execute(node); + } + + for( unsigned i=0; isolver.size(); i++ ) + { + ctime_t t0 = begin(node, node->solver[i]); + //cerr<<"AnimateVisitor::processNodeTpDown solver "<solver[i]->getName()<solver[i]->solve(params, getDt()); + end(node, node->solver[i], t0); + } + + { + helper::ScopedAdvancedTimer step("MechanicalPropagatePositionAndVelocity"); + MechanicalProjectPositionAndVelocityVisitor(&m_mparams, nextTime, + sofa::core::VecCoordId::position(), sofa::core::VecDerivId::velocity() + ).execute( node ); + MechanicalPropagateOnlyPositionAndVelocityVisitor(&m_mparams, nextTime,VecCoordId::position(),VecDerivId::velocity(), + #ifdef SOFA_SUPPORT_MAPPED_MASS + VecDerivId::dx(), + #endif + true).execute( node ); + } + + MechanicalEndIntegrationVisitor endVisitor(this->params, dt); + node->execute(&endVisitor); + + { + IntegrateEndEvent evBegin; + PropagateEventVisitor eventPropagation(this->params, &evBegin); + eventPropagation.execute(node); + } + + return RESULT_PRUNE; + } + /* + if (node->mechanicalModel != NULL) + { + std::cerr << "Graph Error: MechanicalState without solver." << std::endl; + return RESULT_PRUNE; + } + */ + { + // process InteractionForceFields + for_each(this, node, node->interactionForceField, &AnimateVisitor::fwdInteractionForceField); + return RESULT_CONTINUE; + } +} + +// void AnimateVisitor::processNodeBottomUp(simulation::Node* node) +// { +// node->setTime( node->getTime() + node->getDt() ); +// } + + +} // namespace simulation + +} // namespace sofa + diff --git a/pool/shard006/C++/0084816_stackLinkedList.cpp b/pool/shard006/C++/0084816_stackLinkedList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1eaade87f1b1f2cfa6d4be37c7701e9875443484 --- /dev/null +++ b/pool/shard006/C++/0084816_stackLinkedList.cpp @@ -0,0 +1,142 @@ +/* Eddie Rangel */ + + +#include +#include +using namespace std; + +struct node +{ + double d; + node *link; +}; + +class stack +{ + node *entry; + //enum {EMPTY = 0}; + public: + stack(); + stack(const stack &); + ~stack(); + void push (double); + double pop(); + void release(); + double peek() const {return entry -> d;} + bool empty() const; +}; +stack::stack() +{ + entry = NULL; +} +stack::stack(const stack &mystk) +{ + node *src = mystk.entry, + **dest = &entry; + while(src != NULL) + { + *dest = new node; + (*dest) -> d = src -> d; + src = src -> link; + dest = &((*dest) -> link); + } + *dest = NULL; +} +stack::~stack() +{ + release(); +} +void stack::release() +{ + while(!empty()) + pop(); + return; +} +bool stack::empty() const +{ + return (bool)(entry == NULL); +} +void stack::push(double dbl) +{ + node *temp = new node; + temp -> link = entry; + temp -> d = dbl; + entry = temp; + return; +} +double stack::pop() +{ + double r_val = entry -> d; + node *temp = entry; + entry = entry -> link; + delete temp; + return r_val; +} +void sho_stack(stack mystk); + +main() +{ + double nmbr; + char c; + stack mystk; + mystk.release(); + cout << "Please enter +, -, P, C, D, or Q: "; + cin >> c; + c = toupper(c); + while(c != 'Q') + { + switch(c) + { + case '+': + cout << "Please enter a number: "; + cin >> nmbr; + mystk.push(nmbr); + break; + case '-': + if(mystk.empty()) + cout << "Your stack is empty\n"; + else + { + cout << "This is your number: "; + cout << mystk.pop() << '\n'; + } + break; + case 'P': + if(mystk.empty()) + cout << "Your stack is empty\n"; + else + { + cout << "This is your number: "; + cout << mystk.peek() << '\n'; + } + break; + case 'D': + sho_stack(mystk); + break; + case 'C': + mystk.release(); + break; + default: + cout << "You have entered invalid data!\n"; + } + cout << "Please enter +, -, P, C, D, or Q: "; + cin >> c; + c = toupper(c); + } + return 0; +} + +void sho_stack(stack mystk) +{ + cout << "Current stack: "; + while(!mystk.empty()) + cout << mystk.pop() << " "; + cout << '\n'; + mystk.push(9.9); + mystk.push(7.7); + cout << "Now the copy is: "; + while(!mystk.empty()) + cout << mystk.pop() << " "; + cout << '\n'; + return; +} \ No newline at end of file diff --git a/pool/shard006/C++/0084818_Aref.cpp b/pool/shard006/C++/0084818_Aref.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a4a707b2efd3fbd19cbe3561b0de20df1568f604 --- /dev/null +++ b/pool/shard006/C++/0084818_Aref.cpp @@ -0,0 +1,106 @@ +#include "../../../Units/Units.h" +#include "../../../Node/Node.h" +#include "../../../ParseResult/ParseResult.h" +#include "../../../Function/Function.h" +#include "../../../Operation/Cast/Cast.h" +#include "../../../Operation/Destruct/Destruct.h" +#include "../Inst/Inst.h" +#include "../../../llvm_Function.h" + +using namespace dale::ErrorInst; + +namespace dale +{ +bool +FormProcArefParse(Units *units, Function *fn, llvm::BasicBlock *block, + Node *node, bool get_address, bool prefixed_with_core, + ParseResult *pr) +{ + Context *ctx = units->top()->ctx; + + if (!ctx->er->assertArgNums("$", node, 2, 2)) { + return false; + } + + std::vector *lst = node->list; + Node *array_node = (*lst)[1]; + Node *index_node = (*lst)[2]; + + ParseResult initial_array_pr; + bool res = FormProcInstParse(units, fn, block, array_node, false, + false, NULL, &initial_array_pr); + if (!res) { + return false; + } + + if (!(initial_array_pr.type->array_type + || initial_array_pr.type->points_to)) { + std::string type_str; + initial_array_pr.type->toString(&type_str); + Error *e = new Error(IncorrectArgType, array_node, + "$", "a pointer or array", "1", + type_str.c_str()); + ctx->er->addError(e); + return false; + } + + ParseResult array_pr; + bool is_array; + if (initial_array_pr.type->array_type) { + initial_array_pr.getAddressOfValue(ctx, &array_pr); + array_pr.type = + ctx->tr->getPointerType(initial_array_pr.type->array_type); + is_array = true; + } else { + initial_array_pr.copyTo(&array_pr); + is_array = false; + } + + ParseResult index_pr; + res = FormProcInstParse(units, fn, array_pr.block, index_node, false, + false, NULL, &index_pr); + if (!res) { + return false; + } + + llvm::IRBuilder<> builder(index_pr.block); + std::vector indices; + if (!is_array) { + indices.push_back(llvm::cast(index_pr.getValue(ctx))); + } else { + STL::push_back2(&indices, ctx->nt->getLLVMZero(), + llvm::cast(index_pr.getValue(ctx))); + } + llvm::Value *index_ptr = + builder.Insert( + llvm::GetElementPtrInst::Create( + array_pr.getValue(ctx), llvm::ArrayRef(indices) + ), + "aref" + ); + + pr->block = index_pr.block; + + if (array_pr.type->is_array) { + pr->type = ctx->tr->getPointerType(array_pr.type->array_type); + } else { + pr->type = array_pr.type; + } + + pr->set(pr->block, pr->type, index_ptr); + array_pr.block = index_pr.block; + ParseResult destruct_pr; + res = Operation::Destruct(ctx, &array_pr, &destruct_pr); + if (!res) { + return false; + } + index_pr.block = destruct_pr.block; + res = Operation::Destruct(ctx, &index_pr, &destruct_pr); + if (!res) { + return false; + } + pr->block = destruct_pr.block; + + return true; +} +} diff --git a/pool/shard006/C++/0084823_VehicleSim.cpp b/pool/shard006/C++/0084823_VehicleSim.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6f7dd477925f6bc766795f4445a17480ee77f025 --- /dev/null +++ b/pool/shard006/C++/0084823_VehicleSim.cpp @@ -0,0 +1,64 @@ +#include "VehicleSim.h" + +#include + +// Input +#include "input/InputConverter.h" + +namespace vlr +{ + const b2Vec2 gravity(0.0f, -50.0f); + + const float DEFAULT_SCALE = 10.0f; + + VehicleSim::VehicleSim() + : Application(800, 600), _physWorld(gravity), + _worldRenderer(&_physWorld), _lastPhysicsUpdate(glfwGetTime()), + _orthoScale(DEFAULT_SCALE), _simulationRunning(false), + _currentTool(nullptr), _currentToolButton(nullptr), + _worldOptions(&_physWorld, &_worldRenderer), + _timeStep(VEHICLESIM_PHYSICS_STEP), + _velocityIterations(VEHICLESIM_VELOCITY_ITERATIONS), + _positionIterations(VEHICLESIM_POSITION_ITERATIONS), + _camFollow(nullptr) + { + // Update window pointer + glfwSetWindowUserPointer(_window, this); + + // Set callbacks + glfwSetCursorPosCallback(_window, mouse_move_callback); + glfwSetMouseButtonCallback(_window, mouse_callback); + glfwSetKeyCallback(_window, key_callback); + glfwSetScrollCallback(_window, scroll_callback); + glfwSetWindowSizeCallback(_window, resize_callback); + glfwSetCharCallback(_window, char_callback); + + // Initialise box2d + _physWorld.SetDebugDraw(&_worldRenderer); + _worldRenderer.SetFlags(b2Draw::e_shapeBit | b2Draw::e_aabbBit | b2Draw::e_jointBit); + + // Initialise gwen + _guiRenderer = new Gwen::Renderer::OpenGL_DebugFont(); + _guiRenderer->Init(); + + _guiSkin = new Gwen::Skin::TexturedBase(_guiRenderer); + _guiSkin->Init("DefaultSkin.png"); + + _guiCanvas = new Gwen::Controls::Canvas(_guiSkin); + _guiCanvas->SetSize(getWidth(), getHeight()); + + // Initialise camera & viewport etc + resize(getWidth(), getHeight()); + + // Initialise input state + glfwGetCursorPos(_window, &_mouseX, &_mouseY); + + // Initialise GUI + initGui(); + } + + VehicleSim::~VehicleSim() + { + + } +} diff --git a/pool/shard006/C++/0084824_trustitem.cpp b/pool/shard006/C++/0084824_trustitem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1abaf7e310a8c523589248f7d14d5daa004207d7 --- /dev/null +++ b/pool/shard006/C++/0084824_trustitem.cpp @@ -0,0 +1,116 @@ +/* + trustitem.cpp - wraps a gpgme trust item + Copyright (C) 2003 Klarälvdalens Datakonsult AB + + This file is part of GPGME. + + GPGME++ is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + GPGME++ 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 Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with GPGME++; see the file COPYING.LIB. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. +*/ + +#include + +#include + +#include + +#include + +namespace GpgME +{ + +class TrustItem::Private +{ +public: + Private(gpgme_trust_item_t aItem) + : item(aItem) + { + } + + gpgme_trust_item_t item; +}; + +TrustItem::TrustItem(gpgme_trust_item_t item) +{ + d = new Private(item); + if (d->item) { + gpgme_trust_item_ref(d->item); + } +} + +TrustItem::TrustItem(const TrustItem &other) +{ + d = new Private(other.d->item); + if (d->item) { + gpgme_trust_item_ref(d->item); + } +} + +TrustItem::~TrustItem() +{ + if (d->item) { + gpgme_trust_item_unref(d->item); + } + delete d; d = 0; +} + +bool TrustItem::isNull() const +{ + return !d || !d->item; +} + +gpgme_trust_item_t TrustItem::impl() const +{ + return d->item; +} + +const char *TrustItem::keyID() const +{ + return d->item ? d->item->keyid : 0 ; +} + +const char *TrustItem::userID() const +{ + return d->item ? d->item->name : 0 ; +} + +const char *TrustItem::ownerTrustAsString() const +{ + return d->item ? d->item->owner_trust : 0 ; +} + +const char *TrustItem::validityAsString() const +{ + return d->item ? d->item->validity : 0 ; +} + +int TrustItem::trustLevel() const +{ + return d->item ? d->item->level : 0 ; +} + +TrustItem::Type TrustItem::type() const +{ + if (!d->item) { + return Unknown; + } else { + return + d->item->type == 1 ? Key : + d->item->type == 2 ? UserID : + Unknown ; + } +} + +} // namespace GpgME diff --git a/pool/shard006/C++/0084827_paned.cc b/pool/shard006/C++/0084827_paned.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa28299d61eeb353380f0e0619633e8b7aec2b93 --- /dev/null +++ b/pool/shard006/C++/0084827_paned.cc @@ -0,0 +1,200 @@ +/* XFC: Xfce Foundation Classes (User Interface Library) + * Copyright (C) 2004-2005 The XFC Development Team. + * + * paned.cc - GtkPaned, GtkHPaned and GtkVPaned C++ wrapper implementation + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "paned.hh" +#include "private/panedclass.hh" +#include "../gdk/window.hh" + +using namespace Xfc; + +/* Gtk::Paned + */ + +Gtk::Paned::Paned(GtkPaned *paned, bool owns_reference) +: Container((GtkContainer*)paned, owns_reference) +{ +} + +Gtk::Paned::Paned() +: Container((GtkContainer*)PanedClass::create()) +{ +} + +Gtk::Paned::~Paned() +{ +} + +Gdk::Window* +Gtk::Paned::handle() const +{ + return G::Object::wrap(gtk_paned()->handle); +} + +Gtk::Widget* +Gtk::Paned::get_child1() const +{ + GtkWidget *child = gtk_paned_get_child1(gtk_paned()); + return child ? G::Object::wrap(child) : 0; +} + +Gtk::Widget* +Gtk::Paned::get_child2() const +{ + GtkWidget *child = gtk_paned_get_child2(gtk_paned()); + return child ? G::Object::wrap(child) : 0; +} + +void +Gtk::Paned::add1(Widget& child) +{ + gtk_paned_add1(gtk_paned(), child.gtk_widget()); +} + +void +Gtk::Paned::add2(Widget& child) +{ + gtk_paned_add2(gtk_paned(), child.gtk_widget()); +} + + +void +Gtk::Paned::pack1(Widget& child, bool resize, bool shrink) +{ + gtk_paned_pack1(gtk_paned(), child.gtk_widget(), resize, shrink); +} + +void +Gtk::Paned::pack2(Widget& child, bool resize, bool shrink) +{ + gtk_paned_pack2(gtk_paned(), child.gtk_widget(), resize, shrink); +} + +/* Gtk::PanedClass + */ + +void +Gtk::PanedClass::init(GtkPanedClass *g_class) +{ + ContainerClass::init((GtkContainerClass*)g_class); +} + +GType +Gtk::PanedClass::get_type() +{ + static GType type = 0; + if (!type) + { + type = G::TypeInstance::register_type(GTK_TYPE_PANED, (GClassInitFunc)&init); + } + return type; +} + +void* +Gtk::PanedClass::create() +{ + return g_object_new(get_type(), 0); +} + +/* Gtk::HPaned + */ + +Gtk::HPaned::HPaned(GtkHPaned *hpaned, bool owns_reference) +: Paned((GtkPaned*)hpaned, owns_reference) +{ +} + +Gtk::HPaned::HPaned() +: Paned((GtkPaned*)HPanedClass::create()) +{ +} + +Gtk::HPaned::~HPaned() +{ +} + +/* Gtk::HPanedClass + */ + +void +Gtk::HPanedClass::init(GtkHPanedClass *g_class) +{ + PanedClass::init((GtkPanedClass*)g_class); +} + +GType +Gtk::HPanedClass::get_type() +{ + static GType type = 0; + if (!type) + { + type = G::TypeInstance::register_type(GTK_TYPE_HPANED, (GClassInitFunc)&init); + } + return type; +} + +void* +Gtk::HPanedClass::create() +{ + return g_object_new(get_type(), 0); +} + +/* Gtk::VPaned + */ + +Gtk::VPaned::VPaned(GtkVPaned *vpaned, bool owns_reference) +: Paned((GtkPaned*)vpaned, owns_reference) +{ +} + +Gtk::VPaned::VPaned() +: Paned((GtkPaned*)VPanedClass::create()) +{ +} + +Gtk::VPaned::~VPaned() +{ +} + +/* Gtk::VPanedClass + */ + +void +Gtk::VPanedClass::init(GtkVPanedClass *g_class) +{ + PanedClass::init((GtkPanedClass*)g_class); +} + +GType +Gtk::VPanedClass::get_type() +{ + static GType type = 0; + if (!type) + { + type = G::TypeInstance::register_type(GTK_TYPE_VPANED, (GClassInitFunc)&init); + } + return type; +} + +void* +Gtk::VPanedClass::create() +{ + return g_object_new(get_type(), 0); +} + diff --git a/pool/shard006/C++/0084836_MSPolarization.cc b/pool/shard006/C++/0084836_MSPolarization.cc new file mode 100644 index 0000000000000000000000000000000000000000..52aabc7d057ad7023724c0cd80dcf09d869d3d4a --- /dev/null +++ b/pool/shard006/C++/0084836_MSPolarization.cc @@ -0,0 +1,169 @@ +//# MSPolarization.cc: The MeasurementSet POLARIZATION Table +//# Copyright (C) 1999,2000 +//# Associated Universities, Inc. Washington DC, USA. +//# +//# This library is free software; you can redistribute it and/or modify it +//# under the terms of the GNU Library General Public License as published by +//# the Free Software Foundation; either version 2 of the License, or (at your +//# option) any later version. +//# +//# This library 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 Library General Public +//# License for more details. +//# +//# You should have received a copy of the GNU Library General Public License +//# along with this library; if not, write to the Free Software Foundation, +//# Inc., 675 Massachusetts Ave, Cambridge, MA 02139, USA. +//# +//# Correspondence concerning AIPS++ should be addressed as follows: +//# Internet email: aips2-request@nrao.edu. +//# Postal address: AIPS++ Project Office +//# National Radio Astronomy Observatory +//# 520 Edgemont Road +//# Charlottesville, VA 22903-2475 USA +//# +//# $Id$ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace casacore { //# NAMESPACE CASACORE - BEGIN + +MSPolarization::MSPolarization():hasBeenDestroyed_p(True) { } + +MSPolarization::MSPolarization(const String &tableName, TableOption option) + : MSTable(tableName, option),hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + if (! validate(this->tableDesc())) + throw (AipsError("MSPolarization(String &, TableOption) - " + "table is not a valid MSPolarization")); +} + +MSPolarization::MSPolarization(const String& tableName, const String &tableDescName, + TableOption option) + : MSTable(tableName, tableDescName,option), + hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + if (! validate(this->tableDesc())) + throw (AipsError("MSPolarization(String &, String &, TableOption) - " + "table is not a valid MSPolarization")); +} + +MSPolarization::MSPolarization(SetupNewTable &newTab, uInt nrrow, + Bool initialize) + : MSTable(newTab, nrrow, initialize), + hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + if (! validate(this->tableDesc())) + throw (AipsError("MSPolarization(SetupNewTable &, uInt, Bool) - " + "table is not a valid MSPolarization")); +} + +MSPolarization::MSPolarization(const Table &table) + : MSTable(table), hasBeenDestroyed_p(False) +{ + // verify that the now opened table is valid + if (! validate(this->tableDesc())) + throw (AipsError("MSPolarization(const Table &) - " + "table is not a valid MSPolarization")); +} + +MSPolarization::MSPolarization(const MSPolarization &other) + : MSTable(other), + hasBeenDestroyed_p(False) +{ + // verify that other is valid + if (&other != this) + if (! validate(this->tableDesc())) + throw (AipsError("MSPolarization(const MSPolarization &) - " + "table is not a valid MSPolarization")); +} + +MSPolarization::~MSPolarization() +{ +// check to make sure that this MSPolarization is still valid + if (!hasBeenDestroyed_p && !validate()) { + // the table is otherwise OK, so ensure that it is written if necessary + this->flush(); + LogIO os; + os << LogIO::WARN + << "~MSPolarization() - Table written is not a valid MSPolarization" + << LogIO::POST; + } + hasBeenDestroyed_p = True; +} + + +MSPolarization& MSPolarization::operator=(const MSPolarization &other) +{ + if (&other != this) { + MSTable::operator=(other); + hasBeenDestroyed_p=other.hasBeenDestroyed_p; + } + return *this; +} + +MSTableMaps MSPolarization::initMaps() +{ + MSTableMaps maps; + // the PredefinedColumns + // CORR_PRODUCT + colMapDef(maps, CORR_PRODUCT, "CORR_PRODUCT", TpArrayInt, + "Indices describing receptors of feed going into correlation","",""); + // CORR_TYPE + colMapDef(maps, CORR_TYPE, "CORR_TYPE", TpArrayInt, + "The polarization type for each correlation product," + " as a Stokes enum.","",""); + // FLAG_ROW + colMapDef(maps, FLAG_ROW, "FLAG_ROW", TpBool, + "Row flag","",""); + // NUM_CORR + colMapDef(maps, NUM_CORR, "NUM_CORR", TpInt, + "Number of correlation products","",""); + + // PredefinedKeywords + + // init requiredTableDesc + // all required keywords + uInt i; + for (i = UNDEFINED_KEYWORD+1; + i <= NUMBER_PREDEFINED_KEYWORDS; i++) { + addKeyToDesc(maps, PredefinedKeywords(i)); + } + // all required columns + // First define the columns with known dimensionality + addColumnToDesc(maps, CORR_TYPE, 1); + addColumnToDesc(maps, CORR_PRODUCT, 2); + // Now define all other columns (duplicates are skipped) + for (i = UNDEFINED_COLUMN+1; + i <= NUMBER_REQUIRED_COLUMNS; i++) { + addColumnToDesc(maps, PredefinedColumns(i)); + } + + return maps; +} + + +MSPolarization MSPolarization::referenceCopy(const String& newTableName, + const Block& writableColumns) const +{ + return MSPolarization(MSTable:: + referenceCopy(newTableName,writableColumns)); +} + +} //# NAMESPACE CASACORE - END + diff --git a/pool/shard006/C++/0084838_PolicyDetails.cpp b/pool/shard006/C++/0084838_PolicyDetails.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed3987493d9db85ef40f58f9f5866d5c3eca1c70 --- /dev/null +++ b/pool/shard006/C++/0084838_PolicyDetails.cpp @@ -0,0 +1,123 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace DLM +{ +namespace Model +{ + +PolicyDetails::PolicyDetails() : + m_resourceTypesHasBeenSet(false), + m_targetTagsHasBeenSet(false), + m_schedulesHasBeenSet(false) +{ +} + +PolicyDetails::PolicyDetails(JsonView jsonValue) : + m_resourceTypesHasBeenSet(false), + m_targetTagsHasBeenSet(false), + m_schedulesHasBeenSet(false) +{ + *this = jsonValue; +} + +PolicyDetails& PolicyDetails::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("ResourceTypes")) + { + Array resourceTypesJsonList = jsonValue.GetArray("ResourceTypes"); + for(unsigned resourceTypesIndex = 0; resourceTypesIndex < resourceTypesJsonList.GetLength(); ++resourceTypesIndex) + { + m_resourceTypes.push_back(ResourceTypeValuesMapper::GetResourceTypeValuesForName(resourceTypesJsonList[resourceTypesIndex].AsString())); + } + m_resourceTypesHasBeenSet = true; + } + + if(jsonValue.ValueExists("TargetTags")) + { + Array targetTagsJsonList = jsonValue.GetArray("TargetTags"); + for(unsigned targetTagsIndex = 0; targetTagsIndex < targetTagsJsonList.GetLength(); ++targetTagsIndex) + { + m_targetTags.push_back(targetTagsJsonList[targetTagsIndex].AsObject()); + } + m_targetTagsHasBeenSet = true; + } + + if(jsonValue.ValueExists("Schedules")) + { + Array schedulesJsonList = jsonValue.GetArray("Schedules"); + for(unsigned schedulesIndex = 0; schedulesIndex < schedulesJsonList.GetLength(); ++schedulesIndex) + { + m_schedules.push_back(schedulesJsonList[schedulesIndex].AsObject()); + } + m_schedulesHasBeenSet = true; + } + + return *this; +} + +JsonValue PolicyDetails::Jsonize() const +{ + JsonValue payload; + + if(m_resourceTypesHasBeenSet) + { + Array resourceTypesJsonList(m_resourceTypes.size()); + for(unsigned resourceTypesIndex = 0; resourceTypesIndex < resourceTypesJsonList.GetLength(); ++resourceTypesIndex) + { + resourceTypesJsonList[resourceTypesIndex].AsString(ResourceTypeValuesMapper::GetNameForResourceTypeValues(m_resourceTypes[resourceTypesIndex])); + } + payload.WithArray("ResourceTypes", std::move(resourceTypesJsonList)); + + } + + if(m_targetTagsHasBeenSet) + { + Array targetTagsJsonList(m_targetTags.size()); + for(unsigned targetTagsIndex = 0; targetTagsIndex < targetTagsJsonList.GetLength(); ++targetTagsIndex) + { + targetTagsJsonList[targetTagsIndex].AsObject(m_targetTags[targetTagsIndex].Jsonize()); + } + payload.WithArray("TargetTags", std::move(targetTagsJsonList)); + + } + + if(m_schedulesHasBeenSet) + { + Array schedulesJsonList(m_schedules.size()); + for(unsigned schedulesIndex = 0; schedulesIndex < schedulesJsonList.GetLength(); ++schedulesIndex) + { + schedulesJsonList[schedulesIndex].AsObject(m_schedules[schedulesIndex].Jsonize()); + } + payload.WithArray("Schedules", std::move(schedulesJsonList)); + + } + + return payload; +} + +} // namespace Model +} // namespace DLM +} // namespace Aws diff --git a/pool/shard006/C++/0084841_editor_run_script.cpp b/pool/shard006/C++/0084841_editor_run_script.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83ce50a9f943fa1526db5c909b7b4ef603190371 --- /dev/null +++ b/pool/shard006/C++/0084841_editor_run_script.cpp @@ -0,0 +1,91 @@ +/*************************************************************************/ +/* editor_run_script.cpp */ +/*************************************************************************/ +/* This file is part of: */ +/* GODOT ENGINE */ +/* https://godotengine.org */ +/*************************************************************************/ +/* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */ +/* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */ +/* */ +/* 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 "editor_run_script.h" + +#include "editor_node.h" + +void EditorScript::add_root_node(Node *p_node) { + if (!editor) { + EditorNode::add_io_error("EditorScript::add_root_node: " + TTR("Write your logic in the _run() method.")); + return; + } + + if (editor->get_edited_scene()) { + EditorNode::add_io_error("EditorScript::add_root_node: " + TTR("There is an edited scene already.")); + return; + } + + //editor->set_edited_scene(p_node); +} + +EditorInterface *EditorScript::get_editor_interface() { + return EditorInterface::get_singleton(); +} + +Node *EditorScript::get_scene() { + if (!editor) { + EditorNode::add_io_error("EditorScript::get_scene: " + TTR("Write your logic in the _run() method.")); + return nullptr; + } + + return editor->get_edited_scene(); +} + +void EditorScript::_run() { + Ref