diff --git a/pool/shard009/C++/0106823_connection_test.cpp b/pool/shard009/C++/0106823_connection_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3124cd43198a85014d789d7757859df8fc7ab263 --- /dev/null +++ b/pool/shard009/C++/0106823_connection_test.cpp @@ -0,0 +1,80 @@ +#include + +#include "connection.h" +#include "test/fake.h" + +using ::testing::_; +using ::testing::ElementsAreArray; + + +namespace ygg { + + +class MockConnectionDelegate : public Connection::Delegate { +public: + MOCK_METHOD2(OnText, void(Connection*, const Text&)); + MOCK_METHOD2(OnBinary, void(Connection*, const Bytes&)); + MOCK_METHOD1(OnClosed, void(Connection*)); +}; + + +TEST(ConnectionTest, fire_text_event) { + + static const Text kText("second"); + static const Text kExpected(kText); + + Connection::Ptr conn(test::FakeConnection::New()); + + MockConnectionDelegate mock; + EXPECT_CALL(mock, OnText(conn.get(), kExpected)).Times(2); + + conn->FireOnTextEvent("first"); + + conn->BindDelegate(&mock); + conn->FireOnTextEvent(kText); + conn->FireOnTextEvent(kText); + conn->UnbindDelegate(); + + conn->FireOnTextEvent("third"); +} + +TEST(ConnectionTest, fire_binary_event) { + + static const uint8_t kData[10] = {0,1,2,3,4,5,6,7,8,9}; + static const Bytes kBuffer(kData, kData+10); + static const auto kExpected = ElementsAreArray(kData, 10); + + Connection::Ptr conn(test::FakeConnection::New()); + + MockConnectionDelegate mock; + EXPECT_CALL(mock, OnBinary(conn.get(), kExpected)).Times(2); + + conn->FireOnBinaryEvent(kBuffer); + + conn->BindDelegate(&mock); + conn->FireOnBinaryEvent(kBuffer); + conn->FireOnBinaryEvent(kBuffer); + conn->UnbindDelegate(); + + conn->FireOnBinaryEvent(kBuffer); +} + +TEST(ConnectionTest, fire_close_event) { + + Connection::Ptr conn(test::FakeConnection::New()); + + MockConnectionDelegate mock; + EXPECT_CALL(mock, OnClosed(conn.get())).Times(2); + + conn->FireOnClosedEvent(); + + conn->BindDelegate(&mock); + conn->FireOnClosedEvent(); + conn->FireOnClosedEvent(); + conn->UnbindDelegate(); + + conn->FireOnClosedEvent(); +} + + +} // namespace ygg diff --git a/pool/shard009/C++/0106824_text_format.cpp b/pool/shard009/C++/0106824_text_format.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c9a446dcf4614e3c649ab2bd394ac748f6074a4 --- /dev/null +++ b/pool/shard009/C++/0106824_text_format.cpp @@ -0,0 +1,84 @@ +#include "pch.h" +#include "angsys.h" +#include "format_parser.h" + +using namespace ang; +using namespace ang::text; + + +text_format::text_format_flags::text_format_flags() +{ + value = 0; +} + +text_format::text_format_flags::text_format_flags(qword val) +{ + value = val; +} + +text_format::text_format_flags::text_format_flags(ang::text::text_format::target t) +{ + value = 0; + target = t; + switch (t) + { + case bool_: + case_ = 3; + break; + case float_: + pres = 4; + break; + } +} + +text_format::text_format() +{ + flags.value = 0; +} + +text_format::text_format(castr_t format) +{ + flags.value = format_parser::parse(format); +} + +text_format::text_format(qword format) +{ + flags.value = format; +} + +text_format::text_format(const text_format& val) +{ + flags.value = val.flags.value; +} + +text_format::text_format(const text_format_flags& val) +{ + flags.value = val.value; +} + +text_format::~text_format() +{ + flags.value = 0; +} + +text_format::target text_format::format_target()const +{ + return flags.target; +} + +void text_format::format(castr_t format) +{ + flags.value = format_parser::parse(format); +} + +qword text_format::format_flags()const +{ + return flags.value; +} + +text_format& text_format::operator = (const text_format& val) +{ + flags.value = val.flags.value; + return*this; +} + diff --git a/pool/shard009/C++/0106825_datetimecalc.cpp b/pool/shard009/C++/0106825_datetimecalc.cpp new file mode 100644 index 0000000000000000000000000000000000000000..03cf03fbc93020d180a8e490e7206314c27fd2bf --- /dev/null +++ b/pool/shard009/C++/0106825_datetimecalc.cpp @@ -0,0 +1,267 @@ +/******************************************************************************* + * + * FILE NAME: datetimecalc.cpp + * + * DESCRIPTION: + * Code for time and data calculation class. + * This code was generated by qmake. + * + * AUTHOR: James P. Parziale + * + * DATE CREATED: 02/16/2009 + * + * This file may be distributed under the terms of the GNU Public License. + * + ******************************************************************************* + * HISTORY: + * 00 02/16/2009 + * Original version + ******************************************************************************/ + +#include "datetimecalc.h" +#include "about.h" + +#include +using namespace std; + +//****************************************************************************** + +DateTimeCalc::DateTimeCalc(QWidget *parent) : + QMainWindow(parent) +{ + ui.setupUi(this); + + // Set the base time and date fields to the current time and date. + ui.baseTimeEdit->setTime(QTime::currentTime()); + ui.baseDateEdit->setDate(QDate::currentDate()); + ui.resultDateEdit->setDate(QDate::currentDate()); + + ui.baseDateDiffEdit->setDate(QDate::currentDate()); + ui.targetDateDiffEdit->setDate(QDate::currentDate()); + + // Initialize operations + timeOp = GetTimeOp(); + dateOp = GetDateOp(); + + // Initialize time result + timeResult = QTime::currentTime(); + SetTimeResultText(); +} + +DateTimeCalc::~DateTimeCalc() +{ +} + +//****************************************************************************** + +void DateTimeCalc::on_aboutButton_clicked() +{ + About about_dialog(this); + about_dialog.exec(); +} + +void DateTimeCalc::on_actionAbout_triggered() +{ + About about_dialog(this); + about_dialog.exec(); +} + +//****************************************************************************** + +DateTimeCalc::TimeDateOp DateTimeCalc::GetTimeOp() +{ + TimeDateOp ret; + if (ui.timePlusRadioButton->isChecked()) { + ret = Add; + } else if (ui.timeMinusRadioButton->isChecked()) { + ret = Subtract; + } else { + ret = Invalid; + } + return ret; +} + +DateTimeCalc::TimeDateOp DateTimeCalc::GetDateOp() +{ + TimeDateOp ret; + if (ui.datePlusRadioButton->isChecked()) { + ret = Add; + } else if (ui.dateMinusRadioButton->isChecked()) { + ret = Subtract; + } else { + ret = Invalid; + } + return ret; +} + +void DateTimeCalc::SetTimeResultText() +{ + ui.resultTimeEdit->setText(timeResult.toString(Qt::TextDate)); +} + +//****************************************************************************** + +void DateTimeCalc::on_timeNowButton_clicked() +{ + ui.baseTimeEdit->setTime(QTime::currentTime()); +} + +void DateTimeCalc::on_timeOffsetNowButton_clicked() +{ + ui.offsetTimeEdit->setTime(QTime::currentTime()); +} + + +void DateTimeCalc::on_timePlusRadioButton_clicked() +{ + timeOp = Add; +} + +void DateTimeCalc::on_timeMinusRadioButton_clicked() +{ + timeOp = Subtract; +} + +//****************************************************************************** + +void DateTimeCalc::on_dateTodayButton_clicked() +{ + ui.baseDateEdit->setDate(QDate::currentDate()); +} + +void DateTimeCalc::on_datePlusRadioButton_clicked() +{ + dateOp = Add; +} + +void DateTimeCalc::on_dateMinusRadioButton_clicked() +{ + dateOp = Subtract; +} + +//****************************************************************************** + +void DateTimeCalc::on_dateRefTodayButton_clicked() +{ + ui.baseDateDiffEdit->setDate(QDate::currentDate()); +} + +void DateTimeCalc::on_dateTargetTodayButton_clicked() +{ + ui.targetDateDiffEdit->setDate(QDate::currentDate()); +} + +//****************************************************************************** + +void DateTimeCalc::on_timeCalcButton_clicked() +{ + QTime baseQTime = ui.baseTimeEdit->time(); + QTime result = baseQTime; + + QTime offsetQTime = ui.offsetTimeEdit->time(); + int offset = (offsetQTime.hour() * 3600) + + (offsetQTime.minute() * 60) + + offsetQTime.second(); + + switch (timeOp) { + case Add: + result = result.addSecs(offset); + break; + + case Subtract: + result = result.addSecs(-offset); + break; + + default: + printf("ERROR: Invalid time operation.\n"); + break; + } + + timeResult = result; + SetTimeResultText(); +} + +//****************************************************************************** + +void DateTimeCalc::on_dateCalcButton_clicked() +{ + QDate baseQDate = ui.baseDateEdit->date(); + QDate result = baseQDate; + + QString daysText = ui.daysEdit->text(); + QString weeksText = ui.weeksEdit->text(); + QString yearsText = ui.yearsEdit->text(); + + bool ok = true; + int days = daysText.toInt(&ok); + if (!ok) { + printf("ERROR: Invalid number for days.\n"); + } + int weeks = weeksText.toInt(&ok); + if (!ok) { + printf("ERROR: Invalid number for weeks.\n"); + } + int years = yearsText.toInt(&ok); + if (!ok) { + printf("ERROR: Invalid number for years.\n"); + } + + switch (dateOp) { + case Add: + result = result.addDays(days); + result = result.addDays(weeks*7); + result = result.addYears(years); + break; + + case Subtract: + result = result.addDays(-days); + result = result.addDays(-weeks*7); + result = result.addYears(-years); + break; + + default: + printf("ERROR: Invalid date operation.\n"); + break; + } + + ui.resultDateEdit->setDate(result); +} + +//****************************************************************************** + +void DateTimeCalc::on_dateDiffCalcButton_clicked() +{ + QDate baseQDate = ui.baseDateDiffEdit->date(); + QDate baseDate = baseQDate; + + QDate targetQDate = ui.targetDateDiffEdit->date(); + QDate targetDate = targetQDate; + + // Calculate difference in dates + long result = abs(targetDate.daysTo(baseDate)); + + QString resultText = QString("%1").arg(result) + " days;\n"; + + int y = result / 365; + int ld = y / 4; + int d = result - (y * 365) - ld; + int wks = d / 7; + int remDays = d % 7; + + if (remDays < 0) { + remDays += 7; + wks -= 1; + } + if (wks < 0) { + wks += 52; + y -= 1; + } + + resultText += " " + QString("%1").arg(y) + " years,\n" + + " " + QString("%1").arg(wks) + " weeks,\n" + + " " + QString("%1").arg(remDays) + " days"; + + ui.dateDiffResultEdit->setPlainText(resultText); +} + +//****************************************************************************** diff --git a/pool/shard009/C++/0106831_ink_base64.cc b/pool/shard009/C++/0106831_ink_base64.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa0f566926352565c23b6aadeeecbf1264df8f32 --- /dev/null +++ b/pool/shard009/C++/0106831_ink_base64.cc @@ -0,0 +1,163 @@ +/** @file + + A brief file description + + @section license License + + 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. + */ + +/* + * Base64 encoding and decoding as according to RFC1521. Similar to uudecode. + * + * RFC 1521 requires inserting line breaks for long lines. The basic web + * authentication scheme does not require them. This implementation is + * intended for web-related use, and line breaks are not implemented. + * + * These routines return char*'s to malloc-ed strings. The caller is + * responsible for freeing the strings. + */ +#include "ts/ink_platform.h" +#include "ts/ink_base64.h" +#include "ts/ink_assert.h" + +// TODO: The code here seems a bit klunky, and could probably be improved a bit. + +bool +ats_base64_encode(const unsigned char *inBuffer, size_t inBufferSize, char *outBuffer, size_t outBufSize, size_t *length) +{ + static const char _codes[66] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + char *obuf = outBuffer; + char in_tail[4]; + + if (outBufSize < ATS_BASE64_ENCODE_DSTLEN(inBufferSize)) + return false; + + while (inBufferSize > 2) { + *obuf++ = _codes[(inBuffer[0] >> 2) & 077]; + *obuf++ = _codes[((inBuffer[0] & 03) << 4) | ((inBuffer[1] >> 4) & 017)]; + *obuf++ = _codes[((inBuffer[1] & 017) << 2) | ((inBuffer[2] >> 6) & 017)]; + *obuf++ = _codes[inBuffer[2] & 077]; + + inBufferSize -= 3; + inBuffer += 3; + } + + /* + * We've done all the input groups of three chars. We're left + * with 0, 1, or 2 input chars. We have to add zero-bits to the + * right if we don't have enough input chars. + * If 0 chars left, we're done. + * If 1 char left, form 2 output chars, and add 2 pad chars to output. + * If 2 chars left, form 3 output chars, add 1 pad char to output. + */ + if (inBufferSize == 0) { + *obuf = '\0'; + if (length) + *length = (obuf - outBuffer); + } else { + memset(in_tail, 0, sizeof(in_tail)); + memcpy(in_tail, inBuffer, inBufferSize); + + *(obuf) = _codes[(in_tail[0] >> 2) & 077]; + *(obuf + 1) = _codes[((in_tail[0] & 03) << 4) | ((in_tail[1] >> 4) & 017)]; + *(obuf + 2) = _codes[((in_tail[1] & 017) << 2) | ((in_tail[2] >> 6) & 017)]; + *(obuf + 3) = _codes[in_tail[2] & 077]; + + if (inBufferSize == 1) + *(obuf + 2) = '='; + *(obuf + 3) = '='; + *(obuf + 4) = '\0'; + + if (length) + *length = (obuf + 4) - outBuffer; + } + + return true; +} + +bool +ats_base64_encode(const char *inBuffer, size_t inBufferSize, char *outBuffer, size_t outBufSize, size_t *length) +{ + return ats_base64_encode((const unsigned char *)inBuffer, inBufferSize, outBuffer, outBufSize, length); +} + +/*------------------------------------------------------------------------- + This is a reentrant, and malloc free implemetnation of ats_base64_decode. + -------------------------------------------------------------------------*/ +#ifdef DECODE +#undef DECODE +#endif + +#define DECODE(x) printableToSixBit[(unsigned char)x] +#define MAX_PRINT_VAL 63 + +/* Converts a printable character to it's six bit representation */ +const unsigned char printableToSixBit[256] = { + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 62, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, + 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 63, + 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64}; + +bool +ats_base64_decode(const char *inBuffer, size_t inBufferSize, unsigned char *outBuffer, size_t outBufSize, size_t *length) +{ + size_t inBytes = 0; + size_t decodedBytes = 0; + unsigned char *buf = outBuffer; + int inputBytesDecoded = 0; + + // Make sure there is sufficient space in the output buffer + if (outBufSize < ATS_BASE64_DECODE_DSTLEN(inBufferSize)) + return false; + + // Ignore any trailing ='s or other undecodable characters. + // TODO: Perhaps that ought to be an error instead? + while (printableToSixBit[(uint8_t)inBuffer[inBytes]] <= MAX_PRINT_VAL) + ++inBytes; + + for (size_t i = 0; i < inBytes; i += 4) { + buf[0] = (unsigned char)(DECODE(inBuffer[0]) << 2 | DECODE(inBuffer[1]) >> 4); + buf[1] = (unsigned char)(DECODE(inBuffer[1]) << 4 | DECODE(inBuffer[2]) >> 2); + buf[2] = (unsigned char)(DECODE(inBuffer[2]) << 6 | DECODE(inBuffer[3])); + + buf += 3; + inBuffer += 4; + decodedBytes += 3; + inputBytesDecoded += 4; + } + + // Check to see if we decoded a multiple of 4 four + // bytes + if ((inBytes - inputBytesDecoded) & 0x3) { + if (DECODE(inBuffer[-2]) > MAX_PRINT_VAL) { + decodedBytes -= 2; + } else { + decodedBytes -= 1; + } + } + outBuffer[decodedBytes] = '\0'; + + if (length) + *length = decodedBytes; + + return true; +} diff --git a/pool/shard009/C++/0106832_locfromfile.cc b/pool/shard009/C++/0106832_locfromfile.cc new file mode 100644 index 0000000000000000000000000000000000000000..75b3742c8ffa990a58bb149e4c02ab75fca9d34d --- /dev/null +++ b/pool/shard009/C++/0106832_locfromfile.cc @@ -0,0 +1,91 @@ +/* + * locfromfile.{cc,hh} -- play a trace of locations. + * Robert Morris + * + * Copyright (c) 1999-2000 Massachusetts Institute of Technology + * + * 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, subject to the conditions + * listed in the Click LICENSE file. These conditions include: you must + * preserve this copyright notice, and you cannot mention the copyright + * holders in advertising related to the Software without their permission. + * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This + * notice is a summary of the Click LICENSE file; the license in that file is + * legally binding. + */ + +#include +#include "locfromfile.hh" +#include +#include +#include +#include +CLICK_DECLS + +LocFromFile::LocFromFile() +{ + _next = 0; + _move = 1; +} + +LocFromFile::~LocFromFile() +{ +} + +void * +LocFromFile::cast(const char *name) +{ + if(strcmp(name, "GridLocationInfo") == 0) + return(this); + return(GridLocationInfo::cast(name)); +} + +int +LocFromFile::configure(Vector &conf, ErrorHandler *errh) +{ + String filename; + int res = cp_va_kparse(conf, this, errh, + "FILENAME", cpkP+cpkM, cpFilename, &filename, + cpEnd); + if(res >= 0){ + FILE *fp = fopen(filename.c_str(), "r"); + if(fp == 0) + return(errh->error("cannot open file %s", filename.c_str())); + char buf[512]; + while(fgets(buf, sizeof(buf), fp)){ + struct delta d; + if(sscanf(buf, "%lf%lf%lf", &d.interval, &d.lat, &d.lon) == 3){ + _deltas.push_back(d); + } else { + fclose(fp); + return(errh->error("cannot parse a line in file %s", filename.c_str())); + } + } + fclose(fp); + if(_deltas.size() < 1) + return(errh->error("no locations in file %s", filename.c_str())); + click_chatter("read %d deltas from %s", + _deltas.size(), + filename.c_str()); + } + return res; +} + +// Pick a new place to move to, and a time by which we want +// to arrive there. +void +LocFromFile::choose_new_leg(double *nlat, double *nlon, double *nt) +{ + *nlat = _deltas[_next].lat; + *nlon = _deltas[_next].lon; + *nt = _t0 + _deltas[_next].interval; + + _next += 1; + if(_next >= _deltas.size()) + _next = 0; +} + +CLICK_ENDDECLS +ELEMENT_REQUIRES(userlevel GridLocationInfo) +EXPORT_ELEMENT(LocFromFile) diff --git a/pool/shard009/C++/0106833_ShapeArray.cpp b/pool/shard009/C++/0106833_ShapeArray.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1f420f7f7d2945c4675bb68cba56f1d402e1703 --- /dev/null +++ b/pool/shard009/C++/0106833_ShapeArray.cpp @@ -0,0 +1,167 @@ +#include "stdafx.h" +#include "ShapeArray.h" +#include +#include "Util.h" + +using namespace std; + + +size_t hash_value(const struct shpmainheader& header) { + size_t seed = 0; + boost::hash_combine(seed, header.shapetype); + boost::hash_combine(seed, (float)header.xmin); + boost::hash_combine(seed, (float)header.ymin); + boost::hash_combine(seed, (float)header.ymax); + boost::hash_combine(seed, (float)header.zmin); + boost::hash_combine(seed, (float)header.zmax); + return seed; +} + +size_t hash_value(const struct point3d& point) { + size_t seed = 0; + boost::hash_combine(seed, (float)point.x); + boost::hash_combine(seed, (float)point.y); + boost::hash_combine(seed, (float)point.z); + return seed; +} + +size_t hash_value(const struct shpheader& header) { + size_t seed = 0; + boost::hash_combine(seed, (float)header.xmin); + boost::hash_combine(seed, (float)header.ymin); + boost::hash_combine(seed, (float)header.xmax); + boost::hash_combine(seed, (float)header.ymax); + boost::hash_combine(seed, (float)header.zmin); + boost::hash_combine(seed, (float)header.zmax); + boost::hash_combine(seed, header.numparts); + boost::hash_combine(seed, header.numpoints); + return seed; +} + +size_t hash_value(const VI_Shape& shape) { + size_t seed = 0; + boost::hash_combine(seed, shape.ShapeType); + boost::hash_combine(seed, shape.ShapeHeader); + boost::hash_range(seed, shape.Parts.begin(), shape.Parts.end()); + boost::hash_range(seed, shape.Vertices->begin(), shape.Vertices->end()); + return seed; +} + +VI_ShapeArray::VI_ShapeArray(shared_ptr> array, +struct shpmainheader header) +{ + i_array = array; + i_shpHeader = header; + i_hashCode = ComputeHashCode(); + i_numVertices = ComputeNumVertices(); + +} + +bool VI_ShapeArray::HasData() const { + return (bool)i_array; +} + +unsigned VI_ShapeArray::GetNumShapes() const { + return i_array->size(); +} + + +const VI_Shape& VI_ShapeArray::GetValue(unsigned index) const { + return i_array->at(index); +} + +VI_Shape& VI_ShapeArray::GetValue(unsigned index) { + return i_array->at(index); +} + +struct shpmainheader VI_ShapeArray::GetShpMainHeader() const { + return i_shpHeader; +} + +size_t VI_ShapeArray::ComputeHashCode() { + size_t seed = 0; + if (HasData()) { + boost::hash_range(seed, i_array->begin(), i_array->end()); + boost::hash_combine(seed, i_shpHeader); + } + return seed; +} + +size_t VI_ShapeArray::GetHashCode() const { + return i_hashCode; +} + +unsigned VI_ShapeArray::GetNumVertices() const { + return i_numVertices; +} + +unsigned VI_ShapeArray::ComputeNumVertices() { + unsigned total = 0; + if (HasData()) { + for (const auto& it : *i_array) { + total += it.ShapeHeader.numpoints; + } + } + return total; +} +VI_ShapeArray ImportFromSHPFile(const std::string& fileName) { + auto shapes = initVectorArray(); + auto shpHandle = SHPOpen(fileName.c_str(), "rb"); + int numShapes; + int type; + SHPGetInfo(shpHandle, &numShapes, &type, NULL, NULL); + + shared_ptr> shapeArray(new vector(numShapes)); + for (int i = 0; i < numShapes; i++) { + shared_ptr shpObject(SHPReadObject(shpHandle, i), [](SHPObject* obj) { + SHPDestroyObject(obj); + }); + shapeArray->at(i).ShapeHeader.numparts = shpObject->nParts; + shapeArray->at(i).ShapeHeader.numpoints = shpObject->nVertices; + shapeArray->at(i).ShapeHeader.xmax = shpObject->dfXMax; + shapeArray->at(i).ShapeHeader.ymax = shpObject->dfYMax; + shapeArray->at(i).ShapeHeader.zmax = shpObject->dfZMax; + shapeArray->at(i).ShapeHeader.xmin = shpObject->dfXMin; + shapeArray->at(i).ShapeHeader.ymin = shpObject->dfYMin; + shapeArray->at(i).ShapeHeader.zmin = shpObject->dfZMin; + shapeArray->at(i).ShapeType = type; + shapeArray->at(i).Parts.insert(shapeArray->at(i).Parts.begin(), + shpObject->panPartStart, shpObject->panPartStart + shpObject->nParts); + shared_ptr> pointArray(new vector(shpObject->nVertices)); + for (int j = 0; j < shpObject->nVertices; j++) { + pointArray->at(j).x = shpObject->padfX[j]; + pointArray->at(j).y = shpObject->padfY[j]; + pointArray->at(j).z = shpObject->padfZ[j]; + } + shapeArray->at(i).Vertices = pointArray; + } + + struct shpmainheader header; + header.filecode = -1; + header.filelength = -1; + header.mmax = -1; + header.mmin = -1; + header.pad = -1; + header.shapetype = type; + header.unused0 = -1; + header.unused1 = -1; + header.unused2 = -1; + header.unused3 = -1; + header.unused4 = -1; + header.version = -1; + double* MaxBuffer = new double[4]; + double* MinBuffer = new double[4]; + SHPGetInfo(shpHandle, NULL, NULL, MinBuffer, MaxBuffer); + header.xmin = MinBuffer[0]; + header.ymin = MinBuffer[1]; + header.zmin = MinBuffer[2]; + header.xmax = MaxBuffer[0]; + header.ymax = MaxBuffer[1]; + header.zmax = MaxBuffer[2]; + delete[] MaxBuffer; + delete[] MinBuffer; + + SHPClose(shpHandle); + + return VI_ShapeArray(shapeArray, header); +} diff --git a/pool/shard009/C++/0106836_pow.cpp b/pool/shard009/C++/0106836_pow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..83e4dea1ef26e6aaafeedf0554c042b7d5ac3c6a --- /dev/null +++ b/pool/shard009/C++/0106836_pow.cpp @@ -0,0 +1,126 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2015 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 "pow.h" + +#include "arith_uint256.h" +#include "chain.h" +#include "main.h" +#include "primitives/block.h" +#include "uint256.h" + +unsigned int static GetNextWorkRequired_legacy(const CBlockIndex* pindexLast, const Consensus::Params& params) +{ + unsigned int nRetarget = 30; + int64_t nPowTargetTimespan_legacy = params.nPowTargetSpacing * nRetarget; + int64_t nInterval = nPowTargetTimespan_legacy / params.nPowTargetSpacing; + + const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); + + // Genesis block + if (pindexLast == nullptr) + return bnPowLimit.GetCompact(); + + // Only change once per interval + if ((pindexLast->nHeight+1) % nInterval != 0) + { + // Special difficulty rule for testnet: + return pindexLast->nBits; + } + + // This fixes an issue where a 51% attack can change difficulty at will. + // Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz + int blockstogoback = nInterval-1; + if ((pindexLast->nHeight+1) != nInterval) + blockstogoback = nInterval; + + // Go back by what we want to be 14 days worth of blocks + const CBlockIndex* pindexFirst = pindexLast; + for (int i = 0; pindexFirst && i < blockstogoback; i++) + pindexFirst = pindexFirst->pprev; + assert(pindexFirst); + + if (params.fPowNoRetargeting) + return pindexLast->nBits; + + // Limit adjustment step + int64_t nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime(); + if (nActualTimespan < params.nPowTargetTimespan/4) + nActualTimespan = params.nPowTargetTimespan/4; + if (nActualTimespan > params.nPowTargetTimespan*4) + nActualTimespan = params.nPowTargetTimespan*4; + + // Retarget + arith_uint256 bnNew; + bnNew.SetCompact(pindexLast->nBits); + bnNew *= nActualTimespan; + bnNew /= params.nPowTargetTimespan; + + if (bnNew > bnPowLimit) + bnNew = bnPowLimit; + + return bnNew.GetCompact(); +} + + unsigned int GetNextWorkRequired_DGW(const CBlockIndex* pindexLast, bool fProofOfStake, const Consensus::Params& params) + { + const arith_uint256 bnPowLimit = UintToArith256(params.powLimit); + + if(pindexLast->nHeight < 200) + return bnPowLimit.GetCompact(); + + const CBlockIndex* pindexPrev = GetLastBlockIndex(pindexLast, fProofOfStake); + if (pindexPrev->pprev == nullptr) + return bnPowLimit.GetCompact(); // first block + + const CBlockIndex* pindexPrevPrev = GetLastBlockIndex(pindexPrev->pprev, fProofOfStake); + if (pindexPrevPrev->pprev == nullptr) + return bnPowLimit.GetCompact(); // second block + + if (params.fPowNoRetargeting) + return pindexLast->nBits; + + int64_t nActualSpacing = pindexPrev->GetBlockTime() - pindexPrevPrev->GetBlockTime(); + + if (nActualSpacing < 0) + nActualSpacing = params.nPowTargetSpacing; + + arith_uint256 bnNew; + bnNew.SetCompact(pindexPrev->nBits); + bnNew *= ((params.DifficultyAdjustmentInterval() - 1) * params.nPowTargetSpacing + nActualSpacing + nActualSpacing); + bnNew /= ((params.DifficultyAdjustmentInterval() + 1) * params.nPowTargetSpacing); + + if (bnNew <= 0 || bnNew > bnPowLimit) + bnNew = bnPowLimit; + + return bnNew.GetCompact(); +} + +unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, bool fProofOfStake, const Consensus::Params& params) +{ + if(pindexLast->nHeight < 200) + return GetNextWorkRequired_legacy(pindexLast, params); + + return GetNextWorkRequired_DGW(pindexLast, fProofOfStake, params); +} + +bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params) +{ + bool fNegative; + bool fOverflow; + arith_uint256 bnTarget; + + bnTarget.SetCompact(nBits, &fNegative, &fOverflow); + + // Check range + if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit)) + return false; + + // Check proof of work matches claimed amount + if (UintToArith256(hash) > bnTarget) + return false; + + return true; +} diff --git a/pool/shard009/C++/0106841_scripthandler.cpp b/pool/shard009/C++/0106841_scripthandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7622e31552e08564a97365be2e0f6bae6d857649 --- /dev/null +++ b/pool/shard009/C++/0106841_scripthandler.cpp @@ -0,0 +1,60 @@ +/* This file is part of Zanshin + + Copyright 2015 Theo Vaucher + + 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) version 3 or any later version + accepted by the membership of KDE e.V. (or its successor approved + by the membership of KDE e.V.), which shall act as a proxy + defined in Section 14 of version 3 of the license. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + USA. +*/ + + +#include "scripthandler.h" +#include "taskaction.h" + +#include +#include + +using namespace Scripting; + +ScriptHandler::ScriptHandler(const Domain::TaskRepository::Ptr &taskRepository) + : m_taskRepository(taskRepository), + m_engine(new QScriptEngine(this)) +{ + m_engine->globalObject().setProperty("task", m_engine->newQObject(new TaskAction(m_taskRepository))); +} + +QScriptValue ScriptHandler::evaluateFile(const QString &filename) +{ + QFile file(filename); + file.open(QIODevice::ReadOnly); + QByteArray filecontent = file.readAll(); + file.close(); + + return m_engine->evaluate(filecontent, filename); +} + +QScriptValue ScriptHandler::evaluateString(const QString &string) +{ + return m_engine->evaluate(string); +} + +QScriptEngine *ScriptHandler::engine() +{ + return m_engine; +} + +#include "scripthandler.moc" diff --git a/pool/shard009/C++/0106843_ImageRotationInvariant.cpp b/pool/shard009/C++/0106843_ImageRotationInvariant.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19a59270512231ac377d546466ccccafbcaea3e3 --- /dev/null +++ b/pool/shard009/C++/0106843_ImageRotationInvariant.cpp @@ -0,0 +1,60 @@ +/******************************************************************************* + * + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + ******************************************************************************/ +#include "ImageRotationInvariant.hpp" + +namespace impact_tr4 +{ + +void ImageRotationInvariant::calcIntegralInvariant( + const Vector2D degRange /*= Vector2D(1, 180)*/ ) +{ + GrayImage imageBinInv; + ImageFilter::threshold( *mpImage, imageBinInv ); + imageBinInv.invert(); + std::cout << imageBinInv << std::endl; + + GrayImage centeredImage; + Index centerOfMassIndex; + imageBinInv.computeCenterOfMassIndex(centerOfMassIndex, true); +// ImageMoments::centerOfMassIndex(src1, centerOfMassIndex, true); + std::cout << "center of mass index = " << std::endl; + std::cout << centerOfMassIndex << std::endl; + + const int border = std::max(mpImage->width()/2, mpImage->height()/2); + const uint8 extVal = 255; + ImageOperations::extendToCenter(imageBinInv, centeredImage, centerOfMassIndex, border, extVal); + + GrayImage rotImage = centeredImage; + GrayImage resImage = centeredImage; + + // for all angles in the range: + mResultVec.resize(degRange(1)-degRange(0)+1); + int c = 0; + for (int i = degRange(0); i<= degRange(1); ++i) { + ImageOperations::rotateAndScale( centeredImage, rotImage, centerOfMassIndex, i, 1, 255); + + ImageOperations::andOp(centeredImage, rotImage, resImage); + std::cout << resImage << std::endl; + + mResultVec[c] = resImage.countNonZero(); + ++c; + } // end for i + + return; +} // end calcIntegralInvariant + + +} // end of namespace impact_tr4 diff --git a/pool/shard009/C++/0106846_session_login_browsertest.cc b/pool/shard009/C++/0106846_session_login_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1f7ce6315cbc40b6e1c36fa5314536b5004939fa --- /dev/null +++ b/pool/shard009/C++/0106846_session_login_browsertest.cc @@ -0,0 +1,73 @@ +// 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 "base/command_line.h" +#include "chrome/browser/chromeos/login/login_manager_test.h" +#include "chrome/browser/chromeos/login/startup_utils.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/browser/ui/browser.h" +#include "chrome/browser/ui/browser_finder.h" +#include "chrome/browser/ui/browser_window.h" +#include "chrome/browser/ui/view_ids.h" +#include "chrome/common/chrome_switches.h" +#include "components/session_manager/core/session_manager.h" +#include "content/public/test/browser_test.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "ui/views/focus/focus_manager.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" + +namespace chromeos { + +namespace { + +constexpr char kTestUser[] = "test-user@gmail.com"; +constexpr char kTestUserGaiaId[] = "1234567890"; + +} // namespace + +class BrowserLoginTest : public chromeos::LoginManagerTest { + public: + BrowserLoginTest() : LoginManagerTest() { set_should_launch_browser(true); } + + ~BrowserLoginTest() override {} + + void SetUpCommandLine(base::CommandLine* command_line) override { + LoginManagerTest::SetUpCommandLine(command_line); + command_line->AppendSwitch(::switches::kCreateBrowserOnStartupForTests); + } +}; + +IN_PROC_BROWSER_TEST_F(BrowserLoginTest, PRE_BrowserActive) { + RegisterUser(AccountId::FromUserEmailGaiaId(kTestUser, kTestUserGaiaId)); + EXPECT_EQ(session_manager::SessionState::OOBE, + session_manager::SessionManager::Get()->session_state()); + chromeos::StartupUtils::MarkOobeCompleted(); +} + +IN_PROC_BROWSER_TEST_F(BrowserLoginTest, BrowserActive) { + base::HistogramTester histograms; + EXPECT_EQ(session_manager::SessionState::LOGIN_PRIMARY, + session_manager::SessionManager::Get()->session_state()); + LoginUser(AccountId::FromUserEmailGaiaId(kTestUser, kTestUserGaiaId)); + EXPECT_EQ(session_manager::SessionState::ACTIVE, + session_manager::SessionManager::Get()->session_state()); + histograms.ExpectTotalCount("OOBE.BootToSignInCompleted", 1); + + Browser* browser = + chrome::FindAnyBrowser(ProfileManager::GetActiveUserProfile(), false); + EXPECT_TRUE(browser != NULL); + EXPECT_TRUE(browser->window()->IsActive()); + + gfx::NativeWindow window = browser->window()->GetNativeWindow(); + views::Widget* widget = views::Widget::GetWidgetForNativeWindow(window); + views::FocusManager* focus_manager = widget->GetFocusManager(); + EXPECT_TRUE(focus_manager != NULL); + + const views::View* focused_view = focus_manager->GetFocusedView(); + EXPECT_TRUE(focused_view != NULL); + EXPECT_EQ(VIEW_ID_OMNIBOX, focused_view->GetID()); +} + +} // namespace chromeos diff --git a/pool/shard009/C++/0106848_moc_ExtendedTableWidget.cpp b/pool/shard009/C++/0106848_moc_ExtendedTableWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c326060111f335ede8193bf521b970b437f14b1 --- /dev/null +++ b/pool/shard009/C++/0106848_moc_ExtendedTableWidget.cpp @@ -0,0 +1,108 @@ +/**************************************************************************** +** Meta object code from reading C++ file 'ExtendedTableWidget.h' +** +** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.7) +** +** WARNING! All changes made in this file will be lost! +*****************************************************************************/ + +#include "../ExtendedTableWidget.h" +#if !defined(Q_MOC_OUTPUT_REVISION) +#error "The header file 'ExtendedTableWidget.h' doesn't include ." +#elif Q_MOC_OUTPUT_REVISION != 63 +#error "This file was generated using the moc from 4.8.7. It" +#error "cannot be used with the include files from this version of Qt." +#error "(The moc has changed too much.)" +#endif + +QT_BEGIN_MOC_NAMESPACE +static const uint qt_meta_data_ExtendedTableWidget[] = { + + // content: + 6, // revision + 0, // classname + 0, 0, // classinfo + 3, 14, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + 0, // flags + 1, // signalCount + + // signals: signature, parameters, type, tag, flags + 20, 66, 85, 85, 0x05, + + // slots: signature, parameters, type, tag, flags + 86, 109, 85, 85, 0x08, + 115, 140, 85, 85, 0x08, + + 0 // eod +}; + +static const char qt_meta_stringdata_ExtendedTableWidget[] = { + "ExtendedTableWidget\0" + "foreignKeyClicked(QString,QString,QByteArray)\0" + "table,column,value\0\0vscrollbarChanged(int)\0" + "value\0cellClicked(QModelIndex)\0index\0" +}; + +void ExtendedTableWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) +{ + if (_c == QMetaObject::InvokeMetaMethod) { + Q_ASSERT(staticMetaObject.cast(_o)); + ExtendedTableWidget *_t = static_cast(_o); + switch (_id) { + case 0: _t->foreignKeyClicked((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2])),(*reinterpret_cast< const QByteArray(*)>(_a[3]))); break; + case 1: _t->vscrollbarChanged((*reinterpret_cast< int(*)>(_a[1]))); break; + case 2: _t->cellClicked((*reinterpret_cast< const QModelIndex(*)>(_a[1]))); break; + default: ; + } + } +} + +const QMetaObjectExtraData ExtendedTableWidget::staticMetaObjectExtraData = { + 0, qt_static_metacall +}; + +const QMetaObject ExtendedTableWidget::staticMetaObject = { + { &QTableView::staticMetaObject, qt_meta_stringdata_ExtendedTableWidget, + qt_meta_data_ExtendedTableWidget, &staticMetaObjectExtraData } +}; + +#ifdef Q_NO_DATA_RELOCATION +const QMetaObject &ExtendedTableWidget::getStaticMetaObject() { return staticMetaObject; } +#endif //Q_NO_DATA_RELOCATION + +const QMetaObject *ExtendedTableWidget::metaObject() const +{ + return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; +} + +void *ExtendedTableWidget::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_ExtendedTableWidget)) + return static_cast(const_cast< ExtendedTableWidget*>(this)); + return QTableView::qt_metacast(_clname); +} + +int ExtendedTableWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QTableView::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + if (_id < 3) + qt_static_metacall(this, _c, _id, _a); + _id -= 3; + } + return _id; +} + +// SIGNAL 0 +void ExtendedTableWidget::foreignKeyClicked(const QString & _t1, const QString & _t2, const QByteArray & _t3) +{ + void *_a[] = { 0, const_cast(reinterpret_cast(&_t1)), const_cast(reinterpret_cast(&_t2)), const_cast(reinterpret_cast(&_t3)) }; + QMetaObject::activate(this, &staticMetaObject, 0, _a); +} +QT_END_MOC_NAMESPACE diff --git a/pool/shard009/C++/0106854_the_eye.cpp b/pool/shard009/C++/0106854_the_eye.cpp new file mode 100644 index 0000000000000000000000000000000000000000..feabaf8e701b16fe2026f732923f24da8e5a0de2 --- /dev/null +++ b/pool/shard009/C++/0106854_the_eye.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * Copyright (C) 2006-2009 ScriptDev2 + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +/* ScriptData +SDName: The_Eye +SD%Complete: 100 +SDComment: +SDCategory: Tempest Keep, The Eye +EndScriptData */ + +/* ContentData +npc_crystalcore_devastator +EndContentData */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "the_eye.h" + +enum Spells +{ + SPELL_COUNTERCHARGE = 35035, + SPELL_KNOCKAWAY = 22893, +}; + +class npc_crystalcore_devastator : public CreatureScript +{ + public: + + npc_crystalcore_devastator() + : CreatureScript("npc_crystalcore_devastator") + { + } + struct npc_crystalcore_devastatorAI : public ScriptedAI + { + npc_crystalcore_devastatorAI(Creature* creature) : ScriptedAI(creature) + { + Initialize(); + } + + void Initialize() + { + Countercharge_Timer = 9000; + Knockaway_Timer = 25000; + } + + uint32 Knockaway_Timer; + uint32 Countercharge_Timer; + + void Reset() override + { + Initialize(); + } + + void EnterCombat(Unit* /*who*/) override + { + } + + void UpdateAI(uint32 diff) override + { + if (!UpdateVictim()) + return; + + //Check if we have a current target + //Knockaway_Timer + if (Knockaway_Timer <= diff) + { + DoCastVictim(SPELL_KNOCKAWAY, true); + + // current aggro target is knocked away pick new target + Unit* target = SelectTarget(SELECT_TARGET_TOPAGGRO, 0); + + if (!target || target == me->GetVictim()) + target = SelectTarget(SELECT_TARGET_TOPAGGRO, 1); + + if (target) + me->TauntApply(target); + + Knockaway_Timer = 23000; + } + else + Knockaway_Timer -= diff; + + //Countercharge_Timer + if (Countercharge_Timer <= diff) + { + DoCast(me, SPELL_COUNTERCHARGE); + Countercharge_Timer = 45000; + } + else + Countercharge_Timer -= diff; + + DoMeleeAttackIfReady(); + } + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_crystalcore_devastatorAI(creature); + } +}; +void AddSC_the_eye() +{ + new npc_crystalcore_devastator(); +} + diff --git a/pool/shard009/C++/0106858_option.cpp b/pool/shard009/C++/0106858_option.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4b9967a1a38505596e0dbb3c21aa4a56fdeed57 --- /dev/null +++ b/pool/shard009/C++/0106858_option.cpp @@ -0,0 +1,164 @@ + +// option.cpp + +// includes + +#ifdef WINCE +#include +#else +#include +#endif +#include + +#include "option.h" +#include "util.h" + +// constants + +static const bool UseDebug = false; + +// types + +struct option_t { + const char * var; + const char * val; +}; + +// variables + +static option_t Option[] = { + + { "OptionFile", NULL, }, // string + + // options + + { "EngineName", NULL, }, // string + { "EngineDir", NULL, }, // string + { "EngineCommand", NULL, }, // string + + { "Log", NULL, }, // true/false + { "LogFile", NULL, }, // string + + { "Chess960", NULL, }, // true/false + + { "Resign", NULL, }, // true/false + { "ResignMoves", NULL, }, // move number + { "ResignScore", NULL, }, // centipawns + + { "MateScore", NULL, }, // centipawns + + { "Book", NULL, }, // true/false + { "BookFile", NULL, }, // string + + { "BookRandom", NULL, }, // true/false + { "BookLearn", NULL, }, // true/false + + { "KibitzMove", NULL, }, // true/false + { "KibitzPV", NULL, }, // true/false + + { "KibitzCommand", NULL, }, // string + { "KibitzDelay", NULL, }, // seconds + + { "ShowPonder", NULL, }, // true/false + + // work-arounds + + { "UCIVersion", NULL, }, // 1- + { "CanPonder", NULL, }, // true/false + { "SyncStop", NULL, }, // true/false + { "PromoteWorkAround", NULL, }, // true/false + + // { "", NULL, }, + + { NULL, NULL, }, +}; + +// prototypes + +static option_t * option_find (const char var[]); + +// functions + +// option_init() + +void option_init() { + + option_set("OptionFile","polyglot.ini"); + + // options + + option_set("EngineName",""); + option_set("EngineDir","."); + option_set("EngineCommand",""); + + option_set("Log","false"); + option_set("LogFile","polyglot.log"); + + option_set("Chess960","false"); + + option_set("Resign","false"); + option_set("ResignMoves","3"); + option_set("ResignScore","600"); + + option_set("MateScore","10000"); + + option_set("Book","false"); + option_set("BookFile","book.bin"); + + option_set("BookRandom","true"); + option_set("BookLearn","false"); + + option_set("KibitzMove","false"); + option_set("KibitzPV","false"); + + option_set("KibitzCommand","tellall"); + option_set("KibitzDelay","5"); + + option_set("ShowPonder","true"); + + // work-arounds + + option_set("UCIVersion","2"); + option_set("CanPonder","false"); + option_set("SyncStop","false"); + option_set("PromoteWorkAround","false"); + + // option_set("",""); +} + +// option_set() + +bool option_set(const char var[], const char val[]) { + + option_t * opt; + + ASSERT(var!=NULL); + ASSERT(val!=NULL); + + opt = option_find(var); + if (opt == NULL) return false; + + my_string_set(&opt->val,val); + + if (UseDebug) my_log("POLYGLOT OPTION SET \"%s\" -> \"%s\"\n",opt->var,opt->val); + + return true; +} + +// option_find() + +static option_t * option_find(const char var[]) { + + option_t * opt; + + ASSERT(var!=NULL); + + for (opt = &Option[0]; opt->var != NULL; opt++) { + if (my_string_case_equal(opt->var,var)) return opt; + } + + return NULL; +} + +// end of option.cpp + diff --git a/pool/shard009/C++/0106864_push_notifications_subscribe_task_unittest.cc b/pool/shard009/C++/0106864_push_notifications_subscribe_task_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..32522f21a77462ce804dd2e66f43576becf2db8b --- /dev/null +++ b/pool/shard009/C++/0106864_push_notifications_subscribe_task_unittest.cc @@ -0,0 +1,62 @@ +// Copyright (c) 2011 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 "jingle/notifier/listener/push_notifications_subscribe_task.h" + +#include "base/memory/scoped_ptr.h" +#include "base/strings/stringprintf.h" +#include "jingle/notifier/listener/xml_element_util.h" +#include "talk/xmpp/jid.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace buzz { +class XmlElement; +} + +namespace notifier { + +class PushNotificationsSubscribeTaskTest : public testing::Test { + public: + PushNotificationsSubscribeTaskTest() + : jid_("to@jid.com/test123"), task_id_("taskid") { + EXPECT_NE(jid_.Str(), jid_.BareJid().Str()); + } + + protected: + const buzz::Jid jid_; + const std::string task_id_; + + private: + DISALLOW_COPY_AND_ASSIGN(PushNotificationsSubscribeTaskTest); +}; + +TEST_F(PushNotificationsSubscribeTaskTest, MakeSubscriptionMessage) { + SubscriptionList subscriptions; + + Subscription subscription; + subscription.channel = "test_channel1"; + subscription.from = "from.test.com"; + subscriptions.push_back(subscription); + subscription.channel = "test_channel2"; + subscription.from = "from.test2.com"; + subscriptions.push_back(subscription); + scoped_ptr message( + PushNotificationsSubscribeTask::MakeSubscriptionMessage( + subscriptions, jid_, task_id_)); + std::string expected_xml_string = + base::StringPrintf( + "" + "" + "" + "" + "" + "", + jid_.BareJid().Str().c_str(), task_id_.c_str()); + + EXPECT_EQ(expected_xml_string, XmlElementToString(*message)); +} + +} // namespace notifier + diff --git a/pool/shard009/C++/0106870_main.cpp b/pool/shard009/C++/0106870_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..37baf81d1db1149a47aa84a329dbc91ac378abe9 --- /dev/null +++ b/pool/shard009/C++/0106870_main.cpp @@ -0,0 +1,28 @@ +// +// Created by Jean-Antoine Dupont on 11/03/2016. +// + +#include +#include "test/client/Client.h" + +int main() +{ + Client *client = new Client(); + + if (client->getConnectionManager()->connection() != -1) { + + client->getMessageManager()->sendMessage(((ConnectionManager *)client->getConnectionManager())->getSockFd(), "toto", 4); + + void *msg = client->getMessageManager()->receiveMessage(((ConnectionManager *)client->getConnectionManager())->getSockFd()); + + if (msg != nullptr) { + std::cout << ((char *)msg) << std::endl; + } + + client->getConnectionManager()->disconnection(); + } + + delete client; + + return 0; +} diff --git a/pool/shard009/C++/0106872_wisp.cpp b/pool/shard009/C++/0106872_wisp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa0e1b7f5695cb2e555e8f7e0dfd5bc998ebc23e --- /dev/null +++ b/pool/shard009/C++/0106872_wisp.cpp @@ -0,0 +1,60 @@ +#include "Arduino.h" +#include +#include "Wisp.h" + +Wisp::Wisp(int pos, int trail, int starting_brightness, int hue) { + _pos = pos; + _trail = trail; + _brightness = starting_brightness; + _hue = hue; +} + +void Wisp::set_pos(int pos) { + _pos = pos; +} + +int Wisp::get_pos() { + return _pos; +} + +void Wisp::set_trail(int trail) { + _trail = trail; +} + +int Wisp::get_trail() { + return _trail; +} + +void Wisp::set_brightness(int brightness) { + _brightness = brightness; +} + +int Wisp::get_brightness() { + return _brightness; +} + +void Wisp::set_hue(int hue) { + _hue = hue; +} + +int Wisp::get_hue() { + return _hue; +} + +void Wisp::update(CRGB leds[], int brightness_step, int num_leds, int hue_step) { + _trail_num = 0; + for(int i = _pos; _trail_num < _trail; i--) { + + int new_hue = _hue - ((_trail_num + 1) * hue_step); + int new_brightness = _brightness - ((_trail_num + 1) * brightness_step); + if(new_hue < 0) new_hue += 255; + + if(i < 0) { + leds[i + num_leds] = CHSV(new_hue, 255, new_brightness); + } else { + leds[i] = CHSV(new_hue, 255, new_brightness); + } + _trail_num++; + } + _pos++; +} \ No newline at end of file diff --git a/pool/shard009/C++/0106879_dummyserver.cpp b/pool/shard009/C++/0106879_dummyserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51195e536c01b817e7b087100f47f7fbef2cbe9a --- /dev/null +++ b/pool/shard009/C++/0106879_dummyserver.cpp @@ -0,0 +1,73 @@ +// +// Copyright (c) 2007-2009 2009 Universidade Aveiro - Instituto de +// Telecomunicacoes Polo Aveiro +// This file is part of ODTONE - Open Dot Twenty One. +// +// This software is distributed under a license. The full license +// agreement can be found in the file LICENSE in this distribution. +// This software may not be copied, modified, sold or distributed +// other than expressed in the named license agreement. +// +// This software is distributed without any warranty. +// +// Author: Simao Reis +// + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "../mihf/udp_listener.hpp" + +using namespace odtone; +using boost::asio::ip::udp; + +static void process_message(meta_message_ptr& msg) +{ + std::cout << "MIH message: Service=" << msg->sid() + << " Opcode=" << msg->opcode() + << " Action=" << msg->aid() + << std::endl; + + if (msg->mid() == mih::response::get_information) { + mih::ir_bin_data_list bin_data_list; + + *msg >> mih::response(mih::response::get_information) + & mih::tlv_info_resp_bin_data_list(bin_data_list); + + mih::ir_bin_data bd = bin_data_list[0]; + + mih::ie_container_list_of_networks l; + bd.input() & mih::tlv_ie_container_list_of_networks(l); + } +} + + +int main(int argc, char **argv) +{ + boost::asio::io_service io_service; + + dispatch_t dispatch = boost::bind(process_message, _1); + mihf::udp_listener listen(io_service, boost::asio::ip::udp::v4(), + "127.0.0.1", 4000, dispatch); + + listen.start(); + io_service.run(); + + return 0; +} diff --git a/pool/shard009/C++/0106882_jnc_ct_OperatorMgr_Closure.cpp b/pool/shard009/C++/0106882_jnc_ct_OperatorMgr_Closure.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5cb1935875c267d03202cf480758c5c4c912c18c --- /dev/null +++ b/pool/shard009/C++/0106882_jnc_ct_OperatorMgr_Closure.cpp @@ -0,0 +1,210 @@ +//.............................................................................. +// +// This file is part of the Jancy toolkit. +// +// Jancy is distributed under the MIT license. +// For details see accompanying license.txt file, +// the public copy of which is also available at: +// http://tibbo.com/downloads/archive/jancy/license.txt +// +//.............................................................................. + +#include "pch.h" +#include "jnc_ct_OperatorMgr.h" +#include "jnc_ct_Closure.h" +#include "jnc_ct_Module.h" +#include "jnc_ct_ClosureClassType.h" + +namespace jnc { +namespace ct { + +//.............................................................................. + +bool +OperatorMgr::createClosureObject( + const Value& opValue, // thin function or property ptr with closure + Type* thunkType, // function or property type + bool isWeak, + Value* resultValue +) { + ASSERT(thunkType->getTypeKind() == TypeKind_Function || thunkType->getTypeKind() == TypeKind_Property); + + bool result; + + // choose reference function type + + FunctionType* srcFunctionType; + if (opValue.getType()->getTypeKindFlags() & TypeKindFlag_FunctionPtr) { + ASSERT(((FunctionPtrType*)opValue.getType())->getPtrTypeKind() == FunctionPtrTypeKind_Thin); + srcFunctionType = ((FunctionPtrType*)opValue.getType())->getTargetType(); + } else { + ASSERT(opValue.getType()->getTypeKindFlags() & TypeKindFlag_PropertyPtr); + ASSERT(((PropertyPtrType*)opValue.getType())->getPtrTypeKind() == PropertyPtrTypeKind_Thin); + srcFunctionType = ((PropertyPtrType*)opValue.getType())->getTargetType()->getGetterType(); + } + + char buffer1[256]; + char buffer2[256]; + + sl::Array closureArgTypeArray(rc::BufKind_Stack, buffer1, sizeof(buffer1)); + sl::Array closureMap(rc::BufKind_Stack, buffer2, sizeof(buffer2)); + size_t closureArgCount = 0; + size_t closureThisArgIdx = -1; + + // build closure arg type array & closure map + + Closure* closure = opValue.getClosure(); + if (closure) { + closureArgCount = closure->getArgValueList()->getCount(); + closureThisArgIdx = closure->getThisArgIdx(); + + sl::Array srcArgArray = srcFunctionType->getArgArray(); + size_t srcArgCount = srcArgArray.getCount(); + + if (closureArgCount > srcArgCount) { + err::setFormatStringError("closure is too big for '%s'", srcFunctionType->getTypeString().sz()); + return false; + } + + closureArgTypeArray.setCount(closureArgCount); + closureMap.setCount(closureArgCount); + + sl::BoxIterator closureArgValue = closure->getArgValueList()->getHead(); + + size_t j = 0; + + for (size_t i = 0; i < closureArgCount; closureArgValue++, i++) { + if (closureArgValue->isEmpty()) + continue; + + closureArgTypeArray[j] = srcArgArray[i]->getType(); + closureMap[j] = i; + j++; + } + + closureArgCount = j; // account for possible skipped args + } + + // find or create closure class type + + ClosureClassType* closureType; + + if (thunkType->getTypeKind() == TypeKind_Function) { + closureType = m_module->m_typeMgr.getFunctionClosureClassType( + ((FunctionPtrType*)opValue.getType())->getTargetType(), + (FunctionType*)thunkType, + closureArgTypeArray, + closureMap, + closureArgCount, + closureThisArgIdx + ); + } else { + ASSERT(thunkType->getTypeKind() == TypeKind_Property); + + closureType = m_module->m_typeMgr.getPropertyClosureClassType( + ((PropertyPtrType*)opValue.getType())->getTargetType(), + (PropertyType*)thunkType, + closureArgTypeArray, + closureMap, + closureArgCount, + closureThisArgIdx + ); + } + + if (!closureType) + return false; + + // create instance + + Value closureValue; + result = m_module->m_operatorMgr.newOperator(closureType, NULL, &closureValue); + if (!result) + return false; + + const sl::Array& fieldArray = closureType->getFieldArray(); + size_t fieldIdx = 0; + + // save function/property pointer + + Value pfnValue = opValue; + pfnValue.clearClosure(); + + Value fieldValue; + result = + getClassField(closureValue, fieldArray[fieldIdx], NULL, &fieldValue) && + binaryOperator(BinOpKind_Assign, fieldValue, pfnValue); + + if (!result) + return false; + + fieldIdx++; + + // save closure arguments (if any) + + if (closure) { + sl::BoxIterator closureArgValue = closure->getArgValueList()->getHead(); + for (; closureArgValue; closureArgValue++) { + if (closureArgValue->isEmpty()) + continue; + + Value fieldValue; + result = + getClassField(closureValue, fieldArray[fieldIdx], NULL, &fieldValue) && + binaryOperator(BinOpKind_Assign, fieldValue, *closureArgValue); + + if (!result) + return false; + + fieldIdx++; + } + } + + *resultValue = closureValue; + return true; +} + +bool +OperatorMgr::createDataClosureObject( + const Value& opValue, // data ptr + PropertyType* thunkType, // function or property type + Value* resultValue +) { + ASSERT(opValue.getType()->getTypeKind() == TypeKind_DataPtr); + + bool result; + + // find or create closure class type + + DataClosureClassType* closureType = m_module->m_typeMgr.getDataClosureClassType( + ((DataPtrType*)opValue.getType())->getTargetType(), + thunkType + ); + + // create instance + + Value closureValue; + result = m_module->m_operatorMgr.newOperator(closureType, NULL, &closureValue); + if (!result) + return false; + + const sl::Array& fieldArray = closureType->getFieldArray(); + ASSERT(!fieldArray.isEmpty()); + + // save data pointer + + Value fieldValue; + result = + getClassField(closureValue, fieldArray[0], NULL, &fieldValue) && + binaryOperator(BinOpKind_Assign, fieldValue, opValue); + + if (!result) + return false; + + *resultValue = closureValue; + return true; +} + +//.............................................................................. + +} // namespace ct +} // namespace jnc diff --git a/pool/shard009/C++/0106883_HostsBasedSym.cc b/pool/shard009/C++/0106883_HostsBasedSym.cc new file mode 100644 index 0000000000000000000000000000000000000000..ecd155e0fab9d037a889f19ea1a91a1543a8b128 --- /dev/null +++ b/pool/shard009/C++/0106883_HostsBasedSym.cc @@ -0,0 +1,67 @@ + +/* Web Polygraph http://www.web-polygraph.org/ + * Copyright 2003-2011 The Measurement Factory + * Licensed under the Apache License, Version 2.0 */ + +#include "pgl/pgl.h" + +#include "xstd/String.h" +#include "pgl/PglRec.h" +#include "pgl/PglArraySym.h" +#include "pgl/PglNetAddrSym.h" +#include "pgl/HostsBasedSym.h" + + +String HostsBasedSym::TheType = "HostsBased"; + +static String strAddrArr = "addr[]"; +static String strAddresses = "addresses"; +static String strHosts = "hosts"; + + +HostsBasedSym::HostsBasedSym(const String &aType): RecSym(aType, new PglRec) { + // originally, strAddresses were strHosts, and we did not want to + // change class name when the field name has changed + // to avoid renaming a bunhc of files + theRec->bAdd(strAddrArr, strAddresses, 0); +} + +HostsBasedSym::HostsBasedSym(const String &aType, PglRec *aRec): RecSym(aType, aRec) { +} + +bool HostsBasedSym::isA(const String &type) const { + return RecSym::isA(type) || type == TheType; +} + +SynSym *HostsBasedSym::dupe(const String &type) const { + if (isA(type)) + return new HostsBasedSym(this->type(), theRec->clone()); + return RecSym::dupe(type); +} + +int HostsBasedSym::hostCount() const { + if (ArraySym *a = getArraySym(strAddresses)) + return a->count(); + else + return 0; +} + +NetAddrSym *HostsBasedSym::host(int idx) const { + if (ArraySym *a = getArraySym(strAddresses)) { + Assert(idx < a->count()); + return &(NetAddrSym&)(*a)[idx]->cast(NetAddrSym::TheType); + } + return 0; +} + +const ArraySym *HostsBasedSym::addresses() const { + return getArraySym(strAddresses); +} + +bool HostsBasedSym::addresses(ArraySym &addrs) const { + if (const ArraySym *a = addresses()) { + addrs.append(*a); + return true; + } + return false; +} diff --git a/pool/shard009/C++/0106895_dsgd.cc b/pool/shard009/C++/0106895_dsgd.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6f82b7d1fee5f811bebe26f9f3bf05dd732212b --- /dev/null +++ b/pool/shard009/C++/0106895_dsgd.cc @@ -0,0 +1,189 @@ +// Copyright 2017 Rainer Gemulla +// +// 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. +/** \file + * + * Illustrates matrix factorization with DSGD. We first creates factors and then a data matrix + * from these factors. This process ensures that we know the best factorization of the input. + * These matrices are distributed across a cluster. We then try to reconstruct the factors + * using DSGD. + * + * Run with: mpirun --hosts localhost,localhost dsgd + * (make sure to use a production build, otherwise it will be slow) + */ +#include + +#include +#include +#include +#include + +#include + +#include +#include + +log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); + +using namespace std; +using namespace mf; +using namespace mpi2; +using namespace rg; +using namespace boost::numeric::ublas; + +// type of SGD +typedef UpdateTruncate Update; +//typedef UpdateTruncate Update; +typedef RegularizeNone Regularize; +//typedef RegularizeL2 Regularize; +//typedef RegularizeNzl2 Regularize; +typedef SumLoss Loss; +//typedef SumLoss Loss; +typedef NzslLoss TestLoss; + +int main(int argc, char* argv[]) { + // initialize mf library and mpi2 + boost::mpi::communicator& world = mfInit(argc, argv); + + // parameters for the factorization + mf_size_type size1 = 10000; + mf_size_type size2 = 10000; + mf_size_type nnz = 1000000; + double sigma = sqrt(10); // standard deviation + double lambda = 1/sigma/sigma; + mf_size_type r = 10; + + // parameters for distribution + int tasksPerRank = 4; + mf_size_type blocks1 = world.size() * tasksPerRank; + mf_size_type blocks2 = world.size() * tasksPerRank; + + // parameters for SGD + double eps0 = 0.01; + mf_size_type epochs = 10; + SgdOrder order = SGD_ORDER_WOR; + StratumOrder stratumOrder = STRATUM_ORDER_RSEQ; + Update update = Update(UpdateNzslL2(lambda), -10*sigma, 10*sigma); // truncate for numerical stability +// Update update = Update(UpdateNzsl(), -10*sigma, 10*sigma); // truncate for numerical stability + Regularize regularize; +// Regularize regularize = Regularize(lambda); + Loss loss((NzslLoss()), L2Loss(lambda)); +// Loss loss((NzslLoss()), Nzl2Loss(lambda)); + TestLoss testLoss; + mf_size_type testNnz = nnz/100; + BalanceType balanceType = BALANCE_NONE; + BalanceMethod balanceMethod = BALANCE_OPTIMAL; + bool mapReduce = false; + + // start mf library + mfStart(); + + if (world.rank() == 0) + { +#ifndef NDEBUG + LOG4CXX_WARN(logger, "Warning: Debug mode activated (runtimes may be slow)."); +#endif + + // TODO: distribute matrix generation + // generate original factors by sampling from a normal(0,sigma) distribution + Random32 random; // note: this takes a default seed (not randomized!) + DenseMatrix wIn(size1, r); + DenseMatrixCM hIn(r, size2); + generateRandom(wIn, random, boost::normal_distribution<>(0, sigma)); + generateRandom(hIn, random, boost::normal_distribution<>(0, sigma)); + + // generate a sparse matrix by selecting random entries from the generated factors + // and add small Gaussian noise + SparseMatrix v; + generateRandom(v, nnz, wIn, hIn, random); + addRandom(v, random, boost::normal_distribution<>(0, 0.1)); + LOG4CXX_INFO(logger, "Data matrix: " + << v.size1() << " x " << v.size2() << ", " << v.nnz() << " nonzeros"); + LOG4CXX_INFO(logger, "Loss with original factors: " << loss((FactorizationData<>(v, wIn, hIn)))); + + // create a test matrix (without noise) + SparseMatrix vTest; + generateRandom(vTest, testNnz, wIn, hIn, random); + LOG4CXX_INFO(logger, "Test matrix: " + << v.size1() << " x " << v.size2() << ", " << vTest.nnz() << " nonzeros"); + + // take a small sample and remove empty rows/columns + ProjectedSparseMatrix Vsample; + projectRandomSubmatrix(random, v, Vsample, v.size1()/5, v.size2()/5); + projectFrequent(Vsample, 0); + LOG4CXX_INFO(logger, "Sample matrix: " + << Vsample.data.size1() << " x " << Vsample.data.size2() + << ", " << Vsample.data.nnz() << " nonzeros"); + + // generate initial factors by sampling from a uniform[-0.5,0.5] distribution + DenseMatrix w(size1, r); + DenseMatrixCM h(r, size2); + generateRandom(w, random, boost::uniform_real<>(-0.5, 0.5)); + generateRandom(h, random, boost::uniform_real<>(-0.5, 0.5)); + + // distribute the input matrices and test matrix (cheaper than fetching W/H) + DistributedSparseMatrix dv = distributeMatrix("V", blocks1, blocks2, true, v); + LOG4CXX_INFO(logger, "Distributed data matrix: " + << dv.blocks1() << " x " << dv.blocks2() << " blocks"); + DistributedSparseMatrix dvTest = distributeMatrix("VTest", blocks1, blocks2, true, vTest); + DistributedDenseMatrix dw = distributeMatrix("W", blocks1, 1, true, w); + DistributedDenseMatrixCM dh = distributeMatrix("H", 1, blocks2, false, h); + LOG4CXX_INFO(logger, "Distributed factor matrices"); + + // initialize the DSGD + Timer t; + DsgdRunner dsgdRunner(random); + DsgdJob dsgdJob(dv, dw, dh, update, regularize, order, + stratumOrder, mapReduce, tasksPerRank); + //BoldDriver decay(eps0); + DistributedDecayAuto decay(dsgdJob, loss, Vsample, "decay", eps0, + world.size()*tasksPerRank); + Trace trace; + + //std::string s1("Loss"),s2("nzsl"),s3("Regularize"),s4("L2"),s5("nodes"),s6("threads"); + + trace.addField("Loss","nzsl"); + trace.addField("Regularize","L2"); + + trace.addField("nodes",3); + trace.addField("threads",4); + + + // print the test loss + DsgdFactorizationData<> testData(dvTest,dw,dh,tasksPerRank); + LOG4CXX_INFO(logger, "Initial test loss: " << testLoss(testData)); + + // run DSGD to try to reconstruct the original factors + t.start(); + dsgdRunner.run(dsgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss); + //dsgdRunner.run(dsgdJob, loss, epochs, decay, trace); + + t.stop(); + LOG4CXX_INFO(logger, "Total time: " << t); + + // print the test loss + LOG4CXX_INFO(logger, "Final test loss: " << testLoss(testData)); + + // write trace to an R file + LOG4CXX_INFO(logger, "Writing trace to " << "/tmp/dsgd-trace.R"); + trace.toRfile("/tmp/dsgd-trace.R", "dsgd"); + +// cout << squaredSums2(dsgdJob.dw, tasksPerRank) << endl; +// cout << squaredSums1(dsgdJob.dh, tasksPerRank) << endl; + } + + mfStop(); + mfFinalize(); + + return 0; +} diff --git a/pool/shard009/C++/0106896_rinstallprogress.cc b/pool/shard009/C++/0106896_rinstallprogress.cc new file mode 100644 index 0000000000000000000000000000000000000000..229550dde3916c44891578b9c1950b2927a21746 --- /dev/null +++ b/pool/shard009/C++/0106896_rinstallprogress.cc @@ -0,0 +1,150 @@ +/* rinstallprogress.cc + * + * Copyright (c) 2000, 2001 Conectiva S/A + * 2002 Michael Vogt + * + * Author: Alfredo K. Kojima + * Michael Vogt + * + * 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 "config.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#ifdef HAVE_RPM +#include +#endif + +#include "rinstallprogress.h" + +#include "i18n.h" +std::string RInstallProgress::finishMsg = _("\nSuccessfully applied all changes. You can close the window now."); +std::string RInstallProgress::errorMsg = _("\nNot all changes and updates succeeded. For further details of the failure, please expand the 'Details' panel below."); +std::string RInstallProgress::incompleteMsg = + _("\nSuccessfully installed all packages of the current medium. " + "To continue the installation with the next medium close " + "this window."); + +const char* RInstallProgress::getResultStr(pkgPackageManager::OrderResult res) +{ + int size; + switch( res ) { + case 0: // completed + return finishMsg.c_str(); + break; + case 1: // failed + return errorMsg.c_str(); + break; + case 2: // incomplete + return incompleteMsg.c_str(); + break; + } + + return "Unknown install result."; +} + + +pkgPackageManager::OrderResult RInstallProgress::start(pkgPackageManager *pm, + int numPackages, + int numPackagesTotal) +{ + void *dummy; + pkgPackageManager::OrderResult res; + int ret; + pid_t _child_id; + + //cout << "RInstallProgress::start()" << endl; + +#ifdef HAVE_RPM + + _config->Set("RPM::Interactive", "false"); + + res = pm->DoInstallPreFork(); + if (res == pkgPackageManager::Failed) + return res; + + /* + * This will make a pipe from where we can read child's output + */ + int fd[2]; + pipe(fd); + + _child_id = fork(); + + if (_child_id == 0) { + // make the write end of the pipe to the child become the new stdout + // and stderr (for the child) + dup2(fd[1], 1); + dup2(1, 2); + close(fd[0]); + close(fd[1]); + + APT::Progress::PackageManagerProgressFd progress(-1); + res = pm->DoInstallPostFork(&progress); + // dump errors into cerr (pass it to the parent process) + _error->DumpErrors(); + _exit(res); + } + // this is where we read stuff from the child + _childin = fd[0]; + close(fd[1]); + + // make it nonblocking + fcntl(_childin, F_SETFL, O_NONBLOCK); + + _donePackages = 0; + _numPackages = numPackages; + _numPackagesTotal = numPackagesTotal; + +#else + + res = pm->DoInstallPreFork(); + if (res == pkgPackageManager::Failed) + return res; + + _child_id = fork(); + + if (_child_id == 0) { + APT::Progress::PackageManagerProgressFd progress(-1); + res = pm->DoInstallPostFork(&progress); + _exit(res); + } +#endif + + startUpdate(); + while (waitpid(_child_id, &ret, WNOHANG) == 0) + updateInterface(); + + res = (pkgPackageManager::OrderResult) WEXITSTATUS(ret); + + finishUpdate(); + +#ifdef HAVE_RPM + close(_childin); +#endif + + return res; +} + +// vim:sts=4:sw=4 diff --git a/pool/shard009/C++/0106902_ABI38_0_0EventEmitter.cpp b/pool/shard009/C++/0106902_ABI38_0_0EventEmitter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e0b00bbc4cf689b6efd2d009aa86c708cf069a2 --- /dev/null +++ b/pool/shard009/C++/0106902_ABI38_0_0EventEmitter.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include "ABI38_0_0EventEmitter.h" + +#include +#include +#include +#include + +#include "ABI38_0_0RawEvent.h" + +namespace ABI38_0_0facebook { +namespace ABI38_0_0React { + +// TODO(T29874519): Get rid of "top" prefix once and for all. +/* + * Capitalizes the first letter of the event type and adds "top" prefix if + * necessary (e.g. "layout" becames "topLayout"). + */ +static std::string normalizeEventType(const std::string &type) { + auto prefixedType = type; + if (type.find("top", 0) != 0) { + prefixedType.insert(0, "top"); + prefixedType[3] = toupper(prefixedType[3]); + } + return prefixedType; +} + +std::mutex &EventEmitter::DispatchMutex() { + static std::mutex mutex; + return mutex; +} + +ValueFactory EventEmitter::defaultPayloadFactory() { + static auto payloadFactory = + ValueFactory{[](jsi::Runtime &runtime) { return jsi::Object(runtime); }}; + return payloadFactory; +} + +EventEmitter::EventEmitter( + SharedEventTarget eventTarget, + Tag tag, + EventDispatcher::Weak eventDispatcher) + : eventTarget_(std::move(eventTarget)), + eventDispatcher_(std::move(eventDispatcher)) {} + +void EventEmitter::dispatchEvent( + const std::string &type, + const folly::dynamic &payload, + const EventPriority &priority) const { + dispatchEvent( + type, + [payload](jsi::Runtime &runtime) { + return valueFromDynamic(runtime, payload); + }, + priority); +} + +void EventEmitter::dispatchEvent( + const std::string &type, + const ValueFactory &payloadFactory, + const EventPriority &priority) const { + SystraceSection s("EventEmitter::dispatchEvent"); + + auto eventDispatcher = eventDispatcher_.lock(); + if (!eventDispatcher) { + return; + } + + eventDispatcher->dispatchEvent( + RawEvent(normalizeEventType(type), payloadFactory, eventTarget_), + priority); +} + +void EventEmitter::setEnabled(bool enabled) const { + enableCounter_ += enabled ? 1 : -1; + + bool shouldBeEnabled = enableCounter_ > 0; + if (isEnabled_ != shouldBeEnabled) { + isEnabled_ = shouldBeEnabled; + if (eventTarget_) { + eventTarget_->setEnabled(isEnabled_); + } + } + + // Note: Initially, the state of `eventTarget_` and the value `enableCounter_` + // is mismatched intentionally (it's `non-null` and `0` accordingly). We need + // this to support an initial nebula state where the event target must be + // retained without any associated mounted node. + bool shouldBeRetained = enableCounter_ > 0; + if (shouldBeRetained != (eventTarget_ != nullptr)) { + if (!shouldBeRetained) { + eventTarget_.reset(); + } + } +} + +} // namespace ABI38_0_0React +} // namespace ABI38_0_0facebook diff --git a/pool/shard009/C++/0106903_FXNode.cpp b/pool/shard009/C++/0106903_FXNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15aed9aa77793e944374a2b2df73dca2cf829591 --- /dev/null +++ b/pool/shard009/C++/0106903_FXNode.cpp @@ -0,0 +1,120 @@ +// +// libavg - Media Playback Engine. +// Copyright (C) 2003-2021 Ulrich von Zadow +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Current versions can be found at www.libavg.de +// + +#include "FXNode.h" +#include "Player.h" + +#include "../base/ObjectCounter.h" +#include "../graphics/GLContext.h" +#include "../graphics/GPUFilter.h" + + +namespace avg { + +using namespace std; + +FXNode::FXNode(bool bSupportsGLES) + : m_Size(0, 0), + m_bSupportsGLES(bSupportsGLES), + m_bDirty(true) +{ + ObjectCounter::get()->incRef(&typeid(*this)); +} + +FXNode::~FXNode() +{ + ObjectCounter::get()->decRef(&typeid(*this)); +} + +void FXNode::connect() +{ + checkGLES(); + if (m_Size != IntPoint(0,0)) { + m_pFilter = createFilter(m_Size); + } +} + +void FXNode::disconnect() +{ + m_pFilter = GPUFilterPtr(); +} + +void FXNode::setSize(const IntPoint& newSize) +{ + if (newSize != m_Size) { + m_Size = newSize; + if (m_pFilter) { + m_pFilter = createFilter(m_Size); + } + } +} + +void FXNode::apply(GLContext* pContext, GLTexturePtr pSrcTex) +{ + // blt overwrites everything, so no glClear necessary before. + pContext->setBlendMode(GLContext::BLEND_COPY); + m_pFilter->apply(pContext, pSrcTex); +} + +GLTexturePtr FXNode::getTex(GLContext* pContext) +{ + return m_pFilter->getDestTex(pContext); +} + +BitmapPtr FXNode::getImage(GLContext* pContext) +{ + return m_pFilter->getImage(pContext); +} + +FRect FXNode::getRelDestRect() const +{ + return m_pFilter->getRelDestRect(); +} + +bool FXNode::isDirty() const +{ + return m_bDirty; +} + +void FXNode::resetDirty() +{ + m_bDirty = false; +} + +FBOPtr FXNode::getFBO(GLContext* pContext) +{ + return m_pFilter->getFBO(pContext); +} + +void FXNode::setDirty() +{ + m_bDirty = true; +} + +void FXNode::checkGLES() const +{ + if (!m_bSupportsGLES && GLContext::getCurrent()->isGLES()) { + throw Exception(AVG_ERR_UNSUPPORTED, + "This effect is unsupported under OpenGL ES."); + } +} + +} diff --git a/pool/shard009/C++/0106904_touchSensor.cpp b/pool/shard009/C++/0106904_touchSensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0822f63a44089697035e4c3c4fd717028f327773 --- /dev/null +++ b/pool/shard009/C++/0106904_touchSensor.cpp @@ -0,0 +1,76 @@ +/* Copyright 2007-2015 QReal Research Group + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. */ + +#include "touchSensor.h" + +#include + +using namespace nxt::robotModel::real::parts; +using namespace kitBase; +using namespace robotModel; +using namespace utils; +using namespace robotCommunication; + +TouchSensor::TouchSensor(const kitBase::robotModel::DeviceInfo &info + , const kitBase::robotModel::PortInfo &port + , utils::robotCommunication::RobotCommunicator &robotCommunicator) + : kitBase::robotModel::robotParts::TouchSensor(info, port) + , mImplementation(robotCommunicator, port, enums::lowLevelSensorType::SWITCH, enums::sensorMode::RAWMODE) +{ + connect(&mImplementation, &NxtInputDevice::sensorSpecificProcessResponse + , this, &TouchSensor::sensorSpecificProcessResponse); + connect(&mImplementation, &NxtInputDevice::configured, this, &TouchSensor::configurationCompleted); +} + +void TouchSensor::sensorSpecificProcessResponse(const QByteArray &reading) +{ + mImplementation.setState(NxtInputDevice::idle); + int sensorValue = (0xff & reading[13]) << 8 | (0xff & reading[14]); + Tracer::debug(Tracer::sensors, "TouchSensor::sensorSpecificProcessResponse", QString::number(sensorValue)); + if (reading[4] == 0 && sensorValue < 500) { + // Sensor is pressed. + emit newData(1); + } else { + emit newData(0); + } +} + +void TouchSensor::read() +{ + if (!mImplementation.isConfigured()) { + // If sensor is not configured, report failure and return immediately. + // It is not an error, it shall be possible to reconfigure sensor "on the fly", + // but when it is reconfiguring it shall not be available. + emit failure(); + return; + } + + if (mImplementation.state() == NxtInputDevice::pending) { + return; + } + + mImplementation.setState(NxtInputDevice::pending); + QByteArray command(5, 0); + command[0] = 0x03; //command length + command[1] = 0x00; + command[2] = enums::telegramType::directCommandResponseRequired; + command[3] = enums::commandCode::GETINPUTVALUES; + command[4] = mImplementation.lowLevelPort(); + mImplementation.send(command, 18); +} + +void TouchSensor::doConfiguration() +{ + mImplementation.configure(); +} diff --git a/pool/shard009/C++/0106905_glapp.cpp b/pool/shard009/C++/0106905_glapp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8f76b6040f43781a9a9ae40406f82bf12169c2ed --- /dev/null +++ b/pool/shard009/C++/0106905_glapp.cpp @@ -0,0 +1,48 @@ +/*************************************************************** + * Name: Tetro2App.cpp + * Purpose: Code for Application Class + * Author: CHEN Junshi (cjshappy@163.com) + * Created: 2014-02-12 + * Copyright: CHEN Junshi () + * License: + **************************************************************/ + +#include "wx_pch.h" +#include "glapp.h" + +//(*AppHeaders +#include "glmainwindow.h" +#include +#include +#include +//*) + +IMPLEMENT_APP(GLApp); + +bool GLApp::OnInit() +{ + //(*AppInitialize + bool wxsOK = true; + wxInitAllImageHandlers(); + if ( wxsOK ) + { + GLMainWindow* Frame = new GLMainWindow(0); + Frame->Show(); + SetTopWindow(Frame); + + m_pLogFile = fopen("log.txt", "w+"); + delete wxLog::SetActiveTarget(new wxLogStderr(m_pLogFile)); + wxLog::SetTimestamp(wxT("%Y-%m-%d %H:%M:%S")); + wxLog::SetLogLevel(wxLOG_Info); + + wxLogMessage("Launch Application."); + } + //*) + return wxsOK; +} + +int GLApp::OnExit() +{ + fclose(m_pLogFile); + return 0; +} diff --git a/pool/shard009/C++/0106907_FullPermutation.cc b/pool/shard009/C++/0106907_FullPermutation.cc new file mode 100644 index 0000000000000000000000000000000000000000..e43a5acbc0d7d3a1d1c32a3fd3479b47880f9e64 --- /dev/null +++ b/pool/shard009/C++/0106907_FullPermutation.cc @@ -0,0 +1,67 @@ +/* + *-------------------------------------------------------------------------- + * File Name: FullPermutation.cc + * + * Author: Zhao Yanbai [zhaoyanbai@126.com] + * Mon Jul 19 15:14:43 2010 + * + * Description: + * + * 全排列的算法 + * + * 设要全排列的集合为R={r1, r2, ..., rn}. Ri = R - ri. + * 对集合X进行全排列记为P(X). (ri)P(X)表示在全排列P(X)的每一个排列前 + * 面都加上ri得到的排列. + * 则R的全排列定义如下: + * 当n==1时: P(R) = (r) + * 当n >1时: P(R) = {(r1)P(1), (r2)P(2), ...., (rn)P(n)} + *-------------------------------------------------------------------------- + */ + + +#include +using namespace std; + +template +void Swap(T &a, T &b) +{ + T c; + c = a; + a = b; + b = c; +} + + +template +void P(T *set, int b, int e) +{ + if(b == e) + { + for(int i=0; i + +// template , class Pred = equal_to, +// class Alloc = allocator>> +// class unordered_map + +// https://bugs.llvm.org/show_bug.cgi?id=16538 +// https://bugs.llvm.org/show_bug.cgi?id=16549 + +#include +#include + +struct Key { + template Key(const T&) {} + bool operator== (const Key&) const { return true; } +}; + +namespace std +{ + template <> + struct hash + { + size_t operator()(Key const &) const {return 0;} + }; +} + +int +main() +{ + typedef std::unordered_map MapT; + typedef MapT::iterator Iter; + MapT map; + Iter it = map.find(Key(0)); + assert(it == map.end()); + std::pair result = map.insert(std::make_pair(Key(0), 42)); + assert(result.second); + assert(result.first->second == 42); +} diff --git a/pool/shard009/C++/0106909_Scale_dlg.cpp b/pool/shard009/C++/0106909_Scale_dlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f304d23eb997785688f74ac5b586e59f02e961eb --- /dev/null +++ b/pool/shard009/C++/0106909_Scale_dlg.cpp @@ -0,0 +1,58 @@ +// WinProm Copyright 2015 Edward Earl +// All rights reserved. +// +// This software is distributed under a license that is described in +// the LICENSE file that accompanies it. +// +// Scale_dlg.cpp : implementation file +// + +#include "stdafx.h" +#include "winprom.h" +#include "Scale_dlg.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + + +///////////////////////////////////////////////////////////////////////////// +// CScale_dlg dialog + +CScale_dlg::CScale_dlg(CWnd* pParent /*=NULL*/) + : CDialog(CScale_dlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CScale_dlg) + m_scale = 0.0f; + //}}AFX_DATA_INIT +} + +void CScale_dlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CScale_dlg) + DDX_Text(pDX, IDC_SCALE, m_scale); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CScale_dlg, CDialog) + //{{AFX_MSG_MAP(CScale_dlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + + +///////////////////////////////////////////////////////////////////////////// +// CScale_dlg message handlers + +void CScale_dlg::OnOK() +{ + if (!UpdateData()) return; + if (m_scale<=0) { + MessageBox("Scale must be greater than 0.","Winprom Scale Error",MB_OK|MB_ICONERROR); + return; + } + CDialog::OnOK(); +} diff --git a/pool/shard009/C++/0106913_ComputeWindUp.cpp b/pool/shard009/C++/0106913_ComputeWindUp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bed0215d06a825bbed9fd577f9a5a925af79a9eb --- /dev/null +++ b/pool/shard009/C++/0106913_ComputeWindUp.cpp @@ -0,0 +1,341 @@ +#pragma ident "$Id$" + +/** + * @file ComputeWindUp.cpp + * This class computes the wind-up effect on the phase observables, in radians. + */ + +//============================================================================ +// +// This file is part of GPSTk, the GPS Toolkit. +// +// The GPSTk 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 +// any later version. +// +// The GPSTk 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 GPSTk; if not, write to the Free Software Foundation, +// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// Dagoberto Salazar - gAGE ( http://www.gage.es ). 2007, 2008, 2009 +// +//============================================================================ + + +#include "ComputeWindUp.hpp" + + +namespace gpstk +{ + + // Index initially assigned to this class + int ComputeWindUp::classIndex = 4500000; + + + // Returns an index identifying this object. + int ComputeWindUp::getIndex() const + { return index; } + + + // Returns a string identifying this object. + std::string ComputeWindUp::getClassName() const + { return "ComputeWindUp"; } + + + + /* Returns a satTypeValueMap object, adding the new data generated when + * calling this object. + * + * @param time Epoch corresponding to the data. + * @param gData Data object holding the data. + */ + satTypeValueMap& ComputeWindUp::Process( const DayTime& time, + satTypeValueMap& gData ) + throw(ProcessingException) + { + + try + { + + // Compute Sun position at this epoch + SunPosition sunPosition; + Triple sunPos(sunPosition.getPosition(time)); + + // Define a Triple that will hold satellite position, in ECEF + Triple svPos(0.0, 0.0, 0.0); + + SatIDSet satRejectedSet; + + // Loop through all the satellites + for ( satTypeValueMap::iterator it = gData.begin(); + it != gData.end(); + ++it ) + { + + // First check if this satellite has previous arc information + if( satArcMap.find( (*it).first ) == satArcMap.end() ) + { + // If it doesn't have an entry, insert one + satArcMap[ (*it).first ] = 0.0; + }; + + // Then, check both if there is arc information, and if current + // arc number is different from arc number in storage (which + // means a cycle slip happened) + if ( (*it).second.find(TypeID::satArc) != (*it).second.end() && + (*it).second(TypeID::satArc) != satArcMap[ (*it).first ] ) + { + // If different, update satellite arc in storage + satArcMap[ (*it).first ] = (*it).second(TypeID::satArc); + + // Reset phase information + phase_satellite[ (*it).first ].previousPhase = 0.0; + phase_station[ (*it).first ].previousPhase = 0.0; + + } + + + // Use ephemeris if satellite position is not already computed + if( ( (*it).second.find(TypeID::satX) == (*it).second.end() ) || + ( (*it).second.find(TypeID::satY) == (*it).second.end() ) || + ( (*it).second.find(TypeID::satZ) == (*it).second.end() ) ) + { + + if(pEphemeris==NULL) + { + + // If ephemeris is missing, then remove all satellites + satRejectedSet.insert( (*it).first ); + + continue; + + } + else + { + + // Try to get satellite position + // if it is not already computed + try + { + // For our purposes, position at receive time + // is fine enough + Xvt svPosVel(pEphemeris->getXvt( (*it).first, time )); + + // If everything is OK, then continue processing. + svPos[0] = svPosVel.x.theArray[0]; + svPos[1] = svPosVel.x.theArray[1]; + svPos[2] = svPosVel.x.theArray[2]; + + } + catch(...) + { + + // If satellite is missing, then schedule it + // for removal + satRejectedSet.insert( (*it).first ); + + continue; + + } + + } + + } + else + { + + // Get satellite position out of GDS + svPos[0] = (*it).second[TypeID::satX]; + svPos[1] = (*it).second[TypeID::satY]; + svPos[2] = (*it).second[TypeID::satZ]; + + } // End of 'if( ( (*it).second.find(TypeID::satX) == ...' + + + // Let's get wind-up value in radians, and insert it + // into GNSS data structure. + (*it).second[TypeID::windUp] = + getWindUp((*it).first, time, svPos, sunPos); + + } // End of 'for (it = gData.begin(); it != gData.end(); ++it)' + + // Remove satellites with missing data + gData.removeSatID(satRejectedSet); + + return gData; + + } + catch(Exception& u) + { + // Throw an exception if something unexpected happens + ProcessingException e( getClassName() + ":" + + StringUtils::asString( getIndex() ) + ":" + + u.what() ); + + GPSTK_THROW(e); + + } + + } // End of method 'ComputeWindUp::Process()' + + + + /* Sets name of "PRN_GPS"-like file containing satellite data. + * @param name Name of satellite data file. + */ + ComputeWindUp& ComputeWindUp::setFilename(const string& name) + { + + fileData = name; + satData.open(fileData); + + return (*this); + + } // End of method 'ComputeWindUp::setFilename()' + + + + /* Compute the value of the wind-up, in radians. + * @param sat Satellite IDmake + * @param time Epoch of interest + * @param satpos Satellite position, as a Triple + * @param sunpos Sun position, as a Triple + * + * @return Wind-up computation, in radians + */ + double ComputeWindUp::getWindUp( const SatID& satid, + const DayTime& time, + const Triple& sat, + const Triple& sunPosition ) + { + + // Unitary vector from satellite to Earth mass center + Triple rk( ( (-1.0)*(sat.unitVector()) ) ); + + // Unitary vector from Earth mass center to Sun + Triple ri( sunPosition.unitVector() ); + + // rj = rk x ri + Triple rj(rk.cross(ri)); + + // ri = rj x rk + ri = rj.cross(rk); + + // Let's convert ri, rj to unitary vectors. + // Now ri, rj, rk form a base in the ECEF reference frame + ri = ri.unitVector(); + rj = rj.unitVector(); + + + // Get satellite rotation angle + + // Get vector from Earth mass center to receiver + Triple rxPos(nominalPos.X(), nominalPos.Y(), nominalPos.Z()); + + // Compute unitary vector vector from satellite to RECEIVER + Triple rrho( (rxPos-sat).unitVector() ); + + // Vector from SV to Sun center of mass + Triple gps_sun( sunPosition-sat ); + + // Redefine rk: Unitary vector from SV to Earth mass center + rk = (-1.0)*(sat.unitVector()); + + // Redefine rj: rj = rk x gps_sun, then make sure it is unitary + rj = (rk.cross(gps_sun)).unitVector(); + + // Redefine ri: ri = rj x rk, then make sure it is unitary + // Now, ri, rj, rk form a base in the satellite body reference + // frame, expressed in the ECEF reference frame + ri = (rj.cross(rk)).unitVector(); + + + // Projection of "rk" vector to line of sight vector (rrho) + double zk(rrho.dot(rk)); + + // Get a vector without components on rk (i.e., belonging + // to ri, rj plane) + Triple dpp(rrho-zk*rk); + + // Compute dpp components in ri, rj plane + double xk(dpp.dot(ri)); + double yk(dpp.dot(rj)); + + // Compute satellite rotation angle, in radians + double alpha1(std::atan2(yk,xk)); + + + // Get receiver rotation angle + + // Redefine rk: Unitary vector from Receiver to Earth mass center + rk = (-1.0)*(rxPos.unitVector()); + + // Let's define a NORTH unitary vector in the Up, East, North + // (UEN) topocentric reference frame + Triple delta(0.0, 0.0, 1.0); + + // Rotate delta to XYZ reference frame + delta = + (delta.R2(nominalPos.geodeticLatitude())).R3(-nominalPos.longitude()); + + + // Computation of reference trame unitary vectors for receiver + // rj = rk x delta, and make it unitary + rj = (rk.cross(delta)).unitVector(); + + // ri = rj x rk, and make it unitary + ri = (rj.cross(rk)).unitVector(); + + // Projection of "rk" vector to line of sight vector (rrho) + zk = rrho.dot(rk); + + // Get a vector without components on rk (i.e., belonging + // to ri, rj plane) + dpp = rrho-zk*rk; + + // Compute dpp components in ri, rj plane + xk = dpp.dot(ri); + yk = dpp.dot(rj); + + // Compute receiver rotation angle, in radians + double alpha2(std::atan2(yk,xk)); + + double wind_up(0.0); + + // Find out if satellite belongs to block "IIR", because + // satellites of block IIR have a 180 phase shift + if(satData.getBlock( satid, time ) == "IIR") + { + wind_up = PI; + } + + alpha1 = alpha1 + wind_up; + + double da1(alpha1-phase_satellite[satid].previousPhase); + + double da2(alpha2-phase_station[satid].previousPhase); + + // Let's avoid problems when passing from 359 to 0 degrees. + phase_satellite[satid].previousPhase += std::atan2( std::sin(da1), + std::cos(da1) ); + + phase_station[satid].previousPhase += std::atan2( std::sin(da2), + std::cos(da2) ); + + // Compute wind up effect in radians + wind_up = phase_satellite[satid].previousPhase - + phase_station[satid].previousPhase; + + return wind_up; + + } // End of method 'ComputeWindUp::getWindUp()' + + + +} // End of namespace gpstk diff --git a/pool/shard009/C++/0106915_CacheTest.cpp b/pool/shard009/C++/0106915_CacheTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d82effe4f9a6e5a6d33231d2819082067afbd19 --- /dev/null +++ b/pool/shard009/C++/0106915_CacheTest.cpp @@ -0,0 +1,158 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "watchman/LRUCache.h" + +using namespace watchman; + +static constexpr const std::chrono::milliseconds kErrorTTL(1000); + +namespace watchman::lrucache { +template +FOLLY_MAYBE_UNUSED static std::ostream& operator<<( + std::ostream& out, + Node const& node) { + return out << (const void*)&node; +} +} // namespace watchman::lrucache + +TEST(CacheTest, basics) { + LRUCache cache(5, kErrorTTL); + + EXPECT_EQ(cache.size(), 0) << "initially empty"; + EXPECT_EQ(cache.get("foo"), nullptr) << "nullptr for non-existent item"; + + EXPECT_TRUE(cache.set("foo", true)->value()) << "inserted true"; + EXPECT_EQ(cache.size(), 1) << "size is now one"; + EXPECT_TRUE(cache.get("foo")->value()) << "looked up item"; + + EXPECT_FALSE(cache.set("foo", false)->value()) << "replaced true with false"; + EXPECT_FALSE(cache.get("foo")->value()) << "looked up new false item"; + EXPECT_EQ(cache.size(), 1) << "replacement didn't change size"; + + EXPECT_FALSE(cache.erase("foo")->value()) << "erased and returned false foo"; + EXPECT_EQ(cache.erase("foo"), nullptr) + << "double erase doesn't return anything"; + EXPECT_EQ(cache.get("foo"), nullptr) << "nullptr for non-existent item"; + + for (size_t i = 0; i < 6; ++i) { + EXPECT_NE(cache.set(std::to_string(i), true), nullptr) << "inserted"; + } + + EXPECT_EQ(cache.size(), 5) + << "limited to 5 items, despite inserting 6 total. size=" << cache.size(); + + EXPECT_EQ(cache.get("0"), nullptr) << "we expect 0 to have been evicted"; + for (size_t i = 1; i < 6; ++i) { + EXPECT_TRUE(cache.get(std::to_string(i))) << "found later node " << i; + } + + EXPECT_TRUE(cache.set("bar", true)) << "added new item"; + EXPECT_EQ(cache.get("1"), nullptr) << "we expect 1 to be evicted"; + EXPECT_TRUE(cache.get("2")) << "2 should be there, and we just touched it"; + EXPECT_TRUE(cache.set("baz", true)) << "added new item"; + EXPECT_EQ(cache.size(), 5) << "max size still respected"; + EXPECT_TRUE(cache.get("2")) << "2 should still be there; not evicted"; + EXPECT_EQ(cache.get("3"), nullptr) << "we expect 3 to be evicted"; + + cache.clear(); + EXPECT_EQ(cache.size(), 0) << "cleared out and have zero items"; +} + +TEST(CacheTest, future) { + using Cache = LRUCache; + using Node = typename Cache::NodeType; + Cache cache(5, kErrorTTL); + folly::ManualExecutor exec; + + auto now = std::chrono::steady_clock::now(); + + auto okGetter = [&exec](int k) { + return folly::makeFuture(k).via(&exec).thenTry( + [](folly::Try&& key) { return (1 + key.value()) * 2; }); + }; + + auto failGetter = [&exec](int k) { + return folly::makeFuture(k).via(&exec).thenTry( + [](folly::Try&&) -> int { throw std::runtime_error("bleet"); }); + }; + + // Queue up a get via a getter that will succeed + auto f = cache.get(0, okGetter, now); + EXPECT_FALSE(f.isReady()) << "future didn't finish yet"; + + EXPECT_THROW(cache.get(0), std::runtime_error); + + // Queue up a second get using the same getter + auto f2 = cache.get(0, okGetter, now); + EXPECT_FALSE(f2.isReady()) << "also not ready"; + + exec.drain(); + + EXPECT_TRUE(f.isReady()) << "first is ready"; + EXPECT_TRUE(f2.isReady()) << "second is ready"; + + EXPECT_EQ(f.value()->value(), 2) << "got correct value for first"; + EXPECT_EQ(f.value()->value(), f2.value()->value()) + << "got same value for second"; + + // Now to saturate the cache with failed lookups + + cache.clear(); + std::vector>> futures; + for (size_t i = 1; i < 7; ++i) { + futures.emplace_back( + cache.get(i, failGetter, now + std::chrono::milliseconds(i))); + } + + auto drained = exec.drain(); + EXPECT_EQ(drained, 13) << "should be 13 things pending, but have " << drained; + + // Let them make progress + exec.drain(); + + EXPECT_EQ(cache.size(), 5) + << "cache should be full, but has " << cache.size(); + + folly::collectAll(futures.begin(), futures.end()) + .defer( + [](folly::Try>>>&& + result) { + for (auto& r : result.value()) { + EXPECT_TRUE(r.value()->result().hasException()) + << "should be an error node"; + } + }) + .wait(); + + EXPECT_EQ(cache.size(), 5) + << "cache should still be full (no excess) but has " << cache.size(); + + EXPECT_EQ(cache.get(42, now), nullptr) << "we don't have 42 yet"; + + // Now if we "sleep" for long enough, we should be able to evict + // the error nodes and allow the insert to happen. + EXPECT_EQ(cache.get(42, now), nullptr) << "we don't have 42 yet"; + EXPECT_TRUE(cache.set(42, 42, now + kErrorTTL + std::chrono::milliseconds(1))) + << "inserted"; + EXPECT_NE(cache.get(42, now), nullptr) << "we found 42 in the cache"; + EXPECT_EQ(cache.size(), 5) + << "cache should still be full (no excess) but has " << cache.size(); +} + +int main(int argc, char* argv[]) { + testing::InitGoogleTest(&argc, argv); + folly::init(&argc, &argv); + return RUN_ALL_TESTS(); +} diff --git a/pool/shard009/C++/0106919_B.cpp b/pool/shard009/C++/0106919_B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a627751aaad82f9c7b15db649f47ec296b797bc9 --- /dev/null +++ b/pool/shard009/C++/0106919_B.cpp @@ -0,0 +1,114 @@ +/* ======================================== + + ID: mathema6 + TASK: B + LANG: C++11 + (...for USACO solutions) + + * File Name : B.cpp + + * Creation Date : 30-12-2014 + + * Last Modified : + + * Created By : Karel Ha + + * URL : http://codeforces.com/contest/500/problem/B + + * Points Gained (in case of online contest) : 828 / 1000 + + ==========================================*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define FOR(I,A,B) for(int I = (A); I < (B); ++I) +#define REP(I,N) FOR(I,0,N) +#define ALL(A) (A).begin(), (A).end() +#define MSG(a) cout << #a << " == " << a << endl; + +// uncomment following line for debug mode +//#define DEBUG + +int main() { + int n; + cin >> n; + vector p(n); + REP(i,n) { + cin >> p[i]; + } + + vector> A(n); + string line; + REP(i,n) { + A[i].assign(n,false); + cin >> line; + REP(j,n) { + A[i][j] = (line[j] == '0') ? false : true; + } + } + + // FW + REP(k,n) { +#ifdef DEBUG + // display A + MSG(k) + cout << "A:" << endl; + REP(i,n) { + REP(j,n) { + cout << A[i][j] ? "1" : "0"; + } + cout << endl; + } +#endif + + REP(i,n) { + REP(j,n) { + A[i][j] = A[i][j] || (A[i][k] && A[k][j]); + } + } + } + + REP(i,n-1) { + int mi = n+1; + int idx = i; + FOR(j,i,n) { + if (A[i][j] && p[j] < mi) { + mi = p[j]; + idx = j; + } + } + swap(p[i], p[idx]); + } + + REP(i,n) { + cout << p[i]; + if (i < n-1) + cout << " "; + } + return 0; +} diff --git a/pool/shard009/C++/0106920_olethros.cpp b/pool/shard009/C++/0106920_olethros.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f932b7db5131682a22f2bf5aaa83224a2644cdaf --- /dev/null +++ b/pool/shard009/C++/0106920_olethros.cpp @@ -0,0 +1,155 @@ +/*************************************************************************** + + file : olethros.cpp + copyright : (C) 2002-2004 Bernhard Wymann + 2004 Christos Dimitrakakis + email : dimitrak@idiap.ch + version : $Id: olethros.cpp,v 1.10.2.2 2008/11/09 17:50:20 berniw Exp $ + + ***************************************************************************/ + +/*************************************************************************** + * * + * 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. * + * * + ***************************************************************************/ + +/** + \file olethros.cpp + + \brief This is the main file for the Olethros robot. + + The Olethros robot is basically the same as berniw's BT robot with + added learning capabilities. +*/ + +#ifdef _WIN32 +#include +#endif + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "driver.h" + +#ifdef USE_OLETHROS_NAMESPACE +namespace olethros +{ +#endif + +#define BUFSIZE 20 +#define NBBOTS 10 + +static const char* botname[NBBOTS] = { + "olethros 1", "olethros 2", "olethros 3", "olethros 4", "olethros 5", + "olethros 6", "olethros 7", "olethros 8", "olethros 9", "olethros 10" +}; + +static const char* botdesc[NBBOTS] = { + "olethros 1", "olethros 2", "olethros 3", "olethros 4", "olethros 5", + "olethros 6", "olethros 7", "olethros 8", "olethros 9", "olethros 10" +}; + +static Driver *driver[NBBOTS]; + +static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s); +static void newRace(int index, tCarElt* car, tSituation *s); +static void drive(int index, tCarElt* car, tSituation *s); +static int pitcmd(int index, tCarElt* car, tSituation *s); +static void shutdown(int index); +static int InitFuncPt(int index, void *pt); +static void endRace(int index, tCarElt *car, tSituation *s); + + +// Module entry point. +extern "C" int olethros(tModInfo *modInfo) +{ + int i; + + // Clear all structures. + memset(modInfo, 0, 10*sizeof(tModInfo)); + + for (i = 0; i < NBBOTS; i++) { + modInfo[i].name = strdup(botname[i]); // name of the module (short). + modInfo[i].desc = strdup(botdesc[i]); // Description of the module (can be long). + modInfo[i].fctInit = InitFuncPt; // Init function. + modInfo[i].gfId = ROB_IDENT; // Supported framework version. + modInfo[i].index = i; // Indices from 0 to 9. + } + return 0; +} + + +// Module interface initialization. +static int InitFuncPt(int index, void *pt) +{ + tRobotItf *itf = (tRobotItf *)pt; + + // Create robot instance for index. + driver[index] = new Driver(index); + itf->rbNewTrack = initTrack; // Give the robot the track view called. + itf->rbNewRace = newRace; // Start a new race. + itf->rbDrive = drive; // Drive during race. + itf->rbPitCmd = pitcmd; // Pit commands. + itf->rbEndRace = endRace; // End of the current race. + itf->rbShutdown = shutdown; // Called before the module is unloaded. + itf->index = index; // Index used if multiple interfaces. + return 0; +} + + +// Called for every track change or new race. +static void initTrack(int index, tTrack* track, void *carHandle, void **carParmHandle, tSituation *s) +{ + driver[index]->initTrack(track, carHandle, carParmHandle, s); +} + + +// Start a new race. +static void newRace(int index, tCarElt* car, tSituation *s) +{ + driver[index]->newRace(car, s); +} + + +// Drive during race. +static void drive(int index, tCarElt* car, tSituation *s) +{ + driver[index]->drive(s); +} + + +// Pitstop callback. +static int pitcmd(int index, tCarElt* car, tSituation *s) +{ + return driver[index]->pitCommand(s); +} + + +// End of the current race. +static void endRace(int index, tCarElt *car, tSituation *s) +{ + driver[index]->endRace(s); +} + + +// Called before the module is unloaded. +static void shutdown(int index) +{ + delete driver[index]; +} + +#ifdef USE_OLETHROS_NAMESPACE +} +#endif diff --git a/pool/shard009/C++/0106926_SpatialController.cpp b/pool/shard009/C++/0106926_SpatialController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..745a5ba1d26a6640ab32deab141d7a9e4bb91e5a --- /dev/null +++ b/pool/shard009/C++/0106926_SpatialController.cpp @@ -0,0 +1,61 @@ +#include "SpatialController.h" +#include "Scene.h" + +//====================================================================== +using namespace vivid; + +//====================================================================== +SpatialController::SpatialController (): +Rotation (math::MatrixIdentity (math::Mat3f ())) +{ } + +//====================================================================== +SpatialController::~SpatialController () +{ } + +//====================================================================== +void SpatialController::Update (float time) +{ + if (Scene::Validate (Node)) + { + auto& n = Scene::GetNode (Node); + n.Local.SetRotation (Rotation); + n.Local.SetTranslation (Translation); + } +} + +//====================================================================== +void SpatialController::MoveForward (float distance) +{ + Translation += Rotation.GetRow (2) * distance; +} + +//====================================================================== +void SpatialController::MoveBackward (float distance) +{ + Translation -= Rotation.GetRow (2) * distance; +} + +//====================================================================== +void SpatialController::MoveRight (float distance) +{ + Translation += Rotation.GetRow (0) * distance; +} + +//====================================================================== +void SpatialController::MoveLeft (float distance) +{ + Translation -= Rotation.GetRow (0) * distance; +} + +//====================================================================== +void SpatialController::MoveUp (float distance) +{ + Translation += Rotation.GetRow (1) * distance; +} + +//====================================================================== +void SpatialController::MoveDown (float distance) +{ + Translation -= Rotation.GetRow (1) * distance; +} \ No newline at end of file diff --git a/pool/shard009/C++/0106931_os_kick.cpp b/pool/shard009/C++/0106931_os_kick.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a358424069ecdcb3d1f72354056247ee5b5ac12 --- /dev/null +++ b/pool/shard009/C++/0106931_os_kick.cpp @@ -0,0 +1,84 @@ +/* OperServ core functions + * + * (C) 2003-2016 Anope Team + * Contact us at team@anope.org + * + * Please read COPYING and README for further details. + * + * Based on the original code of Epona by Lara. + * Based on the original code of Services by Andy Church. + */ + +#include "module.h" + +class CommandOSKick : public Command +{ + public: + CommandOSKick(Module *creator) : Command(creator, "operserv/kick", 3, 3) + { + this->SetDesc(_("Kick a user from a channel")); + this->SetSyntax(_("\037channel\037 \037user\037 \037reason\037")); + } + + void Execute(CommandSource &source, const std::vector ¶ms) anope_override + { + const Anope::string &chan = params[0]; + const Anope::string &nick = params[1]; + const Anope::string &s = params[2]; + Channel *c; + User *u2; + + if (!(c = Channel::Find(chan))) + { + source.Reply(CHAN_X_NOT_IN_USE, chan.c_str()); + return; + } + + if (c->bouncy_modes) + { + source.Reply(_("Services is unable to change modes. Are your servers' U:lines configured correctly?")); + return; + } + + if (!(u2 = User::Find(nick, true))) + { + source.Reply(NICK_X_NOT_IN_USE, nick.c_str()); + return; + } + + if (!c->Kick(source.service, u2, "%s (%s)", source.GetNick().c_str(), s.c_str())) + { + source.Reply(ACCESS_DENIED); + return; + } + + Log(LOG_ADMIN, source, this) << "on " << u2->nick << " in " << c->name << " (" << s << ")"; + } + + bool OnHelp(CommandSource &source, const Anope::string &subcommand) anope_override + { + this->SendSyntax(source); + source.Reply(" "); + source.Reply(_("Allows staff to kick a user from any channel.\n" + "Parameters are the same as for the standard /KICK\n" + "command. The kick message will have the nickname of the\n" + "IRCop sending the KICK command prepended; for example:\n" + " \n" + "*** SpamMan has been kicked off channel #my_channel by %s (Alcan (Flood))"), source.service->nick.c_str()); + return true; + } +}; + +class OSKick : public Module +{ + CommandOSKick commandoskick; + + public: + OSKick(const Anope::string &modname, const Anope::string &creator) : Module(modname, creator, VENDOR), + commandoskick(this) + { + + } +}; + +MODULE_INIT(OSKick) diff --git a/pool/shard009/C++/0106932_transcoderoptionsflac.cpp b/pool/shard009/C++/0106932_transcoderoptionsflac.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc29471a95efbc33677fde63d5ed68887817e464 --- /dev/null +++ b/pool/shard009/C++/0106932_transcoderoptionsflac.cpp @@ -0,0 +1,44 @@ +/* This file is part of Clementine. + Copyright 2010, David Sansome + + Clementine 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. + + Clementine 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 Clementine. If not, see . +*/ + +#include "transcoderoptionsflac.h" +#include "ui_transcoderoptionsflac.h" + +#include + +const char* TranscoderOptionsFlac::kSettingsGroup = "Transcoder/flacenc"; + +TranscoderOptionsFlac::TranscoderOptionsFlac(QWidget* parent) + : TranscoderOptionsInterface(parent), ui_(new Ui_TranscoderOptionsFlac) { + ui_->setupUi(this); +} + +TranscoderOptionsFlac::~TranscoderOptionsFlac() { delete ui_; } + +void TranscoderOptionsFlac::Load() { + QSettings s; + s.beginGroup(kSettingsGroup); + + ui_->quality->setValue(s.value("quality", 5).toInt()); +} + +void TranscoderOptionsFlac::Save() { + QSettings s; + s.beginGroup(kSettingsGroup); + + s.setValue("quality", ui_->quality->value()); +} diff --git a/pool/shard009/C++/0106938_rpcdump.cpp b/pool/shard009/C++/0106938_rpcdump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bfe8b12fcca2e9a0c0f80692b1cf9045f0401699 --- /dev/null +++ b/pool/shard009/C++/0106938_rpcdump.cpp @@ -0,0 +1,92 @@ +// Copyright (c) 2009-2012 Bitcoin Developers +// Copyright (c) 2011-2012 Litecoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "init.h" // for pwalletMain +#include "bitcoinrpc.h" +#include "ui_interface.h" +#include "base58.h" + +#include + +#define printf OutputDebugStringF + +using namespace json_spirit; +using namespace std; + +class CTxDump +{ +public: + CBlockIndex *pindex; + int64 nValue; + bool fSpent; + CWalletTx* ptx; + int nOut; + CTxDump(CWalletTx* ptx = NULL, int nOut = -1) + { + pindex = NULL; + nValue = 0; + fSpent = false; + this->ptx = ptx; + this->nOut = nOut; + } +}; + +Value importprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 2) + throw runtime_error( + "importprivkey [label]\n" + "Adds a private key (as returned by dumpprivkey) to your wallet."); + + string strSecret = params[0].get_str(); + string strLabel = ""; + if (params.size() > 1) + strLabel = params[1].get_str(); + CBitcoinSecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) throw JSONRPCError(-5,"Invalid private key"); + + CKey key; + bool fCompressed; + CSecret secret = vchSecret.GetSecret(fCompressed); + key.SetSecret(secret, fCompressed); + CKeyID vchAddress = key.GetPubKey().GetID(); + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + pwalletMain->SetAddressBookName(vchAddress, strLabel); + + if (!pwalletMain->AddKey(key)) + throw JSONRPCError(-4,"Error adding key to wallet"); + + pwalletMain->ScanForWalletTransactions(pindexGenesisBlock, true); + pwalletMain->ReacceptWalletTransactions(); + } + + return Value::null; +} + +Value dumpprivkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "dumpprivkey \n" + "Reveals the private key corresponding to ."); + + string strAddress = params[0].get_str(); + CBitcoinAddress address; + if (!address.SetString(strAddress)) + throw JSONRPCError(-5, "Invalid TalaroCoin address"); + CKeyID keyID; + if (!address.GetKeyID(keyID)) + throw JSONRPCError(-3, "Address does not refer to a key"); + CSecret vchSecret; + bool fCompressed; + if (!pwalletMain->GetSecret(keyID, vchSecret, fCompressed)) + throw JSONRPCError(-4,"Private key for address " + strAddress + " is not known"); + return CBitcoinSecret(vchSecret, fCompressed).ToString(); +} diff --git a/pool/shard009/C++/0106941_PageParser.cpp b/pool/shard009/C++/0106941_PageParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe3424f9d6fd6b99e406cb022bb1ed4d892dc15e --- /dev/null +++ b/pool/shard009/C++/0106941_PageParser.cpp @@ -0,0 +1,23 @@ +#include "PageParser.hpp" + +#include +#include + +namespace bmrk { + +PageParser::PageParser(const String& html) : doc_{new CDocument} { + if (html.empty()) { + throw Error{"Empty document"}; + } + doc_->parse(html.c_str()); +} + +String PageParser::getTitle() const { + auto&& node = doc_->find("head title").nodeAt(0); + if (!node.valid()) { + throw Error{"Cannot parse title"}; + } + return node.text(); +} + +} /* bmrk */ diff --git a/pool/shard009/C++/0106946_vbucketmap.cc b/pool/shard009/C++/0106946_vbucketmap.cc new file mode 100644 index 0000000000000000000000000000000000000000..4abf08423f378741ec08483698f860aabb3d491e --- /dev/null +++ b/pool/shard009/C++/0106946_vbucketmap.cc @@ -0,0 +1,201 @@ +/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* + * Copyright 2015 Couchbase, Inc + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "vbucketmap.h" +#include "bucket_logger.h" +#include "ep_engine.h" +#include "kv_bucket.h" +#include +#include + +VBucketMap::VBucketMap(Configuration& config, KVBucket& store) + : size(config.getMaxVbuckets()) { + auto& engine = store.getEPEngine(); + const auto numShards = engine.getWorkLoadPolicy().getNumShards(); + for (size_t shardId = 0; shardId < numShards; shardId++) { + shards.push_back(std::make_unique(engine, shardId)); + } + + config.addValueChangedListener( + "hlc_drift_ahead_threshold_us", + std::make_unique(*this)); + config.addValueChangedListener( + "hlc_drift_behind_threshold_us", + std::make_unique(*this)); +} + +VBucketPtr VBucketMap::getBucket(Vbid id) const { + if (id.get() < size) { + return getShardByVbId(id)->getBucket(id); + } else { + return {}; + } +} + +ENGINE_ERROR_CODE VBucketMap::addBucket(VBucketPtr vb) { + if (vb->getId().get() < size) { + getShardByVbId(vb->getId())->setBucket(vb); + ++vbStateCount[vb->getState() - vbucket_state_active]; + EP_LOG_DEBUG("Mapped new {} in state {}", + vb->getId(), + VBucket::toString(vb->getState())); + return ENGINE_SUCCESS; + } + EP_LOG_WARN("Cannot create {}, max vbuckets is {}", vb->getId(), size); + return ENGINE_ERANGE; +} + +void VBucketMap::enablePersistence(EPBucket& ep) { + for (auto& shard : shards) { + shard->enablePersistence(ep); + } +} + +void VBucketMap::dropVBucketAndSetupDeferredDeletion(Vbid id, + const void* cookie) { + if (id.get() < size) { + getShardByVbId(id)->dropVBucketAndSetupDeferredDeletion(id, cookie); + } +} + +std::vector VBucketMap::getBuckets() const { + std::vector rv; + for (size_t i = 0; i < size; ++i) { + VBucketPtr b(getBucket(Vbid(i))); + if (b) { + rv.push_back(b->getId()); + } + } + return rv; +} + +std::vector VBucketMap::getBucketsSortedByState() const { + std::vector rv; + for (int state = vbucket_state_active; + state <= vbucket_state_dead; ++state) { + for (size_t i = 0; i < size; ++i) { + VBucketPtr b = getBucket(Vbid(i)); + if (b && b->getState() == state) { + rv.push_back(b->getId()); + } + } + } + return rv; +} + +std::vector VBucketMap::getBucketsInState(vbucket_state_t state) const { + std::vector rv; + for (size_t i = 0; i < size; ++i) { + VBucketPtr b = getBucket(Vbid(i)); + if (b && b->getState() == state) { + rv.push_back(b->getId()); + } + } + return rv; +} + +std::vector> VBucketMap::getVBucketsSortedByChkMgrMem() const { + std::vector> rv; + for (size_t i = 0; i < size; ++i) { + VBucketPtr b = getBucket(Vbid(i)); + if (b) { + rv.push_back(std::make_pair(b->getId(), b->getChkMgrMemUsage())); + } + } + + struct SortCtx { + static bool compareSecond(std::pair a, + std::pair b) { + return (a.second < b.second); + } + }; + + std::sort(rv.begin(), rv.end(), SortCtx::compareSecond); + + return rv; +} + +size_t VBucketMap::getVBucketsTotalCheckpointMemoryUsage() const { + size_t checkpointMemoryUsage = 0; + for (size_t i = 0; i < size; ++i) { + VBucketPtr b = getBucket(Vbid(i)); + if (b) { + checkpointMemoryUsage += b->getChkMgrMemUsage(); + } + } + return checkpointMemoryUsage; +} + +KVShard* VBucketMap::getShardByVbId(Vbid id) const { + return shards[id.get() % shards.size()].get(); +} + +KVShard* VBucketMap::getShard(KVShard::id_type shardId) const { + return shards[shardId].get(); +} + +size_t VBucketMap::getNumShards() const { + return shards.size(); +} + +void VBucketMap::setHLCDriftAheadThreshold(std::chrono::microseconds threshold) { + for (size_t id = 0; id < size; id++) { + auto vb = getBucket(Vbid(id)); + if (vb) { + vb->setHLCDriftAheadThreshold(threshold); + } + } +} + +void VBucketMap::setHLCDriftBehindThreshold(std::chrono::microseconds threshold) { + for (size_t id = 0; id < size; id++) { + auto vb = getBucket(Vbid(id)); + if (vb) { + vb->setHLCDriftBehindThreshold(threshold); + } + } +} + +void VBucketMap::VBucketConfigChangeListener::sizeValueChanged(const std::string &key, + size_t value) { + if (key == "hlc_drift_ahead_threshold_us") { + map.setHLCDriftAheadThreshold(std::chrono::microseconds(value)); + } else if (key == "hlc_drift_behind_threshold_us") { + map.setHLCDriftBehindThreshold(std::chrono::microseconds(value)); + } +} + +vbucket_state_t VBucketMap::setState(VBucket& vb, + vbucket_state_t newState, + const nlohmann::json* meta) { + folly::SharedMutex::WriteHolder vbStateLock(vb.getStateLock()); + return setState_UNLOCKED(vb, newState, meta, vbStateLock); +} + +vbucket_state_t VBucketMap::setState_UNLOCKED( + VBucket& vb, + vbucket_state_t newState, + const nlohmann::json* meta, + folly::SharedMutex::WriteHolder& vbStateLock) { + vbucket_state_t oldState = vb.getState(); + vb.setState_UNLOCKED(newState, meta, vbStateLock); + + decVBStateCount(oldState); + incVBStateCount(newState); + + return oldState; +} diff --git a/pool/shard009/C++/0106949_qaudiopluginloader.cpp b/pool/shard009/C++/0106949_qaudiopluginloader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5619b30eb21d5a31701c11cd2e78f30d7aff7af --- /dev/null +++ b/pool/shard009/C++/0106949_qaudiopluginloader.cpp @@ -0,0 +1,170 @@ +/**************************************************************************** +** +** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with +** the Software or, alternatively, in accordance with the terms +** contained in a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qaudiosystemplugin.h" +#include "qaudiopluginloader_p.h" + +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +QAudioPluginLoader::QAudioPluginLoader(const char *iid, const QString &location, Qt::CaseSensitivity): + m_iid(iid) +{ + m_location = location + "/"; + load(); +} + +QAudioPluginLoader::~QAudioPluginLoader() +{ + for (int i = 0; i < m_plugins.count(); i++ ) { + delete m_plugins.at(i); + } +} + +QStringList QAudioPluginLoader::pluginList() const +{ +#if !defined QT_NO_DEBUG + const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0; +#endif + + QStringList paths = QApplication::libraryPaths(); +#ifdef QTM_PLUGIN_PATH + paths << QLatin1String(QTM_PLUGIN_PATH); +#endif +#if !defined QT_NO_DEBUG + if (showDebug) + qDebug() << "Plugin paths:" << paths; +#endif + + //temp variable to avoid multiple identic path + QSet processed; + + /* Discover a bunch o plugins */ + QStringList plugins; + + /* Enumerate our plugin paths */ + for (int i=0; i < paths.count(); i++) { + if (processed.contains(paths.at(i))) + continue; + processed.insert(paths.at(i)); + QDir pluginsDir(paths.at(i)+m_location); + if (!pluginsDir.exists()) + continue; + + QStringList files = pluginsDir.entryList(QDir::Files); +#if !defined QT_NO_DEBUG + if (showDebug) + qDebug()<<"Looking for plugins in "<(&m_mutex)); + + QStringList list; + for (int i = 0; i < m_plugins.count(); i++) { + QAudioSystemPlugin* p = qobject_cast(m_plugins.at(i)->instance()); + if (p) list << p->keys(); + } + + return list; +} + +QObject* QAudioPluginLoader::instance(QString const &key) +{ + QMutexLocker locker(&m_mutex); + + for (int i = 0; i < m_plugins.count(); i++) { + QAudioSystemPlugin* p = qobject_cast(m_plugins.at(i)->instance()); + if (p && p->keys().contains(key)) + return m_plugins.at(i)->instance(); + } + return 0; +} + +QList QAudioPluginLoader::instances(QString const &key) +{ + QMutexLocker locker(&m_mutex); + + QList list; + for (int i = 0; i < m_plugins.count(); i++) { + QAudioSystemPlugin* p = qobject_cast(m_plugins.at(i)->instance()); + if (p && p->keys().contains(key)) + list << m_plugins.at(i)->instance(); + } + return list; +} + +void QAudioPluginLoader::load() +{ + if (!m_plugins.isEmpty()) + return; + + QStringList plugins = pluginList(); + for (int i=0; i < plugins.count(); i++) { + QPluginLoader* loader = new QPluginLoader(plugins.at(i)); + QObject *o = loader->instance(); + if (o != 0 && o->qt_metacast(m_iid) != 0) + m_plugins.append(loader); + else { + qWarning() << "QAudioPluginLoader: Failed to load plugin: " + << plugins.at(i) << loader->errorString(); + } + } +} +QT_END_NAMESPACE + diff --git a/pool/shard009/C++/0106950_RPLidarTest.cpp b/pool/shard009/C++/0106950_RPLidarTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68c8a6ee07e95d9e54b1adb2a4f237bb89b514f5 --- /dev/null +++ b/pool/shard009/C++/0106950_RPLidarTest.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace eeros; +using namespace eeros::safety; +using namespace eeros::control; +using namespace eeros::logger; +using namespace eeros::task; + +double period = 0.01; + +void signalHandler(int signum){ + SafetySystem::exitHandler(); +} + +class ControlSystem { + public: + ControlSystem() : lidar("/dev/ttyUSB1"), td("td", period, true) { + td.addBlock(lidar); + } + RPLidarInput lidar; + TimeDomain td; +}; + +class PPSafetyProperties : public SafetyProperties { + public: + PPSafetyProperties() : slState1("state 1") { + addLevel(slState1); + setEntryLevel(slState1); + }; + SafetyLevel slState1; +}; + +int main() { + Logger::setDefaultStreamLogger(std::cout); + Logger log = Logger::getLogger(); + log.info() << "Program started - Read out RP Lidar sensors data"; + + ControlSystem cs; + Periodic p1("p1", period, cs.td); + PPSafetyProperties sp; + SafetySystem ss(sp, period); + + // create periodic function for logging + Lambda l1 ([&] () { }); + Periodic p2("p2", period, l1); + p2.monitors.push_back([&](PeriodicCounter &pc, Logger &log) { + log.info() << cs.lidar.getOut(0).getSignal().getValue() << ", " + << cs.lidar.getOut(1).getSignal().getValue(); + }); + + auto& executor = Executor::instance(); + executor.setMainTask(ss); + p1.after.push_back(p2); // make sure that logging happens after running of path planner + executor.add(p1); + executor.run(); + + log.info() << "Program finished..."; + return 0; +} + + + diff --git a/pool/shard009/C++/0106952_tst_preferenciastest.cpp b/pool/shard009/C++/0106952_tst_preferenciastest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf8cde5867cc45637e76a151efa4c9bbde8c8d2c --- /dev/null +++ b/pool/shard009/C++/0106952_tst_preferenciastest.cpp @@ -0,0 +1,50 @@ +#include +#include +#include + +#include "preferencias.h" +#include "formprefdb.h" + +class PreferenciasTest : public QObject +{ + Q_OBJECT + +private Q_SLOTS: + void initTestCase(); + void cleanupTestCase(); + void testGuardarPreferencias(); + + private: + preferencias *p; + FormPrefDb *form; + +}; + +void PreferenciasTest::initTestCase() +{ + p = preferencias::getInstancia(); + form = new FormPrefDb(); +} + +void PreferenciasTest::cleanupTestCase() +{ + p=0; + delete form; +} + +void PreferenciasTest::testGuardarPreferencias() +{ + form->cargar(); + form->CkBPuerto->setChecked( false ); + form->guardar(); + p->inicio(); + p->beginGroup( "Preferencias" ); + p->beginGroup( "General" ); + p->beginGroup( "mysql" ); + QCOMPARE( false, p->contains( "puerto" ) ); +} + +QTEST_MAIN(PreferenciasTest) + +#include "tst_preferenciastest.moc" + diff --git a/pool/shard009/C++/0106953_MSP430RegisterInfo.cpp b/pool/shard009/C++/0106953_MSP430RegisterInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..614467bcd24845c06d4ae76b09adfda0c2fa45b7 --- /dev/null +++ b/pool/shard009/C++/0106953_MSP430RegisterInfo.cpp @@ -0,0 +1,162 @@ +//===-- MSP430RegisterInfo.cpp - MSP430 Register Information --------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +// This file contains the MSP430 implementation of the TargetRegisterInfo class. +// +//===----------------------------------------------------------------------===// + +#include "MSP430RegisterInfo.h" +#include "MSP430.h" +#include "MSP430MachineFunctionInfo.h" +#include "MSP430TargetMachine.h" +#include "llvm/ADT/BitVector.h" +#include "llvm/CodeGen/MachineFrameInfo.h" +#include "llvm/CodeGen/MachineFunction.h" +#include "llvm/CodeGen/MachineInstrBuilder.h" +#include "llvm/IR/Function.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Target/TargetMachine.h" +#include "llvm/Target/TargetOptions.h" + +using namespace llvm; + +#define DEBUG_TYPE "msp430-reg-info" + +#define GET_REGINFO_TARGET_DESC +#include "MSP430GenRegisterInfo.inc" + +// FIXME: Provide proper call frame setup / destroy opcodes. +MSP430RegisterInfo::MSP430RegisterInfo() + : MSP430GenRegisterInfo(MSP430::PC) {} + +const MCPhysReg* +MSP430RegisterInfo::getCalleeSavedRegs(const MachineFunction *MF) const { + const TargetFrameLowering *TFI = MF->getSubtarget().getFrameLowering(); + const Function* F = MF->getFunction(); + static const MCPhysReg CalleeSavedRegs[] = { + MSP430::FP, MSP430::R5, MSP430::R6, MSP430::R7, + MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + 0 + }; + static const MCPhysReg CalleeSavedRegsFP[] = { + MSP430::R5, MSP430::R6, MSP430::R7, + MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + 0 + }; + static const MCPhysReg CalleeSavedRegsIntr[] = { + MSP430::FP, MSP430::R5, MSP430::R6, MSP430::R7, + MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15, + 0 + }; + static const MCPhysReg CalleeSavedRegsIntrFP[] = { + MSP430::R5, MSP430::R6, MSP430::R7, + MSP430::R8, MSP430::R9, MSP430::R10, MSP430::R11, + MSP430::R12, MSP430::R13, MSP430::R14, MSP430::R15, + 0 + }; + + if (TFI->hasFP(*MF)) + return (F->getCallingConv() == CallingConv::MSP430_INTR ? + CalleeSavedRegsIntrFP : CalleeSavedRegsFP); + else + return (F->getCallingConv() == CallingConv::MSP430_INTR ? + CalleeSavedRegsIntr : CalleeSavedRegs); + +} + +BitVector MSP430RegisterInfo::getReservedRegs(const MachineFunction &MF) const { + BitVector Reserved(getNumRegs()); + const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); + + // Mark 4 special registers with subregisters as reserved. + Reserved.set(MSP430::PCB); + Reserved.set(MSP430::SPB); + Reserved.set(MSP430::SRB); + Reserved.set(MSP430::CGB); + Reserved.set(MSP430::PC); + Reserved.set(MSP430::SP); + Reserved.set(MSP430::SR); + Reserved.set(MSP430::CG); + + // Mark frame pointer as reserved if needed. + if (TFI->hasFP(MF)) { + Reserved.set(MSP430::FPB); + Reserved.set(MSP430::FP); + } + + return Reserved; +} + +const TargetRegisterClass * +MSP430RegisterInfo::getPointerRegClass(const MachineFunction &MF, unsigned Kind) + const { + return &MSP430::GR16RegClass; +} + +void +MSP430RegisterInfo::eliminateFrameIndex(MachineBasicBlock::iterator II, + int SPAdj, unsigned FIOperandNum, + RegScavenger *RS) const { + assert(SPAdj == 0 && "Unexpected"); + + MachineInstr &MI = *II; + MachineBasicBlock &MBB = *MI.getParent(); + MachineFunction &MF = *MBB.getParent(); + const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); + DebugLoc dl = MI.getDebugLoc(); + int FrameIndex = MI.getOperand(FIOperandNum).getIndex(); + + unsigned BasePtr = (TFI->hasFP(MF) ? MSP430::FP : MSP430::SP); + int Offset = MF.getFrameInfo()->getObjectOffset(FrameIndex); + + // Skip the saved PC + Offset += 2; + + if (!TFI->hasFP(MF)) + Offset += MF.getFrameInfo()->getStackSize(); + else + Offset += 2; // Skip the saved FP + + // Fold imm into offset + Offset += MI.getOperand(FIOperandNum + 1).getImm(); + + if (MI.getOpcode() == MSP430::ADD16ri) { + // This is actually "load effective address" of the stack slot + // instruction. We have only two-address instructions, thus we need to + // expand it into mov + add + const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); + + MI.setDesc(TII.get(MSP430::MOV16rr)); + MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); + + if (Offset == 0) + return; + + // We need to materialize the offset via add instruction. + unsigned DstReg = MI.getOperand(0).getReg(); + if (Offset < 0) + BuildMI(MBB, std::next(II), dl, TII.get(MSP430::SUB16ri), DstReg) + .addReg(DstReg).addImm(-Offset); + else + BuildMI(MBB, std::next(II), dl, TII.get(MSP430::ADD16ri), DstReg) + .addReg(DstReg).addImm(Offset); + + return; + } + + MI.getOperand(FIOperandNum).ChangeToRegister(BasePtr, false); + MI.getOperand(FIOperandNum + 1).ChangeToImmediate(Offset); +} + +unsigned MSP430RegisterInfo::getFrameRegister(const MachineFunction &MF) const { + const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); + + return TFI->hasFP(MF) ? MSP430::FP : MSP430::SP; +} diff --git a/pool/shard009/C++/0106956_helpers.cpp b/pool/shard009/C++/0106956_helpers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88b553c827974b19bea528e4fe2ddcc2ef2b0aac --- /dev/null +++ b/pool/shard009/C++/0106956_helpers.cpp @@ -0,0 +1,328 @@ + +#include "builtin/object.hpp" +#include "call_frame.hpp" +#include "builtin/autoload.hpp" +#include "builtin/symbol.hpp" +#include "builtin/module.hpp" +#include "builtin/compiledmethod.hpp" +#include "builtin/class.hpp" +#include "builtin/staticscope.hpp" +#include "builtin/lookuptable.hpp" +#include "global_cache.hpp" +#include "objectmemory.hpp" +#include "builtin/tuple.hpp" +#include "builtin/system.hpp" +#include "builtin/thread.hpp" +#include "builtin/channel.hpp" +#include "builtin/global_cache_entry.hpp" +#include "builtin/methodtable.hpp" +#include "builtin/location.hpp" + +#include "vm.hpp" +#include "object_utils.hpp" +#include "arguments.hpp" +#include "call_frame.hpp" +#include "lookup_data.hpp" + +#include "on_stack.hpp" + +#include "helpers.hpp" + +namespace rubinius { + namespace Helpers { + Object* const_get_under(STATE, Module* mod, Symbol* name, bool* found) { + Object* res; + + *found = false; + + while(!mod->nil_p()) { + res = mod->get_const(state, name, found); + if(*found) return res; + + // Don't stop when you see Object, because we need to check any + // includes into Object as well, and they're found via superclass + mod = mod->superclass(); + } + + return cNil; + } + + Object* const_get(STATE, CallFrame* call_frame, Symbol* name, bool* found) { + StaticScope *cur; + Object* result; + + *found = false; + + call_frame = call_frame->top_ruby_frame(); + + // Ok, this has to be explained or it will be considered black magic. + // The scope chain always ends with an entry at the top that contains + // a parent of nil, and a module of Object. This entry is put in + // regardless of lexical scoping, it's the default scope. + // + // When looking up a constant, we don't want to consider the default + // scope (ie, Object) initially because we need to lookup up + // the superclass chain first, because falling back on the default. + // + // The rub comes from the fact that if a user explicitly opens up + // Object in their code, we DO consider it. Like: + // + // class Idiot + // A = 2 + // end + // + // class ::Object + // A = 1 + // class Stupid < Idiot + // def foo + // p A + // end + // end + // end + // + // In this code, when A is looked up, Object must be considering during + // the scope walk, NOT during the superclass walk. + // + // So, in this case, foo would print "1", not "2". + // + cur = call_frame->static_scope(); + while(!cur->nil_p()) { + // Detect the toplevel scope (the default) and get outta dodge. + if(cur->top_level_p(state)) break; + + result = cur->module()->get_const(state, name, found); + if(*found) return result; + + cur = cur->parent(); + } + + // Now look up the superclass chain. + cur = call_frame->static_scope(); + if(!cur->nil_p()) { + Module* mod = cur->module(); + while(!mod->nil_p()) { + result = mod->get_const(state, name, found); + if(*found) return result; + + mod = mod->superclass(); + } + } + + // Lastly, check Object specifically + result = G(object)->get_const(state, name, found, true); + if(*found) return result; + + return cNil; + } + + Object* const_missing_under(STATE, Module* under, Symbol* sym, CallFrame* call_frame) { + Array* args = Array::create(state, 1); + args->set(state, 0, sym); + return under->send(state, call_frame, G(sym_const_missing), args); + } + + Object* const_missing(STATE, Symbol* sym, CallFrame* call_frame) { + Module* under; + + call_frame = call_frame->top_ruby_frame(); + + StaticScope* scope = call_frame->static_scope(); + if(scope->nil_p()) { + under = G(object); + } else { + under = scope->module(); + } + + Array* args = Array::create(state, 1); + args->set(state, 0, sym); + return under->send(state, call_frame, G(sym_const_missing), args); + } + + /** @todo Remove redundancy between this and sends. --rue */ + Tuple* locate_method_on(STATE, CallFrame* call_frame, Object* recv, Symbol* name, Object* priv) { + LookupData lookup(recv, recv->lookup_begin(state), CBOOL(priv) ? G(sym_private) : G(sym_protected)); + Dispatch dis(name); + + if(!GlobalCache::resolve(state, dis.name, dis, lookup)) { + return nil(); + } + + return Tuple::from(state, 2, dis.method, dis.module); + } + + Class* open_class(STATE, CallFrame* call_frame, Object* super, Symbol* name, bool* created) { + Module* under; + + call_frame = call_frame->top_ruby_frame(); + + if(call_frame->static_scope()->nil_p()) { + under = G(object); + } else { + under = call_frame->static_scope()->module(); + } + + return open_class(state, call_frame, under, super, name, created); + } + + static Class* add_class(STATE, Module* under, Object* super, Symbol* name) { + if(super->nil_p()) super = G(object); + Class* cls = Class::create(state, as(super)); + + cls->set_name(state, name, under); + under->set_const(state, name, cls); + + return cls; + } + + static Class* check_superclass(STATE, CallFrame* call_frame, Class* cls, Object* super) { + if(super->nil_p()) return cls; + if(cls->true_superclass(state) != super) { + std::ostringstream message; + message << "Superclass mismatch: given " + << as(super)->debug_str(state) + << " but previously set to " + << cls->true_superclass(state)->debug_str(state); + Exception* exc = + Exception::make_type_error(state, Class::type, super, message.str().c_str()); + exc->locations(state, Location::from_call_stack(state, call_frame)); + state->raise_exception(exc); + return NULL; + } + + return cls; + } + + Class* open_class(STATE, CallFrame* call_frame, Module* under, Object* super, Symbol* name, bool* created) { + bool found; + + *created = false; + + Object* obj = under->get_const(state, name, &found); + if(found) { + TypedRoot sup(state, super); + + if(Autoload* autoload = try_as(obj)) { + obj = autoload->resolve(state, call_frame, true); + + // Check if an exception occurred + if(!obj) return NULL; + } + + // Autoload::resolve will return nil if code loading failed, in which + // case we ignore the autoload. + if(!obj->nil_p()) { + return check_superclass(state, call_frame, as(obj), sup.get()); + } + } + + *created = true; + return add_class(state, under, super, name); + } + + Module* open_module(STATE, CallFrame* call_frame, Symbol* name) { + Module* under = G(object); + + call_frame = call_frame->top_ruby_frame(); + + if(!call_frame->static_scope()->nil_p()) { + under = call_frame->static_scope()->module(); + } + + return open_module(state, call_frame, under, name); + } + + Module* open_module(STATE, CallFrame* call_frame, Module* under, Symbol* name) { + Module* module; + bool found; + + Object* obj = under->get_const(state, name, &found); + + if(found) { + if(Autoload* autoload = try_as(obj)) { + obj = autoload->resolve(state, call_frame, true); + } + + // Check if an exception occurred + if(!obj) return NULL; + + // Autoload::resolve will return nil if code loading failed, in which + // case we ignore the autoload. + if(!obj->nil_p()) { + return as(obj); + } + } + + module = Module::create(state); + + module->set_name(state, name, under); + under->set_const(state, name, module); + + return module; + } + + bool yield_debugger(STATE, GCToken gct, CallFrame* call_frame, Object* bp) { + Thread* cur = Thread::current(state); + Thread* debugger = cur->debugger_thread(); + + // No debugger, bail. + if(debugger->nil_p()) { + std::cout << "no debugger\n"; + return true; + } + + Channel* debugger_chan = debugger->control_channel(); + + // Debugger not initialized? bail. + if(debugger_chan->nil_p()) { + std::cout << "no debugger channel\n"; + return true; + } + + // No one waiting on it? Well, nevermind then. + if(!debugger_chan->has_readers_p()) { + std::cout << "no waiters\n"; + return true; + } + + // If we're hitting here, clear any chance that step would be used + // without being explicitly requested. + state->vm()->clear_thread_step(); + + state->set_call_frame(call_frame); + + Channel* my_control = cur->control_channel(); + + // Lazily create our own control channel. + if(my_control->nil_p()) { + my_control = Channel::create(state); + cur->control_channel(state, my_control); + } + + Array* locs = Location::from_call_stack(state, call_frame, true, true); + + OnStack<1> os(state, my_control); + + debugger_chan->send(state, gct, + Tuple::from(state, 4, bp, cur, my_control, locs)); + + // Block until the debugger wakes us back up. + Object* ret = my_control->receive(state, gct, call_frame); + + // Do not access any locals other than ret beyond here unless you add OnStack<> + // to them! The GC has probably run and moved things. + + // if ret is null, then receive was interrupted and there is an exception + // to propagate. + if(!ret) return false; + + // Process a few commands... + if(ret == state->symbol("step")) { + state->vm()->get_attention(); + state->vm()->set_thread_step(); + } + + // All done! + return true; + } + } +} diff --git a/pool/shard009/C++/0106962_keys.cpp b/pool/shard009/C++/0106962_keys.cpp new file mode 100644 index 0000000000000000000000000000000000000000..502ea1b30e9e573012f9914ffd920a013274f7d1 --- /dev/null +++ b/pool/shard009/C++/0106962_keys.cpp @@ -0,0 +1,103 @@ +/* Copyright 2013 - 2015 Matvey Bryksin, Yurii Litvinov and CyberTech Labs 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. */ + +#include "keys.h" + +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) + #include +#else + #include +#endif + +#include + +#include + +#include "keysWorker.h" + +using namespace trikControl; + +Keys::Keys(const trikKernel::Configurer &configurer, const trikHal::HardwareAbstractionInterface &hardwareAbstraction) + : mState("Keys") +{ + mKeysWorker.reset(new KeysWorker(configurer.attributeByDevice("keys", "deviceFile"), mState, hardwareAbstraction)); + if (!mState.isFailed()) { + connect(mKeysWorker.data(), SIGNAL(buttonPressed(int, int)), this, SIGNAL(buttonPressed(int, int))); + connect(mKeysWorker.data(), SIGNAL(buttonPressed(int, int)), this, SLOT(changeButtonState(int, int))); + mKeysWorker->moveToThread(&mWorkerThread); + mWorkerThread.start(); + mState.ready(); + } +} + +Keys::~Keys() +{ + if (mWorkerThread.isRunning()) { + mWorkerThread.quit(); + mWorkerThread.wait(); + } +} + +Keys::Status Keys::status() const +{ + return mState.status(); +} + +void Keys::reset() +{ + mKeysWorker->reset(); +} + +bool Keys::wasPressed(int code) +{ + return mKeysWorker->wasPressed(code); +} + +bool Keys::isPressed(int code) +{ + return mKeysPressed.value(code, false); +} + +void Keys::changeButtonState(int code, int value) +{ + mKeysPressed[code] = value; +} + +int Keys::buttonCode(bool wait) +{ + if (!wait) { + return pressedButton(); + } + + while (true) { + int code = pressedButton(); + if (code == -1) { + usleep(20); + QApplication::processEvents(); + } else { + return code; + } + } +} + +int Keys::pressedButton() +{ + for (int button : mKeysPressed.keys()) { + if (mKeysPressed[button]) { + return button; + } + } + + return -1; +} diff --git a/pool/shard009/C++/0106964_unit-test-semantic-actions.cpp b/pool/shard009/C++/0106964_unit-test-semantic-actions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2f9f4c284a23e5fcf29c27b4a066c68be5c960f8 --- /dev/null +++ b/pool/shard009/C++/0106964_unit-test-semantic-actions.cpp @@ -0,0 +1,131 @@ +// unit-test-semantic-actions.cpp +// Started 14 Aug 2018 +#include "pch-Unit-Tests.hpp" +namespace client { + namespace qi = boost::spirit::qi; + namespace ascii = boost::spirit::ascii; + + template + struct int_parser : qi::grammar + { + typedef int_parser This; + int result = 0; + void set_result(int i) { result = i; } + qi::rule start; + + int_parser() + : base_type{ start } + { + start = qi::lit('<') + >> qi::int_[boost::bind(&This::set_result, this, _1)] + >> qi::lit('>'); + } + }; + + + template + struct coords_parser : qi::grammar + { + typedef coords_parser This; + std::pair result{}; + void set_first(double x) { result.first = x; } + void set_second(double y) { result.second = y; } + qi::rule start; + + coords_parser() + : base_type{ start } + { + start = qi::lit('(') + >> qi::double_[boost::bind(&This::set_first, this, _1)] + >> qi::lit(',') + >> qi::double_[boost::bind(&This::set_second, this, _1)] + >> qi::lit(')'); + } + }; + + + template + struct assignment_parser : qi::grammar + { + typedef assignment_parser This; + typedef std::pair Result_Type; + Result_Type result{}; + void append_head(char x) { result.first += x; } + void set_head(std::vector x) { result.first.assign(x.begin(), x.end()); } + void set_tail(std::vector y) { result.second.assign(y.begin(), y.end()); } + qi::rule start; + qi::rule head; + qi::rule tail; + + assignment_parser() + : base_type{ start } + { + auto head = qi::lexeme[+ascii::alnum[boost::bind(&This::append_head, this, _1)]]; + // [boost::bind(&This::append_head, this, _1)] + // auto tail = qi::lit('"') >> qi::no_skip[*(qi::char_ - '"')] >> qi::lit('"'); + // auto tail = qi::no_skip[*(qi::char_ - '"')]; + + auto tail = qi::lexeme[*qi::char_]; + // [boost::bind(&This::set_tail, this, _1)] + // Logger::WriteMessage(typeid(tail).name()); + // auto start = head >> qi::lit('=') >> tail; + start = head; // >> tail; + } + }; + +} + + +namespace UnitTests { + using namespace Microsoft::VisualStudio::CppUnitTestFramework; + // For test macros see: + // C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\VS\UnitTest\include\CppUnitTestAssert.h + + TEST_CLASS(unit_test_semantic_actions) + { + public: + TEST_METHOD(int_parser_semantic_action) + { + namespace qi = boost::spirit::qi; + namespace ascii = boost::spirit::ascii; + const std::string str = " <22> "; + typedef std::string::const_iterator StringIterator; + client::int_parser grammar; + StringIterator itr = str.begin(), end = str.end(); + Assert::IsTrue(qi::phrase_parse(itr, end, grammar, ascii::space)); + Assert::AreEqual(22, grammar.result); + } + + TEST_METHOD(double_parser_semantic_action) + { + namespace qi = boost::spirit::qi; + namespace ascii = boost::spirit::ascii; + const std::string str = " ( 11 , 22.3 ) "; + typedef std::string::const_iterator StringIterator; + client::coords_parser grammar; + StringIterator itr = str.begin(), end = str.end(); + Assert::IsTrue(qi::phrase_parse(itr, end, grammar, ascii::space)); + Assert::AreEqual(std::make_pair(11.0, 22.3), grammar.result); + } + +#if 0 + TEST_METHOD(assignment_parser_semantic_action) + { + namespace qi = boost::spirit::qi; + namespace ascii = boost::spirit::ascii; + typedef std::string::const_iterator StringIterator; + typedef client::assignment_parser Grammar; + Grammar parser; + Grammar::Result_Type expected{ "white","horse" }; + const std::string str = " white horse "; + StringIterator itr = str.begin(), end = str.end(); + Assert::IsTrue(qi::phrase_parse(itr, end, parser, ascii::space)); + Logger::WriteMessage("assignment_parser_semantic_action"); + Logger::WriteMessage(parser.result.first.c_str()); + Logger::WriteMessage(parser.result.second.c_str()); + // Assert::AreEqual(expected, parser.result); + } +#endif + + }; +} diff --git a/pool/shard009/C++/0106966_DNSServer.cpp b/pool/shard009/C++/0106966_DNSServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..92ab14d0d0f4d7cd16aaa29e35cef84740434854 --- /dev/null +++ b/pool/shard009/C++/0106966_DNSServer.cpp @@ -0,0 +1,165 @@ +#include "./DNSServer.h" +#include +#include + +#define DEBUG +#define DEBUG_OUTPUT Serial + +DNSServer::DNSServer() +{ + _ttl = htonl(60); + _errorReplyCode = DNSReplyCode::NonExistentDomain; +} + +bool DNSServer::start(const uint16_t &port, const String &domainName, + const IPAddress &resolvedIP) +{ + _port = port; + _domainName = domainName; + _resolvedIP[0] = resolvedIP[0]; + _resolvedIP[1] = resolvedIP[1]; + _resolvedIP[2] = resolvedIP[2]; + _resolvedIP[3] = resolvedIP[3]; + downcaseAndRemoveWwwPrefix(_domainName); + return _udp.begin(_port) == 1; +} + +void DNSServer::setErrorReplyCode(const DNSReplyCode &replyCode) +{ + _errorReplyCode = replyCode; +} + +void DNSServer::setTTL(const uint32_t &ttl) +{ + _ttl = htonl(ttl); +} + +void DNSServer::stop() +{ + _udp.stop(); +} + +void DNSServer::downcaseAndRemoveWwwPrefix(String &domainName) +{ + domainName.toLowerCase(); + domainName.replace("www.", ""); +} + +void DNSServer::processNextRequest() +{ + _currentPacketSize = _udp.parsePacket(); + if (_currentPacketSize) + { + _buffer = (unsigned char*)malloc(_currentPacketSize * sizeof(char)); + _udp.read(_buffer, _currentPacketSize); + _dnsHeader = (DNSHeader*) _buffer; + + if (_dnsHeader->QR == DNS_QR_QUERY && + _dnsHeader->OPCode == DNS_OPCODE_QUERY && + requestIncludesOnlyOneQuestion() && + (_domainName == "*" || getDomainNameWithoutWwwPrefix() == _domainName) + ) + { + replyWithIP(); + } + else if (_dnsHeader->QR == DNS_QR_QUERY) + { + replyWithCustomCode(); + } + + free(_buffer); + } +} + +bool DNSServer::requestIncludesOnlyOneQuestion() +{ + return ntohs(_dnsHeader->QDCount) == 1 && + _dnsHeader->ANCount == 0 && + _dnsHeader->NSCount == 0 && + _dnsHeader->ARCount == 0; +} + +String DNSServer::getDomainNameWithoutWwwPrefix() +{ + String parsedDomainName = ""; + unsigned char *start = _buffer + 12; + if (*start == 0) + { + return parsedDomainName; + } + int pos = 0; + while(true) + { + unsigned char labelLength = *(start + pos); + for(int i = 0; i < labelLength; i++) + { + pos++; + parsedDomainName += (char)*(start + pos); + } + pos++; + if (*(start + pos) == 0) + { + downcaseAndRemoveWwwPrefix(parsedDomainName); + return parsedDomainName; + } + else + { + parsedDomainName += "."; + } + } +} + +void DNSServer::replyWithIP() +{ + _dnsHeader->QR = DNS_QR_RESPONSE; + _dnsHeader->ANCount = _dnsHeader->QDCount; + _dnsHeader->QDCount = _dnsHeader->QDCount; + //_dnsHeader->RA = 1; + + _udp.beginPacket(_udp.remoteIP(), _udp.remotePort()); + _udp.write(_buffer, _currentPacketSize); + + _udp.write((uint8_t)192); // answer name is a pointer + _udp.write((uint8_t)12); // pointer to offset at 0x00c + + _udp.write((uint8_t)0); // 0x0001 answer is type A query (host address) + _udp.write((uint8_t)1); + + _udp.write((uint8_t)0); //0x0001 answer is class IN (internet address) + _udp.write((uint8_t)1); + + _udp.write((unsigned char*)&_ttl, 4); + + // Length of RData is 4 bytes (because, in this case, RData is IPv4) + _udp.write((uint8_t)0); + _udp.write((uint8_t)4); + _udp.write(_resolvedIP, sizeof(_resolvedIP)); + _udp.endPacket(); + + + + #ifdef DEBUG + DEBUG_OUTPUT.print("DNS responds: "); + DEBUG_OUTPUT.print(_resolvedIP[0]); + DEBUG_OUTPUT.print("."); + DEBUG_OUTPUT.print(_resolvedIP[1]); + DEBUG_OUTPUT.print("."); + DEBUG_OUTPUT.print(_resolvedIP[2]); + DEBUG_OUTPUT.print("."); + DEBUG_OUTPUT.print(_resolvedIP[3]); + DEBUG_OUTPUT.print(" for "); + DEBUG_OUTPUT.println(getDomainNameWithoutWwwPrefix()); + #endif +} + +void DNSServer::replyWithCustomCode() +{ + _dnsHeader->QR = DNS_QR_RESPONSE; + _dnsHeader->RCode = (unsigned char)_errorReplyCode; + _dnsHeader->QDCount = 0; + + _udp.beginPacket(_udp.remoteIP(), _udp.remotePort()); + _udp.write(_buffer, sizeof(DNSHeader)); + _udp.endPacket(); +} + diff --git a/pool/shard009/C++/0106978_14.40.cpp b/pool/shard009/C++/0106978_14.40.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f59da2dfc84f94386f0017040830db35e29e329d --- /dev/null +++ b/pool/shard009/C++/0106978_14.40.cpp @@ -0,0 +1,61 @@ +// based on ex10.16.cpp +#include +#include +#include +#include + +std::string make_plural(size_t ctr, const std::string &word, + const std::string &ending = "s") { + return (ctr > 1) ? word + ending : word; +} + +void elimDups(std::vector &words) { + std::sort(words.begin(), words.end()); + auto end_unique = std::unique(words.begin(), words.end()); + words.erase(end_unique, words.end()); +} + +struct Shorter { + bool operator()(const std::string &s1, const std::string &s2) const { + return s1.size() < s2.size(); + } +}; + +struct Longer { + Longer(size_t size) : sz(size) { } + bool operator()(const std::string &s) const { return s.size() >= sz; } + +private: + size_t sz; +}; + +struct PrintString { + PrintString(std::ostream &o = std::cout, char d = ' ') + : os(o), delimiter(d) { } + void operator()(const std::string &s) const { os << s << delimiter; } + +private: + std::ostream &os; + char delimiter; +}; + +void biggies(std::vector words, // use value instead of reference + std::vector::size_type sz) { + elimDups(words); + std::stable_sort(words.begin(), words.end(), Shorter()); + auto iter = std::find_if(words.begin(), words.end(), Longer(sz)); + auto count = words.end() - iter; + std::cout << count << " " << make_plural(count, "word") << " of length " + << sz << " or longer." << std::endl; + std::for_each(iter, words.end(), PrintString()); +} + +int main() { + std::vector words; + for (std::string s; std::cin >> s; words.push_back(s)) { } + biggies(words, 3); + std::cout << std::endl; + biggies(words, 5); + + return 0; +} diff --git a/pool/shard009/C++/0106979_11305-3.cc b/pool/shard009/C++/0106979_11305-3.cc new file mode 100644 index 0000000000000000000000000000000000000000..f4087704f533b83f5e0f19a0bfd309b389fd5bb3 --- /dev/null +++ b/pool/shard009/C++/0106979_11305-3.cc @@ -0,0 +1,46 @@ +// { dg-require-namedlocale "en_US.UTF-8" } + +// Copyright (C) 2003-2013 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// 27.8.1.4 Overridden virtual functions + +#include +#include +#include + +void test03() +{ + using namespace std; + bool test __attribute__((unused)) = true; + + wfilebuf fb; + locale loc(locale("en_US.UTF-8")); + fb.pubimbue(loc); + fb.open("tmp_11305-3", ios_base::out); + wfilebuf::int_type n1 = fb.sputc(0x20000000); + wfilebuf* f = fb.close(); + + VERIFY( n1 != wfilebuf::traits_type::eof() ); + VERIFY( f ); +} + +int main() +{ + test03(); + return 0; +} diff --git a/pool/shard009/C++/0106983_demo_main.cc b/pool/shard009/C++/0106983_demo_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..ea86753f8b31843163c46af831adb3eb1024556f --- /dev/null +++ b/pool/shard009/C++/0106983_demo_main.cc @@ -0,0 +1,206 @@ +// 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/at_exit.h" +#include "base/command_line.h" +#include "base/i18n/icu_util.h" +#include "base/macros.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop/message_loop.h" +#include "base/power_monitor/power_monitor.h" +#include "base/power_monitor/power_monitor_device_source.h" +#include "build/build_config.h" +#include "third_party/skia/include/core/SkXfermode.h" +#include "ui/aura/client/default_capture_client.h" +#include "ui/aura/client/window_tree_client.h" +#include "ui/aura/env.h" +#include "ui/aura/test/test_focus_client.h" +#include "ui/aura/test/test_screen.h" +#include "ui/aura/window.h" +#include "ui/aura/window_delegate.h" +#include "ui/aura/window_tree_host.h" +#include "ui/base/hit_test.h" +#include "ui/compositor/paint_recorder.h" +#include "ui/compositor/test/in_process_context_factory.h" +#include "ui/events/event.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/skia_util.h" +#include "ui/gl/gl_surface.h" + +#if defined(USE_X11) +#include "ui/gfx/x/x11_connection.h" // nogncheck +#endif + +#if defined(OS_WIN) +#include "ui/gfx/win/dpi.h" +#endif + +namespace { + +// Trivial WindowDelegate implementation that draws a colored background. +class DemoWindowDelegate : public aura::WindowDelegate { + public: + explicit DemoWindowDelegate(SkColor color) : color_(color) {} + + // Overridden from WindowDelegate: + gfx::Size GetMinimumSize() const override { return gfx::Size(); } + + gfx::Size GetMaximumSize() const override { return gfx::Size(); } + + void OnBoundsChanged(const gfx::Rect& old_bounds, + const gfx::Rect& new_bounds) override { + window_bounds_ = new_bounds; + } + gfx::NativeCursor GetCursor(const gfx::Point& point) override { + return gfx::kNullCursor; + } + int GetNonClientComponent(const gfx::Point& point) const override { + return HTCAPTION; + } + bool ShouldDescendIntoChildForEventHandling( + aura::Window* child, + const gfx::Point& location) override { + return true; + } + bool CanFocus() override { return true; } + void OnCaptureLost() override {} + void OnPaint(const ui::PaintContext& context) override { + ui::PaintRecorder recorder(context, window_bounds_.size()); + recorder.canvas()->DrawColor(color_, SkXfermode::kSrc_Mode); + gfx::Rect r; + recorder.canvas()->GetClipBounds(&r); + // Fill with a non-solid color so that the compositor will exercise its + // texture upload path. + while (!r.IsEmpty()) { + r.Inset(2, 2); + recorder.canvas()->FillRect(r, color_, SkXfermode::kXor_Mode); + } + } + void OnDeviceScaleFactorChanged(float device_scale_factor) override {} + void OnWindowDestroying(aura::Window* window) override {} + void OnWindowDestroyed(aura::Window* window) override {} + void OnWindowTargetVisibilityChanged(bool visible) override {} + bool HasHitTestMask() const override { return false; } + void GetHitTestMask(gfx::Path* mask) const override {} + + private: + SkColor color_; + gfx::Rect window_bounds_; + + DISALLOW_COPY_AND_ASSIGN(DemoWindowDelegate); +}; + +class DemoWindowTreeClient : public aura::client::WindowTreeClient { + public: + explicit DemoWindowTreeClient(aura::Window* window) : window_(window) { + aura::client::SetWindowTreeClient(window_, this); + } + + ~DemoWindowTreeClient() override { + aura::client::SetWindowTreeClient(window_, nullptr); + } + + // Overridden from aura::client::WindowTreeClient: + aura::Window* GetDefaultParent(aura::Window* context, + aura::Window* window, + const gfx::Rect& bounds) override { + if (!capture_client_) { + capture_client_.reset( + new aura::client::DefaultCaptureClient(window_->GetRootWindow())); + } + return window_; + } + + private: + aura::Window* window_; + + scoped_ptr capture_client_; + + DISALLOW_COPY_AND_ASSIGN(DemoWindowTreeClient); +}; + +int DemoMain() { +#if defined(USE_X11) + // This demo uses InProcessContextFactory which uses X on a separate Gpu + // thread. + gfx::InitializeThreadedX11(); +#endif + + gfx::GLSurface::InitializeOneOff(); + +#if defined(OS_WIN) + gfx::SetDefaultDeviceScaleFactor(1.0f); +#endif + + // The ContextFactory must exist before any Compositors are created. + bool context_factory_for_test = false; + scoped_ptr context_factory( + new ui::InProcessContextFactory(context_factory_for_test, nullptr)); + context_factory->set_use_test_surface(false); + + // Create the message-loop here before creating the root window. + base::MessageLoopForUI message_loop; + + base::PowerMonitor power_monitor(make_scoped_ptr( + new base::PowerMonitorDeviceSource)); + + aura::Env::CreateInstance(true); + aura::Env::GetInstance()->set_context_factory(context_factory.get()); + scoped_ptr test_screen( + aura::TestScreen::Create(gfx::Size())); + gfx::Screen::SetScreenInstance(test_screen.get()); + scoped_ptr host( + test_screen->CreateHostForPrimaryDisplay()); + scoped_ptr window_tree_client( + new DemoWindowTreeClient(host->window())); + aura::test::TestFocusClient focus_client; + aura::client::SetFocusClient(host->window(), &focus_client); + + // Create a hierarchy of test windows. + gfx::Rect window1_bounds(100, 100, 400, 400); + DemoWindowDelegate window_delegate1(SK_ColorBLUE); + aura::Window window1(&window_delegate1); + window1.set_id(1); + window1.Init(ui::LAYER_TEXTURED); + window1.SetBounds(window1_bounds); + window1.Show(); + aura::client::ParentWindowWithContext(&window1, host->window(), gfx::Rect()); + + gfx::Rect window2_bounds(200, 200, 350, 350); + DemoWindowDelegate window_delegate2(SK_ColorRED); + aura::Window window2(&window_delegate2); + window2.set_id(2); + window2.Init(ui::LAYER_TEXTURED); + window2.SetBounds(window2_bounds); + window2.Show(); + aura::client::ParentWindowWithContext(&window2, host->window(), gfx::Rect()); + + gfx::Rect window3_bounds(10, 10, 50, 50); + DemoWindowDelegate window_delegate3(SK_ColorGREEN); + aura::Window window3(&window_delegate3); + window3.set_id(3); + window3.Init(ui::LAYER_TEXTURED); + window3.SetBounds(window3_bounds); + window3.Show(); + window2.AddChild(&window3); + + host->Show(); + base::MessageLoopForUI::current()->Run(); + + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + base::CommandLine::Init(argc, argv); + + // The exit manager is in charge of calling the dtors of singleton objects. + base::AtExitManager exit_manager; + + base::i18n::InitializeICU(); + + return DemoMain(); +} diff --git a/pool/shard009/C++/0106991_DlgFilesSetup.cpp b/pool/shard009/C++/0106991_DlgFilesSetup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5efa4c2db4bb389bb615fca33e6a7bfd306f810d --- /dev/null +++ b/pool/shard009/C++/0106991_DlgFilesSetup.cpp @@ -0,0 +1,155 @@ +#include "Uvs2.h" +#pragma hdrstop + +class TextCompareCtrl; + +#define LAYOUTFILE +#include + +class ExtendedButton : public FrameRight