diff --git a/pool/shard007/C++/0095105_boss_lockmaw.cpp b/pool/shard007/C++/0095105_boss_lockmaw.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..28822e4a3673a90412ccf517884ce9bb213df7a9
--- /dev/null
+++ b/pool/shard007/C++/0095105_boss_lockmaw.cpp
@@ -0,0 +1,160 @@
+/*
+ *
+ * Copyright (C) 2011-2012 ArkCORE2
+ * Copyright (C) 2010-2012 Project SkyFire
+ *
+ *
+ * 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"ScriptPCH.h"
+#include"WorldPacket.h"
+#include"lost_city_of_the_tolvir.h"
+#include"ScriptMgr.h"
+#include"ScriptedCreature.h"
+#include"SpellScript.h"
+#include"SpellAuraEffects.h"
+
+enum Spells
+{
+ SPELL_DUST_FLAIL = 81642,
+ SPELL_SCENT_OF_BLOOD = 81690,
+ H_SPELL_SCENT_OF_BLOOD = 89998,
+ SPELL_VENOMOUS_RAGE = 81706,
+ SPELL_VISCOUS_POISON = 81630,
+ H_SPELL_VISCOUS_POISON = 90004,
+};
+
+enum Events
+{
+ EVENT_DUST_FLAIL = 1,
+ EVENT_SCENT_OF_BLOOD = 2,
+ EVENT_VENOMOUS_RAGE = 3,
+ EVENT_VISCOUS_POISON = 4,
+};
+
+enum SummonIds
+{
+ NPC_FRENZIED_CROCOLISK = 43658,
+};
+
+const Position SummonLocations[4] =
+{
+ //Frenzied Crocolisks
+ {-11033.29f, -1674.57f, -0.56f, 1.09f},
+ {-11029.84f, -1673.09f, -0.37f, 2.33f},
+ {-11007.25f, -1666.37f, -0.23f, 2.46f},
+ {-11006.83f, -1666.85f, -0.25f, 2.23f},
+};
+
+class boss_lockmaw : public CreatureScript
+{
+ public:
+ boss_lockmaw() : CreatureScript("boss_lockmaw") {}
+
+ CreatureAI* GetAI(Creature* creature) const
+ {
+ return new boss_lockmawAI(creature);
+ }
+ struct boss_lockmawAI : public ScriptedAI
+ {
+ boss_lockmawAI(Creature* creature) : ScriptedAI(creature), Summons(me)
+ {
+ instance = creature->GetInstanceScript();
+ }
+
+ InstanceScript* instance;
+ EventMap events;
+ SummonList Summons;
+ bool check_in;
+
+ void Reset ()
+ {
+ events.Reset();
+ Summons.DespawnAll();
+
+ if (instance && (instance->GetData(DATA_LOCKMAW_EVENT) != DONE && !check_in))
+ instance->SetData(DATA_LOCKMAW_EVENT, NOT_STARTED);
+
+ check_in = false;
+ }
+
+ void JustDied(Unit* /*Kill*/)
+ {
+ Summons.DespawnAll();
+ if (instance)
+ instance->SetData(DATA_LOCKMAW_EVENT, DONE);
+ }
+
+ void EnterCombat(Unit* /*Ent*/)
+ {
+ if (instance)
+ instance->SetData(DATA_LOCKMAW_EVENT, IN_PROGRESS);
+
+ DoZoneInCombat();
+ }
+
+ void UpdateAI(const uint32 uiDiff)
+ {
+ if (!UpdateVictim()) /* No target to kill */
+ return;
+
+ events.Update(uiDiff);
+
+ if (me->HasUnitState(UNIT_STATE_CASTING))
+ return;
+
+ while (uint32 eventId = events.ExecuteEvent())
+ {
+ switch (eventId)
+ {
+ case EVENT_DUST_FLAIL:
+ DoCast(me->getVictim(), SPELL_DUST_FLAIL);
+ events.ScheduleEvent(EVENT_DUST_FLAIL, urand(6000, 10000));
+ return;
+ case EVENT_VISCOUS_POISON:
+ if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true))
+ DoCast(me->getVictim(), SPELL_VISCOUS_POISON);
+ events.ScheduleEvent(EVENT_VISCOUS_POISON, 2000);
+ return;
+ case EVENT_SCENT_OF_BLOOD:
+ if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, true))
+ DoCast(me->getVictim(), SPELL_SCENT_OF_BLOOD);
+ for (uint8 i=0; i<4; i++)
+ {
+ Creature* Crocolisk = me->SummonCreature(NPC_FRENZIED_CROCOLISK, SummonLocations[i], TEMPSUMMON_CORPSE_DESPAWN);
+ Crocolisk->AddThreat(me->getVictim(), 0.0f);
+ DoZoneInCombat(Crocolisk);
+ }
+ events.ScheduleEvent(EVENT_SCENT_OF_BLOOD, 6000);
+ return;
+ case EVENT_VENOMOUS_RAGE:
+ if (me->GetHealthPct() < 30)
+ DoCast(me, SPELL_VENOMOUS_RAGE);
+ events.ScheduleEvent(EVENT_VENOMOUS_RAGE, 1000);
+ return;
+ default:
+ break;
+ }
+ }
+
+ DoMeleeAttackIfReady();
+ }
+ };
+};
+
+void AddSC_boss_lockmaw()
+{
+ new boss_lockmaw();
+}
\ No newline at end of file
diff --git a/pool/shard007/C++/0095108_awt_Container.cpp b/pool/shard007/C++/0095108_awt_Container.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..65ded5910963de3f43a41cc195e6f28e20d9a4f3
--- /dev/null
+++ b/pool/shard007/C++/0095108_awt_Container.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright 1998-2008 Sun Microsystems, Inc. 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. Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+#include "awt_Container.h"
+#include "awt.h"
+
+/************************************************************************
+ * AwtContainer fields
+ */
+
+jfieldID AwtContainer::layoutMgrID;
+jmethodID AwtContainer::findComponentAtMID;
+
+/************************************************************************
+ * AwtContainer native methods
+ */
+
+extern "C" {
+
+JNIEXPORT void JNICALL
+Java_java_awt_Container_initIDs(JNIEnv *env, jclass cls) {
+ TRY;
+
+ AwtContainer::layoutMgrID =
+ env->GetFieldID(cls, "layoutMgr", "Ljava/awt/LayoutManager;");
+
+ AwtContainer::findComponentAtMID =
+ env->GetMethodID(cls, "findComponentAt", "(IIZ)Ljava/awt/Component;");
+
+ DASSERT(AwtContainer::layoutMgrID != NULL);
+ DASSERT(AwtContainer::findComponentAtMID);
+
+ CATCH_BAD_ALLOC;
+}
+
+} /* extern "C" */
diff --git a/pool/shard007/C++/0095114_rssdownloadrulelist.cpp b/pool/shard007/C++/0095114_rssdownloadrulelist.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..55d52b2d844d5f398239fa970a8df606ed6b4b68
--- /dev/null
+++ b/pool/shard007/C++/0095114_rssdownloadrulelist.cpp
@@ -0,0 +1,185 @@
+/*
+ * Bittorrent Client using Qt and libtorrent.
+ * Copyright (C) 2010 Christophe Dumez
+ *
+ * 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.
+ *
+ * In addition, as a special exception, the copyright holders give permission to
+ * link this program with the OpenSSL project's "OpenSSL" library (or with
+ * modified versions of it that use the same license as the "OpenSSL" library),
+ * and distribute the linked executables. You must obey the GNU General Public
+ * License in all respects for all of the code used other than "OpenSSL". If you
+ * modify file(s), you may extend this exception to your version of the file(s),
+ * but you are not obligated to do so. If you do not wish to do so, delete this
+ * exception statement from your version.
+ *
+ * Contact : chris@qbittorrent.org
+ */
+
+#include
+#include
+#include
+
+#include "base/preferences.h"
+#include "base/qinisettings.h"
+#include "rssdownloadrulelist.h"
+
+using namespace Rss;
+
+DownloadRuleList::DownloadRuleList()
+{
+ loadRulesFromStorage();
+}
+
+DownloadRulePtr DownloadRuleList::findMatchingRule(const QString &feedUrl, const QString &articleTitle) const
+{
+ Q_ASSERT(Preferences::instance()->isRssDownloadingEnabled());
+ QStringList ruleNames = m_feedRules.value(feedUrl);
+ foreach (const QString &rule_name, ruleNames) {
+ DownloadRulePtr rule = m_rules[rule_name];
+ if (rule->isEnabled() && rule->matches(articleTitle)) return rule;
+ }
+ return DownloadRulePtr();
+}
+
+void DownloadRuleList::replace(DownloadRuleList *other)
+{
+ m_rules.clear();
+ m_feedRules.clear();
+ foreach (const QString &name, other->ruleNames()) {
+ saveRule(other->getRule(name));
+ }
+}
+
+void DownloadRuleList::saveRulesToStorage()
+{
+ QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
+ qBTRSS.setValue("download_rules", toVariantHash());
+}
+
+void DownloadRuleList::loadRulesFromStorage()
+{
+ QIniSettings qBTRSS("qBittorrent", "qBittorrent-rss");
+ loadRulesFromVariantHash(qBTRSS.value("download_rules").toHash());
+}
+
+QVariantHash DownloadRuleList::toVariantHash() const
+{
+ QVariantHash ret;
+ foreach (const DownloadRulePtr &rule, m_rules.values()) {
+ ret.insert(rule->name(), rule->toVariantHash());
+ }
+ return ret;
+}
+
+void DownloadRuleList::loadRulesFromVariantHash(const QVariantHash &h)
+{
+ QVariantHash::ConstIterator it = h.begin();
+ QVariantHash::ConstIterator itend = h.end();
+ for ( ; it != itend; ++it) {
+ DownloadRulePtr rule = DownloadRule::fromVariantHash(it.value().toHash());
+ if (rule && !rule->name().isEmpty())
+ saveRule(rule);
+ }
+}
+
+void DownloadRuleList::saveRule(const DownloadRulePtr &rule)
+{
+ qDebug() << Q_FUNC_INFO << rule->name();
+ Q_ASSERT(rule);
+ if (m_rules.contains(rule->name())) {
+ qDebug("This is an update, removing old rule first");
+ removeRule(rule->name());
+ }
+ m_rules.insert(rule->name(), rule);
+ // Update feedRules hashtable
+ foreach (const QString &feedUrl, rule->rssFeeds()) {
+ m_feedRules[feedUrl].append(rule->name());
+ }
+ qDebug() << Q_FUNC_INFO << "EXIT";
+}
+
+void DownloadRuleList::removeRule(const QString &name)
+{
+ qDebug() << Q_FUNC_INFO << name;
+ if (!m_rules.contains(name)) return;
+ DownloadRulePtr rule = m_rules.take(name);
+ // Update feedRules hashtable
+ foreach (const QString &feedUrl, rule->rssFeeds()) {
+ m_feedRules[feedUrl].removeOne(rule->name());
+ }
+}
+
+void DownloadRuleList::renameRule(const QString &oldName, const QString &newName)
+{
+ if (!m_rules.contains(oldName)) return;
+
+ DownloadRulePtr rule = m_rules.take(oldName);
+ rule->setName(newName);
+ m_rules.insert(newName, rule);
+ // Update feedRules hashtable
+ foreach (const QString &feedUrl, rule->rssFeeds()) {
+ m_feedRules[feedUrl].replace(m_feedRules[feedUrl].indexOf(oldName), newName);
+ }
+}
+
+DownloadRulePtr DownloadRuleList::getRule(const QString &name) const
+{
+ return m_rules.value(name);
+}
+
+QStringList DownloadRuleList::ruleNames() const
+{
+ return m_rules.keys();
+}
+
+bool DownloadRuleList::isEmpty() const
+{
+ return m_rules.isEmpty();
+}
+
+bool DownloadRuleList::serialize(const QString &path)
+{
+ QFile f(path);
+ if (f.open(QIODevice::WriteOnly)) {
+ QDataStream out(&f);
+ out.setVersion(QDataStream::Qt_4_5);
+ out << toVariantHash();
+ f.close();
+ return true;
+ }
+
+ return false;
+}
+
+bool DownloadRuleList::unserialize(const QString &path)
+{
+ QFile f(path);
+ if (f.open(QIODevice::ReadOnly)) {
+ QDataStream in(&f);
+ in.setVersion(QDataStream::Qt_4_5);
+ QVariantHash tmp;
+ in >> tmp;
+ f.close();
+ if (tmp.isEmpty())
+ return false;
+ qDebug("Processing was successful!");
+ loadRulesFromVariantHash(tmp);
+ return true;
+ } else {
+ qDebug("Error: could not open file at %s", qPrintable(path));
+ return false;
+ }
+}
diff --git a/pool/shard007/C++/0095115_main.cpp b/pool/shard007/C++/0095115_main.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b348e569e0b3f50b61877592a55a66f2818ff68f
--- /dev/null
+++ b/pool/shard007/C++/0095115_main.cpp
@@ -0,0 +1,68 @@
+#include "almath.h"
+#include "vector"
+
+#include
+
+using namespace almath::network;
+
+
+void print_table(Table t);
+
+int main()
+{
+
+
+ std::vector x = { 'a', 'b', 'c', 'd' };
+
+
+
+ almath::network::Table test(x, x, -1);
+
+ print_table(test);
+
+ test.editElement('a', 'a', 1);
+
+ int newRow[4] = {5, 6, 3, 4};
+ int newCol[4] = {5, 2, 3, 1};
+
+ print_table(test);
+
+ test.addColumnData('b', newRow);
+ test.addRowData('d', newCol);
+
+ test.addRow('e');
+
+ int newCol1[5] = {1, 2, 3, 4, 5};
+
+ test.addColumnData('e', newCol1);
+
+
+ return 0;
+}
+
+void print_table(Table t)
+{
+ const std::vector *rows = t.getRows();
+ const std::vector *columns = t.getColumns();
+
+ for(int i = 0; i < columns->size(); i++)
+ {
+ std::cout << "\t" << (*columns)[i];
+ }
+
+ std::cout << std::endl;
+ for(int i = 0; i < columns->size(); i++)
+ {
+ std::cout << "\t" << "__";
+ }
+ std::cout << std::endl;
+
+ for (int i = 0; i < rows->size(); i++)
+ {
+ std::cout << (*rows)[i] << "|\t";
+ for(int x = 0; x < columns->size(); x++)
+ std::cout << t[(*rows)[i]][x] << "\t";
+
+ std::cout << std::endl;
+ }
+}
\ No newline at end of file
diff --git a/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc b/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc
new file mode 100644
index 0000000000000000000000000000000000000000..8a803c4712058bfa89e25f400d99fc12c15ad6d8
--- /dev/null
+++ b/pool/shard007/C++/0095118_browser_plugin_geolocation_permission_context.cc
@@ -0,0 +1,94 @@
+// 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 "content/browser/browser_plugin/browser_plugin_geolocation_permission_context.h"
+
+#include "base/bind.h"
+#include "content/browser/browser_plugin/browser_plugin_guest.h"
+#include "content/browser/web_contents/web_contents_impl.h"
+#include "content/public/browser/browser_thread.h"
+#include "content/public/browser/render_process_host.h"
+#include "content/public/browser/render_view_host.h"
+
+namespace content {
+
+BrowserPluginGeolocationPermissionContext::
+ BrowserPluginGeolocationPermissionContext() {
+}
+
+BrowserPluginGeolocationPermissionContext::
+ ~BrowserPluginGeolocationPermissionContext() {
+}
+
+void BrowserPluginGeolocationPermissionContext::RequestGeolocationPermission(
+ int render_process_id,
+ int render_view_id,
+ int bridge_id,
+ const GURL& requesting_frame,
+ base::Callback callback) {
+ if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::Bind(
+ &BrowserPluginGeolocationPermissionContext::
+ RequestGeolocationPermission,
+ this,
+ render_process_id,
+ render_view_id,
+ bridge_id,
+ requesting_frame,
+ callback));
+ return;
+ }
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+
+ // Note that callback.Run(true) allows geolocation access, callback.Run(false)
+ // denies geolocation access.
+ // We need to go to the renderer to ask embedder's js if we are allowed to
+ // have geolocation access.
+ RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
+ render_view_id);
+ if (rvh) {
+ DCHECK(rvh->GetProcess()->IsGuest());
+ WebContentsImpl* guest_web_contents =
+ static_cast(rvh->GetDelegate()->GetAsWebContents());
+ BrowserPluginGuest* guest = guest_web_contents->GetBrowserPluginGuest();
+ guest->AskEmbedderForGeolocationPermission(bridge_id,
+ requesting_frame,
+ callback);
+ }
+}
+
+void BrowserPluginGeolocationPermissionContext::
+ CancelGeolocationPermissionRequest(int render_process_id,
+ int render_view_id,
+ int bridge_id,
+ const GURL& requesting_frame) {
+ if (!BrowserThread::CurrentlyOn(BrowserThread::UI)) {
+ BrowserThread::PostTask(
+ BrowserThread::UI, FROM_HERE,
+ base::Bind(
+ &BrowserPluginGeolocationPermissionContext::
+ CancelGeolocationPermissionRequest,
+ this,
+ render_process_id,
+ render_view_id,
+ bridge_id,
+ requesting_frame));
+ return;
+ }
+ DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
+ RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
+ render_view_id);
+ if (rvh) {
+ DCHECK(rvh->GetProcess()->IsGuest());
+ WebContentsImpl* guest_web_contents =
+ static_cast(rvh->GetDelegate()->GetAsWebContents());
+ BrowserPluginGuest* guest = guest_web_contents->GetBrowserPluginGuest();
+ if (guest)
+ guest->CancelGeolocationRequest(bridge_id);
+ }
+}
+
+} // namespace content
diff --git a/pool/shard007/C++/0095119_csg_dump.cc b/pool/shard007/C++/0095119_csg_dump.cc
new file mode 100644
index 0000000000000000000000000000000000000000..d9dd2614f448d10d5819a8228d0bc185ef4c56f5
--- /dev/null
+++ b/pool/shard007/C++/0095119_csg_dump.cc
@@ -0,0 +1,99 @@
+/*
+ * Copyright 2009-2021 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/csg/csgapplication.h"
+
+using namespace std;
+using namespace votca::csg;
+
+class CsgDumpApp : public CsgApplication {
+ string ProgramName() override { return "csg_dump"; }
+ void HelpText(ostream &out) override {
+ out << "Print atoms that are read from topology file to help"
+ " debugging atom naming.";
+ }
+ void Initialize() override {
+ CsgApplication::Initialize();
+ AddProgramOptions("Specific options")(
+ "excl", " display exclusion list instead of molecule list");
+ }
+
+ bool EvaluateTopology(Topology *top, Topology *top_ref) override;
+
+ bool DoMapping() override { return true; }
+ bool DoMappingDefault(void) override { return false; }
+};
+
+int main(int argc, char **argv) {
+ CsgDumpApp app;
+
+ return app.Exec(argc, argv);
+}
+
+bool CsgDumpApp::EvaluateTopology(Topology *top, Topology *) {
+ if (!OptionsMap().count("excl")) {
+ cout << "Boundary Condition: ";
+ if (top->getBoxType() == BoundaryCondition::typeAuto) {
+ cout << "auto";
+ } else if (top->getBoxType() == BoundaryCondition::typeTriclinic) {
+ cout << "triclinic";
+ } else if (top->getBoxType() == BoundaryCondition::typeOrthorhombic) {
+ cout << "orthorhombic";
+ } else if (top->getBoxType() == BoundaryCondition::typeOpen) {
+ cout << "open";
+ }
+ cout << endl;
+ if (top->getBoxType() != BoundaryCondition::typeOpen) {
+ cout << " Box matix:";
+ Eigen::Matrix3d box = top->getBox();
+ for (votca::Index i = 0; i < 3; i++) {
+ for (votca::Index j = 0; j < 3; j++) {
+ cout << " " << box(i, j);
+ }
+ cout << endl << " ";
+ }
+ }
+
+ cout << "\nList of residues:\n";
+ for (votca::Index i = 0; i < top->ResidueCount(); i++) {
+ cout << i << " name: " << top->getResidue(i).getName()
+ << " id: " << top->getResidue(i).getId() << endl;
+ }
+
+ cout << "\nList of molecules:\n";
+ for (const auto &mol : top->Molecules()) {
+ cout << "molecule: " << mol.getId() + 1 << " " << mol.getName()
+ << " beads: " << mol.BeadCount() << endl;
+ for (votca::Index i = 0; i < mol.BeadCount(); ++i) {
+ votca::Index resnr = mol.getBead(i)->getResnr();
+ cout << mol.getBeadId(i) << " Name " << mol.getBeadName(i) << " Type "
+ << mol.getBead(i)->getType() << " Mass "
+ << mol.getBead(i)->getMass() << " Resnr " << resnr << " Resname "
+ << top->getResidue(resnr).getName() << " Charge "
+ << mol.getBead(i)->getQ() << endl;
+ }
+ }
+ } else {
+ cout << "\nList of exclusions:\n" << top->getExclusions();
+ }
+
+ return true;
+}
diff --git a/pool/shard007/C++/0095120_pair.cpp b/pool/shard007/C++/0095120_pair.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..cb60c8582fb4486b16d1dd7fcf7e7d622c7be709
--- /dev/null
+++ b/pool/shard007/C++/0095120_pair.cpp
@@ -0,0 +1,141 @@
+/*
+ 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 "macros.hpp"
+#include "pair.hpp"
+#include "err.hpp"
+#include "pipe.hpp"
+#include "msg.hpp"
+
+zmq::pair_t::pair_t (class ctx_t *parent_, uint32_t tid_, int sid_) :
+ socket_base_t (parent_, tid_, sid_),
+ pipe (NULL),
+ last_in (NULL)
+{
+ options.type = ZMQ_PAIR;
+}
+
+zmq::pair_t::~pair_t ()
+{
+ zmq_assert (!pipe);
+}
+
+void zmq::pair_t::xattach_pipe (pipe_t *pipe_, bool subscribe_to_all_)
+{
+ LIBZMQ_UNUSED (subscribe_to_all_);
+
+ zmq_assert (pipe_ != NULL);
+
+ // ZMQ_PAIR socket can only be connected to a single peer.
+ // The socket rejects any further connection requests.
+ if (pipe == NULL)
+ pipe = pipe_;
+ else
+ pipe_->terminate (false);
+}
+
+void zmq::pair_t::xpipe_terminated (pipe_t *pipe_)
+{
+ if (pipe_ == pipe) {
+ if (last_in == pipe) {
+ saved_credential.set_deep_copy (last_in->get_credential ());
+ last_in = NULL;
+ }
+ pipe = NULL;
+ }
+}
+
+void zmq::pair_t::xread_activated (pipe_t *)
+{
+ // There's just one pipe. No lists of active and inactive pipes.
+ // There's nothing to do here.
+}
+
+void zmq::pair_t::xwrite_activated (pipe_t *)
+{
+ // There's just one pipe. No lists of active and inactive pipes.
+ // There's nothing to do here.
+}
+
+int zmq::pair_t::xsend (msg_t *msg_)
+{
+ if (!pipe || !pipe->write (msg_)) {
+ errno = EAGAIN;
+ return -1;
+ }
+
+ if (!(msg_->flags () & msg_t::more))
+ pipe->flush ();
+
+ // Detach the original message from the data buffer.
+ int rc = msg_->init ();
+ errno_assert (rc == 0);
+
+ return 0;
+}
+
+int zmq::pair_t::xrecv (msg_t *msg_)
+{
+ // Deallocate old content of the message.
+ int rc = msg_->close ();
+ errno_assert (rc == 0);
+
+ if (!pipe || !pipe->read (msg_)) {
+ // Initialise the output parameter to be a 0-byte message.
+ rc = msg_->init ();
+ errno_assert (rc == 0);
+
+ errno = EAGAIN;
+ return -1;
+ }
+ last_in = pipe;
+ return 0;
+}
+
+bool zmq::pair_t::xhas_in ()
+{
+ if (!pipe)
+ return false;
+
+ return pipe->check_read ();
+}
+
+bool zmq::pair_t::xhas_out ()
+{
+ if (!pipe)
+ return false;
+
+ return pipe->check_write ();
+}
+
+const zmq::blob_t &zmq::pair_t::get_credential () const
+{
+ return last_in ? last_in->get_credential () : saved_credential;
+}
diff --git a/pool/shard007/C++/0095121_put.cc b/pool/shard007/C++/0095121_put.cc
new file mode 100644
index 0000000000000000000000000000000000000000..ba86706efb62a32d4bcad9ca4c8b83ca6e97d7db
--- /dev/null
+++ b/pool/shard007/C++/0095121_put.cc
@@ -0,0 +1,91 @@
+// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
+// This source code is licensed under both the GPLv2 (found in the
+// COPYING file in the root directory) and Apache 2.0 License
+// (found in the LICENSE.Apache file in the root directory).
+
+#include
+#include "rocksdb/slice.h"
+#include "rocksdb/merge_operator.h"
+#include "utilities/merge_operators.h"
+
+namespace { // anonymous namespace
+
+using ROCKSDB_NAMESPACE::Logger;
+using ROCKSDB_NAMESPACE::MergeOperator;
+using ROCKSDB_NAMESPACE::Slice;
+
+// A merge operator that mimics Put semantics
+// Since this merge-operator will not be used in production,
+// it is implemented as a non-associative merge operator to illustrate the
+// new interface and for testing purposes. (That is, we inherit from
+// the MergeOperator class rather than the AssociativeMergeOperator
+// which would be simpler in this case).
+//
+// From the client-perspective, semantics are the same.
+class PutOperator : public MergeOperator {
+ public:
+ bool FullMerge(const Slice& /*key*/, const Slice* /*existing_value*/,
+ const std::deque& operand_sequence,
+ std::string* new_value, Logger* /*logger*/) const override {
+ // Put basically only looks at the current/latest value
+ assert(!operand_sequence.empty());
+ assert(new_value != nullptr);
+ new_value->assign(operand_sequence.back());
+ return true;
+ }
+
+ bool PartialMerge(const Slice& /*key*/, const Slice& /*left_operand*/,
+ const Slice& right_operand, std::string* new_value,
+ Logger* /*logger*/) const override {
+ new_value->assign(right_operand.data(), right_operand.size());
+ return true;
+ }
+
+ using MergeOperator::PartialMergeMulti;
+ bool PartialMergeMulti(const Slice& /*key*/,
+ const std::deque& operand_list,
+ std::string* new_value,
+ Logger* /*logger*/) const override {
+ new_value->assign(operand_list.back().data(), operand_list.back().size());
+ return true;
+ }
+
+ static const char* kClassName() { return "PutOperator"; }
+ static const char* kNickName() { return "put_v1"; }
+ const char* Name() const override { return kClassName(); }
+ const char* NickName() const override { return kNickName(); }
+};
+
+class PutOperatorV2 : public PutOperator {
+ bool FullMerge(const Slice& /*key*/, const Slice* /*existing_value*/,
+ const std::deque& /*operand_sequence*/,
+ std::string* /*new_value*/,
+ Logger* /*logger*/) const override {
+ assert(false);
+ return false;
+ }
+
+ bool FullMergeV2(const MergeOperationInput& merge_in,
+ MergeOperationOutput* merge_out) const override {
+ // Put basically only looks at the current/latest value
+ assert(!merge_in.operand_list.empty());
+ merge_out->existing_operand = merge_in.operand_list.back();
+ return true;
+ }
+
+ static const char* kNickName() { return "put"; }
+ const char* NickName() const override { return kNickName(); }
+};
+
+} // end of anonymous namespace
+
+namespace ROCKSDB_NAMESPACE {
+
+std::shared_ptr MergeOperators::CreateDeprecatedPutOperator() {
+ return std::make_shared();
+}
+
+std::shared_ptr MergeOperators::CreatePutOperator() {
+ return std::make_shared();
+}
+} // namespace ROCKSDB_NAMESPACE
diff --git a/pool/shard007/C++/0095125_pmt_tests.cpp b/pool/shard007/C++/0095125_pmt_tests.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c1d216d09445b64d56bf6d6991e45daa5d678b17
--- /dev/null
+++ b/pool/shard007/C++/0095125_pmt_tests.cpp
@@ -0,0 +1,126 @@
+// Copyright (c) 2012-2016 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 "consensus/merkle.h"
+#include "merkleblock.h"
+#include "serialize.h"
+#include "streams.h"
+#include "uint256.h"
+#include "arith_uint256.h"
+#include "version.h"
+#include "test/test_bitcoin.h"
+
+#include
+
+#include
+
+class CPartialMerkleTreeTester : public CPartialMerkleTree
+{
+public:
+ // flip one bit in one of the hashes - this should break the authentication
+ void Damage() {
+ unsigned int n = InsecureRandRange(vHash.size());
+ int bit = InsecureRandBits(8);
+ *(vHash[n].begin() + (bit>>3)) ^= 1<<(bit&7);
+ }
+};
+
+BOOST_FIXTURE_TEST_SUITE(pmt_tests, BasicTestingSetup)
+
+BOOST_AUTO_TEST_CASE(pmt_test1)
+{
+ SeedInsecureRand(false);
+ static const unsigned int nTxCounts[] = {1, 4, 7, 17, 56, 100, 127, 256, 312, 513, 1000, 4095};
+
+ for (int i = 0; i < 12; i++) {
+ unsigned int nTx = nTxCounts[i];
+
+ // build a block with some dummy transactions
+ CBlock block;
+ for (unsigned int j=0; j vTxid(nTx, uint256());
+ for (unsigned int j=0; jGetHash();
+ int nHeight = 1, nTx_ = nTx;
+ while (nTx_ > 1) {
+ nTx_ = (nTx_+1)/2;
+ nHeight++;
+ }
+
+ // check with random subsets with inclusion chances 1, 1/2, 1/4, ..., 1/128
+ for (int att = 1; att < 15; att++) {
+ // build random subset of txid's
+ std::vector vMatch(nTx, false);
+ std::vector vMatchTxid1;
+ for (unsigned int j=0; j(nTx, 1 + vMatchTxid1.size()*nHeight);
+ BOOST_CHECK(ss.size() <= 10 + (258*n+7)/8);
+
+ // deserialize into a tester copy
+ CPartialMerkleTreeTester pmt2;
+ ss >> pmt2;
+
+ // extract merkle root and matched txids from copy
+ std::vector vMatchTxid2;
+ std::vector vIndex;
+ uint256 merkleRoot2 = pmt2.ExtractMatches(vMatchTxid2, vIndex);
+
+ // check that it has the same merkle root as the original, and a valid one
+ BOOST_CHECK(merkleRoot1 == merkleRoot2);
+ BOOST_CHECK(!merkleRoot2.IsNull());
+
+ // check that it contains the matched transactions (in the same order!)
+ BOOST_CHECK(vMatchTxid1 == vMatchTxid2);
+
+ // check that random bit flips break the authentication
+ for (int j=0; j<4; j++) {
+ CPartialMerkleTreeTester pmt3(pmt2);
+ pmt3.Damage();
+ std::vector vMatchTxid3;
+ uint256 merkleRoot3 = pmt3.ExtractMatches(vMatchTxid3, vIndex);
+ BOOST_CHECK(merkleRoot3 != merkleRoot1);
+ }
+ }
+ }
+}
+
+BOOST_AUTO_TEST_CASE(pmt_malleability)
+{
+ std::vector vTxid = {
+ ArithToUint256(1), ArithToUint256(2),
+ ArithToUint256(3), ArithToUint256(4),
+ ArithToUint256(5), ArithToUint256(6),
+ ArithToUint256(7), ArithToUint256(8),
+ ArithToUint256(9), ArithToUint256(10),
+ ArithToUint256(9), ArithToUint256(10),
+ };
+ std::vector vMatch = {false, false, false, false, false, false, false, false, false, true, true, false};
+
+ CPartialMerkleTree tree(vTxid, vMatch);
+ std::vector vIndex;
+ BOOST_CHECK(tree.ExtractMatches(vTxid, vIndex).IsNull());
+}
+
+BOOST_AUTO_TEST_SUITE_END()
diff --git a/pool/shard007/C++/0095127_simpledeformation.cpp b/pool/shard007/C++/0095127_simpledeformation.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..89a20788d60a15f6354644b54c9317933220f0cc
--- /dev/null
+++ b/pool/shard007/C++/0095127_simpledeformation.cpp
@@ -0,0 +1,94 @@
+// Aqsis
+// Copyright (C) 2001, Paul C. Gregory and the other authors and contributors
+// 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 software's owners 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.
+//
+// (This is the New BSD license)
+
+#include "renderer.h"
+#include "surfaces.h"
+
+static GeometryPtr createPatch(const float P[12], const float Cs[3],
+ const Mat4& trans = Mat4())
+{
+ PrimvarStorageBuilder builder;
+ builder.add(Primvar::P, P, 12);
+ builder.add(PrimvarSpec(PrimvarSpec::Constant, PrimvarSpec::Color, 1, ustring("Cs")),
+ Cs, 3);
+ IclassStorage storReq(1,4,4,4,4);
+ GeometryPtr patch(new Patch(builder.build(storReq)));
+ patch->transform(trans);
+ return patch;
+}
+
+void renderSimpleDeformationScene()
+{
+ Options opts;
+ opts.xRes = 1024;
+ opts.yRes = 1024;
+ opts.gridSize = 8;
+ opts.clipNear = 0.1;
+ opts.superSamp = Imath::V2i(4,4);
+ opts.pixelFilter = makeSincFilter(Vec2(3.0,3.0));
+ opts.shutterMin = 0;
+ opts.shutterMax = 2;
+
+ Attributes attrs;
+ attrs.shadingRate = 1;
+ attrs.smoothShading = true;
+ attrs.surfaceShader = createShader("default");
+
+ Mat4 camToScreen = perspectiveProjection(90, opts.clipNear, opts.clipFar);
+
+ // Output variables.
+ VarList outVars;
+ outVars.push_back(Stdvar::Ci);
+
+ Renderer renderer(opts, camToScreen, outVars);
+
+ {
+ float Cs[3] = {1,1,1};
+ GeometryKeys keys;
+ float P1[12] = {-0.4,-0.4,1, -0.4,-0.3,1, -0.3,-0.4,1, -0.3,-0.3,1};
+ keys.push_back(GeometryKey(0, createPatch(P1,Cs)));
+ float P2[12] = {-0.1,-0.1,1, -0.1,0.1,1, 0.1,-0.1,1, 0.1,0.1,1};
+ keys.push_back(GeometryKey(2, createPatch(P2,Cs)));
+ renderer.add(keys, attrs);
+ }
+
+ {
+ float Cs[3] = {0.6,0.4,0.4};
+ GeometryKeys keys;
+ float P1[12] = {1,0,2, 0,1.1,2, 0,-1.1,2, -1,0,2};
+ keys.push_back(GeometryKey(0, createPatch(P1,Cs)));
+ float P2[12] = {1.5,0,2, 0,0.8,2, 0,-0.8,2, -1.5,0,2};
+ keys.push_back(GeometryKey(2, createPatch(P2,Cs)));
+ renderer.add(keys, attrs);
+ }
+
+ renderer.render();
+}
+
diff --git a/pool/shard007/C++/0095128_DemoColorImageByScore.cpp b/pool/shard007/C++/0095128_DemoColorImageByScore.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ef60244467c540579c158c5bbe96710a63dcb8fe
--- /dev/null
+++ b/pool/shard007/C++/0095128_DemoColorImageByScore.cpp
@@ -0,0 +1,74 @@
+/*=========================================================================
+ *
+ * Copyright David Doria 2011 daviddoria@gmail.com
+ *
+ * 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.txt
+ *
+ * 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.
+ *
+ *=========================================================================*/
+
+// Submodules
+#include
+#include
+
+// ITK
+#include "itkImageFileReader.h"
+
+// Boost
+#include
+
+int main(int argc, char *argv[])
+{
+ if(argc != 3)
+ {
+ std::cerr << "Required arguments: image mask" << std::endl;
+ return EXIT_FAILURE;
+ }
+ std::string imageFilename = argv[1];
+ std::string maskFilename = argv[2];
+ std::cout << "Reading image: " << imageFilename << std::endl;
+ std::cout << "Reading mask: " << maskFilename << std::endl;
+
+ typedef itk::VectorImage FloatVectorImageType;
+ typedef itk::ImageFileReader ImageReaderType;
+ ImageReaderType::Pointer imageReader = ImageReaderType::New();
+ imageReader->SetFileName(imageFilename.c_str());
+ imageReader->Update();
+
+ typedef itk::ImageFileReader MaskReaderType;
+ MaskReaderType::Pointer maskReader = MaskReaderType::New();
+ maskReader->SetFileName(maskFilename.c_str());
+ maskReader->Update();
+
+ std::shared_ptr patchCompare(new SelfPatchCompare);
+ patchCompare->SetNumberOfComponentsPerPixel(imageReader->GetOutput()->GetNumberOfComponentsPerPixel());
+ //patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchAverageAbsoluteSourceDifference,patchCompare,_1));
+ //patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchColorDifference,patchCompare,_1));
+ patchCompare->FunctionsToCompute.push_back(boost::bind(&SelfPatchCompare::SetPatchDepthDifference,patchCompare.get(),_1));
+ //patchCompare->SetImage(imageReader->GetOutput());
+ //patchCompare->SetMask(maskReader->GetOutput());
+
+ PatchBasedInpainting inpainting;
+ inpainting.SetMask(maskReader->GetOutput());
+ inpainting.SetImage(imageReader->GetOutput());
+ //inpainting.PatchSortFunction = &SortByDepthDifference;
+ //inpainting.SetPatchCompare(patchCompare);
+ inpainting.Initialize();
+ inpainting.Iterate();
+
+ CandidatePairs candidatePairs = inpainting.GetPotentialCandidatePairs()[0];
+ //patchCompare->SetPairs(&candidatePairs);
+ //patchCompare->ComputeAllSourceDifferences();
+ WriteImageOfScores(candidatePairs, imageReader->GetOutput()->GetLargestPossibleRegion(), "ScoreImage_TargetPatch.mha");
+
+ return EXIT_SUCCESS;
+}
diff --git a/pool/shard007/C++/0095129_led.cpp b/pool/shard007/C++/0095129_led.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..e1e9551a29281bf5dc6c36db3e206d688f93dc94
--- /dev/null
+++ b/pool/shard007/C++/0095129_led.cpp
@@ -0,0 +1,62 @@
+/*
+ * led.cpp - Implementation of LED class which abstracts LED functionality with
+ * the naze32
+ *
+ * Copyright (c) 2016 James Jackson
+ *
+ * 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 "led.h"
+#include "board.h"
+
+LED::LED(){}
+
+LED::LED(GPIO_TypeDef* port, uint16_t pin) :
+ gpio_(port, pin, GPIO_Mode_Out_PP)
+{
+ gpio_.write(HIGH);
+}
+
+void LED::toggle()
+{
+ gpio_.toggle();
+}
+
+void LED::turn_on()
+{
+ gpio_.write(LOW);
+}
+
+void LED::turn_off()
+{
+ gpio_.write(HIGH);
+}
+
+void LED::blink(uint32_t ms_delay)
+{
+ static uint32_t last_time = 0;
+ uint32_t now = millis();
+
+ if(now - last_time > ms_delay)
+ {
+ toggle();
+ last_time = now;
+ }
+}
diff --git a/pool/shard007/C++/0095136_websocket_server.cpp b/pool/shard007/C++/0095136_websocket_server.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..26e847de6d77dfaee9c2fceb15b9f2002f6c6e3e
--- /dev/null
+++ b/pool/shard007/C++/0095136_websocket_server.cpp
@@ -0,0 +1,172 @@
+#include "websocket_server.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace {
+const QString kWebsocketCertPath = WEBSOCKET_CERT_PATH;
+
+// Names used for a websocket JSON object.
+const QString kMessageType = "type";
+const QString kPayload = "data";
+
+} // namespace
+
+WebsocketServer::WebsocketServer(quint16 port)
+ : m_websocket_server(new QWebSocketServer("PACC server",
+ QWebSocketServer::SecureMode))
+{
+ QSslConfiguration sslConfiguration;
+ QFile cert_file(kWebsocketCertPath + "/localhost.crt");
+ cert_file.open(QIODevice::ReadOnly);
+ QSslCertificate certificate(&cert_file, QSsl::Pem);
+ cert_file.close();
+
+ QFile key_file(kWebsocketCertPath + "/localhost.key");
+ key_file.open(QIODevice::ReadOnly);
+ QSslKey ssl_key(&key_file, QSsl::Rsa, QSsl::Pem);
+ key_file.close();
+
+ if (certificate.isNull() || ssl_key.isNull()) {
+ qCritical() << QString("The websocket certificate could not be loaded. "
+ "Please verify that localhost.crt and "
+ "localhost.key exist in %s and are readable by "
+ "the pacc module.")
+ .arg(kWebsocketCertPath);
+ exit(1);
+ }
+
+ sslConfiguration.setPeerVerifyMode(QSslSocket::VerifyNone);
+ sslConfiguration.setLocalCertificate(certificate);
+ sslConfiguration.setPrivateKey(ssl_key);
+ sslConfiguration.setProtocol(QSsl::TlsV1SslV3);
+ m_websocket_server->setSslConfiguration(sslConfiguration);
+
+ connect(m_websocket_server.data(), &QWebSocketServer::newConnection,
+ this, &WebsocketServer::onNewConnection);
+ connect(m_websocket_server.data(), &QWebSocketServer::sslErrors,
+ [](const QList &) {
+ qWarning() << "Ssl errors occurred";
+ });
+ connect(m_websocket_server.data(), &QWebSocketServer::acceptError,
+ [](QAbstractSocket::SocketError socketError) {
+ qWarning() << "SocketError: " << QString::number(socketError);
+ });
+ connect(m_websocket_server.data(), &QWebSocketServer::serverError,
+ [](QWebSocketProtocol::CloseCode closeCode) {
+ qWarning() << "ServerError: " << QString::number(closeCode);
+ });
+ connect(m_websocket_server.data(), &QWebSocketServer::peerVerifyError,
+ [](const QSslError &error) {
+ qWarning() << "PeerVerifyError: " << error.errorString();
+ });
+
+ Q_ASSERT(m_websocket_server->listen(QHostAddress::Any, port) &&
+ "Could not start the websocket server");
+}
+
+WebsocketServer::~WebsocketServer() {
+}
+
+void WebsocketServer::onNewConnection() {
+ QWebSocket *socket = m_websocket_server->nextPendingConnection();
+
+ QMutexLocker l(&m_socket_mutex);
+ connect(socket, &QWebSocket::textMessageReceived,
+ this, &WebsocketServer::processTextMessage);
+ connect(socket, &QWebSocket::disconnected,
+ this, &WebsocketServer::socketDisconnected);
+ void (QWebSocket::*error)(QAbstractSocket::SocketError) =
+ &QWebSocket::error;
+ connect(socket, error, [](QAbstractSocket::SocketError error) {
+ qWarning() << "onError" << QString::number(error);
+ });
+
+ if (!m_socket.isNull()) {
+ qWarning() << "There is already a client connected!";
+ }
+ m_socket.reset(socket);
+
+ // Sends all the pending messages.
+ while (!m_pending_messages.isEmpty()) {
+ const QString &pending_message = m_pending_messages.takeFirst();
+ m_socket->sendTextMessage(pending_message);
+ }
+
+ emit clientConnected();
+}
+
+void WebsocketServer::sendMessage(const QString &type,
+ const QJsonValue &payload) {
+ // Assembles the message.
+ QJsonObject json_message;
+ json_message[kMessageType] = type;
+ json_message[kPayload] = payload;
+
+ QJsonDocument document(json_message);
+ QString message = QString::fromUtf8(document.toJson());
+
+ // Sends the message if there is a socket connected or adds it to the
+ // pending queue.
+ QMutexLocker l(&m_socket_mutex);
+ if (m_socket) {
+ m_socket->sendTextMessage(message);
+ } else {
+ m_pending_messages.append(message);
+ }
+}
+
+void WebsocketServer::processTextMessage(QString message) {
+ QWebSocket *socket = qobject_cast(sender());
+
+ // Checks if the socket matches.
+ if (socket != m_socket.data()) {
+ qWarning() << "Message from wrong socket. Ignoring.";
+ return;
+ }
+
+ // Parses the message.
+ QJsonParseError parse_error;
+ QJsonDocument document =
+ QJsonDocument::fromJson(message.toUtf8(), &parse_error);
+ if (parse_error.error != QJsonParseError::NoError) {
+ qWarning() << "Failed to parse the websocket message: "
+ << parse_error.errorString();
+ return;
+ }
+ if (!document.isObject()) {
+ qWarning() << "Invalid websocket message.";
+ return;
+ }
+
+ QJsonObject msg_object = document.object();
+ if (!msg_object.contains(kMessageType)) {
+ qWarning() << "Invalid websocket message.";
+ return;
+ }
+
+ // Reads the message.
+ const QString &type = msg_object[kMessageType].toString();
+ const QJsonValue &payload = msg_object[kPayload];
+
+ emit messageReceived(type, payload);
+}
+
+void WebsocketServer::socketDisconnected() {
+ QWebSocket *socket = qobject_cast(sender());
+ QMutexLocker l(&m_socket_mutex);
+ if (socket == m_socket.data()) {
+ m_socket.take();
+ }
+ socket->deleteLater();
+
+ l.unlock();
+ emit clientDisconnected();
+}
diff --git a/pool/shard007/C++/0095139_test_thread_exit.cpp b/pool/shard007/C++/0095139_test_thread_exit.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..577bcd05d036eba3dc8d2de28dbe7eb6cfa17829
--- /dev/null
+++ b/pool/shard007/C++/0095139_test_thread_exit.cpp
@@ -0,0 +1,63 @@
+// (C) Copyright 2009 Anthony Williams
+//
+// 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
+#include
+#include
+#include
+
+#define BOOST_TEST_MODULE Boost.Threads: thread exit test suite
+
+#include
+
+boost::thread::id exit_func_thread_id;
+
+void exit_func()
+{
+ exit_func_thread_id=boost::this_thread::get_id();
+}
+
+void tf1()
+{
+ boost::this_thread::at_thread_exit(exit_func);
+ BOOST_CHECK(exit_func_thread_id!=boost::this_thread::get_id());
+}
+
+BOOST_AUTO_TEST_CASE(test_thread_exit_func_runs_when_thread_exits)
+{
+ exit_func_thread_id=boost::thread::id();
+ boost::thread t(&tf1);
+ boost::thread::id const t_id=t.get_id();
+ t.join();
+ BOOST_CHECK(exit_func_thread_id==t_id);
+}
+
+struct fo
+{
+ void operator()()
+ {
+ exit_func_thread_id=boost::this_thread::get_id();
+ }
+};
+
+void tf2()
+{
+ boost::this_thread::at_thread_exit(fo());
+ BOOST_CHECK(exit_func_thread_id!=boost::this_thread::get_id());
+}
+
+
+BOOST_AUTO_TEST_CASE(test_can_use_function_object_for_exit_func)
+{
+ exit_func_thread_id=boost::thread::id();
+ boost::thread t(tf2);
+ boost::thread::id const t_id=t.get_id();
+ t.join();
+ BOOST_CHECK(exit_func_thread_id==t_id);
+}
diff --git a/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc b/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc
new file mode 100644
index 0000000000000000000000000000000000000000..7f0bb03232477d054dffed0d98ed7f27dda30835
--- /dev/null
+++ b/pool/shard007/C++/0095148_ice_transport_adapter_impl.cc
@@ -0,0 +1,220 @@
+// Copyright 2018 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 "third_party/blink/renderer/modules/peerconnection/adapters/ice_transport_adapter_impl.h"
+
+#include
+
+#include "base/notreached.h"
+#include "third_party/webrtc/api/ice_transport_factory.h"
+
+namespace blink {
+
+IceTransportAdapterImpl::IceTransportAdapterImpl(
+ Delegate* delegate,
+ std::unique_ptr port_allocator,
+ std::unique_ptr async_resolver_factory)
+ : delegate_(delegate),
+ port_allocator_(std::move(port_allocator)),
+ async_resolver_factory_(std::move(async_resolver_factory)) {
+ // These settings are copied from PeerConnection:
+ // https://codesearch.chromium.org/chromium/src/third_party/webrtc/pc/peerconnection.cc?l=4708&rcl=820ebd0f661696043959b5105b2814e0edd8b694
+ port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
+ port_allocator_->set_flags(port_allocator_->flags() |
+ cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
+ cricket::PORTALLOCATOR_ENABLE_IPV6 |
+ cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
+ port_allocator_->Initialize();
+
+ webrtc::IceTransportInit ice_transport_init;
+ ice_transport_init.set_port_allocator(port_allocator_.get());
+ ice_transport_init.set_async_resolver_factory(async_resolver_factory_.get());
+ ice_transport_channel_ =
+ webrtc::CreateIceTransport(std::move(ice_transport_init));
+ SetupIceTransportChannel();
+ // We need to set the ICE role even before Start is called since the Port
+ // assumes that the role has been set before receiving incoming connectivity
+ // checks. These checks can race with the information signaled for Start.
+ ice_transport_channel()->SetIceRole(cricket::ICEROLE_CONTROLLING);
+ // The ICE tiebreaker is used to determine which side is controlling/
+ // controlled when both sides start in the same role. The number is randomly
+ // generated so that each peer can calculate a.tiebreaker <= b.tiebreaker
+ // consistently.
+ ice_transport_channel()->SetIceTiebreaker(rtc::CreateRandomId64());
+}
+
+IceTransportAdapterImpl::IceTransportAdapterImpl(
+ Delegate* delegate,
+ rtc::scoped_refptr ice_transport)
+ : delegate_(delegate), ice_transport_channel_(ice_transport) {
+ // The native webrtc peer connection might have been closed in the meantime,
+ // clearing the ice transport channel; don't do anything in that case. |this|
+ // will eventually be destroyed when the blink layer gets notified by the
+ // webrtc layer that the transport has been cleared.
+ if (ice_transport_channel())
+ SetupIceTransportChannel();
+}
+
+IceTransportAdapterImpl::~IceTransportAdapterImpl() = default;
+
+static uint32_t GetCandidateFilterForPolicy(IceTransportPolicy policy) {
+ switch (policy) {
+ case IceTransportPolicy::kRelay:
+ return cricket::CF_RELAY;
+ case IceTransportPolicy::kAll:
+ return cricket::CF_ALL;
+ }
+ NOTREACHED();
+ return 0;
+}
+
+void IceTransportAdapterImpl::StartGathering(
+ const cricket::IceParameters& local_parameters,
+ const cricket::ServerAddresses& stun_servers,
+ const WebVector& turn_servers,
+ IceTransportPolicy policy) {
+ if (port_allocator_) {
+ port_allocator_->set_candidate_filter(GetCandidateFilterForPolicy(policy));
+ port_allocator_->SetConfiguration(
+ stun_servers,
+ const_cast&>(turn_servers)
+ .ReleaseVector(),
+ port_allocator_->candidate_pool_size(),
+ port_allocator_->prune_turn_ports());
+ }
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "StartGathering called, but ICE transport released";
+ return;
+ }
+ ice_transport_channel()->SetIceParameters(local_parameters);
+ ice_transport_channel()->MaybeStartGathering();
+ DCHECK_EQ(ice_transport_channel()->gathering_state(),
+ cricket::kIceGatheringGathering);
+}
+
+void IceTransportAdapterImpl::Start(
+ const cricket::IceParameters& remote_parameters,
+ cricket::IceRole role,
+ const Vector& initial_remote_candidates) {
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "Start called, but ICE transport released";
+ return;
+ }
+ ice_transport_channel()->SetRemoteIceParameters(remote_parameters);
+ ice_transport_channel()->SetIceRole(role);
+ for (const auto& candidate : initial_remote_candidates) {
+ ice_transport_channel()->AddRemoteCandidate(candidate);
+ }
+}
+
+void IceTransportAdapterImpl::HandleRemoteRestart(
+ const cricket::IceParameters& new_remote_parameters) {
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "HandleRemoteRestart called, but ICE transport released";
+ return;
+ }
+ ice_transport_channel()->RemoveAllRemoteCandidates();
+ ice_transport_channel()->SetRemoteIceParameters(new_remote_parameters);
+}
+
+void IceTransportAdapterImpl::AddRemoteCandidate(
+ const cricket::Candidate& candidate) {
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "AddRemoteCandidate called, but ICE transport released";
+ return;
+ }
+ ice_transport_channel()->AddRemoteCandidate(candidate);
+}
+
+void IceTransportAdapterImpl::SetupIceTransportChannel() {
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "SetupIceTransportChannel called, but ICE transport released";
+ return;
+ }
+ ice_transport_channel()->SignalGatheringState.connect(
+ this, &IceTransportAdapterImpl::OnGatheringStateChanged);
+ ice_transport_channel()->SignalCandidateGathered.connect(
+ this, &IceTransportAdapterImpl::OnCandidateGathered);
+ ice_transport_channel()->SignalIceTransportStateChanged.connect(
+ this, &IceTransportAdapterImpl::OnStateChanged);
+ ice_transport_channel()->SignalNetworkRouteChanged.connect(
+ this, &IceTransportAdapterImpl::OnNetworkRouteChanged);
+ ice_transport_channel()->SignalRoleConflict.connect(
+ this, &IceTransportAdapterImpl::OnRoleConflict);
+}
+
+void IceTransportAdapterImpl::OnGatheringStateChanged(
+ cricket::IceTransportInternal* transport) {
+ DCHECK_EQ(transport, ice_transport_channel());
+ delegate_->OnGatheringStateChanged(
+ ice_transport_channel()->gathering_state());
+}
+
+void IceTransportAdapterImpl::OnCandidateGathered(
+ cricket::IceTransportInternal* transport,
+ const cricket::Candidate& candidate) {
+ DCHECK_EQ(transport, ice_transport_channel());
+ delegate_->OnCandidateGathered(candidate);
+}
+
+void IceTransportAdapterImpl::OnStateChanged(
+ cricket::IceTransportInternal* transport) {
+ DCHECK_EQ(transport, ice_transport_channel());
+ delegate_->OnStateChanged(ice_transport_channel()->GetIceTransportState());
+}
+
+void IceTransportAdapterImpl::OnNetworkRouteChanged(
+ absl::optional new_network_route) {
+ if (!ice_transport_channel()) {
+ LOG(ERROR) << "OnNetworkRouteChanged called, but ICE transport released";
+ return;
+ }
+ const absl::optional selected_pair =
+ ice_transport_channel()->GetSelectedCandidatePair();
+ if (!selected_pair) {
+ // The selected connection will only be null if the ICE connection has
+ // totally failed, at which point we'll get a StateChanged signal. The
+ // client will implicitly clear the selected candidate pair when it receives
+ // the failed state change, so we don't need to give an explicit callback
+ // here.
+ return;
+ }
+ delegate_->OnSelectedCandidatePairChanged(std::make_pair(
+ selected_pair->local_candidate(), selected_pair->remote_candidate()));
+}
+
+static const char* IceRoleToString(cricket::IceRole role) {
+ switch (role) {
+ case cricket::ICEROLE_CONTROLLING:
+ return "controlling";
+ case cricket::ICEROLE_CONTROLLED:
+ return "controlled";
+ default:
+ return "unknown";
+ }
+}
+
+static cricket::IceRole IceRoleReversed(cricket::IceRole role) {
+ switch (role) {
+ case cricket::ICEROLE_CONTROLLING:
+ return cricket::ICEROLE_CONTROLLED;
+ case cricket::ICEROLE_CONTROLLED:
+ return cricket::ICEROLE_CONTROLLING;
+ default:
+ return cricket::ICEROLE_UNKNOWN;
+ }
+}
+
+void IceTransportAdapterImpl::OnRoleConflict(
+ cricket::IceTransportInternal* transport) {
+ DCHECK_EQ(transport, ice_transport_channel());
+ // This logic is copied from JsepTransportController.
+ cricket::IceRole reversed_role =
+ IceRoleReversed(ice_transport_channel()->GetIceRole());
+ LOG(INFO) << "Got role conflict; switching to "
+ << IceRoleToString(reversed_role) << " role.";
+ ice_transport_channel()->SetIceRole(reversed_role);
+}
+
+} // namespace blink
diff --git a/pool/shard007/C++/0095151_ipc.cc b/pool/shard007/C++/0095151_ipc.cc
new file mode 100644
index 0000000000000000000000000000000000000000..ee98c5d0d50066be7cd2739b9c362fbf3b3a2942
--- /dev/null
+++ b/pool/shard007/C++/0095151_ipc.cc
@@ -0,0 +1,212 @@
+/*
+ * \brief Implementation of the Genode IPC-framework
+ * \author Martin Stein
+ * \date 2012-02-12
+ */
+
+/*
+ * Copyright (C) 2012-2013 Genode Labs GmbH
+ *
+ * This file is part of the Genode OS framework, which is distributed
+ * under the terms of the GNU General Public License version 2.
+ */
+
+/* Genode includes */
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+/* base-hw includes */
+#include
+#include
+
+namespace Hw { extern Genode::Untyped_capability _main_thread_cap; }
+
+using namespace Genode;
+
+enum
+{
+ /* size of the callee-local name of a targeted RPC object */
+ RPC_OBJECT_ID_SIZE = sizeof(Native_thread_id),
+
+ /*
+ * The RPC framework marshalls a return value into reply messages to
+ * deliver exceptions, wich occured during the RPC call to the caller.
+ * This defines the size of this value.
+ */
+ RPC_RETURN_VALUE_SIZE = sizeof(umword_t),
+};
+
+
+/*****************************
+ ** IPC marshalling support **
+ *****************************/
+
+void Ipc_ostream::_marshal_capability(Native_capability const &cap) {
+ _snd_msg->cap_add(cap); }
+
+
+void Ipc_istream::_unmarshal_capability(Native_capability &cap) {
+ cap = _rcv_msg->cap_get(); }
+
+
+/*****************
+ ** Ipc_ostream **
+ *****************/
+
+Ipc_ostream::Ipc_ostream(Native_capability dst, Msgbuf_base *snd_msg)
+:
+ Ipc_marshaller(&snd_msg->buf[0], snd_msg->size()),
+ _snd_msg(snd_msg), _dst(dst)
+{
+ _write_offset = align_natural(RPC_OBJECT_ID_SIZE);
+ _snd_msg->reset();
+}
+
+
+/*****************
+ ** Ipc_istream **
+ *****************/
+
+void Ipc_istream::_wait()
+{
+ /* FIXME: this shall be not supported */
+ Kernel::pause_current_thread();
+}
+
+
+Ipc_istream::Ipc_istream(Msgbuf_base *rcv_msg)
+:
+ Ipc_unmarshaller(&rcv_msg->buf[0], rcv_msg->size()),
+ Native_capability(Thread_base::myself() ? Thread_base::myself()->tid().cap
+ : Hw::_main_thread_cap),
+ _rcv_msg(rcv_msg), _rcv_cs(-1)
+{ _read_offset = align_natural(RPC_OBJECT_ID_SIZE); }
+
+
+Ipc_istream::~Ipc_istream() { }
+
+
+/****************
+ ** Ipc_client **
+ ****************/
+
+void Ipc_client::_call()
+{
+ retry(
+ [&] () {
+
+ /* send request and receive corresponding reply */
+ Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset);
+
+ switch (Kernel::send_request_msg(Ipc_ostream::dst().dst(),
+ _rcv_msg->cap_rcv_window())) {
+ case -1: throw Blocking_canceled();
+ case -2: throw Allocator::Out_of_memory();
+ default:
+ _rcv_msg->reset();
+ _snd_msg->reset();
+ Thread_base::myself()->utcb()->copy_to(*_rcv_msg);
+
+ /* reset unmarshaller */
+ _write_offset = _read_offset =
+ align_natural(RPC_OBJECT_ID_SIZE);
+ }
+
+ },
+ [&] () { upgrade_pd_session_quota(3*4096); });
+}
+
+
+Ipc_client::Ipc_client(Native_capability const &srv, Msgbuf_base *snd_msg,
+ Msgbuf_base *rcv_msg, unsigned short rcv_caps)
+: Ipc_istream(rcv_msg), Ipc_ostream(srv, snd_msg), _result(0) {
+ rcv_msg->cap_rcv_window(rcv_caps); }
+
+
+/****************
+ ** Ipc_server **
+ ****************/
+
+Ipc_server::Ipc_server(Msgbuf_base *snd_msg,
+ Msgbuf_base *rcv_msg) :
+ Ipc_istream(rcv_msg),
+ Ipc_ostream(Native_capability(), snd_msg),
+ _reply_needed(false) { }
+
+
+void Ipc_server::_prepare_next_reply_wait()
+{
+ /* now we have a request to reply */
+ _reply_needed = true;
+
+ /* leave space for RPC method return value */
+ _write_offset = align_natural(RPC_OBJECT_ID_SIZE +
+ RPC_RETURN_VALUE_SIZE);
+
+ /* reset unmarshaller */
+ _read_offset = align_natural(RPC_OBJECT_ID_SIZE);
+}
+
+
+void Ipc_server::_wait()
+{
+ retry(
+ [&] () {
+
+ /* receive request */
+ switch (Kernel::await_request_msg(Msgbuf_base::MAX_CAP_ARGS)) {
+ case -1: throw Blocking_canceled();
+ case -2: throw Allocator::Out_of_memory();
+ default:
+ _rcv_msg->reset();
+ Thread_base::myself()->utcb()->copy_to(*_rcv_msg);
+
+ /* update server state */
+ _prepare_next_reply_wait();
+ }
+
+ },
+ [&] () { upgrade_pd_session_quota(3*4096); });
+}
+
+
+void Ipc_server::_reply()
+{
+ Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset);
+ _snd_msg->reset();
+ Kernel::send_reply_msg(0, false);
+}
+
+
+void Ipc_server::_reply_wait()
+{
+ /* if there is no reply, wait for request */
+ if (!_reply_needed) {
+ _wait();
+ return;
+ }
+
+ retry(
+ [&] () {
+ /* send reply and receive next request */
+ Thread_base::myself()->utcb()->copy_from(*_snd_msg, _write_offset);
+ switch (Kernel::send_reply_msg(Msgbuf_base::MAX_CAP_ARGS, true)) {
+ case -1: throw Blocking_canceled();
+ case -2: throw Allocator::Out_of_memory();
+ default:
+ _rcv_msg->reset();
+ _snd_msg->reset();
+ Thread_base::myself()->utcb()->copy_to(*_rcv_msg);
+
+ /* update server state */
+ _prepare_next_reply_wait();
+ }
+
+ },
+ [&] () { upgrade_pd_session_quota(3*4096); });
+}
diff --git a/pool/shard007/C++/0095153_sortstrategy.cpp b/pool/shard007/C++/0095153_sortstrategy.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..f85fe9ee58a7c9d985ee17e783adf09bdafbbc06
--- /dev/null
+++ b/pool/shard007/C++/0095153_sortstrategy.cpp
@@ -0,0 +1,90 @@
+/*
+ * (c) 2015 Raghavendra Nayak, All Rights Reserved.
+ * www.openguru.com/
+ */
+
+#include
+#include
+
+// This abstract class provides the SortingAlgorithm interface
+class SortingAlgorithms
+{
+public:
+ SortingAlgorithms() {}
+ virtual ~SortingAlgorithms() {}
+
+ virtual void sort(const std::string& arrayName) = 0;
+};
+
+// Implements the SortingAlgorithm interface via QuickSort
+class QuickSort : public SortingAlgorithms
+{
+public:
+ virtual void sort(const std::string& arrayName) {
+ std::cout << "Sorting " << arrayName << " using QuickSort." << std::endl;
+ }
+};
+
+// Implements the SortingAlgorithm interface via MergeSort
+class MergeSort : public SortingAlgorithms
+{
+public:
+ virtual void sort(const std::string& arrayName) {
+ std::cout << "Sorting " << arrayName << " using MergeSort." << std::endl;
+ }
+};
+
+// Implements the SortingAlgorithm interface via BubbleSort
+class BubbleSort : public SortingAlgorithms
+{
+public:
+ virtual void sort(const std::string& arrayName) {
+ std::cout << "Sorting " << arrayName << " using BubbleSort." << std::endl;
+ }
+};
+
+class Array
+{
+ SortingAlgorithms* sortStrategy;
+ std::string arrayName;
+public:
+ enum SortStrategy
+ {
+ QUICK, MERGE, BUBBLE
+ };
+ Array(const std::string& arrayName)
+ : sortStrategy(nullptr), arrayName(arrayName) {
+ }
+ void setStrategy(const int type) {
+ switch (type) {
+ case QUICK:
+ sortStrategy = new QuickSort();
+ break;
+ case MERGE:
+ sortStrategy = new MergeSort();
+ break;
+ case BUBBLE:
+ sortStrategy = new BubbleSort();
+ default:
+ break;
+ }
+ }
+ void applyStrategy() {
+ if (sortStrategy != nullptr) {
+ sortStrategy->sort(arrayName);
+ }
+ }
+};
+
+int main(int argc, char **argv)
+{
+ Array intArray("integer array");
+ int sortStrategy;
+ std::cout << "Enter the strategy for sorting: Quick(0) Merge(1) Bubble(2) : ";
+ std::cin >> sortStrategy;
+
+ intArray.setStrategy(sortStrategy);
+ intArray.applyStrategy();
+
+ return 0;
+}
diff --git a/pool/shard007/C++/0095157_clippingPlane.cpp b/pool/shard007/C++/0095157_clippingPlane.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..b1d9cc08c111c819c3ea40e52010e3b6b0e3a4ce
--- /dev/null
+++ b/pool/shard007/C++/0095157_clippingPlane.cpp
@@ -0,0 +1,101 @@
+/****************************************************************************
+
+ Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
+
+ This file is part of the QGLViewer library version 2.6.1.
+
+ http://www.libqglviewer.com - contact@libqglviewer.com
+
+ This file may be used under the terms of the GNU General Public License
+ versions 2.0 or 3.0 as published by the Free Software Foundation and
+ appearing in the LICENSE file included in the packaging of this file.
+ In addition, as a special exception, Gilles Debunne gives you certain
+ additional rights, described in the file GPL_EXCEPTION in this package.
+
+ libQGLViewer uses dual licensing. Commercial/proprietary software must
+ purchase a libQGLViewer Commercial License.
+
+ This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
+ WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
+
+*****************************************************************************/
+
+#include "clippingPlane.h"
+#include "QGLViewer/manipulatedFrame.h"
+
+using namespace std;
+using namespace qglviewer;
+
+// Draws a spiral
+void Viewer::draw()
+{
+ const float nbSteps = 200.0;
+
+ glBegin(GL_QUAD_STRIP);
+ for (int i=0; imatrix());
+ // Since the Clipping Plane equation is multiplied by the current modelView, we can define a
+ // constant equation (plane normal along Z and passing by the origin) since we are here in the
+ // manipulatedFrame coordinates system (we glMultMatrixd() with the manipulatedFrame matrix()).
+ static const GLdouble equation[] = { 0.0, 0.0, 1.0, 0.0 };
+ glClipPlane(GL_CLIP_PLANE0, equation);
+
+ // Draw a plane representation: Its normal...
+ glColor3f(0.8f, 0.8f, 0.8f);
+ drawArrow(0.4f, 0.015f);
+ // ...and a quad (with a slightly shifted z so that it is not clipped).
+ glBegin(GL_QUADS);
+ glVertex3f(-1.0, -1.0, 0.001f);
+ glVertex3f(-1.0, 1.0, 0.001f);
+ glVertex3f( 1.0, 1.0, 0.001f);
+ glVertex3f( 1.0, -1.0, 0.001f);
+ glEnd();
+ glPopMatrix();
+}
+
+void Viewer::init()
+{
+ // Restore previous viewer state.
+ restoreStateFromFile();
+
+ // Opens help window
+ help();
+
+ // The ManipulatedFrame will be used to position the clipping plane
+ setManipulatedFrame(new ManipulatedFrame());
+
+ // Enable plane clipping
+ glEnable(GL_CLIP_PLANE0);
+}
+
+QString Viewer::helpString() const
+{
+ QString text("C l i p p i n g P l a n e
");
+ text += "The standard OpenGL GL_CLIP_PLANE feature is used to add an additionnal clipping ";
+ text += "plane in the scene, which position and orientation are set by a ManipulatedFrame.
";
+ text += "Hold the Control key pressed down while using the mouse to modify the plane orientation (left button) ";
+ text += "and position (right button) and to interactively see the clipped result.
";
+ text += "Since the plane equation is defined with respect to the current modelView matrix, a constant equation (normal";
+ text += "along the Z axis) can be used since we transformed the coordinates system using the matrix() method.";
+
+ return text;
+}
diff --git a/pool/shard007/C++/0095169_bitcoin.cpp b/pool/shard007/C++/0095169_bitcoin.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..464a0b37ff7fbe821776859cf28b5f7ff7830b06
--- /dev/null
+++ b/pool/shard007/C++/0095169_bitcoin.cpp
@@ -0,0 +1,270 @@
+/*
+ * W.J. van der Laan 2011-2012
+ */
+#include "bitcoingui.h"
+#include "clientmodel.h"
+#include "walletmodel.h"
+#include "optionsmodel.h"
+#include "guiutil.h"
+#include "guiconstants.h"
+
+#include "init.h"
+#include "ui_interface.h"
+#include "qtipcserver.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED)
+#define _BITCOIN_QT_PLUGINS_INCLUDED
+#define __INSURE__
+#include
+Q_IMPORT_PLUGIN(qcncodecs)
+Q_IMPORT_PLUGIN(qjpcodecs)
+Q_IMPORT_PLUGIN(qtwcodecs)
+Q_IMPORT_PLUGIN(qkrcodecs)
+Q_IMPORT_PLUGIN(qtaccessiblewidgets)
+#endif
+
+// Need a global reference for the notifications to find the GUI
+static BitcoinGUI *guiref;
+static QSplashScreen *splashref;
+
+static void ThreadSafeMessageBox(const std::string& message, const std::string& caption, int style)
+{
+ // Message from network thread
+ if(guiref)
+ {
+ bool modal = (style & CClientUIInterface::MODAL);
+ // in case of modal message, use blocking connection to wait for user to click OK
+ QMetaObject::invokeMethod(guiref, "error",
+ modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection,
+ Q_ARG(QString, QString::fromStdString(caption)),
+ Q_ARG(QString, QString::fromStdString(message)),
+ Q_ARG(bool, modal));
+ }
+ else
+ {
+ printf("%s: %s\n", caption.c_str(), message.c_str());
+ fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str());
+ }
+}
+
+static bool ThreadSafeAskFee(int64 nFeeRequired, const std::string& strCaption)
+{
+ if(!guiref)
+ return false;
+ if(nFeeRequired < MIN_TX_FEE || nFeeRequired <= nTransactionFee || fDaemon)
+ return true;
+ bool payFee = false;
+
+ QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(),
+ Q_ARG(qint64, nFeeRequired),
+ Q_ARG(bool*, &payFee));
+
+ return payFee;
+}
+
+static void ThreadSafeHandleURI(const std::string& strURI)
+{
+ if(!guiref)
+ return;
+
+ QMetaObject::invokeMethod(guiref, "handleURI", GUIUtil::blockingGUIThreadConnection(),
+ Q_ARG(QString, QString::fromStdString(strURI)));
+}
+
+static void InitMessage(const std::string &message)
+{
+ if(splashref)
+ {
+ splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(255,255,200));
+ QApplication::instance()->processEvents();
+ }
+}
+
+static void QueueShutdown()
+{
+ QMetaObject::invokeMethod(QCoreApplication::instance(), "quit", Qt::QueuedConnection);
+}
+
+/*
+ Translate string to current locale using Qt.
+ */
+static std::string Translate(const char* psz)
+{
+ return QCoreApplication::translate("bitcoin-core", psz).toStdString();
+}
+
+/* Handle runaway exceptions. Shows a message box with the problem and quits the program.
+ */
+static void handleRunawayException(std::exception *e)
+{
+ PrintExceptionContinue(e, "Runaway exception");
+ QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. EBT can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
+ exit(1);
+}
+
+#ifndef BITCOIN_QT_TEST
+int main(int argc, char *argv[])
+{
+ // Do this early as we don't want to bother initializing if we are just calling IPC
+ ipcScanRelay(argc, argv);
+
+ // Internal string conversion is all UTF-8
+ QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8"));
+ QTextCodec::setCodecForCStrings(QTextCodec::codecForTr());
+
+ Q_INIT_RESOURCE(bitcoin);
+ QApplication app(argc, argv);
+
+ // Install global event filter that makes sure that long tooltips can be word-wrapped
+ app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app));
+
+ // Command-line options take precedence:
+ ParseParameters(argc, argv);
+
+ // ... then bitcoin.conf:
+ if (!boost::filesystem::is_directory(GetDataDir(false)))
+ {
+ // This message can not be translated, as translation is not initialized yet
+ // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
+ QMessageBox::critical(0, "EBT",
+ QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
+ return 1;
+ }
+ ReadConfigFile(mapArgs, mapMultiArgs);
+
+ // Application identification (must be set before OptionsModel is initialized,
+ // as it is used to locate QSettings)
+ app.setOrganizationName("EBT");
+ app.setOrganizationDomain("EBT.su");
+ if(GetBoolArg("-testnet")) // Separate UI settings for testnet
+ app.setApplicationName("EBT-Qt-testnet");
+ else
+ app.setApplicationName("EBT-Qt");
+
+ // ... then GUI settings:
+ OptionsModel optionsModel;
+
+ // Get desired locale (e.g. "de_DE") from command line or use system locale
+ QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString()));
+ QString lang = lang_territory;
+ // Convert to "de" only by truncating "_DE"
+ lang.truncate(lang_territory.lastIndexOf('_'));
+
+ QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator;
+ // Load language files for configured locale:
+ // - First load the translator for the base language, without territory
+ // - Then load the more specific locale translator
+
+ // Load e.g. qt_de.qm
+ if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
+ app.installTranslator(&qtTranslatorBase);
+
+ // Load e.g. qt_de_DE.qm
+ if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
+ app.installTranslator(&qtTranslator);
+
+ // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc)
+ if (translatorBase.load(lang, ":/translations/"))
+ app.installTranslator(&translatorBase);
+
+ // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc)
+ if (translator.load(lang_territory, ":/translations/"))
+ app.installTranslator(&translator);
+
+ // Subscribe to global signals from core
+ uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox);
+ uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee);
+ uiInterface.ThreadSafeHandleURI.connect(ThreadSafeHandleURI);
+ uiInterface.InitMessage.connect(InitMessage);
+ uiInterface.QueueShutdown.connect(QueueShutdown);
+ uiInterface.Translate.connect(Translate);
+
+ // Show help message immediately after parsing command-line options (for "-lang") and setting locale,
+ // but before showing splash screen.
+ if (mapArgs.count("-?") || mapArgs.count("--help"))
+ {
+ GUIUtil::HelpMessageBox help;
+ help.showOrPrint();
+ return 1;
+ }
+
+ QSplashScreen splash(QPixmap(":/images/splash"), 0);
+ if (GetBoolArg("-splash", true) && !GetBoolArg("-min"))
+ {
+ splash.show();
+ splash.setAutoFillBackground(true);
+ splashref = &splash;
+ }
+
+ app.processEvents();
+
+ app.setQuitOnLastWindowClosed(false);
+
+ try
+ {
+ // Regenerate startup link, to fix links to old versions
+ if (GUIUtil::GetStartOnSystemStartup())
+ GUIUtil::SetStartOnSystemStartup(true);
+
+ BitcoinGUI window;
+ guiref = &window;
+ if(AppInit2())
+ {
+ {
+ // Put this in a block, so that the Model objects are cleaned up before
+ // calling Shutdown().
+
+ optionsModel.Upgrade(); // Must be done after AppInit2
+
+ if (splashref)
+ splash.finish(&window);
+
+ ClientModel clientModel(&optionsModel);
+ WalletModel walletModel(pwalletMain, &optionsModel);
+
+ window.setClientModel(&clientModel);
+ window.setWalletModel(&walletModel);
+
+ // If -min option passed, start window minimized.
+ if(GetBoolArg("-min"))
+ {
+ window.showMinimized();
+ }
+ else
+ {
+ window.show();
+ }
+
+ // Place this here as guiref has to be defined if we don't want to lose URIs
+ ipcInit(argc, argv);
+
+ app.exec();
+
+ window.hide();
+ window.setClientModel(0);
+ window.setWalletModel(0);
+ guiref = 0;
+ }
+ // Shutdown the core and its threads, but don't exit Bitcoin-Qt here
+ Shutdown(NULL);
+ }
+ else
+ {
+ return 1;
+ }
+ } catch (std::exception& e) {
+ handleRunawayException(&e);
+ } catch (...) {
+ handleRunawayException(NULL);
+ }
+ return 0;
+}
+#endif // BITCOIN_QT_TEST
diff --git a/pool/shard007/C++/0095170_rotatecamera.cpp b/pool/shard007/C++/0095170_rotatecamera.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..06d28dc363a7810f1d110798255afcbb4f3a7f3f
--- /dev/null
+++ b/pool/shard007/C++/0095170_rotatecamera.cpp
@@ -0,0 +1,118 @@
+
+#include "global.h"
+#include "rotatecamera.h"
+
+
+using namespace cv;
+
+
+cRotateCamera::cRotateCamera()
+{
+ SimpleBlobDetector::Params params;
+
+ // Change thresholds
+ params.minThreshold = 1;
+ params.maxThreshold = 20;
+
+ // Filter by Area.
+ params.filterByArea = true;
+ params.minArea = g_config.m_detectPointMinArea;
+ params.maxArea = g_config.m_detectPointMaxArea;
+
+ // Filter by Circularity
+ params.filterByCircularity = true;
+ params.minCircularity = 0.1f;
+
+ // Filter by Convexity
+ params.filterByConvexity = true;
+ params.minConvexity = 0.87f;
+
+ // Filter by Inertia
+ params.filterByInertia = true;
+ params.minInertiaRatio = 0.01f;
+
+
+ m_params = params;
+}
+
+cRotateCamera::~cRotateCamera()
+{
+
+}
+
+
+// Ä«¸Þ¶ó ȸÀüÀ» ÀνÄÇÑ´Ù.
+void cRotateCamera::DetectCameraRotate(cCamera &camera0, const vector &contours, const Mat &skewTransform)
+{
+ int thresholdValue = g_config.m_binaryThreshold; // ÀÓ°è°ª(Threshold) ¼³Á¤
+ int sensitive = g_config.m_rotateSensitivity;
+
+ cRectContours origContours(contours);
+ cRectContours target = origContours;
+ target.ScaleCenter(0.2f);
+
+
+ cvNamedWindow("HUV05-binarization", 0);
+ cvResizeWindow("HUV05-binarization", 640, 480);
+ cvMoveWindow("HUV05-binarization", -660, 520);
+ cvCreateTrackbar("Threshold", "HUV05-binarization", &thresholdValue, 255, NULL);
+ cvCreateTrackbar("Sensitivity", "HUV05-binarization", &sensitive, 300, NULL);
+
+ Mat src(camera0.Resolution().height, camera0.Resolution().width, CV_8UC(3));
+ while (1)
+ {
+ Mat &cam = camera0.ShowCaptureUndistortion(skewTransform, src);
+ if (cam.empty())
+ continue;
+
+ Mat grayscaleMat = src.clone();
+ cvtColor(src, grayscaleMat, CV_RGB2GRAY); // Ä÷¯¸¦ Èæ¹éÀ¸·Î º¯È¯
+
+ Mat binaryMat(grayscaleMat.size(), grayscaleMat.type());
+ cv::threshold(grayscaleMat, binaryMat, thresholdValue, 255, cv::THRESH_BINARY);
+
+
+ //----------------------------------------------------------------------------------------------
+ // À̹ÌÁö¿¡¼ Æ÷ÀÎÅ͸¦ ã´Â´Ù.
+ SimpleBlobDetector detector(m_params);
+
+ // Detect blobs.
+ std::vector keypoints;
+ detector.detect(binaryMat, keypoints);
+
+ // Draw detected blobs as red circles.
+ // DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures the size of the circle corresponds to the size of blob
+ Mat im_with_keypoints;
+ drawKeypoints(binaryMat, keypoints, im_with_keypoints, Scalar::all(-1), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
+
+ origContours.Draw(im_with_keypoints, Scalar(0, 255, 0), 2);
+ target.Draw(im_with_keypoints, Scalar(0, 0, 255), 2);
+
+ if (!keypoints.empty())
+ {
+ if (keypoints.size() == 4)
+ {
+ // 4°³ÀÇ Æ÷ÀÎÆ®¸¦ ¾ÈÁ¤ÀûÀ¸·Î ãÀ¸¸é, À§Ä¡¸¦ ÀúÀåÇϰí, Detect¸¦ Á¾·áÇÑ´Ù.
+ cRectContours detectRect(keypoints);
+ detectRect.Draw(im_with_keypoints, Scalar(0, 255, 255), 2);
+
+ // ¿øÁ¡¿¡¼ ¹þ¾î³ ±æÀ̸¦ Ãâ·ÂÇÑ´Ù.
+ vector centerLine;
+ centerLine.push_back(detectRect.Center());
+ centerLine.push_back(origContours.Center());
+ DrawLines(im_with_keypoints, centerLine, Scalar(255, 0, 0), 2);
+ //
+
+ Point offset = (origContours.Center() - detectRect.Center()) * (sensitive / 100.f);
+ target.Init(origContours.Center() + offset, 10.f);
+ }
+ }
+
+ imshow("HUV05-binarization", im_with_keypoints);
+
+ if (cvWaitKey(10) == VK_ESCAPE)
+ break;
+ }
+
+ cvDestroyWindow("HUV05-binarization");
+}
diff --git a/pool/shard007/C++/0095178_hotmetadata.cpp b/pool/shard007/C++/0095178_hotmetadata.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4cdb3f709a57fba04000a2c228284fea105fc25d
--- /dev/null
+++ b/pool/shard007/C++/0095178_hotmetadata.cpp
@@ -0,0 +1,86 @@
+//
+// Copyright (c) Microsoft. All rights reserved.
+// Licensed under the MIT license. See LICENSE file in the project root for full license information.
+//
+//
+// File: HotMetaData.cpp
+//
+
+//
+// Class code:MetaData::HotMetaData represents a reader of hot data in MetaData hot stream.
+//
+// ======================================================================================
+
+#include "external.h"
+
+#include "hotmetadata.h"
+#include "hotdataformat.h"
+#include "hotheapsdirectoryiterator.h"
+
+namespace MetaData
+{
+
+// --------------------------------------------------------------------------------------
+//
+// Class code:MetaData::HotMetaData represents a reader of hot data in MetaData hot stream.
+//
+__checkReturn
+HRESULT
+HotMetaData::Initialize(
+ DataBuffer data)
+{
+ m_Data = data;
+
+ return S_OK;
+} // HotMetaData::Initialize
+
+// --------------------------------------------------------------------------------------
+//
+// Returns iterator of stored hot heaps (code:HotHeap).
+//
+__checkReturn
+HRESULT
+HotMetaData::GetHeapsDirectoryIterator(
+ HotHeapsDirectoryIterator *pHeapsDirectoryIterator)
+{
+ if (m_Data.GetSize() < sizeof(struct HotMetaDataHeader))
+ {
+ Debug_ReportError("Invalid hot MetaData format - header doesn't fit into the hot data.");
+ return METADATA_E_INVALID_FORMAT;
+ }
+
+ struct HotMetaDataHeader *pHeader;
+ if (!m_Data.PeekDataAt(
+ m_Data.GetSize() - sizeof(struct HotMetaDataHeader),
+ &pHeader))
+ {
+ Debug_ReportInternalError("There's a bug, because previous size check succeeded.");
+ return METADATA_E_INTERNAL_ERROR;
+ }
+ // Get rid of the read header
+ DataBuffer heapsData = m_Data;
+ if (!heapsData.TruncateBySize(sizeof(struct HotMetaDataHeader)))
+ {
+ Debug_ReportInternalError("There's a bug, because previous size check succeeded.");
+ return METADATA_E_INTERNAL_ERROR;
+ }
+ DataBuffer heapsDirectoryData = heapsData;
+ if (!heapsDirectoryData.SkipToExactSize(pHeader->m_nHeapsDirectoryStart_NegativeOffset))
+ {
+ Debug_ReportError("Invalid hot MetaData format - heaps directory offset reaches in front of hot data.");
+ return METADATA_E_INVALID_FORMAT;
+ }
+ if (!heapsData.TruncateBySize(pHeader->m_nHeapsDirectoryStart_NegativeOffset))
+ {
+ Debug_ReportInternalError("There's a bug, because previous call to SkipToExactSize succeeded.");
+ return METADATA_E_INVALID_FORMAT;
+ }
+
+ pHeapsDirectoryIterator->Initialize(
+ heapsDirectoryData,
+ heapsData);
+
+ return S_OK;
+} // HotMetaData::GetHeapsDirectoryIterator
+
+}; // namespace MetaData
diff --git a/pool/shard007/C++/0095185_test_window_manager.cc b/pool/shard007/C++/0095185_test_window_manager.cc
new file mode 100644
index 0000000000000000000000000000000000000000..ef9cc1f41538bd47e83c9ecbac31483502ca804a
--- /dev/null
+++ b/pool/shard007/C++/0095185_test_window_manager.cc
@@ -0,0 +1,112 @@
+// Copyright 2014 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/ozone/platform/test/test_window_manager.h"
+
+#include "base/bind.h"
+#include "base/file_util.h"
+#include "base/location.h"
+#include "base/stl_util.h"
+#include "base/threading/worker_pool.h"
+#include "third_party/skia/include/core/SkCanvas.h"
+#include "third_party/skia/include/core/SkSurface.h"
+#include "ui/gfx/codec/png_codec.h"
+#include "ui/gfx/skia_util.h"
+#include "ui/gfx/vsync_provider.h"
+#include "ui/ozone/public/surface_ozone_canvas.h"
+
+namespace ui {
+
+namespace {
+
+void WriteDataToFile(const base::FilePath& location, const SkBitmap& bitmap) {
+ DCHECK(!location.empty());
+ std::vector png_data;
+ gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, true, &png_data);
+ base::WriteFile(location,
+ reinterpret_cast(vector_as_array(&png_data)),
+ png_data.size());
+}
+
+class FileSurface : public SurfaceOzoneCanvas {
+ public:
+ FileSurface(const base::FilePath& location) : location_(location) {}
+ virtual ~FileSurface() {}
+
+ // SurfaceOzoneCanvas overrides:
+ virtual void ResizeCanvas(const gfx::Size& viewport_size) OVERRIDE {
+ surface_ = skia::AdoptRef(SkSurface::NewRaster(SkImageInfo::MakeN32Premul(
+ viewport_size.width(), viewport_size.height())));
+ }
+ virtual skia::RefPtr GetCanvas() OVERRIDE {
+ return skia::SharePtr(surface_->getCanvas());
+ }
+ virtual void PresentCanvas(const gfx::Rect& damage) OVERRIDE {
+ if (location_.empty())
+ return;
+ SkBitmap bitmap;
+ bitmap.setInfo(surface_->getCanvas()->imageInfo());
+
+ // TODO(dnicoara) Use SkImage instead to potentially avoid a copy.
+ // See crbug.com/361605 for details.
+ if (surface_->getCanvas()->readPixels(&bitmap, 0, 0)) {
+ base::WorkerPool::PostTask(
+ FROM_HERE, base::Bind(&WriteDataToFile, location_, bitmap), true);
+ }
+ }
+ virtual scoped_ptr CreateVSyncProvider() OVERRIDE {
+ return scoped_ptr();
+ }
+
+ private:
+ base::FilePath location_;
+ skia::RefPtr surface_;
+};
+
+} // namespace
+
+TestWindowManager::TestWindowManager(const base::FilePath& dump_location)
+ : location_(dump_location) {
+}
+
+TestWindowManager::~TestWindowManager() {
+}
+
+void TestWindowManager::Initialize() {
+ if (location_.empty())
+ return;
+ if (!DirectoryExists(location_) && !base::CreateDirectory(location_) &&
+ location_ != base::FilePath("/dev/null"))
+ PLOG(FATAL) << "unable to create output directory";
+ if (!base::PathIsWritable(location_))
+ PLOG(FATAL) << "unable to write to output location";
+}
+
+int32_t TestWindowManager::AddWindow(TestWindow* window) {
+ return windows_.Add(window);
+}
+
+void TestWindowManager::RemoveWindow(int32_t window_id, TestWindow* window) {
+ DCHECK_EQ(window, windows_.Lookup(window_id));
+ windows_.Remove(window_id);
+}
+
+base::FilePath TestWindowManager::base_path() const {
+ return location_;
+}
+
+scoped_ptr TestWindowManager::CreateCanvasForWidget(
+ gfx::AcceleratedWidget widget) {
+ TestWindow* window = windows_.Lookup(widget);
+ DCHECK(window);
+ return make_scoped_ptr(new FileSurface(window->path()));
+}
+
+bool TestWindowManager::LoadEGLGLES2Bindings(
+ AddGLLibraryCallback add_gl_library,
+ SetGLGetProcAddressProcCallback set_gl_get_proc_address) {
+ return false;
+}
+
+} // namespace ui
diff --git a/pool/shard007/C++/0095186_TcrDistributionManager.cpp b/pool/shard007/C++/0095186_TcrDistributionManager.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2e5512dc0348cbad5fbbd9c0feb61eeb1fff4391
--- /dev/null
+++ b/pool/shard007/C++/0095186_TcrDistributionManager.cpp
@@ -0,0 +1,60 @@
+/*
+ * 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 "TcrDistributionManager.hpp"
+#include "ThinClientRegion.hpp"
+#include "TcrEndpoint.hpp"
+#include
+#include "Utils.hpp"
+using namespace apache::geode::client;
+
+TcrDistributionManager::TcrDistributionManager(
+ ThinClientRegion* region, TcrConnectionManager& connManager)
+ : ThinClientDistributionManager(connManager, region) {
+ GF_R_ASSERT(region != nullptr);
+ m_clientNotification =
+ region->getAttributes().getClientNotificationEnabled();
+}
+
+void TcrDistributionManager::getEndpointNames(
+ std::unordered_set& endpointNames) {
+ Utils::parseEndpointNamesString(m_region->getAttributes().getEndpoints(),
+ endpointNames);
+}
+
+void TcrDistributionManager::destroyAction() {
+ if (m_activeEndpoint >= 0) {
+ m_region->unregisterKeys();
+ }
+}
+
+void TcrDistributionManager::postUnregisterAction() {
+ if (m_clientNotification) {
+ m_region->localInvalidateFailover();
+ }
+}
+
+bool TcrDistributionManager::preFailoverAction() {
+ return !m_region->isDestroyed();
+}
+
+bool TcrDistributionManager::postFailoverAction(TcrEndpoint* endpoint) {
+ if (m_clientNotification) {
+ return (m_region->registerKeys(endpoint) == GF_NOERR);
+ }
+ return true;
+}
diff --git a/pool/shard007/C++/0095191_X3DShadersContext.cpp b/pool/shard007/C++/0095191_X3DShadersContext.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..5c04552a78b3cd203588eb32be9f4945dc9975d1
--- /dev/null
+++ b/pool/shard007/C++/0095191_X3DShadersContext.cpp
@@ -0,0 +1,230 @@
+/* -*- Mode: C++; coding: utf-8; tab-width: 3; indent-tabs-mode: tab; c-basic-offset: 3 -*-
+ *******************************************************************************
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright create3000, Scheffelstraße 31a, Leipzig, Germany 2011.
+ *
+ * All rights reserved. Holger Seelig .
+ *
+ * THIS IS UNPUBLISHED SOURCE CODE OF create3000.
+ *
+ * The copyright notice above does not evidence any actual of intended
+ * publication of such source code, and is an unpublished work by create3000.
+ * This material contains CONFIDENTIAL INFORMATION that is the property of
+ * create3000.
+ *
+ * No permission is granted to copy, distribute, or create derivative works from
+ * the contents of this software, in whole or in part, without the prior written
+ * permission of create3000.
+ *
+ * NON-MILITARY USE ONLY
+ *
+ * All create3000 software are effectively free software with a non-military use
+ * restriction. It is free. Well commented source is provided. You may reuse the
+ * source in any way you please with the exception anything that uses it must be
+ * marked to indicate is contains 'non-military use only' components.
+ *
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * Copyright 1999, 2016 Holger Seelig .
+ *
+ * This file is part of the Titania Project.
+ *
+ * Titania is free software: you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License version 3 only, as published by the
+ * Free Software Foundation.
+ *
+ * Titania 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 3 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 3
+ * along with Titania. If not, see for a
+ * copy of the GPLv3 License.
+ *
+ * For Silvio, Joy and Adi.
+ *
+ ******************************************************************************/
+
+#include "X3DShadersContext.h"
+
+#include "../../Browser/Core/BrowserOptions.h"
+#include "../../Browser/Networking/config.h"
+#include "../../Browser/Shaders/ShaderTest.h"
+#include "../../Browser/X3DBrowser.h"
+#include "../../Components/Networking/LoadSensor.h"
+#include "../../Components/Shaders/ComposedShader.h"
+#include "../../Components/Shaders/ShaderPart.h"
+#include "../../Rendering/OpenGL.h"
+
+#include
+
+namespace titania {
+namespace X3D {
+
+X3DShadersContext::X3DShadersContext () :
+ X3DBaseNode (),
+ shaders (true),
+ shadingLanguageVersion (),
+ maxVertexUniformVectors (0),
+ maxFragmentUniformVectors (0),
+ maxVertexAttributes (0),
+ pointShader (),
+ wireframeShader (),
+ gouraudShader (),
+ phongShader (),
+ defaultShader (),
+ shadowShader ()
+{
+ addChildObjects (shaders,
+ pointShader,
+ wireframeShader,
+ gouraudShader,
+ phongShader,
+ defaultShader,
+ shadowShader);
+}
+
+void
+X3DShadersContext::initialize ()
+{
+ if (getBrowser () -> getLoadUrlObjects ())
+ {
+ std::istringstream shadingLanguageVersionStream ((const char*) glGetString (GL_SHADING_LANGUAGE_VERSION));
+
+ shadingLanguageVersionStream .imbue (std::locale::classic ());
+
+ shadingLanguageVersionStream >> shadingLanguageVersion;
+
+ glGetIntegerv (GL_MAX_VERTEX_UNIFORM_VECTORS, &maxVertexUniformVectors);
+ glGetIntegerv (GL_MAX_FRAGMENT_UNIFORM_VECTORS, &maxFragmentUniformVectors);
+ glGetIntegerv (GL_MAX_VERTEX_ATTRIBS, &maxVertexAttributes);
+
+ // Shaders
+
+ if (getBrowser () -> getSharedContext ())
+ {
+ pointShader = getBrowser () -> getSharedContext () -> getPointShader ();
+ wireframeShader = getBrowser () -> getSharedContext () -> getWireframeShader ();
+ gouraudShader = getBrowser () -> getSharedContext () -> getGouraudShader ();
+ phongShader = getBrowser () -> getSharedContext () -> getPhongShader ();
+ shadowShader = getBrowser () -> getSharedContext () -> getShadowShader ();
+ }
+ else
+ {
+ pointShader = createShader (getExecutionContext (), "TitaniaPointSet", { get_shader ("Shaders/PointSet.vs") .str () }, { get_shader ("Shaders/PointSet.fs") .str () });
+ wireframeShader = createShader (getExecutionContext (), "TitaniaWireframe", { get_shader ("Shaders/Wireframe.vs") .str () }, { get_shader ("Shaders/Wireframe.fs") .str () });
+ gouraudShader = createShader (getExecutionContext (), "TitaniaGouraud", { get_shader ("Shaders/Gouraud.vs") .str () }, { get_shader ("Shaders/Gouraud.fs") .str () });
+ phongShader = createShader (getExecutionContext (), "TitaniaPhong", { get_shader ("Shaders/Phong.vs") .str () }, { get_shader ("Shaders/Phong.fs") .str () });
+ shadowShader = createShader (getExecutionContext (), "TitaniaShadow", { get_shader ("Shaders/Phong.vs") .str () }, { get_shader ("Shaders/Phong.fs") .str () }, true);
+
+ gouraudShader -> isValid () .addInterest (&X3DShadersContext::set_gouraud_shader_valid, this);
+ phongShader -> isValid () .addInterest (&X3DShadersContext::set_phong_shader_valid, this);
+ shadowShader -> isValid () .addInterest (&X3DShadersContext::set_shadow_shader_valid, this);
+ }
+
+ // Shading
+
+ getBrowser () -> getBrowserOptions () -> getShading () .addInterest (&X3DShadersContext::set_shading, this);
+
+ set_shading ();
+ }
+}
+
+X3DPtr
+X3DShadersContext::createShader (X3DExecutionContext* const executionContext,
+ const std::string & name,
+ const MFString & vertexUrl,
+ const MFString & fragmentUrl,
+ const bool shadow)
+{
+ const auto vertexPart = MakePtr (executionContext);
+ const auto fragmentPart = MakePtr (executionContext);
+ const auto shaderNode = MakePtr (executionContext);
+
+ fragmentPart -> setName (name + "FragmentShaderPart");
+ vertexPart -> setName (name + "VertexShaderPart");
+ shaderNode -> setName (name + "ComposedShader");
+
+ vertexPart -> setShadow (shadow);
+ fragmentPart -> setShadow (shadow);
+
+ fragmentPart -> type () = "FRAGMENT";
+ vertexPart -> url () = vertexUrl;
+ fragmentPart -> url () = fragmentUrl;
+
+ shaderNode -> setCustom (false);
+ shaderNode -> parts () .emplace_back (vertexPart);
+ shaderNode -> parts () .emplace_back (fragmentPart);
+
+ vertexPart -> setup ();
+ fragmentPart -> setup ();
+ shaderNode -> setup ();
+
+ return shaderNode;
+}
+
+void
+X3DShadersContext::set_gouraud_shader_valid ()
+{
+ gouraudShader -> isValid () .removeInterest (&X3DShadersContext::set_gouraud_shader_valid, this);
+
+ if (gouraudShader -> isValid () and ShaderTest::verify (getBrowser (), gouraudShader))
+ return;
+
+ getBrowser () -> getConsole () -> warn ("*** Warning: All else fails, using fallback VRML shader.\n\n");
+
+ gouraudShader -> parts () [0] -> setField ("url", MFString ({ get_shader ("Shaders/Fallback.vs") .str () }));
+ gouraudShader -> parts () [1] -> setField ("url", MFString ({ get_shader ("Shaders/Fallback.fs") .str () }));
+}
+
+void
+X3DShadersContext::set_phong_shader_valid ()
+{
+ phongShader -> isValid () .removeInterest (&X3DShadersContext::set_phong_shader_valid, this);
+
+ if (phongShader -> isValid () and ShaderTest::verify (getBrowser (), phongShader))
+ return;
+
+ getBrowser () -> getConsole () -> warn ("*** Warning: Phong shading not possible, using Gouraud shading.\n\n");
+
+ phongShader = gouraudShader;
+
+ set_shading ();
+}
+
+void
+X3DShadersContext::set_shadow_shader_valid ()
+{
+ shadowShader -> isValid () .removeInterest (&X3DShadersContext::set_shadow_shader_valid, this);
+
+ if (shadowShader -> isValid () and ShaderTest::verify (getBrowser (), shadowShader))
+ return;
+
+ getBrowser () -> getConsole () -> warn ("*** Warning: Shadow shading not possible, using Gouraud shading.\n\n");
+
+ shadowShader = gouraudShader;
+}
+
+void
+X3DShadersContext::set_shading ()
+{
+ const auto & shading = getBrowser () -> getBrowserOptions () -> getShading ();
+
+ if (shading == ShadingType::PHONG)
+ {
+ defaultShader = getPhongShader ();
+ }
+ else // GOURAUD
+ {
+ defaultShader = getGouraudShader ();
+ }
+}
+
+X3DShadersContext::~X3DShadersContext ()
+{ }
+
+} // X3D
+} // titania
diff --git a/pool/shard007/C++/0095194_arcball.cpp b/pool/shard007/C++/0095194_arcball.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1c8961ad86b697f006ae3b597964cddd5461588c
--- /dev/null
+++ b/pool/shard007/C++/0095194_arcball.cpp
@@ -0,0 +1,132 @@
+#include "vixen.h"
+#include "vxutil.h"
+#include "util/vxarcball.h"
+
+namespace Vixen {
+VX_IMPLEMENT_CLASSID(ArcBall, Engine, VX_ArcBall);
+
+ArcBall::ArcBall() : MouseEngine()
+{
+ m_Ball.Set(Vec3(0,0,0), 0);
+ m_Rotation.Set(Vec3(0,0,0), 1);
+ m_Button = MouseEvent::LEFT;
+ GetMessenger()->Observe(this, Event::MOUSE, NULL);
+}
+
+Vec3 ArcBall::WhereOnSphere(const Vec2& pos) const
+{
+ Vec3 ballMouse;
+ float mag;
+ Model* mod = (Model*) GetTarget();
+
+ ballMouse.x = -(pos.x - m_Ball.Center.x) / m_Ball.Radius;
+ ballMouse.y = (pos.y - m_Ball.Center.y) / m_Ball.Radius;
+ mag = ballMouse.x * ballMouse.x + ballMouse.y * ballMouse.y;
+ if (mag > 1)
+ {
+ float scale = float(1 / sqrt(mag));
+ ballMouse.x = ballMouse.x * scale;
+ ballMouse.y = ballMouse.y * scale;
+ ballMouse.z = 0;
+ }
+ else
+ ballMouse.z = sqrt(1.0f - mag);
+ return ballMouse;
+}
+
+Quat ArcBall::QuatFromPoints(const Vec3& from, const Vec3& to)
+{
+ Quat qu;
+ qu.x = from.y * to.z - from.z * to.y;
+ qu.y = from.z * to.x - from.x * to.z;
+ qu.z = from.x * to.y - from.y * to.x;
+ qu.w = from.x * to.x + from.y * to.y + from.z * to.z;
+ return qu;
+}
+
+void ArcBall::Initialize(const Vec2& pos)
+{
+ Model* model = (Model*) GetTarget();
+ Scene* scene = GetMainScene();
+ Sphere sphere;
+
+ if (model && model->IsClass(VX_Model))
+ {
+ if (model->IsClass(VX_Camera))
+ {
+ Vec3 p;
+ scene->GetModels()->GetBound(&sphere, Model::WORLD);
+ sphere.Radius = model->GetTranslation().Distance(sphere.Center);
+ }
+ else
+ model->GetBound(&sphere, Model::WORLD);
+ m_Ball.Center.Set(sphere.Center.x, sphere.Center.y, sphere.Center.z);
+ m_Rotation.Set(model->GetRotation());
+ m_Ball.Radius = sphere.Radius;
+ }
+ else
+ {
+ float w = scene->GetViewport().Width();
+ float h = scene->GetViewport().Height();
+ m_Ball.Center.Set(w / 2, h / 2, 0);
+ m_Rotation.Set(Vec3(0, 0, 0), 1);
+ m_Ball.Radius = (w > h) ? m_Ball.Center.x : m_Ball.Center.y;
+ }
+}
+
+void ArcBall::OnMouse(const Vec2& pos, uint32 flags)
+{
+ SharedObj* target = GetTarget();
+ int mouseflags = MouseFlags;
+ Vec2 oldpos = MousePos;
+
+ MouseEngine::OnMouse(pos, flags); // update position and flags
+ if (flags != m_Button) // not dragging now?
+ return;
+ if ((mouseflags & m_Button) == 0) // starting a drag?
+ {
+ Initialize(pos);
+ return;
+ }
+ Vec3 from = WhereOnSphere(oldpos); // where we were on the sphere last event
+ Vec3 to = WhereOnSphere(pos); // where we are on the sphere now
+ m_Rotation = QuatFromPoints(from, to); // relative rotation quat
+ if (target && target->IsClass(VX_Model))
+ {
+ Matrix mtx;
+ Model* mod = (Model*) target;
+ Vec3 t = mod->GetTranslation();
+
+ if (mod->IsClass(VX_Camera))
+ {
+ mod->Translate(m_Ball.Center);
+ mod->Rotate(m_Rotation);
+ mod->Translate(-m_Ball.Center);
+ }
+ else
+ {
+ mtx.TranslationMatrix(-m_Ball.Center);
+ mtx.Rotate(m_Rotation);
+ mtx.SetTranslation(t);
+ ((Model*) target)->SetTransform(&mtx);
+ }
+ }
+ if (IsSet(SharedObj::DOEVENTS))
+ LogEvent();
+}
+
+/*
+ * If we should be logging events, log the navigate event here
+ */
+void ArcBall::LogEvent()
+{
+ NavigateEvent* event = new NavigateEvent;
+
+ event->Sender = this;
+ event->Time = 0;
+ event->Flags = NavigateEvent::ROTATION | NavigateEvent::YROTATION | NavigateEvent::XROTATION | NavigateEvent::ZROTATION;
+ event->Rot = m_Rotation;
+ event->Log();
+}
+
+} // end Vixen
\ No newline at end of file
diff --git a/pool/shard007/C++/0095197_ChunkChecksum.cc b/pool/shard007/C++/0095197_ChunkChecksum.cc
new file mode 100644
index 0000000000000000000000000000000000000000..3a0817782f381591b4861f0badd9efd3481df007
--- /dev/null
+++ b/pool/shard007/C++/0095197_ChunkChecksum.cc
@@ -0,0 +1,88 @@
+/* */
+#include "ChunkChecksum.h"
+#include "A2STR.h"
+
+namespace aria2 {
+
+ChunkChecksum::ChunkChecksum():pieceLength_(0) {}
+
+ChunkChecksum::ChunkChecksum
+(std::string hashType,
+ std::vector pieceHashes,
+ int32_t pieceLength)
+ : hashType_(std::move(hashType)),
+ pieceHashes_(std::move(pieceHashes)),
+ pieceLength_(pieceLength)
+{}
+
+bool ChunkChecksum::validateChunk
+(const std::string& actualDigest,
+ size_t index) const
+{
+ const std::string& digest = getPieceHash(index);
+ return !digest.empty() && actualDigest == digest;
+}
+
+int64_t ChunkChecksum::getEstimatedDataLength() const
+{
+ return static_cast(pieceLength_)*pieceHashes_.size();
+}
+
+size_t ChunkChecksum::countPieceHash() const
+{
+ return pieceHashes_.size();
+}
+
+const std::string& ChunkChecksum::getPieceHash(size_t index) const
+{
+ if(index < pieceHashes_.size()) {
+ return pieceHashes_[index];
+ } else {
+ return A2STR::NIL;
+ }
+}
+
+void ChunkChecksum::setHashType(std::string hashType)
+{
+ hashType_ = std::move(hashType);
+}
+
+void ChunkChecksum::setPieceHashes(std::vector pieceHashes)
+{
+ pieceHashes_ = std::move(pieceHashes);
+}
+
+} // namespace aria2
diff --git a/pool/shard007/C++/0095209_Particle.cpp b/pool/shard007/C++/0095209_Particle.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1004dafa02c2a509bbd701028fc954c6293dc7fa
--- /dev/null
+++ b/pool/shard007/C++/0095209_Particle.cpp
@@ -0,0 +1,80 @@
+/*
+ * Particle.cpp
+ */
+
+#include "Particle.h"
+#include "map.h"
+#include "Robot.h"
+#include "Point.h"
+#include "config.h"
+
+Particle::Particle(Point p_pPoint,double p_dYaw,double p_dBel)
+ :_particleLocation(p_pPoint),
+ _particleYaw(p_dYaw),
+ _particleBelief(p_dBel)
+{
+}
+
+void Particle::update(Point p_dDeltaLocation, double p_dDeltaYaw)
+{
+ // Update The location according to delta
+ _particleLocation.x += p_dDeltaLocation.x;
+ _particleLocation.y += p_dDeltaLocation.y;
+ _particleYaw += p_dDeltaYaw;
+
+ // Robot path posterior
+ double probOfPath = this->getParticleProbability(p_dDeltaLocation, p_dDeltaYaw);
+
+ // Calculate new belief according to path, observations and previous belief
+ _particleBelief = SAFETY_FACTORY * _particleBelief * probOfPath ;//* ProbOfObs;
+
+ // Check to see if particle exceeded the maximum probability
+ if (_particleBelief > 1)
+ {
+ _particleBelief = 1;
+ }
+}
+
+// Calculates the probability that the movement is accurate
+double Particle::getParticleProbability(Point p_pLocation, double p_dDeltaYaw)
+{
+ // Distance Traveled
+ double distance = sqrt(pow(p_pLocation.x, 2) + pow(p_pLocation.y, 2));
+
+ // Kept moving forward
+ if ((p_dDeltaYaw == 0) && (distance < DISTANCE_LIMIT))
+ {
+ return 1;
+ }
+ else if ((distance < DISTANCE_LIMIT) && (p_dDeltaYaw < YAW_LIMIT))
+ {
+ return 0.8;
+ }
+ else if (((distance > DISTANCE_LIMIT) && (p_dDeltaYaw < YAW_LIMIT)) ||
+ ((distance < DISTANCE_LIMIT) && (p_dDeltaYaw > YAW_LIMIT)))
+ {
+ return 0.6;
+ }
+ else
+ {
+ return 0.2;
+ }
+}
+
+Particle* Particle::CreateParticle()
+{
+ double newX = _particleLocation.x + (rand() % 21) / 100;
+ double newY = _particleLocation.y + (rand() % 21) / 100;
+ double newYaw = _particleYaw + (rand() % 61 - 30.0) * PI / 180.0;
+ return new Particle(Point(newX, newY), newYaw, _particleBelief);//, new Map(*_particleMap));
+}
+
+
+double Particle::getBelief()
+{
+ return this->_particleBelief;
+}
+
+Particle::~Particle()
+{
+}
diff --git a/pool/shard007/C++/0095217_propagateremotemove.cpp b/pool/shard007/C++/0095217_propagateremotemove.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..8b9af4eb12a39824dcdf79a940ce5a545f3b7cdb
--- /dev/null
+++ b/pool/shard007/C++/0095217_propagateremotemove.cpp
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) by Olivier Goffart
+ *
+ * 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.
+ */
+
+#include "propagateremotemove.h"
+#include "owncloudpropagator_p.h"
+#include "account.h"
+#include "syncjournalfilerecord.h"
+#include "filesystem.h"
+#include
+#include
+
+namespace OCC {
+
+MoveJob::MoveJob(AccountPtr account, const QString& path,
+ const QString &destination, QObject* parent)
+ : AbstractNetworkJob(account, path, parent), _destination(destination)
+{ }
+
+
+void MoveJob::start()
+{
+ QNetworkRequest req;
+ req.setRawHeader("Destination", QUrl::toPercentEncoding(_destination, "/"));
+ setReply(davRequest("MOVE", path(), req));
+ setupConnections(reply());
+
+ if( reply()->error() != QNetworkReply::NoError ) {
+ qWarning() << Q_FUNC_INFO << " Network error: " << reply()->errorString();
+ }
+ AbstractNetworkJob::start();
+}
+
+
+QString MoveJob::errorString()
+{
+ if (_timedout) {
+ return tr("Connection timed out");
+ } else if (reply()->hasRawHeader("OC-ErrorString")) {
+ return reply()->rawHeader("OC-ErrorString");
+ } else {
+ return reply()->errorString();
+ }
+}
+
+bool MoveJob::finished()
+{
+ emit finishedSignal();
+ return true;
+}
+
+void PropagateRemoteMove::start()
+{
+ if (_propagator->_abortRequested.fetchAndAddRelaxed(0))
+ return;
+
+ qDebug() << Q_FUNC_INFO << _item->_file << _item->_renameTarget;
+
+ QString targetFile(_propagator->getFilePath(_item->_renameTarget));
+
+ if (_item->_file == _item->_renameTarget) {
+ // The parents has been renamed already so there is nothing more to do.
+ finalize();
+ return;
+ }
+ if (_item->_file == QLatin1String("Shared") ) {
+ // Before owncloud 7, there was no permissions system. At the time all the shared files were
+ // in a directory called "Shared" and were not supposed to be moved, otherwise bad things happens
+
+ QString versionString = _propagator->account()->serverVersion();
+ if (versionString.contains('.') && versionString.split('.')[0].toInt() < 7) {
+ QString originalFile(_propagator->getFilePath(QLatin1String("Shared")));
+ _propagator->addTouchedFile(originalFile);
+ _propagator->addTouchedFile(targetFile);
+ QString renameError;
+ if( FileSystem::rename(targetFile, originalFile, &renameError) ) {
+ done(SyncFileItem::NormalError, tr("This folder must not be renamed. It is renamed back to its original name."));
+ } else {
+ done(SyncFileItem::NormalError, tr("This folder must not be renamed. Please name it back to Shared."));
+ }
+ return;
+ }
+ }
+
+ _job = new MoveJob(_propagator->account(),
+ _propagator->_remoteFolder + _item->_file,
+ _propagator->_remoteDir + _item->_renameTarget,
+ this);
+ connect(_job, SIGNAL(finishedSignal()), this, SLOT(slotMoveJobFinished()));
+ _propagator->_activeJobs++;
+ _job->start();
+
+}
+
+void PropagateRemoteMove::abort()
+{
+ if (_job && _job->reply())
+ _job->reply()->abort();
+}
+
+void PropagateRemoteMove::slotMoveJobFinished()
+{
+ _propagator->_activeJobs--;
+
+ Q_ASSERT(_job);
+
+ qDebug() << Q_FUNC_INFO << _job->reply()->request().url() << "FINISHED WITH STATUS"
+ << _job->reply()->error()
+ << (_job->reply()->error() == QNetworkReply::NoError ? QLatin1String("") : _job->reply()->errorString());
+
+ QNetworkReply::NetworkError err = _job->reply()->error();
+ _item->_httpErrorCode = _job->reply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
+
+ if (err != QNetworkReply::NoError) {
+
+ if( checkForProblemsWithShared(_item->_httpErrorCode,
+ tr("The file was renamed but is part of a read only share. The original file was restored."))) {
+ return;
+ }
+
+ SyncFileItem::Status status = classifyError(err, _item->_httpErrorCode);
+ done(status, _job->errorString());
+ return;
+ }
+
+ _item->_requestDuration = _job->duration();
+ _item->_responseTimeStamp = _job->responseTimestamp();
+
+ if (_item->_httpErrorCode != 201 ) {
+ // Normaly we expect "201 Created"
+ // If it is not the case, it might be because of a proxy or gateway intercepting the request, so we must
+ // throw an error.
+ done(SyncFileItem::NormalError, tr("Wrong HTTP code returned by server. Expected 201, but received \"%1 %2\".")
+ .arg(_item->_httpErrorCode).arg(_job->reply()->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString()));
+ return;
+ }
+
+ finalize();
+
+}
+
+void PropagateRemoteMove::finalize()
+{
+ _propagator->_journal->deleteFileRecord(_item->_originalFile);
+ SyncJournalFileRecord record(*_item, _propagator->getFilePath(_item->_renameTarget));
+ record._path = _item->_renameTarget;
+
+ _propagator->_journal->setFileRecord(record);
+ _propagator->_journal->commit("Remote Rename");
+ done(SyncFileItem::Success);
+}
+
+
+}
+
diff --git a/pool/shard007/C++/0095224_TableViewPlugin.cpp b/pool/shard007/C++/0095224_TableViewPlugin.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ae569839e363c10b6a4296338d460f7a26fb69a6
--- /dev/null
+++ b/pool/shard007/C++/0095224_TableViewPlugin.cpp
@@ -0,0 +1,123 @@
+/*!
+ \file TableViewPlugin.cpp
+ \author Dane Gardner
+
+ \section LICENSE
+ This file is part of the Parallel Tools GUI Framework (PTGF)
+ Copyright (C) 2010-2013 Argo Navis Technologies, LLC
+
+ 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 "TableViewPlugin.h"
+
+#include
+#include
+
+#include "TableView.h"
+
+namespace Plugins {
+namespace TableView {
+
+/*! \namespace Plugins::TableView
+ \brief Contains the TableViewPlugin.
+ */
+
+/*! \class TableViewPlugin
+ \version 0.4.dev
+ \brief
+
+ \par Depends on Plugins:
+
+ \todo Document this more explicitly.
+ */
+
+TableViewPlugin::TableViewPlugin(QObject *parent) : QObject(parent)
+{
+ m_Name = "TableView";
+ m_Version = QString("%1.%2.%3").arg(VER_MAJ).arg(VER_MIN).arg(VER_PAT);
+}
+
+TableViewPlugin::~TableViewPlugin()
+{
+}
+
+bool TableViewPlugin::initialize(QStringList &args, QString *err)
+{
+ Q_UNUSED(args)
+ Q_UNUSED(err)
+
+ try {
+
+ Core::PluginManager::PluginManager &pluginManager = Core::PluginManager::PluginManager::instance();
+ pluginManager.addObject(this); /* Register ourselves as an IViewFactory */
+
+ } catch(...) {
+ return false;
+ }
+
+ return true;
+}
+
+void TableViewPlugin::shutdown()
+{
+}
+
+QString TableViewPlugin::name()
+{
+ return m_Name;
+}
+
+QString TableViewPlugin::version()
+{
+ return m_Version;
+}
+
+QList TableViewPlugin::dependencies()
+{
+ return m_Dependencies;
+}
+
+QString TableViewPlugin::viewName()
+{
+ return "Table View";
+}
+
+bool TableViewPlugin::viewHandles(QAbstractItemModel *model)
+{
+ Q_UNUSED(model)
+
+ /* We can handle pretty much anything, so there's no checking needed */
+ return true;
+}
+
+QAbstractItemView *TableViewPlugin::viewWidget(QAbstractItemModel *model)
+{
+ /* Check to see if we should even try to handle this model */
+ if(!viewHandles(model)) {
+ return NULL;
+ }
+
+ TableView *tableView = new TableView();
+ tableView->setModel(model);
+ return tableView;
+}
+
+} // namespace TableView
+} // namespace Plugins
+
+#if QT_VERSION < 0x050000
+Q_EXPORT_PLUGIN(Plugins::TableView::TableViewPlugin)
+#endif
diff --git a/pool/shard007/C++/0095225_tmwxPrintout.cpp b/pool/shard007/C++/0095225_tmwxPrintout.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..6ca4b2e0fdb86e3f60f7c706104ad26336a54c57
--- /dev/null
+++ b/pool/shard007/C++/0095225_tmwxPrintout.cpp
@@ -0,0 +1,89 @@
+/*******************************************************************************
+File: tmwxPrintout.cpp
+Project: TreeMaker 5.x
+Purpose: Source file for TreeMaker printout class
+Author: Robert J. Lang
+Modified by:
+Created: 2004-06-21
+Copyright: ©2004 Robert J. Lang. All Rights Reserved.
+*******************************************************************************/
+
+#include "tmwxPrintout.h"
+#include "tmwxView.h"
+#include "tmwxDesignCanvas.h"
+#include "tmwxFoldedFormFrame.h"
+#include "tmwxStr.h"
+#include "tmModel.h"
+
+/**********
+class tmwxPrintout
+**********/
+
+/*****
+Constructor
+*****/
+tmwxPrintout::tmwxPrintout(tmwxView* view, const wxString& title)
+ : wxDocPrintout(view, title), mDoc(view->GetDoc()), mView(view)
+{
+ TMASSERT(mView);
+ TMASSERT(mDoc);
+}
+
+
+/*****
+Called by the framework to obtain information about page range.
+*****/
+void tmwxPrintout::GetPageInfo(int* minPage, int* maxPage, int* selPageFrom,
+ int* selPageTo)
+{
+ *minPage = 1;
+ *maxPage = gFoldedFormFrame->CanPrint() ? 2 : 1;
+ *selPageFrom = 1;
+ *selPageTo = 1;
+}
+
+
+/*****
+Return true if the printout can provide the given page.
+*****/
+bool tmwxPrintout::HasPage(int pageNum)
+{
+ if (pageNum == 1) return true;
+ if (pageNum == 2 && gFoldedFormFrame->CanPrint()) return true;
+ return false;
+}
+
+
+/*****
+Print a single page of the document.
+*****/
+bool tmwxPrintout::OnPrintPage(int page)
+{
+ switch(page) {
+ case 1: {
+ // Draw the canvas image on the DC to create the printed image, letting
+ // the canvas know to tweak its presentation for printing and scale it to
+ // fit the DC.
+ tmwxDesignCanvas* canvas = mView->GetDesignCanvas();
+ wxDC* dc = GetDC();
+ canvas->SetPrinting(true);
+ canvas->OnDraw(*dc);
+ canvas->SetPrinting(false);
+ return true;
+ }
+ case 2: {
+ // Draw the folded form, if it exists; otherwise return false.
+ tmwxFoldedFormFrame* theFrame = gFoldedFormFrame;
+ if (theFrame->CanPrint()) {
+ wxDC* dc = GetDC();
+ theFrame->SetPrinting(true);
+ theFrame->OnDraw(*dc);
+ theFrame->SetPrinting(false);
+ return true;
+ }
+ return false;
+ }
+ default:
+ return false;
+ }
+}
diff --git a/pool/shard007/C++/0095227_wizardpage.cpp b/pool/shard007/C++/0095227_wizardpage.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..7acfd795e9706c13d636ed50a8cefd6ea31a5fb7
--- /dev/null
+++ b/pool/shard007/C++/0095227_wizardpage.cpp
@@ -0,0 +1,52 @@
+/*
+ * Cantata
+ *
+ * Copyright (c) 2011-2014 Craig Drummond
+ *
+ * ----
+ *
+ * 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; see the file COPYING. If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "wizardpage.h"
+#include "support/icon.h"
+#include "support/utils.h"
+#include
+#include
+
+void WizardPage::setBackground(const Icon &i)
+{
+ int size=fontMetrics().height()*10;
+ size=((int)(size/4))*4;
+ pix=i.pixmap(size, QIcon::Disabled);
+ if (pix.width()str = "";
+}
+
+String::String(char c) {
+
+ this->str = (char*)c;
+}
+
+String::String(const char* str) {
+ this->str = str;
+}
+
+String::String(String& s) {
+ this->str = s.toCharArray();
+}
+
+String::String(bool b) {
+ if (b == true) {
+ this->str = "true";
+ } else if (b == false) {
+ this->str = "false";
+ } else {
+ this->str = "NULL";
+ }
+}
+
+String::String(int n) {
+ this->str = itoa(n, 10);
+}
+
+int String::getLength() {
+ size_t len = 0;
+ while (this->str[len])
+ len++;
+ return len;
+}
+
+bool String::equals(const char* compare) {
+ String me(compare);
+
+
+ return (*this == me);
+}
+
+bool String::equals(String& s) {
+ return (*this == s);
+}
+
+
+const char* String::toCharArray() {
+ return this->str;
+}
+
+char String::operator[] (int j)
+{
+ if (j > this->getLength()) return 0;
+ return this->str[j];
+}
+
+
+bool String::operator== (String& lhs) {
+ if (lhs.getLength() != this->getLength()) return false;
+
+ unsigned cap = lhs.getLength();
+ unsigned int n = 0;
+ while ((n < cap) && (lhs.toCharArray()[n] == this->toCharArray()[n])) n++;
+ return (n == cap);
+}
+
+bool String::operator== (const char* str) {
+
+ String nigga(str);
+ return (*this == nigga);
+}
+
+String& String::operator+= (String& c) {
+
+ String ret;
+ int length = this->getLength();
+ int length2 = c.getLength();
+ int len = length+length2;
+ char str[len];
+
+ for (int j=0; j < length; j++)
+ str[j] = this->str[j];
+
+ for (int i=0; i < c.getLength(); i++)
+ str[length+i] = c[i];
+
+ length = len;
+ ret = str;
+ return ret;
+}
diff --git a/pool/shard007/C++/0095231_line_following.cpp b/pool/shard007/C++/0095231_line_following.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..097ee99f1f1e4bec49ed6a638524954381e1ae6f
--- /dev/null
+++ b/pool/shard007/C++/0095231_line_following.cpp
@@ -0,0 +1,206 @@
+#include "line_following.hh"
+
+//Follow line until junction reached
+void lf_until_junction(void)
+{
+ #ifdef __virtual__
+ cout << __PRETTY_FUNCTION__ << " was called\n";
+ delay(1000);
+ return;
+ #endif
+ char left_speed, right_speed;
+ while(1)//!(get_linesensors()==0b111))
+ {
+ get_linesensors();
+ switch(line_sensors[0])
+ {
+ case 0b000:
+ //All sensors off line
+ if(line_sensors[1]&0b100){
+ //cout << __func__ << ": Detected end of stub";
+ //set_motors(0, 0);
+ //return;
+ }
+ cout << __func__ << ": Lost line, calling lf_line_recovery()\n";
+ lf_line_recovery(ROT_SPEED);
+ break;
+
+ case 0b111: case 0b011:
+ //Both left and right high, must be at a junction
+ DEBUG("Junction detected");
+ //if((line_sensors[1]==0b111)&(line_sensors[0]==0b111))
+ return;
+ //delay(100);
+ break;
+
+ case 0b100:
+ //Only centre sensor high, everything is happy
+ left_speed = right_speed = SPEED;
+ break;
+ case 0b101: case 0b001:
+ //Left on line, right off - Boost right motor
+ left_speed=SPEED-CORRECTION;
+ right_speed=SPEED;
+ break;
+ case 0b110: case 0b010:
+ //Right on line, left off - Boost left motor
+ left_speed=SPEED;
+ right_speed=SPEED-CORRECTION;
+ break;
+ default:
+ cout << " lf_until_junction(): get_linesensors() returned something funny: " << line_sensors[0] << endl;
+ break;
+ }
+ set_motors(left_speed, right_speed);
+ }
+ set_motors(0, 0);
+ return;
+}
+
+//To be called only at a junction
+void lf_turn(turning turn)
+{
+ #ifdef __virtual__
+ cout << __PRETTY_FUNCTION__ << " was called with argument ";
+ print_turn(turn); cout << endl;
+ delay(1000);
+ return;
+ #endif
+
+ bool reverse = false;
+ unsigned int node = status.current_node;
+ directions dir = status.direction;
+ if((node==4)&&(dir==WEST))
+ reverse = true;
+ else if((node==11)&&(dir==SOUTH))
+ reverse = true;
+ else if((node==10)&&(dir==EAST))
+ reverse = true;
+ if((turn==FORWARD)|(turn==BACKWARD))
+ reverse=false;
+
+ if(reverse){
+ cout << "reverse to turn called\n";
+ reverse_to_line(turn);
+ return; //don't do another turn
+ }
+
+ switch(turn)
+ {
+ case LEFT:
+ DEBUG("Performing left turn");
+ unit_forwards();
+ set_motors(128+127, 127);
+ delay(800); //wait for the sensors to clear the line
+ set_motors(128+20, 20);
+ while(!(get_linesensors()&0b100)); //wait for the center sensor to hit the line
+ break;
+
+ case RIGHT:
+ DEBUG("Performing right turn");
+ unit_forwards();
+ set_motors(127, 128+127);
+ delay(800); //wait for the sensors to clear the line
+ set_motors(20, 128+20);
+ while(!(get_linesensors()&0b100)); //wait for the centre sensor to return to the line
+ break;
+
+ case FORWARD:
+ DEBUG("Going straight on");
+ set_motors(SPEED, SPEED);
+ delay(150); //just enough to advance past the junction
+ get_linesensors();
+ return;
+ break;
+
+ case BACKWARD:
+ DEBUG("Performing 180deg turn");
+ unit_forwards();
+ set_motors(127, 128+127);
+ delay(1800); //to find empirically - must go past a 90 deg line if there is one
+ set_motors(20, 128+20);
+ while(!(get_linesensors()&0b100));
+ break;
+
+ default:
+ cout << " lf_turn(): invalid turn asked for\n"; //Panic
+ //throw(INVALID_TURN);
+
+ }
+ set_motors(0,0);
+ return;
+}
+
+
+void lf_line_recovery(char rot_speed)
+{
+ #ifdef __virtual__
+ cout << __PRETTY_FUNCTION__ << " was called with argument " << int(rot_speed) << endl;
+ delay(1000);
+ return;
+ #endif
+//we've lost the line
+//rotate on the spot toward where the line last was
+ set_motors(0, 0);
+ DEBUG("Attempting to recover line");
+ if(line_sensors[1]&0b001) //Left sensor before leaving was high
+ set_motors(128+rot_speed, rot_speed);
+
+ else if(line_sensors[1]&0b010) //Right sensor before leaving was high
+ set_motors(rot_speed, 128+rot_speed);
+
+ else
+ {
+ cout << " lf_line_recovery(): line_recovery() was called at an odd time\n";
+ cout << " lf_line_recovery(): neither right nor left sensor was high last cycle\n";
+ cout << " lf_line_recovery(): line_sensors[] are: " << line_sensors[0] << " " << line_sensors[1] << endl;
+
+ //throw(WRONG_LINE_RECOVERY);
+ return;
+ }
+
+ while(!(get_linesensors()&0b100)); //wait for centre line sensor to be high
+
+ set_motors(0, 0);
+ cout << __func__ << ": Success\n";
+ return;
+}
+
+void unit_forwards(void)
+{
+ #ifdef __virtual__
+ cout << __PRETTY_FUNCTION__ << "was called\n";
+ delay(1000);
+ return;
+ #endif
+ DEBUG("Travelling a unit step forwards");
+ set_motors(60, 60);
+ delay(1400); //empirically found
+ set_motors(0, 0);
+ return;
+}
+//called in perform_action, taking a left/right turn to get onto line
+void reverse_to_line(turning turn)
+{
+ #ifdef __virtual__
+ cout << __PRETTY_FUNCTION__ << "was called with argument ";
+ print_turn(turn); cout << endl;
+ delay(1000);
+ return;
+ #endif
+ set_motors(128+50, 128+50);
+ delay(1000);
+ set_conveyor(0);
+ if(turn == RIGHT)
+ {
+ set_motors(60,128+60);
+ }
+ else
+ {
+ set_motors(128+60,60);
+ }
+ delay(1700);
+ set_motors(80, 80);
+ while(!(get_linesensors()&0b100));
+ set_motors(0,0);
+}
diff --git a/pool/shard007/C++/0095232_abstractliveedittool.cpp b/pool/shard007/C++/0095232_abstractliveedittool.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..741804274932dfeaebd796cbe9477457b27c702a
--- /dev/null
+++ b/pool/shard007/C++/0095232_abstractliveedittool.cpp
@@ -0,0 +1,185 @@
+/****************************************************************************
+**
+** Copyright (C) 2012 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 "abstractliveedittool.h"
+#include "qdeclarativeviewinspector.h"
+#include "../qdeclarativeviewinspector_p.h"
+
+#include
+
+#include
+#include
+#include
+
+namespace QmlJSDebugger {
+
+AbstractLiveEditTool::AbstractLiveEditTool(QDeclarativeViewInspector *editorView)
+ : QObject(editorView), m_inspector(editorView)
+{
+}
+
+
+AbstractLiveEditTool::~AbstractLiveEditTool()
+{
+}
+
+QDeclarativeViewInspector *AbstractLiveEditTool::inspector() const
+{
+ return m_inspector;
+}
+
+QDeclarativeView *AbstractLiveEditTool::view() const
+{
+ return m_inspector->declarativeView();
+}
+
+QGraphicsScene* AbstractLiveEditTool::scene() const
+{
+ return view()->scene();
+}
+
+void AbstractLiveEditTool::updateSelectedItems()
+{
+ selectedItemsChanged(items());
+}
+
+QList AbstractLiveEditTool::items() const
+{
+ return inspector()->selectedItems();
+}
+
+bool AbstractLiveEditTool::topItemIsMovable(const QList & itemList)
+{
+ QGraphicsItem *firstSelectableItem = topMovableGraphicsItem(itemList);
+ if (firstSelectableItem == 0)
+ return false;
+ if (toQDeclarativeItem(firstSelectableItem) != 0)
+ return true;
+
+ return false;
+
+}
+
+bool AbstractLiveEditTool::topSelectedItemIsMovable(const QList &itemList)
+{
+ QList selectedItems = inspector()->selectedItems();
+
+ foreach (QGraphicsItem *item, itemList) {
+ QDeclarativeItem *declarativeItem = toQDeclarativeItem(item);
+ if (declarativeItem
+ && selectedItems.contains(declarativeItem)
+ /*&& (declarativeItem->qmlItemNode().hasShowContent() || selectNonContentItems)*/)
+ return true;
+ }
+
+ return false;
+
+}
+
+bool AbstractLiveEditTool::topItemIsResizeHandle(const QList &/*itemList*/)
+{
+ return false;
+}
+
+QDeclarativeItem *AbstractLiveEditTool::toQDeclarativeItem(QGraphicsItem *item)
+{
+ return qobject_cast(item->toGraphicsObject());
+}
+
+QGraphicsItem *AbstractLiveEditTool::topMovableGraphicsItem(const QList &itemList)
+{
+ foreach (QGraphicsItem *item, itemList) {
+ if (item->flags().testFlag(QGraphicsItem::ItemIsMovable))
+ return item;
+ }
+ return 0;
+}
+
+QDeclarativeItem *AbstractLiveEditTool::topMovableDeclarativeItem(const QList
+ &itemList)
+{
+ foreach (QGraphicsItem *item, itemList) {
+ QDeclarativeItem *declarativeItem = toQDeclarativeItem(item);
+ if (declarativeItem /*&& (declarativeItem->qmlItemNode().hasShowContent())*/)
+ return declarativeItem;
+ }
+
+ return 0;
+}
+
+QList AbstractLiveEditTool::toGraphicsObjectList(const QList
+ &itemList)
+{
+ QList gfxObjects;
+ foreach (QGraphicsItem *item, itemList) {
+ QGraphicsObject *obj = item->toGraphicsObject();
+ if (obj)
+ gfxObjects << obj;
+ }
+
+ return gfxObjects;
+}
+
+QString AbstractLiveEditTool::titleForItem(QGraphicsItem *item)
+{
+ QString className("QGraphicsItem");
+ QString objectStringId;
+
+ QString constructedName;
+
+ QGraphicsObject *gfxObject = item->toGraphicsObject();
+ if (gfxObject) {
+ className = gfxObject->metaObject()->className();
+
+ className.remove(QRegExp("_QMLTYPE_\\d+"));
+ className.remove(QRegExp("_QML_\\d+"));
+ if (className.startsWith(QLatin1String("QDeclarative")))
+ className = className.remove(QLatin1String("QDeclarative"));
+
+ QDeclarativeItem *declarativeItem = qobject_cast(gfxObject);
+ if (declarativeItem) {
+ objectStringId = QDeclarativeViewInspector::idStringForObject(declarativeItem);
+ }
+
+ if (!objectStringId.isEmpty()) {
+ constructedName = objectStringId + " (" + className + QLatin1Char(')');
+ } else {
+ if (!gfxObject->objectName().isEmpty()) {
+ constructedName = gfxObject->objectName() + " (" + className + QLatin1Char(')');
+ } else {
+ constructedName = className;
+ }
+ }
+ }
+
+ return constructedName;
+}
+
+
+} // namespace QmlJSDebugger
diff --git a/pool/shard007/C++/0095235_Map.cpp b/pool/shard007/C++/0095235_Map.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..57766a4f9ebfe1ef4e787fcf5883665e22766f4c
--- /dev/null
+++ b/pool/shard007/C++/0095235_Map.cpp
@@ -0,0 +1,79 @@
+#include
+
+#include "graphic/Map.hpp"
+
+namespace graphic
+{
+
+Map::Map(const algo::Map& map) :
+ m_width(map.getWidth()),
+ m_height(map.getHeight()),
+ m_shapes(new sf::RectangleShape[m_width * m_height])
+{
+ this->initRectangles(map);
+ this->initCircles(map);
+}
+
+Map::~Map()
+{
+ delete[] m_shapes;
+}
+
+
+void
+Map::initRectangles(const algo::Map& map)
+{
+ unsigned int x, y;
+ sf::RectangleShape model;
+
+ model.setSize(sf::Vector2f(TILE_SIZE, TILE_SIZE));
+ model.setOutlineThickness(TILE_OUTLINE_THICKNESS);
+ model.setOutlineColor(TILE_OUTLINE_COLOR);
+
+ for (x = 0; x < m_width; x++)
+ {
+ for (y = 0; y < m_height; y++)
+ {
+ sf::RectangleShape& shape = m_shapes[y * m_width + x];
+ shape = model;
+ shape.setFillColor(map.at(x, y) == '0' ? WALL_COLOR : PATH_COLOR);
+ shape.setPosition(x * TILE_SIZE + TILE_OUTLINE_THICKNESS, y * TILE_SIZE + TILE_OUTLINE_THICKNESS);
+ }
+ }
+}
+
+
+void
+Map::initCircles(const algo::Map& map)
+{
+ sf::CircleShape model;
+
+ model.setRadius(POINT_RADIUS);
+ model.setOutlineThickness(POINT_OUTLINE_THICKNESS);
+ model.setOutlineColor(POINT_OUTLINE_COLOR);
+
+ m_begin = model;
+ m_begin.setFillColor(BEGIN_FILL_COLOR);
+ m_begin.move(map.getBegin().x * TILE_SIZE + POINT_SHIFT, map.getBegin().y * TILE_SIZE + POINT_SHIFT);
+
+ m_end = model;
+ m_end.setFillColor(END_FILL_COLOR);
+ m_end.move(map.getEnd().x * TILE_SIZE + POINT_SHIFT, map.getEnd().y * TILE_SIZE + POINT_SHIFT);
+}
+
+
+void
+Map::draw(sf::RenderTarget& target, sf::RenderStates states) const
+{
+ unsigned int i;
+
+ for (i = 0; i < m_width * m_height; i++)
+ {
+ target.draw(m_shapes[i], states);
+ }
+
+ target.draw(m_begin, states);
+ target.draw(m_end, states);
+}
+
+}
diff --git a/pool/shard007/C++/0095236_SysClass.cpp b/pool/shard007/C++/0095236_SysClass.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..23453c2607f3ed9fc14e0d258750c20744599b33
--- /dev/null
+++ b/pool/shard007/C++/0095236_SysClass.cpp
@@ -0,0 +1,200 @@
+/*
+This file is part of WME Lite.
+http://dead-code.org/redir.php?target=wmelite
+
+Copyright (c) 2011 Jan Nedoma
+
+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 "persistent.h"
+#include "SysInstance.h"
+#include "SysClass.h"
+#include "SysClassRegistry.h"
+#include "BGame.h"
+#include "BPersistMgr.h"
+
+namespace WinterMute {
+
+//////////////////////////////////////////////////////////////////////////
+CSysClass::CSysClass(const AnsiString &name, PERSISTBUILD build, PERSISTLOAD load, bool persistent_class) {
+ m_Name = name;
+
+ m_Build = build;
+ m_Load = load;
+ m_Next = NULL;
+ m_SavedID = -1;
+ m_Persistent = persistent_class;
+ m_NumInst = 0;
+
+ CSysClassRegistry::GetInstance()->RegisterClass(this);
+}
+
+
+//////////////////////////////////////////////////////////////////////////
+CSysClass::~CSysClass() {
+ CSysClassRegistry::GetInstance()->UnregisterClass(this);
+ RemoveAllInstances();
+}
+
+//////////////////////////////////////////////////////////////////////////
+bool CSysClass::RemoveAllInstances() {
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ delete(*it);
+ }
+ m_Instances.clear();
+ m_InstanceMap.clear();
+
+ return true;
+}
+
+//////////////////////////////////////////////////////////////////////////
+CSysInstance *CSysClass::AddInstance(void *instance, int id, int savedId) {
+ CSysInstance *inst = new CSysInstance(instance, id, this);
+ inst->SetSavedID(savedId);
+ m_Instances.insert(inst);
+
+ m_InstanceMap[instance] = inst;
+
+ CSysClassRegistry::GetInstance()->AddInstanceToTable(inst, instance);
+
+ return inst;
+}
+
+
+//////////////////////////////////////////////////////////////////////////
+bool CSysClass::RemoveInstance(void *instance) {
+ InstanceMap::iterator mapIt = m_InstanceMap.find(instance);
+ if (mapIt == m_InstanceMap.end()) return false;
+
+ Instances::iterator it = m_Instances.find((*mapIt).second);
+ if (it != m_Instances.end()) {
+ delete(*it);
+ m_Instances.erase(it);
+ }
+
+ m_InstanceMap.erase(mapIt);
+
+ return false;
+}
+
+//////////////////////////////////////////////////////////////////////////
+int CSysClass::GetInstanceID(void *pointer) {
+ InstanceMap::iterator mapIt = m_InstanceMap.find(pointer);
+ if (mapIt == m_InstanceMap.end()) return -1;
+ else return (*mapIt).second->GetID();
+}
+
+//////////////////////////////////////////////////////////////////////////
+void *CSysClass::IDToPointer(int savedID) {
+ //slow
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ if ((*it)->GetSavedID() == savedID) return (*it)->GetInstance();
+ }
+ return NULL;
+}
+
+//////////////////////////////////////////////////////////////////////////
+int CSysClass::GetNumInstances() {
+ return m_Instances.size();
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::Dump(FILE *stream) {
+ fprintf(stream, "%03d %c %-20s instances: %d\n", m_ID, m_Persistent ? 'p' : ' ', m_Name.c_str(), GetNumInstances());
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::SaveTable(CBGame *Game, CBPersistMgr *PersistMgr) {
+ PersistMgr->PutString(m_Name.c_str());
+ PersistMgr->PutDWORD(m_ID);
+ PersistMgr->PutDWORD(m_Instances.size());
+
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ PersistMgr->PutDWORD((*it)->GetID());
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::LoadTable(CBGame *Game, CBPersistMgr *PersistMgr) {
+ m_SavedID = PersistMgr->GetDWORD();
+ int numInstances = PersistMgr->GetDWORD();
+
+ for (int i = 0; i < numInstances; i++) {
+ if (m_Persistent) {
+ int instId = PersistMgr->GetDWORD();
+
+ if (i > 0) {
+ Game->LOG(0, "Warning: attempting to load multiple instances of persistent class %s (%d)", m_Name.c_str(), numInstances);
+ continue;
+ }
+
+ Instances::iterator it = m_Instances.begin();
+ if (it != m_Instances.end()) {
+ (*it)->SetSavedID(instId);
+ CSysClassRegistry::GetInstance()->AddInstanceToTable((*it), (*it)->GetInstance());
+ } else Game->LOG(0, "Warning: instance %d of persistent class %s not found", i, m_Name.c_str());
+ }
+ // normal instances, create empty objects
+ else {
+ void *emptyObject = m_Build();
+ AddInstance(emptyObject, CSysClassRegistry::GetInstance()->GetNextID(), PersistMgr->GetDWORD());
+ }
+
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::SaveInstances(CBGame *Game, CBPersistMgr *PersistMgr) {
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ // write instace header
+ PersistMgr->PutDWORD(m_ID);
+ PersistMgr->PutDWORD((*it)->GetID());
+
+ m_Load((*it)->GetInstance(), PersistMgr);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::LoadInstance(void *instance, CBPersistMgr *PersistMgr) {
+ m_Load(instance, PersistMgr);
+}
+
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::ResetSavedIDs() {
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ (*it)->SetSavedID(-1);
+ }
+}
+
+//////////////////////////////////////////////////////////////////////////
+void CSysClass::InstanceCallback(SYS_INSTANCE_CALLBACK lpCallback, void *lpData) {
+ Instances::iterator it;
+ for (it = m_Instances.begin(); it != m_Instances.end(); ++it) {
+ lpCallback((*it)->GetInstance(), lpData);
+ }
+}
+
+} // end of namespace WinterMute
diff --git a/pool/shard007/C++/0095238_background_application_loader.cc b/pool/shard007/C++/0095238_background_application_loader.cc
new file mode 100644
index 0000000000000000000000000000000000000000..d9a8533214cf6b6a1462076cb9e4f0dd438536db
--- /dev/null
+++ b/pool/shard007/C++/0095238_background_application_loader.cc
@@ -0,0 +1,74 @@
+// Copyright 2014 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 "mojo/runner/android/background_application_loader.h"
+
+#include
+
+#include "base/bind.h"
+#include "base/run_loop.h"
+#include "mojo/shell/application_manager.h"
+
+namespace mojo {
+namespace runner {
+
+BackgroundApplicationLoader::BackgroundApplicationLoader(
+ scoped_ptr real_loader,
+ const std::string& thread_name,
+ base::MessageLoop::Type message_loop_type)
+ : loader_(std::move(real_loader)),
+ message_loop_type_(message_loop_type),
+ thread_name_(thread_name),
+ message_loop_created_(true, false) {}
+
+BackgroundApplicationLoader::~BackgroundApplicationLoader() {
+ if (thread_)
+ thread_->Join();
+}
+
+void BackgroundApplicationLoader::Load(
+ const GURL& url,
+ InterfaceRequest application_request) {
+ DCHECK(application_request.is_pending());
+ if (!thread_) {
+ // TODO(tim): It'd be nice if we could just have each Load call
+ // result in a new thread like DynamicService{Loader, Runner}. But some
+ // loaders are creating multiple ApplicationImpls (NetworkApplicationLoader)
+ // sharing a delegate (etc). So we have to keep it single threaded, wait
+ // for the thread to initialize, and post to the TaskRunner for subsequent
+ // Load calls for now.
+ thread_.reset(new base::DelegateSimpleThread(this, thread_name_));
+ thread_->Start();
+ message_loop_created_.Wait();
+ DCHECK(task_runner_.get());
+ }
+
+ task_runner_->PostTask(
+ FROM_HERE,
+ base::Bind(&BackgroundApplicationLoader::LoadOnBackgroundThread,
+ base::Unretained(this), url,
+ base::Passed(&application_request)));
+}
+
+void BackgroundApplicationLoader::Run() {
+ base::MessageLoop message_loop(message_loop_type_);
+ base::RunLoop loop;
+ task_runner_ = message_loop.task_runner();
+ quit_closure_ = loop.QuitClosure();
+ message_loop_created_.Signal();
+ loop.Run();
+
+ // Destroy |loader_| on the thread it's actually used on.
+ loader_.reset();
+}
+
+void BackgroundApplicationLoader::LoadOnBackgroundThread(
+ const GURL& url,
+ InterfaceRequest application_request) {
+ DCHECK(task_runner_->RunsTasksOnCurrentThread());
+ loader_->Load(url, std::move(application_request));
+}
+
+} // namespace runner
+} // namespace mojo
diff --git a/pool/shard007/C++/0095240_main.cpp b/pool/shard007/C++/0095240_main.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..dadad5dbc16cf178719b2f63dd482cb6b01090af
--- /dev/null
+++ b/pool/shard007/C++/0095240_main.cpp
@@ -0,0 +1,105 @@
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include "MainWindow.h"
+#include "Session.h"
+#include "ContactBook.h"
+#include "Device.h"
+#include "ExampleDevice.h"
+#include "DeviceVcfFile.h"
+#include "Exceptions.h"
+
+
+
+
+
+/** Creates a new session and fills it with example data. */
+std::unique_ptr makeExampleSession()
+{
+ std::unique_ptr session(new Session);
+ session->addDevice(std::unique_ptr(new ExampleDevice));
+
+ // Test: add a device based on a VCF file
+ QJsonObject cfg;
+ cfg["type"] = QString::fromUtf8("VcfFile");
+ cfg["fileName"] = QString::fromUtf8("Contacts.vcf");
+ session->addDevice(Device::createFromConfig(cfg));
+
+ return session;
+}
+
+
+
+
+
+/** Loads the session, either from the current folder ("portable app") or from the user's home.
+If neither contain any reasonable data, creates an empty data file. */
+std::unique_ptr loadSession()
+{
+ // First try loading from the current folder ("portable app"):
+ auto session = Session::loadFromFile("ContactBookSanitizer.cbsSession");
+ if (session != nullptr)
+ {
+ return session;
+ }
+
+ // No current folder data, load from user's home:
+ auto homePath = QDir::homePath() + "/";
+ session = Session::loadFromFile(homePath + "ContactBookSanitizer.cbsSession");
+ if (session != nullptr)
+ {
+ return session;
+ }
+
+ // No data could be read, create a new example session file
+ qDebug() << "No session could be loaded. Creating a new session with example data.";
+ session = makeExampleSession();
+
+ // First try writing session to the current folder; if it fails, we're installed, if it succeeds, we're portable
+ try
+ {
+ session->saveToFile("ContactBookSanitizer.cbsSession");
+ qDebug() << "Detected a portable installation, session will be stored in current folder.";
+ return session;
+ }
+ catch (const EFileError & exc)
+ {
+ qDebug()
+ << "Failed to write the session file to current folder: " << exc.m_Message
+ << "; this usually means we're running in installed mode. Will retry the home path.";
+ }
+
+ // We're installed, save to local home:
+ try
+ {
+ session->saveToFile(homePath + "ContactBookSanitizer.cbsSession");
+ qDebug() << "Detected an installed environment, session will be stored in home path: " << homePath;
+ return session;
+ }
+ catch (const EFileError & exc)
+ {
+ QString msg("Failed to write the session file to both current folder and the home path: %1; session data will be lost after you close the app.");
+ msg.arg(exc.m_Message);
+ qWarning() << msg;
+ QMessageBox::warning(nullptr, QString::fromUtf8("ContactBookSanitizer"), msg);
+ }
+ return session;
+}
+
+
+
+
+
+int main(int argc, char *argv[])
+{
+ QApplication a(argc, argv);
+ MainWindow w(loadSession());
+ w.show();
+
+ return a.exec();
+}
diff --git a/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc b/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc
new file mode 100644
index 0000000000000000000000000000000000000000..49e9eb9c5051adea44f55b886653d0d1e932081f
--- /dev/null
+++ b/pool/shard007/C++/0095242_extension_uninstall_dialog_view.cc
@@ -0,0 +1,247 @@
+// 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 "base/basictypes.h"
+#include "base/compiler_specific.h"
+#include "base/string_util.h"
+#include "base/utf_string_conversions.h"
+#include "chrome/browser/extensions/extension_uninstall_dialog.h"
+#include "chrome/browser/profiles/profile.h"
+#include "chrome/browser/ui/browser_list.h"
+#include "chrome/browser/ui/browser_window.h"
+#include "chrome/common/extensions/extension.h"
+#include "grit/generated_resources.h"
+#include "ui/base/l10n/l10n_util.h"
+#include "ui/gfx/compositor/compositor.h"
+#include "ui/gfx/compositor/layer.h"
+#include "ui/views/controls/image_view.h"
+#include "ui/views/controls/label.h"
+#include "ui/views/layout/layout_constants.h"
+#include "ui/views/view.h"
+#include "ui/views/widget/widget.h"
+#include "ui/views/window/dialog_delegate.h"
+
+#if defined(USE_ASH)
+#include "ash/shell.h"
+#endif
+
+namespace {
+
+const int kRightColumnWidth = 210;
+const int kIconSize = 69;
+
+class ExtensionUninstallDialogDelegateView;
+
+// Returns parent window for extension uninstall dialog.
+// For ash, use app list window if it is visible.
+// For other platforms or when app list is not visible on ash,
+// use browser window of given |profile|.
+// Note this function could return NULL if ash app list is not visible and
+// there is no browser window open for |profile|.
+gfx::NativeWindow GetParent(Profile* profile) {
+#if defined(USE_ASH)
+ gfx::NativeWindow app_list = ash::Shell::GetInstance()->GetAppListWindow();
+ if (app_list)
+ return app_list;
+#endif
+
+ Browser* browser = BrowserList::GetLastActiveWithProfile(profile);
+ if (browser && browser->window())
+ return browser->window()->GetNativeHandle();
+
+ return NULL;
+}
+
+// Views implementation of the uninstall dialog.
+class ExtensionUninstallDialogViews : public ExtensionUninstallDialog {
+ public:
+ ExtensionUninstallDialogViews(Profile* profile,
+ ExtensionUninstallDialog::Delegate* delegate);
+ virtual ~ExtensionUninstallDialogViews();
+
+ // Forwards the accept and cancels to the delegate.
+ void ExtensionUninstallAccepted();
+ void ExtensionUninstallCanceled();
+
+ ExtensionUninstallDialogDelegateView* view() { return view_; }
+
+ private:
+ void Show() OVERRIDE;
+
+ ExtensionUninstallDialogDelegateView* view_;
+
+ DISALLOW_COPY_AND_ASSIGN(ExtensionUninstallDialogViews);
+};
+
+// The dialog's view, owned by the views framework.
+class ExtensionUninstallDialogDelegateView : public views::DialogDelegateView {
+ public:
+ ExtensionUninstallDialogDelegateView(
+ ExtensionUninstallDialogViews* dialog_view,
+ const Extension* extension,
+ SkBitmap* icon);
+ virtual ~ExtensionUninstallDialogDelegateView();
+
+ // Called when the ExtensionUninstallDialog has been destroyed to make sure
+ // we invalidate pointers.
+ void DialogDestroyed() { dialog_ = NULL; }
+
+ private:
+ // views::DialogDelegate:
+ virtual string16 GetDialogButtonLabel(ui::DialogButton button) const OVERRIDE;
+ virtual int GetDefaultDialogButton() const OVERRIDE {
+ return ui::DIALOG_BUTTON_CANCEL;
+ }
+ virtual bool Accept() OVERRIDE;
+ virtual bool Cancel() OVERRIDE;
+
+ // views::WidgetDelegate:
+ virtual ui::ModalType GetModalType() const OVERRIDE {
+ return ui::MODAL_TYPE_WINDOW;
+ }
+ virtual views::View* GetContentsView() OVERRIDE { return this; }
+ virtual string16 GetWindowTitle() const OVERRIDE;
+
+ // views::View:
+ virtual gfx::Size GetPreferredSize() OVERRIDE;
+
+ virtual void Layout() OVERRIDE;
+
+ ExtensionUninstallDialogViews* dialog_;
+
+ views::ImageView* icon_;
+ views::Label* heading_;
+
+ DISALLOW_COPY_AND_ASSIGN(ExtensionUninstallDialogDelegateView);
+};
+
+ExtensionUninstallDialogViews::ExtensionUninstallDialogViews(
+ Profile* profile, ExtensionUninstallDialog::Delegate* delegate)
+ : ExtensionUninstallDialog(profile, delegate),
+ view_(NULL) {
+}
+
+ExtensionUninstallDialogViews::~ExtensionUninstallDialogViews() {
+ // Close the widget (the views framework will delete view_).
+ if (view_) {
+ view_->DialogDestroyed();
+ view_->GetWidget()->CloseNow();
+ }
+}
+
+void ExtensionUninstallDialogViews::Show() {
+ gfx::NativeWindow parent = GetParent(profile_);
+ if (!parent) {
+ delegate_->ExtensionUninstallCanceled();
+ return;
+ }
+
+ view_ = new ExtensionUninstallDialogDelegateView(this, extension_, &icon_);
+ views::Widget::CreateWindowWithParent(view_, parent)->Show();
+}
+
+void ExtensionUninstallDialogViews::ExtensionUninstallAccepted() {
+ // The widget gets destroyed when the dialog is accepted.
+ view_ = NULL;
+ delegate_->ExtensionUninstallAccepted();
+}
+
+void ExtensionUninstallDialogViews::ExtensionUninstallCanceled() {
+ // The widget gets destroyed when the dialog is canceled.
+ view_ = NULL;
+ delegate_->ExtensionUninstallCanceled();
+}
+
+ExtensionUninstallDialogDelegateView::ExtensionUninstallDialogDelegateView(
+ ExtensionUninstallDialogViews* dialog_view,
+ const Extension* extension,
+ SkBitmap* icon)
+ : dialog_(dialog_view) {
+ // Scale down to icon size, but allow smaller icons (don't scale up).
+ gfx::Size size(icon->width(), icon->height());
+ if (size.width() > kIconSize || size.height() > kIconSize)
+ size = gfx::Size(kIconSize, kIconSize);
+ icon_ = new views::ImageView();
+ icon_->SetImageSize(size);
+ icon_->SetImage(*icon);
+ AddChildView(icon_);
+
+ heading_ = new views::Label(
+ l10n_util::GetStringFUTF16(IDS_EXTENSION_UNINSTALL_PROMPT_HEADING,
+ UTF8ToUTF16(extension->name())));
+ heading_->SetMultiLine(true);
+ AddChildView(heading_);
+}
+
+ExtensionUninstallDialogDelegateView::~ExtensionUninstallDialogDelegateView() {
+}
+
+string16 ExtensionUninstallDialogDelegateView::GetDialogButtonLabel(
+ ui::DialogButton button) const {
+ return l10n_util::GetStringUTF16((button == ui::DIALOG_BUTTON_OK) ?
+ IDS_EXTENSION_PROMPT_UNINSTALL_BUTTON : IDS_CANCEL);
+}
+
+bool ExtensionUninstallDialogDelegateView::Accept() {
+ if (dialog_)
+ dialog_->ExtensionUninstallAccepted();
+ return true;
+}
+
+bool ExtensionUninstallDialogDelegateView::Cancel() {
+ if (dialog_)
+ dialog_->ExtensionUninstallCanceled();
+ return true;
+}
+
+string16 ExtensionUninstallDialogDelegateView::GetWindowTitle() const {
+ return l10n_util::GetStringUTF16(IDS_EXTENSION_UNINSTALL_PROMPT_TITLE);
+}
+
+
+gfx::Size ExtensionUninstallDialogDelegateView::GetPreferredSize() {
+ int width = kRightColumnWidth;
+ width += kIconSize;
+ width += views::kPanelHorizMargin * 3;
+
+ int height = views::kPanelVertMargin * 2;
+ height += heading_->GetHeightForWidth(kRightColumnWidth);
+
+ return gfx::Size(width,
+ std::max(height, kIconSize + views::kPanelVertMargin * 2));
+}
+
+void ExtensionUninstallDialogDelegateView::Layout() {
+ int x = views::kPanelHorizMargin;
+ int y = views::kPanelVertMargin;
+
+ heading_->SizeToFit(kRightColumnWidth);
+
+ if (heading_->height() <= kIconSize) {
+ icon_->SetBounds(x, y, kIconSize, kIconSize);
+ x += kIconSize;
+ x += views::kPanelHorizMargin;
+
+ heading_->SetX(x);
+ heading_->SetY(y + (kIconSize - heading_->height()) / 2);
+ } else {
+ icon_->SetBounds(x,
+ y + (heading_->height() - kIconSize) / 2,
+ kIconSize,
+ kIconSize);
+ x += kIconSize;
+ x += views::kPanelHorizMargin;
+
+ heading_->SetX(x);
+ heading_->SetY(y);
+ }
+}
+
+} // namespace
+
+// static
+ExtensionUninstallDialog* ExtensionUninstallDialog::Create(
+ Profile* profile, Delegate* delegate) {
+ return new ExtensionUninstallDialogViews(profile, delegate);
+}
diff --git a/pool/shard007/C++/0095243_memory.cpp b/pool/shard007/C++/0095243_memory.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..971de3dce6cca6771d2cba400ef922eec2e6557d
--- /dev/null
+++ b/pool/shard007/C++/0095243_memory.cpp
@@ -0,0 +1,129 @@
+/* ----------------------------------------------------------------------
+ LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
+ http://lammps.sandia.gov, Sandia National Laboratories
+ Steve Plimpton, sjplimp@sandia.gov
+
+ Copyright (2003) Sandia Corporation. Under the terms of Contract
+ DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
+ certain rights in this software. This software is distributed under
+ the GNU General Public License.
+
+ See the README file in the top-level LAMMPS directory.
+------------------------------------------------------------------------- */
+
+#include
+#include
+#include
+#include "memory.h"
+#include "error.h"
+
+#if defined(LMP_USER_INTEL) && defined(__INTEL_COMPILER)
+#ifndef LMP_INTEL_NO_TBB
+#define LMP_USE_TBB_ALLOCATOR
+#include "tbb/scalable_allocator.h"
+#else
+#include
+#endif
+#endif
+
+#if defined(LMP_USER_INTEL) && !defined(LAMMPS_MEMALIGN)
+#define LAMMPS_MEMALIGN 64
+#endif
+
+using namespace LAMMPS_NS;
+
+/* ---------------------------------------------------------------------- */
+
+Memory::Memory(LAMMPS *lmp) : Pointers(lmp) {}
+
+/* ----------------------------------------------------------------------
+ safe malloc
+------------------------------------------------------------------------- */
+
+void *Memory::smalloc(bigint nbytes, const char *name)
+{
+ if (nbytes == 0) return NULL;
+
+#if defined(LAMMPS_MEMALIGN)
+ void *ptr;
+
+#if defined(LMP_USE_TBB_ALLOCATOR)
+ ptr = scalable_aligned_malloc(nbytes, LAMMPS_MEMALIGN);
+#else
+ int retval = posix_memalign(&ptr, LAMMPS_MEMALIGN, nbytes);
+ if (retval) ptr = NULL;
+#endif
+
+#else
+ void *ptr = malloc(nbytes);
+#endif
+ if (ptr == NULL) {
+ char str[128];
+ sprintf(str,"Failed to allocate " BIGINT_FORMAT " bytes for array %s",
+ nbytes,name);
+ error->one(FLERR,str);
+ }
+ return ptr;
+}
+
+/* ----------------------------------------------------------------------
+ safe realloc
+------------------------------------------------------------------------- */
+
+void *Memory::srealloc(void *ptr, bigint nbytes, const char *name)
+{
+ if (nbytes == 0) {
+ destroy(ptr);
+ return NULL;
+ }
+
+#if defined(LMP_USE_TBB_ALLOCATOR)
+ ptr = scalable_aligned_realloc(ptr, nbytes, LAMMPS_MEMALIGN);
+#elif defined(LMP_INTEL_NO_TBB) && defined(LAMMPS_MEMALIGN) && \
+ defined(__INTEL_COMPILER)
+
+ ptr = realloc(ptr, nbytes);
+ uintptr_t offset = ((uintptr_t)(const void *)(ptr)) % LAMMPS_MEMALIGN;
+ if (offset) {
+ void *optr = ptr;
+ ptr = smalloc(nbytes, name);
+ memcpy(ptr, optr, MIN(nbytes,malloc_usable_size(optr)));
+ free(optr);
+ }
+#else
+ ptr = realloc(ptr,nbytes);
+#endif
+ if (ptr == NULL) {
+ char str[128];
+ sprintf(str,"Failed to reallocate " BIGINT_FORMAT " bytes for array %s",
+ nbytes,name);
+ error->one(FLERR,str);
+ }
+ return ptr;
+}
+
+/* ----------------------------------------------------------------------
+ safe free
+------------------------------------------------------------------------- */
+
+void Memory::sfree(void *ptr)
+{
+ if (ptr == NULL) return;
+ #if defined(LMP_USE_TBB_ALLOCATOR)
+ scalable_aligned_free(ptr);
+ #else
+ free(ptr);
+ #endif
+}
+
+/* ----------------------------------------------------------------------
+ erroneous usage of templated create/grow functions
+------------------------------------------------------------------------- */
+
+void Memory::fail(const char *name)
+{
+ char str[128];
+ snprintf(str,128,
+ "Cannot create/grow a vector/array of pointers for %s",name);
+ error->one(FLERR,str);
+}
diff --git a/pool/shard007/C++/0095244_cmakeeditorfactory.cpp b/pool/shard007/C++/0095244_cmakeeditorfactory.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..19ce5aa245e566efe6ab2be372d1d2aa35d0a577
--- /dev/null
+++ b/pool/shard007/C++/0095244_cmakeeditorfactory.cpp
@@ -0,0 +1,78 @@
+/**************************************************************************
+**
+** This file is part of Qt Creator
+**
+** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
+**
+** Contact: Nokia Corporation (qt-info@nokia.com)
+**
+** 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.
+**
+** If you are unsure which license is appropriate for your use, please
+** contact the sales department at http://qt.nokia.com/contact.
+**
+**************************************************************************/
+
+#include "cmakeeditorfactory.h"
+#include "cmakeprojectconstants.h"
+#include "cmakeeditor.h"
+
+#include
+#include
+
+using namespace CMakeProjectManager;
+using namespace CMakeProjectManager::Internal;
+
+CMakeEditorFactory::CMakeEditorFactory(CMakeManager *manager, TextEditor::TextEditorActionHandler *handler)
+ : m_mimeTypes(QStringList() << QLatin1String(CMakeProjectManager::Constants::CMAKEMIMETYPE)),
+ m_manager(manager),
+ m_actionHandler(handler)
+{
+
+}
+
+CMakeEditorFactory::~CMakeEditorFactory()
+{
+}
+
+QString CMakeEditorFactory::id() const
+{
+ return QLatin1String(CMakeProjectManager::Constants::CMAKE_EDITOR_ID);
+}
+
+QString CMakeEditorFactory::displayName() const
+{
+ return tr(CMakeProjectManager::Constants::CMAKE_EDITOR_DISPLAY_NAME);
+}
+
+Core::IFile *CMakeEditorFactory::open(const QString &fileName)
+{
+ Core::IEditor *iface = Core::EditorManager::instance()->openEditor(fileName, id());
+ return iface ? iface->file() : 0;
+}
+
+Core::IEditor *CMakeEditorFactory::createEditor(QWidget *parent)
+{
+ CMakeEditor *rc = new CMakeEditor(parent, this, m_actionHandler);
+ TextEditor::TextEditorSettings::instance()->initializeEditor(rc);
+ return rc->editableInterface();
+}
+
+QStringList CMakeEditorFactory::mimeTypes() const
+{
+ return m_mimeTypes;
+}
diff --git a/pool/shard007/C++/0095245_bundle.cpp b/pool/shard007/C++/0095245_bundle.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..ce429b8765225592ff93a0ede8a83d925d26931e
--- /dev/null
+++ b/pool/shard007/C++/0095245_bundle.cpp
@@ -0,0 +1,141 @@
+/*
+ *** Pointer Bundle
+ *** src/model/bundle.cpp
+ Copyright T. Youngs 2007-2016
+
+ 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 "model/bundle.h"
+#include "model/model.h"
+#include "math/constants.h"
+#include
+
+ATEN_USING_NAMESPACE
+
+// Constructor
+Bundle::Bundle()
+{
+ clear();
+}
+
+Bundle::Bundle(Forcefield* ptr)
+{
+ clear();
+ ff = ptr;
+}
+
+Bundle::Bundle(Model* ptr)
+{
+ clear();
+ m = ptr;
+}
+
+Bundle::Bundle(Pattern* ptr)
+{
+ clear();
+ p = ptr;
+}
+
+Bundle::Bundle(Atom* ptr)
+{
+ clear();
+ i = ptr;
+}
+
+Bundle::Bundle(Grid* ptr)
+{
+ clear();
+ g = ptr;
+}
+
+Bundle::Bundle(Glyph* ptr)
+{
+ clear();
+ gl = ptr;
+}
+
+// Return reendersource for stored model
+Model* Bundle::rs()
+{
+ return (m == NULL ? NULL : m->renderSourceModel());
+}
+
+// Clear pointers
+void Bundle::clear()
+{
+ m = 0;
+ s = 0;
+ ff = 0;
+ g = 0;
+ i = 0;
+ p = 0;
+ gl = 0;
+}
+
+// Check for non-null pointers
+bool Bundle::isNull(int ptrs) const
+{
+ if ((ptrs&Bundle::AtomPointer) && (i == 0)) return true;
+ if ((ptrs&Bundle::PatternPointer) && (p == 0)) return true;
+ if ((ptrs&Bundle::ModelPointer) && (m == 0)) return true;
+ if ((ptrs&Bundle::GridPointer) && (g == 0)) return true;
+ if ((ptrs&Bundle::SitePointer) && (s == 0)) return true;
+ if ((ptrs&Bundle::ForcefieldPointer) && (ff == 0)) return true;
+ if ((ptrs&Bundle::GlyphPointer) && (gl == 0)) return true;
+ return false;
+}
+
+// Notify of non-null pointers
+bool Bundle::notifyNull(int ptrs) const
+{
+ if ((ptrs&Bundle::AtomPointer) && (i == 0))
+ {
+ printf("--> No active atom.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::PatternPointer) && (p == 0))
+ {
+ printf("--> No active pattern.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::ModelPointer) && (m == 0))
+ {
+ printf("--> No active model.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::GridPointer) && (g == 0))
+ {
+ printf("--> No active grid.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::SitePointer) && (s == 0))
+ {
+ printf("--> No active site.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::ForcefieldPointer) && (ff == 0))
+ {
+ printf("--> No active forcefield.\n");
+ return true;
+ }
+ if ((ptrs&Bundle::GlyphPointer) && (gl == 0))
+ {
+ printf("--> No active glyph.\n");
+ return true;
+ }
+ return false;
+}
diff --git a/pool/shard007/C++/0095246_AboutScreen.cpp b/pool/shard007/C++/0095246_AboutScreen.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..4185bb8f87a774208952a75086f40d64a927d16b
--- /dev/null
+++ b/pool/shard007/C++/0095246_AboutScreen.cpp
@@ -0,0 +1,75 @@
+#include
+#include // Core graphics library
+
+#include "AboutScreen.h"
+
+AboutScreen::AboutScreen(Adafruit_ILI9341* adafruitTft, ScreenUtils* sUtils, TimeUtils* tUtils, DateTimeCounter* counter) {
+ tft = adafruitTft;
+ screenUtils = sUtils;
+ timeUtils = tUtils;
+ dateTimeCounter = counter;
+}
+
+void AboutScreen::open(String versionNumber)
+{
+ tft->fillScreen(ILI9341_BLACK);
+
+ screenUtils->drawBatteryStateOfCharge(101);
+
+ tft->setTextWrap(false);
+ tft->setFont(&DroidSansMono8pt7b);
+
+ tft->setCursor(50, 30);
+ tft->setTextColor(ILI9341_GREEN, ILI9341_BLACK);
+ tft->println("www.diveino.hu");
+
+ screenUtils->drawBmpFile((char *)"Touch/logo.bmp", 50, 70);
+ screenUtils->drawButtonFrame(40, 60, 160, 160, 10, false);
+
+ tft->setTextColor(ILI9341_WHITE, ILI9341_BLACK);
+ tft->setCursor(10, 310);
+ tft->println(versionNumber);
+
+ dateTimeCounter->init(timeUtils->getCurrentTime());
+}
+
+int AboutScreen::handleTouch(Adafruit_FT6206* touchScreen)
+{
+ if (touchScreen->touched()) {
+ TS_Point touchPoint = touchScreen->getPoint();
+
+ // flip it around to match the screen.
+ touchPoint.x = map(touchPoint.x, 0, 240, 240, 0);
+ touchPoint.y = map(touchPoint.y, 0, 320, 320, 0);
+
+ if (50 < touchPoint.x && touchPoint.x < 50+140 &&
+ 70 < touchPoint.y && touchPoint.y < 70+140) {
+ drawButtonPress(BUTTON_HOME);
+ return GO_HOME;
+ }
+ delay(100);
+ }
+
+ return NO_ACTION;
+}
+
+void AboutScreen::drawButtonPress(int button) {
+ switch (button) {
+ case BUTTON_HOME:
+ screenUtils->drawButtonFrame(40, 60, 160, 160, 10, true);
+ break;
+ }
+
+ delay(100);
+
+ switch (button) {
+ case BUTTON_HOME:
+ screenUtils->drawButtonFrame(40, 60, 160, 160, 10, false);
+ break;
+ }
+}
+
+void AboutScreen::drawCurrentTime()
+{
+ dateTimeCounter->update(timeUtils->getCurrentTime());
+}
diff --git a/pool/shard007/C++/0095248_recursive_mutex_impl.cc b/pool/shard007/C++/0095248_recursive_mutex_impl.cc
new file mode 100644
index 0000000000000000000000000000000000000000..29c4c680787ccb2aee767c2f778de72825240780
--- /dev/null
+++ b/pool/shard007/C++/0095248_recursive_mutex_impl.cc
@@ -0,0 +1,245 @@
+/*
+ * Copyright (c) 2005, Eric Crahen
+ *
+ * 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 "debug.h"
+
+#include "recursive_mutex_impl.h"
+#include "thread_impl.h"
+
+#include "zthread/guard.h"
+
+#include
+#include
+#include
+
+namespace zthread {
+
+/**
+ * Create a new RecursiveMutexImpl
+ *
+ * @exception Initialization_Exception thrown if resources could not be
+ * properly allocated
+ */
+RecursiveMutexImpl::RecursiveMutexImpl() : _owner(0), _count(0) {}
+
+/**
+ * Destroy this RecursiveMutexImpl and release its resources
+ */
+RecursiveMutexImpl::~RecursiveMutexImpl() {
+#ifndef NDEBUG
+
+ // It is an error to destroy a mutex that has not been released
+ if (_owner != 0) {
+ ZTDEBUG("** You are destroying a mutex which was never released. **\n");
+ assert(0); // Destroyed mutex while in use
+ }
+
+ if (_waiters.size() > 0) {
+ ZTDEBUG("** You are destroying a mutex which is blocking %zd threads. **\n",
+ _waiters.size());
+ assert(0); // Destroyed mutex while in use
+ }
+
+#endif
+}
+
+void RecursiveMutexImpl::Acquire() {
+ // Get the monitor for the current thread
+ Monitor& m = ThreadImpl::current()->getMonitor();
+ Monitor::STATE state;
+
+ Guard g1(_lock);
+
+ // If there is an entry count and the current thread is
+ // the owner, increment the count and continue.
+ if (_owner == &m)
+ _count++;
+
+ else {
+ // Acquire the lock if it is free and there are no waiting threads
+ if (_owner == 0 && _waiters.empty()) {
+ assert(_count == 0);
+
+ _owner = &m;
+ _count++;
+
+ } else { // Otherwise, wait()
+
+ _waiters.push_back(&m);
+
+ m.Acquire();
+
+ {
+ Guard g2(g1);
+ state = m.wait();
+ }
+
+ m.Release();
+
+ // Remove from waiter list, regarless of weather release() is called or
+ // not. The monitor is sticky, so its possible a state 'stuck' from a
+ // previous operation and will leave the wait() w/o release() having
+ // been called.
+ List::iterator i = std::find(_waiters.begin(), _waiters.end(), &m);
+ if (i != _waiters.end()) _waiters.erase(i);
+
+ // If awoke due to a notify(), take ownership.
+ switch (state) {
+ case Monitor::SIGNALED:
+
+ assert(_owner == 0);
+ assert(_count == 0);
+
+ _owner = &m;
+ _count++;
+
+ break;
+
+ case Monitor::INTERRUPTED:
+ throw InterruptedException();
+
+ default:
+ throw SynchronizationException();
+ }
+ }
+ }
+}
+
+bool RecursiveMutexImpl::tryAcquire(unsigned long timeout) {
+ // Get the monitor for the current thread
+ Monitor& m = ThreadImpl::current()->getMonitor();
+
+ Guard g1(_lock);
+
+ // If there is an entry count and the current thread is
+ // the owner, increment the count and continue.
+ if (_owner == &m)
+ _count++;
+
+ else {
+ // Acquire the lock if it is free and there are no waiting threads
+ if (_owner == 0 && _waiters.empty()) {
+ assert(_count == 0);
+
+ _owner = &m;
+ _count++;
+
+ } else { // Otherwise, wait()
+
+ _waiters.push_back(&m);
+
+ Monitor::STATE state = Monitor::TIMEDOUT;
+
+ // Don't bother waiting if the timeout is 0
+ if (timeout) {
+ m.Acquire();
+
+ {
+ Guard g2(g1);
+ state = m.wait(timeout);
+ }
+
+ m.Release();
+ }
+
+ // Remove from waiter list, regarless of weather release() is called or
+ // not. The monitor is sticky, so its possible a state 'stuck' from a
+ // previous operation and will leave the wait() w/o release() having
+ // been called.
+ List::iterator i = std::find(_waiters.begin(), _waiters.end(), &m);
+ if (i != _waiters.end()) _waiters.erase(i);
+
+ // If awoke due to a notify(), take ownership.
+ switch (state) {
+ case Monitor::SIGNALED:
+
+ assert(_count == 0);
+ assert(_owner == 0);
+
+ _owner = &m;
+ _count++;
+
+ break;
+
+ case Monitor::INTERRUPTED:
+ throw InterruptedException();
+
+ case Monitor::TIMEDOUT:
+ return false;
+
+ default:
+ throw SynchronizationException();
+ }
+ }
+ }
+
+ return true;
+}
+
+void RecursiveMutexImpl::release() {
+ // Get the monitor for the current thread
+ Monitor& m = ThreadImpl::current()->getMonitor();
+
+ Guard g1(_lock);
+
+ // Make sure the operation is valid
+ if (!(_owner == &m)) throw InvalidOpException();
+
+ // Update the count, if it has reached 0, wake another waiter.
+ if (--_count == 0) {
+ _owner = 0;
+
+ // Try to find a waiter with a backoff & retry scheme
+ for (;;) {
+ // Go through the list, attempt to notify() a waiter.
+ for (List::iterator i = _waiters.begin(); i != _waiters.end();) {
+ // Try the monitor lock, if it cant be locked skip to the next waiter
+ Monitor* n = *i;
+ if (n->TryAcquire()) {
+ // If notify() is not sucessful, it is because the wait() has already
+ // been ended (killed/interrupted/notify'd)
+ bool woke = n->notify();
+ n->Release();
+
+ // Once notify() succeeds, return
+ if (woke) return;
+
+ } else
+ ++i;
+ }
+
+ if (_waiters.empty()) return;
+
+ { // Backoff and try again
+
+ Guard g2(g1);
+ ThreadImpl::yield();
+ }
+ }
+ }
+}
+
+} // namespace ZThread
diff --git a/pool/shard007/C++/0095254_cmd_reverse_frames.cpp b/pool/shard007/C++/0095254_cmd_reverse_frames.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..da468324f1b3de91b3b0d07549e543fdcf2e4552
--- /dev/null
+++ b/pool/shard007/C++/0095254_cmd_reverse_frames.cpp
@@ -0,0 +1,67 @@
+// Aseprite
+// Copyright (C) 2001-2015 David Capello
+//
+// 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.
+
+#ifdef HAVE_CONFIG_H
+#include "config.h"
+#endif
+
+#include "app/app.h"
+#include "app/commands/command.h"
+#include "app/context_access.h"
+#include "app/modules/gui.h"
+#include "app/ui/main_window.h"
+#include "app/ui/timeline.h"
+#include "app/document_range_ops.h"
+
+namespace app {
+
+class ReverseFramesCommand : public Command {
+public:
+ ReverseFramesCommand();
+ Command* clone() const override { return new ReverseFramesCommand(*this); }
+
+protected:
+ bool onEnabled(Context* context);
+ void onExecute(Context* context);
+};
+
+ReverseFramesCommand::ReverseFramesCommand()
+ : Command("ReverseFrames",
+ "Reverse Frames",
+ CmdUIOnlyFlag)
+{
+}
+
+bool ReverseFramesCommand::onEnabled(Context* context)
+{
+ DocumentRange range = App::instance()->getMainWindow()->getTimeline()->range();
+
+ return
+ context->checkFlags(ContextFlags::ActiveDocumentIsWritable) &&
+ range.enabled() &&
+ range.frames() >= 2; // We need at least 2 frames to reverse
+}
+
+void ReverseFramesCommand::onExecute(Context* context)
+{
+ DocumentRange range = App::instance()->getMainWindow()->getTimeline()->range();
+ if (!range.enabled())
+ return; // Nothing to do
+
+ Document* doc = context->activeDocument();
+
+ reverse_frames(doc, range);
+
+ update_screen_for_document(doc);
+}
+
+Command* CommandFactory::createReverseFramesCommand()
+{
+ return new ReverseFramesCommand;
+}
+
+} // namespace app
diff --git a/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp b/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..2f94909ea05104e44677cfa6fbdbd901ec0fb7f4
--- /dev/null
+++ b/pool/shard007/C++/0095257_OgreCgProgramManagerDll.cpp
@@ -0,0 +1,72 @@
+/*
+-----------------------------------------------------------------------------
+This source file is part of OGRE
+ (Object-oriented Graphics Rendering Engine)
+For the latest info, see http://www.ogre3d.org/
+
+Copyright (c) 2000-2012 Torus Knot Software Ltd
+
+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 "OgreStableHeaders.h"
+#include "OgreCgPlugin.h"
+#include "OgreCgProgram.h"
+#include "OgreRoot.h"
+
+namespace Ogre {
+
+ CgPlugin* cgPlugin;
+#ifndef OGRE_STATIC_LIB
+ //-----------------------------------------------------------------------
+ extern "C" void _OgreCgPluginExport dllStartPlugin(void)
+ {
+ // Create new plugin
+ cgPlugin = OGRE_NEW CgPlugin();
+
+ // Register
+ Root::getSingleton().installPlugin(cgPlugin);
+
+
+ }
+ extern "C" void _OgreCgPluginExport dllStopPlugin(void)
+ {
+ Root::getSingleton().uninstallPlugin(cgPlugin);
+ OGRE_DELETE cgPlugin;
+ }
+#endif
+
+ void checkForCgError(const String& ogreMethod, const String& errorTextPrefix, CGcontext context)
+ {
+ CGerror error = cgGetError();
+ if (error != CG_NO_ERROR)
+ {
+ String msg = errorTextPrefix + cgGetErrorString(error);
+
+ if (error == CG_COMPILER_ERROR)
+ {
+ // Get listing with full compile errors
+ msg = msg + "\n" + cgGetLastListing(context);
+ }
+ OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, msg, ogreMethod);
+ }
+ }
+
+}
diff --git a/pool/shard007/C++/0095259_animation-playlist.cpp b/pool/shard007/C++/0095259_animation-playlist.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..99a61ca9129360a9e0d5d7ab33e114c23181d1a2
--- /dev/null
+++ b/pool/shard007/C++/0095259_animation-playlist.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 2014 Samsung Electronics Co., Ltd.
+ *
+ * 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.
+ *
+ */
+
+// CLASS HEADER
+#include
+
+
+// INTERNAL INCLUDES
+#include
+#include
+#include
+
+
+namespace Dali
+{
+
+namespace Internal
+{
+
+AnimationPlaylist* AnimationPlaylist::New()
+{
+ return new AnimationPlaylist();
+}
+
+AnimationPlaylist::AnimationPlaylist()
+{
+}
+
+AnimationPlaylist::~AnimationPlaylist()
+{
+}
+
+void AnimationPlaylist::AnimationCreated( Animation& animation )
+{
+ mAnimations.PushBack( &animation );
+}
+
+void AnimationPlaylist::AnimationDestroyed( Animation& animation )
+{
+ Dali::Vector< Animation* >::Iterator iter = std::find( mAnimations.Begin(), mAnimations.End(), &animation );
+ DALI_ASSERT_ALWAYS( iter != mAnimations.End() && "Animation not found" );
+
+ mAnimations.Remove( iter );
+}
+
+void AnimationPlaylist::OnPlay( Animation& animation )
+{
+ mPlaylist.push_back( Dali::Animation(&animation) );
+}
+
+void AnimationPlaylist::OnClear( Animation& animation )
+{
+ std::vector< Dali::Animation >::iterator iter = std::find( mPlaylist.begin(), mPlaylist.end(), Dali::Animation(&animation) );
+ std::vector< Dali::Animation >::iterator last = mPlaylist.end();
+ if( iter != last )
+ {
+ --last; // move to real last
+ std::swap( *iter, *last ); // swap
+ mPlaylist.resize( mPlaylist.size() - 1u );
+ }
+}
+
+void AnimationPlaylist::NotifyCompleted()
+{
+ std::vector< Dali::Animation > finishedAnimations;
+
+ // Since animations can be unreferenced during the signal emissions, iterators into animationPointers may be invalidated.
+ // First copy and reference the finished animations, then emit signals
+ for ( Dali::Vector< Animation* >::Iterator iter = mAnimations.Begin(); iter != mAnimations.End(); ++iter )
+ {
+ Animation* animation = *iter;
+
+ if ( animation->HasFinished() )
+ {
+ finishedAnimations.push_back( Dali::Animation(animation) );
+
+ // The animation may be present in mPlaylist - remove if necessary
+ // Note that the animation "Finish" signal is emitted after Stop() has been called
+ std::vector< Dali::Animation >::iterator iter = std::find( mPlaylist.begin(), mPlaylist.end(), Dali::Animation(animation) );
+ DALI_ASSERT_DEBUG(iter != mPlaylist.end());
+ mPlaylist.erase( iter );
+ }
+ }
+
+ // Now it's safe to emit the signals
+ for ( std::vector< Dali::Animation >::iterator iter = finishedAnimations.begin(); iter != finishedAnimations.end(); ++iter )
+ {
+ Dali::Animation& handle = *iter;
+
+ GetImplementation(handle).EmitSignalFinish();
+ }
+}
+
+} // namespace Internal
+
+} // namespace Dali
diff --git a/pool/shard007/C++/0095261_Http.cpp b/pool/shard007/C++/0095261_Http.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..9b5c0a91ca6a2e2eae3ba0dceb94c36da666e7fd
--- /dev/null
+++ b/pool/shard007/C++/0095261_Http.cpp
@@ -0,0 +1,176 @@
+/*
+Copyright_License {
+
+ XCSoar Glide Computer - http://www.xcsoar.org/
+ Copyright (C) 2000-2021 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 "Http.hpp"
+#include "Assert.hxx"
+#include "Util.hxx"
+#include "Class.hxx"
+#include "Error.hxx"
+#include "net/http/Easy.hxx"
+#include "net/http/Adapter.hxx"
+#include "net/http/Handler.hxx"
+
+extern "C" {
+#include
+}
+
+#include