diff --git a/pool/shard011/C++/0121588_pty_util.cc b/pool/shard011/C++/0121588_pty_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..351f4730c27e9d4a8645831c5e022dc4787d7567 --- /dev/null +++ b/pool/shard011/C++/0121588_pty_util.cc @@ -0,0 +1,58 @@ +// Copyright 2019 The gVisor Authors. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "test/util/pty_util.h" + +#include +#include + +#include "test/util/file_descriptor.h" +#include "test/util/posix_error.h" + +namespace gvisor { +namespace testing { + +PosixErrorOr OpenReplica(const FileDescriptor& master) { + return OpenReplica(master, O_NONBLOCK | O_RDWR | O_NOCTTY); +} + +PosixErrorOr OpenReplica(const FileDescriptor& master, + int flags) { + PosixErrorOr n = ReplicaID(master); + if (!n.ok()) { + return PosixErrorOr(n.error()); + } + return Open(absl::StrCat("/dev/pts/", n.ValueOrDie()), flags); +} + +PosixErrorOr ReplicaID(const FileDescriptor& master) { + // Get pty index. + int n; + int ret = ioctl(master.get(), TIOCGPTN, &n); + if (ret < 0) { + return PosixError(errno, "ioctl(TIOCGPTN) failed"); + } + + // Unlock pts. + int unlock = 0; + ret = ioctl(master.get(), TIOCSPTLCK, &unlock); + if (ret < 0) { + return PosixError(errno, "ioctl(TIOSPTLCK) failed"); + } + + return n; +} + +} // namespace testing +} // namespace gvisor diff --git a/pool/shard011/C++/0121589_NMR_ModelReaderNode093_Color.cpp b/pool/shard011/C++/0121589_NMR_ModelReaderNode093_Color.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6758f811380a4ce2a2e472fc46ca8a05a2e4c062 --- /dev/null +++ b/pool/shard011/C++/0121589_NMR_ModelReaderNode093_Color.cpp @@ -0,0 +1,168 @@ +/*++ + +Copyright (C) 2018 3MF Consortium + +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Abstract: +NMR_ModelReaderNode093_Color.cpp implements the Model Reader Color Node Class. +A color reader model node is a parser for the color node of an XML Model Stream. + +--*/ + +#include "Model/Reader/v093/NMR_ModelReaderNode093_Color.h" + +#include "Model/Classes/NMR_ModelConstants.h" +#include "Common/NMR_Exception.h" +#include "Common/NMR_Exception_Windows.h" +#include "Common/NMR_StringUtils.h" +#include +#include + +namespace NMR { + + CModelReaderNode093_Color::CModelReaderNode093_Color(_In_ PModelWarnings pWarnings) + : CModelReaderNode(pWarnings) + { + m_nResourceID = 0; + m_nTextureID = 0; + } + + void CModelReaderNode093_Color::parseXML(_In_ CXmlReader * pXMLReader) + { + // Parse name + parseName(pXMLReader); + + // Parse attribute + parseAttributes(pXMLReader); + + // Parse Content + parseContent(pXMLReader); + + // Parse Color + parseColor(); + } + + nfColor CModelReaderNode093_Color::retrieveColor() + { + return m_cColor; + } + + void CModelReaderNode093_Color::parseColor() + { + m_cColor = 0; + + try { + if (m_sColorString.length() > 0) { + nfChar bFirstChar = m_sColorString[0]; + if (bFirstChar == '#') { + if (fnStringToSRGBColor(m_sColorString.c_str(), m_cColor)) { + return; + } + } + + if (bFirstChar == 's') { + std::string sSubStr = m_sColorString.substr(0, 5); + if (sSubStr == "scRGB") { + // parse scRGB String + throw CNMRException(NMR_ERROR_NOTIMPLEMENTED); + } + } + + if (bFirstChar == L't') { + std::string sSubStr = m_sColorString.substr(0, 4); + if (sSubStr == "tex(") { + // parse Texture String + + if (m_sColorString.length() > 4) { + std::string sTexID = m_sColorString.substr(4, m_sColorString.length() - sSubStr.length() - 1); + nfInt32 nValue = fnStringToInt32(sTexID.c_str()); + if ((nValue < 0) || (nValue >= XML_3MF_MAXRESOURCEINDEX)) + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + + m_nTextureID = nValue + 1; + return; + } + else { + throw CNMRException(NMR_ERROR_INVALIDTEXTUREREFERENCE); + } + } + } + + if (bFirstChar == 'C') { + std::string sSubStr4 = m_sColorString.substr(0, 4); + if (sSubStr4 == "CMYK") { + throw CNMRException(NMR_ERROR_NOTSUPPORTINGLEGACYCMYK); + } + } + + } + + throw CNMRException(NMR_ERROR_INVALIDVALUEINCOLORSTRING); + } + catch (CNMRException & Exception) { + m_pWarnings->addException(Exception, mrwMissingMandatoryValue); + } + + } + + + ModelResourceID CModelReaderNode093_Color::retrieveID() + { + try { + //if (m_nUniqueResourceID == 0) + //throw CNMRException(NMR_ERROR_MISSINGMODELCOLORID); + } + catch (CNMRException & Exception) { + m_pWarnings->addException(Exception, mrwMissingMandatoryValue); + } + + return m_nResourceID; + } + + void CModelReaderNode093_Color::OnAttribute(_In_z_ const nfChar * pAttributeName, _In_z_ const nfChar * pAttributeValue) + { + __NMRASSERT(pAttributeName); + __NMRASSERT(pAttributeValue); + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLOR_VALUE) == 0) { + m_sColorString = pAttributeValue; + } + + if (strcmp(pAttributeName, XML_3MF_ATTRIBUTE_COLOR_ID) == 0) { + if (m_nResourceID != 0) + throw CNMRException(NMR_ERROR_DUPLICATECOLORID); + + // Convert to integer and make a input and range check! + m_nResourceID = fnStringToUint32(pAttributeValue); + m_nResourceID++; + } + + } + + ModelResourceID CModelReaderNode093_Color::retrieveTextureID() + { + return m_nTextureID; + } + +} diff --git a/pool/shard011/C++/0121590_flowtab.cpp b/pool/shard011/C++/0121590_flowtab.cpp new file mode 100644 index 0000000000000000000000000000000000000000..365bed9b0f42298cf4fa03621a44ca3fb4cc3b06 --- /dev/null +++ b/pool/shard011/C++/0121590_flowtab.cpp @@ -0,0 +1,99 @@ +/************************************************************************* +* Copyright (c) 2015, Synopsys, Inc. * +* All rights reserved. * +* * +* Redistribution and use in source and binary forms, with or without * +* modification, are permitted provided that the following conditions are * +* met: * +* * +* 1. Redistributions of source code must retain the above copyright * +* notice, this list of conditions and the following disclaimer. * +* * +* 2. Redistributions in binary form must reproduce the above copyright * +* notice, this list of conditions and the following disclaimer in the * +* documentation and/or other materials provided with the distribution. * +* * +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * +* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * +* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * +* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * +* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * +*************************************************************************/ +// FlowTab.cpp : implementation file +// + +#include "stdafx.h" +#include "discovermdi.h" +#include "FlowTab.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CFlowTab + +CFlowTab::CFlowTab() +{ +} + +CFlowTab::~CFlowTab() +{ +} + + +BEGIN_MESSAGE_MAP(CFlowTab, CTabCtrl) + //{{AFX_MSG_MAP(CFlowTab) + ON_WM_LBUTTONDOWN() + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CFlowTab message handlers + +void CFlowTab::OnLButtonDown(UINT nFlags, CPoint point) { +int* elements; +POINT p; +int item; +TC_HITTESTINFO test; + + p.x=point.x; + p.y=point.y; + test.pt.x=p.x; + test.pt.y=p.y; + test.flags=TCHT_NOWHERE; + item=HitTest(&test); + if(item==-1) return; + SetCurSel(item); + + // Register or get clipboard format for the task flow node + UINT formatID=RegisterClipboardFormat("DiscoverTaskFlowNode"); + // Alocate memory for all selected elements indexes. + // The DragAndDrop Target will receve this array + HGLOBAL dataID = GlobalAlloc(GMEM_FIXED,3*sizeof(int)); + elements = (int *)::GlobalLock(dataID); + // Fill an array with the selected elements + elements[0]=OP_MOVE; + elements[1]=1; + elements[2]=item; + GlobalUnlock(dataID); + m_DropSource.CacheGlobalData(formatID, dataID); + m_DropSource.DoDragDrop(); + + + NMHDR info; + info.hwndFrom=*this; + info.idFrom=GetWindowLong(*this,GWL_ID); + info.code=TCN_SELCHANGE; + SetFocus(); + GetParent()->SendMessage(WM_NOTIFY,(WPARAM)GetWindowLong(*this,GWL_ID),(LPARAM)&info); +} + diff --git a/pool/shard011/C++/0121591_MeanSquaredLogError.cpp b/pool/shard011/C++/0121591_MeanSquaredLogError.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0afe1db38791a59e5913b516566cf15d2b511560 --- /dev/null +++ b/pool/shard011/C++/0121591_MeanSquaredLogError.cpp @@ -0,0 +1,45 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * Written (W) 2012 Heiko Strathmann + * Copyright (C) 2012 Berlin Institute of Technology and Max-Planck-Society + */ + +#include +#include +#include +#include + +using namespace shogun; + +float64_t CMeanSquaredLogError::evaluate(CLabels* predicted, CLabels* ground_truth) +{ + ASSERT(predicted && ground_truth); + ASSERT(predicted->get_num_labels()==ground_truth->get_num_labels()); + ASSERT(predicted->get_label_type()==LT_REGRESSION); + ASSERT(ground_truth->get_label_type()==LT_REGRESSION); + + int32_t length=predicted->get_num_labels(); + float64_t msle=0.0; + for (int32_t i=0; iget_label(i); + float64_t truth=((CRegressionLabels*) ground_truth)->get_label(i); + + if (prediction<=-1.0 || truth<=-1.0) + { + SG_WARNING("Negative label[%d] in %s is not allowed, ignoring!\n", + i, get_name()); + continue; + } + + float64_t a=CMath::log(prediction+1); + float64_t b=CMath::log(truth+1); + msle+=CMath::sq(a-b); + } + msle /= length; + return CMath::sqrt(msle); +} diff --git a/pool/shard011/C++/0121592_User.cc b/pool/shard011/C++/0121592_User.cc new file mode 100644 index 0000000000000000000000000000000000000000..af3abbecb9802b98c5131f0cbbbf378a64f5fcc2 --- /dev/null +++ b/pool/shard011/C++/0121592_User.cc @@ -0,0 +1,95 @@ +/* + * Copyright (C) 1996-2015 The Squid Software Foundation and contributors + * + * Squid software is distributed under GPLv2+ license and includes + * contributions from numerous individuals and organizations. + * Please see the COPYING and CONTRIBUTORS files for details. + */ + +#include "squid.h" +#include "auth/basic/Config.h" +#include "auth/basic/User.h" +#include "auth/CredentialsCache.h" +#include "Debug.h" +#include "SquidConfig.h" +#include "SquidTime.h" + +Auth::Basic::User::User(Auth::Config *aConfig, const char *aRequestRealm) : + Auth::User(aConfig, aRequestRealm), + passwd(NULL), + queue(NULL), + currentRequest(NULL) +{} + +Auth::Basic::User::~User() +{ + safe_free(passwd); +} + +int32_t +Auth::Basic::User::ttl() const +{ + if (credentials() != Auth::Ok && credentials() != Auth::Pending) + return -1; // TTL is obsolete NOW. + + int32_t basic_ttl = expiretime - squid_curtime + static_cast(config)->credentialsTTL; + int32_t global_ttl = static_cast(expiretime - squid_curtime + ::Config.authenticateTTL); + + return min(basic_ttl, global_ttl); +} + +bool +Auth::Basic::User::authenticated() const +{ + if ((credentials() == Auth::Ok) && (expiretime + static_cast(config)->credentialsTTL > squid_curtime)) + return true; + + debugs(29, 4, "User not authenticated or credentials need rechecking."); + + return false; +} + +bool +Auth::Basic::User::valid() const +{ + if (username() == NULL) + return false; + if (passwd == NULL) + return false; + return true; +} + +void +Auth::Basic::User::updateCached(Auth::Basic::User *from) +{ + debugs(29, 9, HERE << "Found user '" << from->username() << "' already in the user cache as '" << this << "'"); + + assert(strcmp(from->username(), username()) == 0); + + if (strcmp(from->passwd, passwd)) { + debugs(29, 4, HERE << "new password found. Updating in user master record and resetting auth state to unchecked"); + credentials(Auth::Unchecked); + xfree(passwd); + passwd = from->passwd; + from->passwd = NULL; + } + + if (credentials() == Auth::Failed) { + debugs(29, 4, HERE << "last attempt to authenticate this user failed, resetting auth state to unchecked"); + credentials(Auth::Unchecked); + } +} + +CbcPointer +Auth::Basic::User::Cache() +{ + static CbcPointer p(new Auth::CredentialsCache("basic", "GC Basic user credentials")); + return p; +} + +void +Auth::Basic::User::addToNameCache() +{ + Cache()->insert(userKey(), this); +} + diff --git a/pool/shard011/C++/0121595_RenderLayerFilterInfo.cpp b/pool/shard011/C++/0121595_RenderLayerFilterInfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7746bd4ae08b3826a51219db76ada72702647064 --- /dev/null +++ b/pool/shard011/C++/0121595_RenderLayerFilterInfo.cpp @@ -0,0 +1,136 @@ +/* + * Copyright (C) 2012 Adobe Systems Incorporated. All rights reserved. + * Copyright (C) 2013 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above + * copyright notice, this list of conditions and the following + * disclaimer. + * 2. Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, + * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR + * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF + * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +#include "config.h" +#include "RenderLayerFilterInfo.h" + +#include "CachedSVGDocument.h" +#include "CachedSVGDocumentReference.h" +#include "FilterEffectRenderer.h" +#include "RenderSVGResourceFilter.h" +#include + +namespace WebCore { + +HashMap>& RenderLayer::FilterInfo::map() +{ + static NeverDestroyed>> map; + return map; +} + +RenderLayer::FilterInfo* RenderLayer::FilterInfo::getIfExists(const RenderLayer& layer) +{ + ASSERT(layer.m_hasFilterInfo == map().contains(&layer)); + + return layer.m_hasFilterInfo ? map().get(&layer) : nullptr; +} + +RenderLayer::FilterInfo& RenderLayer::FilterInfo::get(RenderLayer& layer) +{ + ASSERT(layer.m_hasFilterInfo == map().contains(&layer)); + + auto& info = map().add(&layer, nullptr).iterator->value; + if (!info) { + info = std::make_unique(layer); + layer.m_hasFilterInfo = true; + } + return *info; +} + +void RenderLayer::FilterInfo::remove(RenderLayer& layer) +{ + ASSERT(layer.m_hasFilterInfo == map().contains(&layer)); + if (!layer.m_hasFilterInfo) + return; + + map().remove(&layer); + layer.m_hasFilterInfo = false; +} + +RenderLayer::FilterInfo::FilterInfo(RenderLayer& layer) + : m_layer(layer) +{ +} + +RenderLayer::FilterInfo::~FilterInfo() +{ + removeReferenceFilterClients(); +} + +void RenderLayer::FilterInfo::setRenderer(RefPtr&& renderer) +{ + m_renderer = renderer; +} + +void RenderLayer::FilterInfo::notifyFinished(CachedResource&) +{ + m_layer.filterNeedsRepaint(); +} + +void RenderLayer::FilterInfo::updateReferenceFilterClients(const FilterOperations& operations) +{ + removeReferenceFilterClients(); + for (auto& operation : operations.operations()) { + if (!is(*operation)) + continue; + auto& referenceOperation = downcast(*operation); + auto* documentReference = referenceOperation.cachedSVGDocumentReference(); + if (auto* cachedSVGDocument = documentReference ? documentReference->document() : nullptr) { + // Reference is external; wait for notifyFinished(). + cachedSVGDocument->addClient(*this); + m_externalSVGReferences.append(cachedSVGDocument); + } else { + // Reference is internal; add layer as a client so we can trigger filter repaint on SVG attribute change. + auto* filter = m_layer.renderer().document().getElementById(referenceOperation.fragment()); + if (!filter) + continue; + auto* renderer = filter->renderer(); + if (!is(renderer)) + continue; + downcast(*renderer).addClientRenderLayer(&m_layer); + m_internalSVGReferences.append(filter); + } + } +} + +void RenderLayer::FilterInfo::removeReferenceFilterClients() +{ + for (auto& resourceHandle : m_externalSVGReferences) + resourceHandle->removeClient(*this); + m_externalSVGReferences.clear(); + + for (auto& filter : m_internalSVGReferences) { + if (auto* renderer = filter->renderer()) + downcast(*renderer).removeClientRenderLayer(&m_layer); + } + m_internalSVGReferences.clear(); +} + +} // namespace WebCore diff --git a/pool/shard011/C++/0121596_TestAudioAC3toMP2.cpp b/pool/shard011/C++/0121596_TestAudioAC3toMP2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71d8000430ac2d4284c2e37b3c4f96a02cb3fec7 --- /dev/null +++ b/pool/shard011/C++/0121596_TestAudioAC3toMP2.cpp @@ -0,0 +1,159 @@ +/* + * File: TestAudioAC3toMP2.cpp + * Author: jhoelscher + * + * Created on 15. Juni 2009, 18:31 + */ + +#include "org/esb/io/File.h" +#include "org/esb/av/FormatInputStream.h" +#include "org/esb/av/PacketInputStream.h" +#include "org/esb/av/FormatOutputStream.h" +#include "org/esb/av/PacketOutputStream.h" +#include "org/esb/av/Packet.h" +#include "org/esb/av/Encoder.h" +#include "org/esb/av/Decoder.h" +#include "org/esb/av/Frame.h" +#include "org/esb/av/FrameConverter.h" +#include "org/esb/util/Decimal.h" + + +#include "org/esb/io/FileInputStream.h" +#include "org/esb/io/FileOutputStream.h" +//#include "org/esb/lang/StackDumper.h" +#include +using namespace org::esb::io; +using namespace org::esb::av; +using namespace org::esb::util; +using namespace org::esb::lang; + +class PacketSink : public Sink { +public: + + PacketSink() { + } + + void write(void * p) { + + LOGDEBUG("Write Packet to Term Sink"); + Packet* pt = (Packet*) p; + boost::shared_ptr pEnc(new Packet(*pt)); + pkts.push_back(pEnc); + } + + std::list > getList() { + return pkts; + } +private: + std::list > pkts; + +}; + +int main(int argc, char ** argv) { +// StackDumper stack("."); + // int stream_id = 2; + // File infile("/media/video/ChocolateFactory.ts"); + // File infile("/home/jhoelscher/MediaEncodingCluster/big_buck_bunny_480p_surround-fix.avi"); + std::string src; + + if (argc == 1) { + src = MEC_SOURCE_DIR; + src.append("/test.dvd"); + } else { + src = argv[1]; + } + int stream_id = 1; + if (argc == 3) { + stream_id = atoi(argv[2]); + } + + File infile(src); +// int stream_id = atoi(argv[2]); + File outfile("test.mp3"); + + FormatInputStream fis(&infile); + fis.dumpFormat(); + PacketInputStream pis(&fis); + + FormatOutputStream fos(&outfile); + PacketOutputStream pos(&fos); + + AVCodecContext * c = fis.getFormatContext()->streams[stream_id]->codec; + Decoder dec(c->codec_id); //CODEC_ID_EAC3 + LOGDEBUG("ChannelLayout:" << fis.getFormatContext()->streams[stream_id]->codec->channel_layout) + // Decoder dec(c); + + + dec.setChannels(c->channels); + // dec.setChannels(2); + dec.setBitRate(c->bit_rate); + dec.setSampleRate(c->sample_rate); + dec.setSampleFormat(c->sample_fmt); + dec.setTimeBase(c->time_base); + + + dec.ctx->request_channels = 2; + // dec.ctx->request_channel_layout = 2; + dec.open(); + + + + LOGDEBUG(dec.toString()); + + // Encoder enc(CODEC_ID_VORBIS); + Encoder enc(CODEC_ID_MP3); + enc.setChannels(2); + enc.setBitRate(128000); + enc.setSampleRate(48000); + enc.setSampleFormat(dec.getSampleFormat()); + AVRational ar; + ar.num = 1; + ar.den = enc.getSampleRate(); + enc.setTimeBase(ar); + // enc.setFlag(CODEC_FLAG_GLOBAL_HEADER); + // enc.setPixelFormat(PIX_FMT_YUV420P); + // enc.ctx->bits_per_raw_sample=dec.ctx + enc.open(); + LOGDEBUG(enc.toString()); + LOGDEBUG("Encoder Frame Size:" << enc.ctx->frame_size); + + + pos.setEncoder(enc, 0); + pos.init(); + + FrameConverter conv(&dec, &enc); + PacketSink sink; + enc.setSink(&sink); +// enc.setOutputStream(&pos); + Packet p; + for (int a = 0; a < 1000; ) { + + pis.readPacket(p); + if (p.getStreamIndex() == stream_id) { + a++; + p.setStreamIndex(0); + p.toString(); + Frame * tmp = dec.decode2(p); + tmp->toString(); + + // continue; + if (!tmp->isFinished()) { + continue; + } + Frame * f = new Frame(); + conv.convert(*tmp, *f); + f->toString(); + // pos.writePacket(p); + enc.encode(*f); + delete tmp; + delete f; + + } + } + list< boost::shared_ptr > encoded = sink.getList(); + list< boost::shared_ptr >::iterator it = encoded.begin(); + for (; it != encoded.end(); it++) { + pos.writePacket(*(*it).get()); + } + Log::close(); +} diff --git a/pool/shard011/C++/0121597_resolve_reduce_attributes.cc b/pool/shard011/C++/0121597_resolve_reduce_attributes.cc new file mode 100644 index 0000000000000000000000000000000000000000..c3246ab90fc49290181f7055cf51337c61630ff3 --- /dev/null +++ b/pool/shard011/C++/0121597_resolve_reduce_attributes.cc @@ -0,0 +1,76 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include +#include +#include +#include + +#include "tensorflow/contrib/lite/toco/graph_transformations/graph_transformations.h" +#include "tensorflow/contrib/lite/toco/model.h" +#include "tensorflow/contrib/lite/toco/tooling_util.h" +#include "tensorflow/core/platform/logging.h" + +namespace toco { + +template +bool ResolveAttributes(Model* model, T* op) { + if (!op->axis.empty()) { + // Attributes already resolved + return false; + } + if (op->inputs.size() != 2) return false; + if (!IsConstantParameterArray(*model, op->inputs[1])) return false; + + const Array& indices_array = model->GetArray(op->inputs[1]); + if (!indices_array.has_shape()) return false; + op->axis = indices_array.GetBuffer().data; + return true; +} + +::tensorflow::Status ResolveReduceAttributes::Run(Model* model, + std::size_t op_index, + bool* modified) { + *modified = false; + Operator* op = model->operators[op_index].get(); + switch (op->type) { + case OperatorType::kMean: + *modified = ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + case OperatorType::kSum: + *modified = + ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + case OperatorType::kReduceProd: + *modified = + ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + case OperatorType::kReduceMin: + *modified = + ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + case OperatorType::kReduceMax: + *modified = + ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + case OperatorType::kAny: + *modified = + ResolveAttributes(model, static_cast(op)); + return ::tensorflow::Status::OK(); + default: + return ::tensorflow::Status::OK(); + } +} + +} // namespace toco diff --git a/pool/shard011/C++/0121599_gsl_distribution.cpp b/pool/shard011/C++/0121599_gsl_distribution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f7365611283b1a97b6876cba1fa5d4f042cab61a --- /dev/null +++ b/pool/shard011/C++/0121599_gsl_distribution.cpp @@ -0,0 +1,150 @@ +//#include "stdafx.h" +#include +#include +#include +#include +#include +#include +#include + + +namespace { +namespace local { + +void unit_gaussian_distribution() +{ + // + { + const int N = 1000; + std::vector data; + data.reserve(N); + for (int i = 0; i < N; ++i) + data.push_back(gsl_ran_ugaussian_pdf(-3.0 + 6.0 * i / N)); + } + + // + { + const double x = 2.0; + + const double P = gsl_cdf_ugaussian_P(x); + std::cout << "prob(x < " << x << ") = " << P << std::endl; + + const double Q = gsl_cdf_ugaussian_Q(x); + std::cout << "prob(x < " << x << ") = " << Q << std::endl; + + const double xp = gsl_cdf_ugaussian_Pinv(P); + std::cout << "Pinv(" << P << ") = " << xp << std::endl; + + const double xq = gsl_cdf_ugaussian_Qinv(Q); + std::cout << "Qinv(" << Q << ") = " << xq << std::endl; + } +} + +void gaussian_distribution() +{ + // + { + const double sigma = 2.0; + + const int N = 1000; + std::vector data; + data.reserve(N); + for (int i = 0; i < N; ++i) + data.push_back(gsl_ran_gaussian_pdf(-3.0 + 6.0 * i / N, sigma)); + } + + // + { + const double sigma = 2.0; + const double x = 2.0; + + const double P = gsl_cdf_gaussian_P(x, sigma); + std::cout << "prob(x < " << x << ") = " << P << std::endl; + + const double Q = gsl_cdf_gaussian_Q(x, sigma); + std::cout << "prob(x < " << x << ") = " << Q << std::endl; + + const double xp = gsl_cdf_gaussian_Pinv(P, sigma); + std::cout << "Pinv(" << P << ") = " << xp << std::endl; + + const double xq = gsl_cdf_gaussian_Qinv(Q, sigma); + std::cout << "Qinv(" << Q << ") = " << xq << std::endl; + } +} + +void bivariate_gaussian_distribution() +{ + { + const double mu_x = -1.0, mu_y = 2.0, sigma_x = 2.0, sigma_y = std::sqrt(3.0), sigma_xy = -2.25, rho = sigma_xy / (sigma_x * sigma_y); + const double x = 0.5, y = 1.5; + std::cout << "p([0.5, 1.5] | [-1.0, 2.0], [4.0, -2.25 ; -2.25, 3.0]) = " << gsl_ran_bivariate_gaussian_pdf(x - mu_x, y - mu_y, sigma_x, sigma_y, rho) << std::endl; + } + + { + const double mu_x = 1.0, mu_y = -1.0, sigma_x = std::sqrt(0.9), sigma_y = std::sqrt(0.3), sigma_xy = 0.4, rho = sigma_xy / (sigma_x * sigma_y); + const double x = 0.5, y = -0.5; + std::cout << "p([0.5, -0.5] | [1.0, -1.0], [0.9, 0.4 ; 0.4, 0.3]) = " << gsl_ran_bivariate_gaussian_pdf(x - mu_x, y - mu_y, sigma_x, sigma_y, rho) << std::endl; + } +} + +void multivariate_gaussian_distribution() +{ + { + gsl_vector *mu = gsl_vector_alloc(2); + gsl_matrix *covL = gsl_matrix_alloc(2, 2); + gsl_vector *x = gsl_vector_alloc(2); + gsl_vector *work = gsl_vector_alloc(2); + + gsl_vector_set(mu, 0, -1.0); gsl_vector_set(mu, 1, 2.0); + gsl_matrix_set(covL, 0, 0, 4.0); gsl_matrix_set(covL, 0, 1, -2.25); gsl_matrix_set(covL, 1, 0, -2.25); gsl_matrix_set(covL, 1, 1, 3.0); + gsl_vector_set(x, 0, 0.5); gsl_vector_set(x, 1, 1.5); + + gsl_linalg_cholesky_decomp(covL); + + double pdf = 0.0; + gsl_ran_multivariate_gaussian_pdf(x, mu, covL, &pdf, work); + std::cout << "p([0.5, 1.5] | [-1.0, 2.0], [4.0, -2.25 ; -2.25, 3.0]) = " << pdf << std::endl; + + gsl_vector_free(mu); + gsl_matrix_free(covL); + gsl_vector_free(x); + gsl_vector_free(work); + } + + { + gsl_vector *mu = gsl_vector_alloc(2); + gsl_matrix *covL = gsl_matrix_alloc(2, 2); + gsl_vector *x = gsl_vector_alloc(2); + gsl_vector *work = gsl_vector_alloc(2); + + gsl_vector_set(mu, 0, 1.0); gsl_vector_set(mu, 1, -1.0); + gsl_matrix_set(covL, 0, 0, 0.9); gsl_matrix_set(covL, 0, 1, 0.4); gsl_matrix_set(covL, 1, 0, 0.4); gsl_matrix_set(covL, 1, 1, 0.3); + gsl_vector_set(x, 0, 0.5); gsl_vector_set(x, 1, -0.5); + + gsl_linalg_cholesky_decomp(covL); + + double pdf = 0.0; + gsl_ran_multivariate_gaussian_pdf(x, mu, covL, &pdf, work); + std::cout << "p([0.5, -0.5] | [1.0, -1.0], [0.9, 0.4 ; 0.4, 0.3]) = " << pdf << std::endl; + + gsl_vector_free(mu); + gsl_matrix_free(covL); + gsl_vector_free(x); + gsl_vector_free(work); + } +} + +} // namespace local +} // unnamed namespace + +namespace my_gsl { + +void distribution() +{ + local::unit_gaussian_distribution(); + local::gaussian_distribution(); + local::bivariate_gaussian_distribution(); + local::multivariate_gaussian_distribution(); +} + +} // namespace my_gsl diff --git a/pool/shard011/C++/0121600_timeslice_timeout.cpp b/pool/shard011/C++/0121600_timeslice_timeout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..803a7c379e633ecaa263d80658beb75b5630ae02 --- /dev/null +++ b/pool/shard011/C++/0121600_timeslice_timeout.cpp @@ -0,0 +1,55 @@ + +INTERFACE: + +#include "timeout.h" + +class Timeslice_timeout : public Timeout +{ +}; + +IMPLEMENTATION: + +#include +#include "globals.h" +#include "sched_context.h" +#include "std_macros.h" + +/* Initialize global valiable timeslice_timeout */ +DEFINE_PER_CPU Per_cpu timeslice_timeout; +DEFINE_PER_CPU static Per_cpu the_timeslice_timeout(Per_cpu_data::Cpu_num); + +PUBLIC +Timeslice_timeout::Timeslice_timeout(Cpu_number cpu) +{ + timeslice_timeout.cpu(cpu) = this; +} + + +/** + * Timeout expiration callback function + * @return true to force a reschedule + */ +PRIVATE +bool +Timeslice_timeout::expired() +{ + Sched_context::Ready_queue &rq = Sched_context::rq.current(); + Sched_context *sched = rq.current_sched(); + + if (sched) + { +#if 0 + Context *owner = sched->owner(); + + // Ensure sched is owner's current timeslice + assert (owner->sched() == sched); +#endif + sched->replenish(); + rq.requeue(sched); + rq.invalidate_sched(); + +// owner->switch_sched(sched); + } + + return true; // Force reschedule +} diff --git a/pool/shard011/C++/0121602_BLECharacteristic.cpp b/pool/shard011/C++/0121602_BLECharacteristic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6957182ab6f950aaa0b9222864a3bff5772132dc --- /dev/null +++ b/pool/shard011/C++/0121602_BLECharacteristic.cpp @@ -0,0 +1,147 @@ +#include "Arduino.h" + +#include "BLEDeviceLimits.h" + +#include "BLECharacteristic.h" + +BLECharacteristic::BLECharacteristic(const char* uuid, unsigned char properties, unsigned char valueSize) : + BLELocalAttribute(uuid, BLETypeCharacteristic), + _properties(properties), + _valueSize(min(valueSize, BLE_ATTRIBUTE_MAX_VALUE_LENGTH)), + _value(NULL), + _valueLength(0), + _written(false), + _subscribed(false), + _listener(NULL) +{ + memset(this->_eventHandlers, 0x00, sizeof(this->_eventHandlers)); + + if (valueSize) { + this->_value = (unsigned char*)malloc(this->_valueSize); + } +} + +BLECharacteristic::BLECharacteristic(const char* uuid, unsigned char properties, const char* value) : + BLELocalAttribute(uuid, BLETypeCharacteristic), + _properties(properties), + _valueSize(min(strlen(value), BLE_ATTRIBUTE_MAX_VALUE_LENGTH)), + _value(NULL), + _valueLength(0), + _written(false), + _subscribed(false), + _listener(NULL) +{ + memset(this->_eventHandlers, 0x00, sizeof(this->_eventHandlers)); + + this->_value = (unsigned char*)malloc(this->_valueSize); + this->setValue(value); +} + +BLECharacteristic::~BLECharacteristic() { + if (this->_value) { + free(this->_value); + } +} + +unsigned char BLECharacteristic::properties() const { + return this->_properties; +} + +unsigned char BLECharacteristic::valueSize() const { + return this->_valueSize; +} + +unsigned const char* BLECharacteristic::value() const { + return this->_value; +} + +unsigned char BLECharacteristic::valueLength() const { + return this->_valueLength; +} + +bool BLECharacteristic::fixedLength() const { + return false; +} + +unsigned char BLECharacteristic::operator[] (int offset) const { + return this->_value[offset]; +} + +bool BLECharacteristic::setValue(const unsigned char value[], unsigned char length) { + bool success = true; + + this->_valueLength = min(length, this->_valueSize); + + memcpy(this->_value, value, this->_valueLength); + + if (this->_listener) { + success = this->_listener->characteristicValueChanged(*this); + } + + return success; +} + +bool BLECharacteristic::setValue(const char* value) { + return this->setValue((const unsigned char *)value, strlen(value)); +} + +bool BLECharacteristic::broadcast() { + bool success = false; + + if (this->_listener) { + success = this-_listener->broadcastCharacteristic(*this); + } + + return success; +} + +bool BLECharacteristic::written() { + bool written = this->_written; + + this->_written = false; + + return written; +} + +void BLECharacteristic::setValue(BLECentral& central, const unsigned char value[], unsigned char length) { + this->setValue(value, length); + + this->_written = true; + + BLECharacteristicEventHandler eventHandler = this->_eventHandlers[BLEWritten]; + if (eventHandler) { + eventHandler(central, *this); + } +} + +bool BLECharacteristic::subscribed() { + return this->_subscribed; +} + +void BLECharacteristic::setSubscribed(BLECentral& central, bool subscribed) { + this->_subscribed = subscribed; + + BLECharacteristicEventHandler eventHandler = this->_eventHandlers[subscribed ? BLESubscribed : BLEUnsubscribed]; + + if (eventHandler) { + eventHandler(central, *this); + } +} + +bool BLECharacteristic::canNotify() { + return (this->_listener) ? this->_listener->canNotifyCharacteristic(*this) : false; +} + +bool BLECharacteristic::canIndicate() { + return (this->_listener) ? this->_listener->canIndicateCharacteristic(*this) : false; +} + +void BLECharacteristic::setEventHandler(BLECharacteristicEvent event, BLECharacteristicEventHandler eventHandler) { + if (event < sizeof(this->_eventHandlers)) { + this->_eventHandlers[event] = eventHandler; + } +} + +void BLECharacteristic::setValueChangeListener(BLECharacteristicValueChangeListener& listener) { + this->_listener = &listener; +} diff --git a/pool/shard011/C++/0121603_ana2morfsar.cc b/pool/shard011/C++/0121603_ana2morfsar.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b598a7fba16550ad388b1f5483a8056c096b4e7 --- /dev/null +++ b/pool/shard011/C++/0121603_ana2morfsar.cc @@ -0,0 +1,241 @@ +////////////////////////////////////////////////////////////////// +// +// EUSTAGGER LITE +// +// Copyright (C) 1996-2013 IXA Taldea +// EHU-UPV +// +// This file is part of EUSTAGGER LITE. +// +// EUSTAGGER LITE 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. +// +// EUSTAGGER LITE 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 Foobar. If not, see . +// +// Contact: Ixa Taldea (ixa@ehu.es) +// 649 Posta kutxa +// 20080 Donostia (Basque Country) +// +////////////////////////////////////////////////////////////////// + + +/* *************************************************** + * **************************************************** */ +#include +#include +#include +#include +#include +#include "ana2morfsar.h" +#include "morfsarFormatu.h" + + +Ana2Morfsar* yyparseAna2Morfsar; + +using namespace std; +/* ******************************************************************* */ +/* ***** METODO PRIBATUAK ******************************************** */ +/* ******************************************************************* */ + +/* ******************************************************************* */ + +void Ana2Morfsar::toMorfsar(){ + extern int ana2morfsarparse(); // LEX-YACC modulua + extern FILE* ana2morfsarin; // LEX-YACC moduluaren sarrerako FILE*; + if (fpFitxAna == NULL) { + cerr << "Errorea Ana2Morfsar::toMorfsar()" << endl; + exit( EXIT_FAILURE ); + } + ana2morfsarin=fpFitxAna; + yyparseAna2Morfsar = this; + ana2morfsarparse(); + fclose( fpFitxAna ); +} + +void Ana2Morfsar::toMorfsar(const std::string segString){ + extern void bufferParse(char *buffer, int size); + char *buffer; + //ofstream out ("tmp.segp"); + //if (!out) { + // cerr << "Ezin daiteke tmp.segp fitxategia sortu" << endl; + //} + //out << segString << endl; + if (fpFitxAna != NULL) { + fpFitxAna = NULL; + } + buffer = (char *) malloc(segString.length()+2); /* bukeran \0\0 egotea eskatzen du */ + buffer[0] = '\0'; + strcpy(buffer,segString.c_str()); + buffer[segString.length()+1] = '\0'; // bukaeran \0\0 behar du + yyparseAna2Morfsar = this; + bufferParse(buffer,segString.length()+2); + +} + + +void Ana2Morfsar::read_data_version() { + this->dataversion = "4.4.9"; +} + +/* ******************************************************************* */ +/* ***** METODO PUBLIKOAK ******************************************* */ +/* ******************************************************************* */ + +Ana2Morfsar::Ana2Morfsar(){ + this->tamaina=1; + this->read_data_version(); + srand(time(0)); +} +/* ******************************************************************* */ + +Ana2Morfsar::Ana2Morfsar(const string &segp, int tam) { + this->tamaina=tam; + this->read_data_version(); + srand(time(0)); + this->setAnaFitx(segp); +} + +/* ******************************************************************* */ + +Ana2Morfsar::~Ana2Morfsar(){} + +/* ******************************************************************* */ + +void Ana2Morfsar::setMorfsarFitx(const string & morfsar) { + ifstream in (morfsar.c_str()); + if (!in) { + cerr << "ERROREA" << endl; + cerr << "\t ana2morfsar::setMorfsarFitx() => Ezin kargatu " << morfsar << " fitxategia." << endl << endl; + exit(0); + } + string sar; + while(!in.eof()) { + string line; + getline(in, line); + + sar += line + "\n"; + if (line.find("]).") != string::npos) { // lehen != -1 + morfsarForm.addMorfsarSar(sar); + sar = ""; + } + } + in.close(); +} + +/* ******************************************************************* */ + +void Ana2Morfsar::setAnaFitx(const string &segp) { + if ( !( this->fpFitxAna = fopen(segp.c_str() , "r" )) ){ + cerr << "Errorea Ana2Morfsar::setAnaFitx --> fopen(" << segp <<")"<toMorfsar(); +} + +void Ana2Morfsar::setAnaString(const string &segIrteera) { + this->toMorfsar(segIrteera); +} + +/* ******************************************************************* */ + +void Ana2Morfsar::setAnaTam(int tamaina) { this->tamaina = tamaina; } + + +/* ******************************************************************* */ + +int Ana2Morfsar::getAnaTam() {return this->tamaina; } + +/* ******************************************************************* */ + +void Ana2Morfsar::add2Gorputza(string type, string value, bool symBal) { + this->morfsarForm.add2Gorputza(type, value, symBal); +} + +/* ******************************************************************* */ + +void Ana2Morfsar::setForma(string forma,const std::string bereiz) { + this->morfsarForm.setForma(forma,bereiz); +} + +/* ******************************************************************* */ + +void Ana2Morfsar::morfemaBerria() { + this->morfsarForm.morfemaBerria(); +} + + +/* ******************************************************************* */ + +void Ana2Morfsar::analisiaBukatu() { + this->morfsarForm.analisiaBukatu(); +} + + +/* ******************************************************************* */ + +void Ana2Morfsar::begin() { this->morfsarForm.begin(tamaina);} + +/* ******************************************************************* */ + +bool Ana2Morfsar::ready() { return !this->morfsarForm.end(); } + +/* ******************************************************************* */ + +void Ana2Morfsar::next() { this->morfsarForm.next(); } + +/* ******************************************************************* */ + +string Ana2Morfsar::current() { + string morfsarFitx; + bool fExist=false; + do{ + ostringstream tmpFitx; + tmpFitx << TMP_PATH << rand() << ".tmp.morfsar"; + morfsarFitx=tmpFitx.str(); + + ifstream fIn; + fIn.open(morfsarFitx.c_str()); + fExist=fIn.is_open(); + fIn.close(); + } while (fExist); + return this->morfsarForm.current(morfsarFitx); + } + +/* ******************************************************************* */ + +string Ana2Morfsar::current(string & tmpFitx) { + return this->morfsarForm.current(tmpFitx); +} + +/* ******************************************************************* */ + +vector Ana2Morfsar::execute(string & amaraunIzen) { + vector morfsarV; + int kont=0; + for (this->begin(); this->ready(); this->next()) { + kont++; + string morfsarFitx; + if (tamaina>0) { + ostringstream kontOSS; + kontOSS.fill('0'); + kontOSS.width(6); + kontOSS << kont; + morfsarFitx = amaraunIzen + "." + kontOSS.str() + ".morfsar"; + } + else morfsarFitx= amaraunIzen + ".morfsar"; + + this->current(morfsarFitx); + morfsarV.push_back(morfsarFitx); + } + return morfsarV; +} + +/* ******************************************************************* */ diff --git a/pool/shard011/C++/0121605_CaiGpsNav.cpp b/pool/shard011/C++/0121605_CaiGpsNav.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4649a2f15045beba0299401b4e41d47e89aaa66 --- /dev/null +++ b/pool/shard011/C++/0121605_CaiGpsNav.cpp @@ -0,0 +1,77 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2015 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +// + + +// CAUTION! +// caiGpsNavParseNMEA is called from com port read thread +// all other functions are called from windows message loop thread + +#include "Device/Driver/CaiGpsNav.hpp" +#include "Device/Driver.hpp" +#include "Device/Port/Port.hpp" +#include "Operation/Operation.hpp" + +#include + +static constexpr char CtrlC = '\x03'; + +class CaiGpsNavDevice : public AbstractDevice { +private: + Port &port; + +public: + CaiGpsNavDevice(Port &_port):port(_port) {} + +public: + virtual bool EnableNMEA(OperationEnvironment &env) override; +}; + +bool +CaiGpsNavDevice::EnableNMEA(OperationEnvironment &env) +{ + port.Write(CtrlC); + env.Sleep(200); + port.Write("NMEA\r"); + + // This is for a slightly different mode, that + // apparently outputs pressure info too... + //port.Write("PNP\r\n"); + //port.Write("LOG 0\r\n"); + + return true; +} + +static Device * +CaiGpsNavCreateOnPort(const DeviceConfig &config, Port &com_port) +{ + return new CaiGpsNavDevice(com_port); +} + +const struct DeviceRegister gps_nav_driver = { + _T("CAI GPS-NAV"), + _T("Cambridge CAI GPS-NAV"), + 0, + CaiGpsNavCreateOnPort, +}; diff --git a/pool/shard011/C++/0121606_PixelShader.cpp b/pool/shard011/C++/0121606_PixelShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b54f6249928efe5bac3ec32c5a732894bb34c5c1 --- /dev/null +++ b/pool/shard011/C++/0121606_PixelShader.cpp @@ -0,0 +1,38 @@ +/// @file +/// @author Boris Mikic +/// @version 3.3 +/// +/// @section LICENSE +/// +/// This program is free software; you can redistribute it and/or modify it under +/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php + +#include +#include + +#include "PixelShader.h" + +namespace april +{ + PixelShader::PixelShader() + { + } + + PixelShader::~PixelShader() + { + } + + bool PixelShader::_loadData(chstr filename, unsigned char** data, long* size) + { + if (!hresource::exists(filename)) + { + return false; + } + hresource stream(filename); + *size = stream.size(); + *data = new unsigned char[*size]; + stream.read_raw(*data, *size); + return true; + } + +} diff --git a/pool/shard011/C++/0121610_ClientRequestFactory.cpp b/pool/shard011/C++/0121610_ClientRequestFactory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1365b3eb96f8202d3935ab2b65457bbe56288023 --- /dev/null +++ b/pool/shard011/C++/0121610_ClientRequestFactory.cpp @@ -0,0 +1,139 @@ +#include "include/global.h" + + +#include "alinous.runtime.engine.debugger/AlinousServerDebugHttpResponse.h" +#include "alinous.runtime.engine.debugger.client/IClientRequest.h" +#include "alinous.runtime.engine.debugger/IHttpAccessMethod.h" +#include "alinous.runtime.engine.debugger/AlinousDebugCommandSender.h" +#include "alinous.runtime.engine.debugger.client/TerminateServerRequest.h" +#include "alinous.runtime.engine.debugger.client/StatusThreadRequest.h" +#include "alinous.runtime.engine.debugger.client/ClearBreakpointsRequest.h" +#include "alinous.runtime.engine.debugger.client/AddBreakpointsRequest.h" +#include "alinous.runtime.engine.debugger.client/SetupAllBreakPointsRequest.h" +#include "alinous.runtime.engine.debugger.client/ResumeRequest.h" +#include "alinous.runtime.engine.debugger.client/StepOverRequest.h" +#include "alinous.runtime.engine.debugger.client/StepInRequest.h" +#include "alinous.runtime.engine.debugger.client/StepReturnRequest.h" +#include "alinous.runtime.engine.debugger.client/ClientRequestFactory.h" + +namespace alinous {namespace runtime {namespace engine {namespace debugger {namespace client { + + + + + +bool ClientRequestFactory::__init_done = __init_static_variables(); +bool ClientRequestFactory::__init_static_variables(){ + Java2CppSystem::getSelf(); + ThreadContext* ctx = ThreadContext::newThreadContext(); + { + GCNotifier __refobj1(ctx, __FILEW__, __LINE__, L"ClientRequestFactory", L"__init_static_variables"); + } + ctx->localGC(); + delete ctx; + return true; +} + ClientRequestFactory::ClientRequestFactory(ThreadContext* ctx) throw() : IObject(ctx) +{ +} +void ClientRequestFactory::__construct_impl(ThreadContext* ctx) throw() +{ +} + ClientRequestFactory::~ClientRequestFactory() throw() +{ + ThreadContext *ctx = ThreadContext::getCurentContext(); + if(ctx != nullptr){ctx->incGcDenial();} + __releaseRegerences(false, ctx); + if(ctx != nullptr){ctx->decGcDenial();} +} +void ClientRequestFactory::__releaseRegerences(bool prepare, ThreadContext* ctx) throw() +{ + if(!prepare){ + return; + } +} +IClientRequest* ClientRequestFactory::createRequest(Map* params, ThreadContext* ctx) throw() +{ + String* command = params->get(AlinousDebugCommandSender::COMMAND, ctx); + IClientRequest* retRequest = nullptr; + if(command == nullptr) + { + return nullptr; + } + else + { + if(command->equals(IClientRequest::CMD_TERMINATE, ctx)) + { + retRequest = (new(ctx) TerminateServerRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_STATUS_THREAD, ctx)) + { + retRequest = (new(ctx) StatusThreadRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_CLEAR_BREAKPOINTS, ctx)) + { + retRequest = (new(ctx) ClearBreakpointsRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_ADD_BREAKPOINTS, ctx)) + { + retRequest = (new(ctx) AddBreakpointsRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_SETUP_ALL_BREAKPOINTS, ctx)) + { + retRequest = (new(ctx) SetupAllBreakPointsRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_RESUME, ctx)) + { + retRequest = (new(ctx) ResumeRequest(0, ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_STEP_OVER, ctx)) + { + retRequest = (new(ctx) StepOverRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_STEP_IN, ctx)) + { + retRequest = (new(ctx) StepInRequest(ctx)); + } + else + { + if(command->equals(IClientRequest::CMD_STEP_RETURN, ctx)) + { + retRequest = (new(ctx) StepReturnRequest(ctx)); + } + } + } + } + } + } + } + } + } + } + if(retRequest != nullptr) + { + retRequest->importParams(params, ctx); + } + return retRequest; +} +IClientRequest* ClientRequestFactory::createDefault(ThreadContext* ctx) throw() +{ + return (new(ctx) StatusThreadRequest(ctx)); +} +void ClientRequestFactory::__cleanUp(ThreadContext* ctx){ +} +}}}}} + diff --git a/pool/shard011/C++/0121611_drawing-group.cpp b/pool/shard011/C++/0121611_drawing-group.cpp new file mode 100644 index 0000000000000000000000000000000000000000..38ace001f4922efd8092a7abbb00f16a0cae0076 --- /dev/null +++ b/pool/shard011/C++/0121611_drawing-group.cpp @@ -0,0 +1,167 @@ +/** + * @file + * Group belonging to an SVG drawing element. + *//* + * Authors: + * Krzysztof Kosiński + * + * Copyright (C) 2011 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "display/cairo-utils.h" +#include "display/drawing.h" +#include "display/drawing-context.h" +#include "display/drawing-item.h" +#include "display/drawing-group.h" +#include "style.h" + +namespace Inkscape { + +DrawingGroup::DrawingGroup(Drawing &drawing) + : DrawingItem(drawing) + , _style(NULL) + , _child_transform(NULL) +{} + +DrawingGroup::~DrawingGroup() +{ + if (_style) + sp_style_unref(_style); + delete _child_transform; // delete NULL; is safe +} + +/** + * Set whether the group returns children from pick calls. + * Previously this feature was called "transparent groups". + */ +void +DrawingGroup::setPickChildren(bool p) +{ + _pick_children = p; +} + +void +DrawingGroup::setStyle(SPStyle *style) +{ + _setStyleCommon(_style, style); +} + +/** + * Set additional transform for the group. + * This is applied after the normal transform and mainly useful for + * markers, clipping paths, etc. + */ +void +DrawingGroup::setChildTransform(Geom::Affine const &new_trans) +{ + Geom::Affine current; + if (_child_transform) { + current = *_child_transform; + } + + if (!Geom::are_near(current, new_trans, 1e-18)) { + // mark the area where the object was for redraw. + _markForRendering(); + if (new_trans.isIdentity()) { + delete _child_transform; // delete NULL; is safe + _child_transform = NULL; + } else { + _child_transform = new Geom::Affine(new_trans); + } + _markForUpdate(STATE_ALL, true); + } +} + +unsigned +DrawingGroup::_updateItem(Geom::IntRect const &area, UpdateContext const &ctx, unsigned flags, unsigned reset) +{ + unsigned beststate = STATE_ALL; + bool outline = _drawing.outline(); + + UpdateContext child_ctx(ctx); + if (_child_transform) { + child_ctx.ctm = *_child_transform * ctx.ctm; + } + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + i->update(area, child_ctx, flags, reset); + } + if (beststate & STATE_BBOX) { + _bbox = Geom::OptIntRect(); + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + if (i->visible()) { + _bbox.unionWith(outline ? i->geometricBounds() : i->visualBounds()); + } + } + } + return beststate; +} + +unsigned +DrawingGroup::_renderItem(DrawingContext &dc, Geom::IntRect const &area, unsigned flags, DrawingItem *stop_at) +{ + if (stop_at == NULL) { + // normal rendering + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + i->render(dc, area, flags, stop_at); + } + } else { + // background rendering + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + if (&*i == stop_at) return RENDER_OK; // do not render the stop_at item at all + if (i->isAncestorOf(stop_at)) { + // render its ancestors without masks, opacity or filters + i->render(dc, area, flags | RENDER_FILTER_BACKGROUND, stop_at); + // stop further rendering + return RENDER_OK; + } else { + i->render(dc, area, flags, stop_at); + } + } + } + return RENDER_OK; +} + +void +DrawingGroup::_clipItem(DrawingContext &dc, Geom::IntRect const &area) +{ + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + i->clip(dc, area); + } +} + +DrawingItem * +DrawingGroup::_pickItem(Geom::Point const &p, double delta, unsigned flags) +{ + for (ChildrenList::iterator i = _children.begin(); i != _children.end(); ++i) { + DrawingItem *picked = i->pick(p, delta, flags); + if (picked) { + return _pick_children ? picked : this; + } + } + return NULL; +} + +bool +DrawingGroup::_canClip() +{ + return true; +} + +bool is_drawing_group(DrawingItem *item) +{ + return dynamic_cast(item) != NULL; +} + +} // end namespace Inkscape + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/pool/shard011/C++/0121614_rangeSensor.cpp b/pool/shard011/C++/0121614_rangeSensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..66142db07735a276a76da46a02c7d228304c9b6d --- /dev/null +++ b/pool/shard011/C++/0121614_rangeSensor.cpp @@ -0,0 +1,121 @@ +/* Copyright 2014 - 2015 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 "rangeSensor.h" + +#include + +#include +#include +#include +#include + +#include "configurerHelper.h" +#include "rangeSensorWorker.h" +#include "moduleLoader.h" + +using namespace trikControl; + +RangeSensor::RangeSensor(const QString &port, const trikKernel::Configurer &configurer, ModuleLoader &moduleLoader + , const trikHal::HardwareAbstractionInterface &hardwareAbstraction) + : mState("Range Sensor on " + port) +{ + if (!moduleLoader.load(configurer.attributeByPort(port, "module")) + || !moduleLoader.load(configurer.attributeByDevice("rangeSensor", "commonModule"))) + { + QLOG_ERROR() << "Module loading failed"; + mState.fail(); + return; + } + + mMinValue = ConfigurerHelper::configureInt(configurer, mState, port, "minValue"); + mMaxValue = ConfigurerHelper::configureInt(configurer, mState, port, "maxValue"); + + mSensorWorker.reset(new RangeSensorWorker(configurer.attributeByPort(port, "eventFile"), mState + , hardwareAbstraction, mMinValue, mMaxValue, configurer.attributeByPort(port, "filter"))); + + if (!mState.isFailed()) { + mSensorWorker->moveToThread(&mWorkerThread); + + connect(mSensorWorker.data(), &RangeSensorWorker::newData, this, &RangeSensor::newData); + + QLOG_INFO() << "Starting RangeSensor worker thread" << &mWorkerThread; + QEventLoop l; + connect(&mWorkerThread, &QThread::started, &l, &QEventLoop::quit); + + mWorkerThread.setObjectName(mSensorWorker->metaObject()->className()); + mWorkerThread.start(); + + l.exec(); + } +} + +RangeSensor::~RangeSensor() +{ + if (mWorkerThread.isRunning()) { + mWorkerThread.quit(); + mWorkerThread.wait(); + } +} + +RangeSensor::Status RangeSensor::status() const +{ + return mState.status(); +} + +void RangeSensor::init() +{ + if (mState.isFailed()) { + mState.resetFailure(); + } + + QMetaObject::invokeMethod(mSensorWorker.data(), &RangeSensorWorker::init); +} + +int RangeSensor::read() +{ + if (!mState.isFailed()) { + // Read is called synchronously and only takes prepared value from sensor. + return mSensorWorker->read(); + } else { + return -1; + } +} + +int RangeSensor::readRawData() +{ + if (!mState.isFailed()) { + // Read is called synchronously and only takes prepared value from sensor. + return mSensorWorker->readRawData(); + } else { + return -1; + } +} + +void RangeSensor::stop() +{ + if (!mState.isFailed()) { + QMetaObject::invokeMethod(mSensorWorker.data(), &RangeSensorWorker::stop); + } +} + +int RangeSensor::minValue() const +{ + return mMinValue; +} + +int RangeSensor::maxValue() const +{ + return mMaxValue; +} diff --git a/pool/shard011/C++/0121615_xfa_layout_appadapter.cpp b/pool/shard011/C++/0121615_xfa_layout_appadapter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..562beb9001d1b9371b0566f23e0f329645e206eb --- /dev/null +++ b/pool/shard011/C++/0121615_xfa_layout_appadapter.cpp @@ -0,0 +1,56 @@ +// Copyright 2014 PDFium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com + +#include "xfa/src/foxitlib.h" +#include "xfa/src/fxfa/src/common/xfa_utils.h" +#include "xfa/src/fxfa/src/common/xfa_object.h" +#include "xfa/src/fxfa/src/common/xfa_document.h" +#include "xfa/src/fxfa/src/common/xfa_parser.h" +#include "xfa/src/fxfa/src/common/xfa_script.h" +#include "xfa/src/fxfa/src/common/xfa_docdata.h" +#include "xfa/src/fxfa/src/common/xfa_doclayout.h" +#include "xfa/src/fxfa/src/common/xfa_localemgr.h" +#include "xfa/src/fxfa/src/common/xfa_fm2jsapi.h" +#include "xfa_document_layout_imp.h" +#include "xfa_layout_itemlayout.h" +#include "xfa_layout_pagemgr_new.h" +#include "xfa_layout_appadapter.h" +FX_DWORD XFA_GetRelevant(CXFA_Node* pFormItem, FX_DWORD dwParentRelvant) { + FX_DWORD dwRelevant = XFA_LAYOUTSTATUS_Viewable | XFA_LAYOUTSTATUS_Printable; + CFX_WideStringC wsRelevant; + if (pFormItem->TryCData(XFA_ATTRIBUTE_Relevant, wsRelevant)) { + if (wsRelevant == FX_WSTRC(L"+print") || wsRelevant == FX_WSTRC(L"print")) { + dwRelevant &= ~XFA_LAYOUTSTATUS_Viewable; + } else if (wsRelevant == FX_WSTRC(L"-print")) { + dwRelevant &= ~XFA_LAYOUTSTATUS_Printable; + } + } + if (!(dwParentRelvant & XFA_LAYOUTSTATUS_Viewable) && + (dwRelevant != XFA_LAYOUTSTATUS_Viewable)) { + dwRelevant &= ~XFA_LAYOUTSTATUS_Viewable; + } + if (!(dwParentRelvant & XFA_LAYOUTSTATUS_Printable) && + (dwRelevant != XFA_LAYOUTSTATUS_Printable)) { + dwRelevant &= ~XFA_LAYOUTSTATUS_Printable; + } + return dwRelevant; +} +void XFA_ReleaseLayoutItem(CXFA_LayoutItem* pLayoutItem) { + CXFA_LayoutItem* pNode = pLayoutItem->m_pFirstChild; + while (pNode) { + CXFA_LayoutItem* pNext = pNode->m_pNextSibling; + pNode->m_pParent = nullptr; + XFA_ReleaseLayoutItem(pNode); + pNode = pNext; + } + IXFA_Notify* pNotify = + pLayoutItem->m_pFormNode->GetDocument()->GetParser()->GetNotify(); + if (pLayoutItem->m_pFormNode->GetClassID() == XFA_ELEMENT_PageArea) { + pNotify->OnPageEvent(static_cast(pLayoutItem), + XFA_PAGEEVENT_PageRemoved); + } + delete pLayoutItem; +} diff --git a/pool/shard011/C++/0121616_TcpConnector.cpp b/pool/shard011/C++/0121616_TcpConnector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e9f02a28a24b0526a677b6e8353e21d5bc534e04 --- /dev/null +++ b/pool/shard011/C++/0121616_TcpConnector.cpp @@ -0,0 +1,162 @@ +// Copyright (c) 2011-2016 The Cryptonote developers +// Copyright (c) 2014-2017 XDN-project developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "TcpConnector.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "Dispatcher.h" +#include "ErrorMessage.h" +#include "TcpConnection.h" + +namespace System { + +namespace { + +struct ConnectorContext : public OperationContext { + int connection; +}; + +} + +TcpConnector::TcpConnector() : dispatcher(nullptr) { +} + +TcpConnector::TcpConnector(Dispatcher& dispatcher) : dispatcher(&dispatcher), context(nullptr) { +} + +TcpConnector::TcpConnector(TcpConnector&& other) : dispatcher(other.dispatcher) { + if (other.dispatcher != nullptr) { + assert(other.context == nullptr); + context = nullptr; + other.dispatcher = nullptr; + } +} + +TcpConnector::~TcpConnector() { + assert(dispatcher == nullptr || context == nullptr); +} + +TcpConnector& TcpConnector::operator=(TcpConnector&& other) { + dispatcher = other.dispatcher; + if (other.dispatcher != nullptr) { + assert(other.context == nullptr); + context = nullptr; + other.dispatcher = nullptr; + } + + return *this; +} + +TcpConnection TcpConnector::connect(const Ipv4Address& address, uint16_t port) { + assert(dispatcher != nullptr); + assert(context == nullptr); + if (dispatcher->interrupted()) { + throw InterruptedException(); + } + + std::string message; + int connection = ::socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connection == -1) { + message = "socket failed, " + lastErrorMessage(); + } else { + sockaddr_in bindAddress; + bindAddress.sin_family = AF_INET; + bindAddress.sin_port = 0; + bindAddress.sin_addr.s_addr = INADDR_ANY; + if (bind(connection, reinterpret_cast(&bindAddress), sizeof bindAddress) != 0) { + message = "bind failed, " + lastErrorMessage(); + } else { + int flags = fcntl(connection, F_GETFL, 0); + if (flags == -1 || fcntl(connection, F_SETFL, flags | O_NONBLOCK) == -1) { + message = "fcntl failed, " + lastErrorMessage(); + } else { + sockaddr_in addressData; + addressData.sin_family = AF_INET; + addressData.sin_port = htons(port); + addressData.sin_addr.s_addr = htonl(address.getValue()); + int result = ::connect(connection, reinterpret_cast(&addressData), sizeof addressData); + if (result == -1) { + if (errno == EINPROGRESS) { + ConnectorContext connectorContext; + connectorContext.context = dispatcher->getCurrentContext(); + connectorContext.interrupted = false; + connectorContext.connection = connection; + + struct kevent event; + EV_SET(&event, connection, EVFILT_WRITE, EV_ADD | EV_ENABLE, 0, 0, &connectorContext); + if (kevent(dispatcher->getKqueue(), &event, 1, NULL, 0, NULL) == -1) { + message = "kevent failed, " + lastErrorMessage(); + } else { + context = &connectorContext; + dispatcher->getCurrentContext()->interruptProcedure = [&] { + assert(dispatcher != nullptr); + assert(context != nullptr); + ConnectorContext* connectorContext = static_cast(context); + if (!connectorContext->interrupted) { + if (close(connectorContext->connection) == -1) { + throw std::runtime_error("TcpListener::stop, close failed, " + lastErrorMessage()); + } + + dispatcher->pushContext(connectorContext->context); + connectorContext->interrupted = true; + } + }; + + dispatcher->dispatch(); + dispatcher->getCurrentContext()->interruptProcedure = nullptr; + assert(dispatcher != nullptr); + assert(connectorContext.context == dispatcher->getCurrentContext()); + assert(context == &connectorContext); + context = nullptr; + connectorContext.context = nullptr; + if (connectorContext.interrupted) { + throw InterruptedException(); + } + + struct kevent event; + EV_SET(&event, connection, EVFILT_WRITE, EV_ADD | EV_DISABLE, 0, 0, NULL); + + if (kevent(dispatcher->getKqueue(), &event, 1, NULL, 0, NULL) == -1) { + message = "kevent failed, " + lastErrorMessage(); + } else { + int retval = -1; + socklen_t retValLen = sizeof(retval); + int s = getsockopt(connection, SOL_SOCKET, SO_ERROR, &retval, &retValLen); + if (s == -1) { + message = "getsockopt failed, " + lastErrorMessage(); + } else { + if (retval != 0) { + message = "getsockopt failed, " + lastErrorMessage(); + } else { + return TcpConnection(*dispatcher, connection); + } + } + } + } + } + } else { + return TcpConnection(*dispatcher, connection); + } + } + } + + int result = close(connection); + assert(result != -1);; + } + + throw std::runtime_error("TcpConnector::connect, " + message); +} + +} diff --git a/pool/shard011/C++/0121617_PostRAHazardRecognizer.cpp b/pool/shard011/C++/0121617_PostRAHazardRecognizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..425a59dc03752d82362f02b998bc3c87d933bdfe --- /dev/null +++ b/pool/shard011/C++/0121617_PostRAHazardRecognizer.cpp @@ -0,0 +1,98 @@ +//===----- PostRAHazardRecognizer.cpp - hazard recognizer -----------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +// +/// \file +/// This runs the hazard recognizer and emits noops when necessary. This +/// gives targets a way to run the hazard recognizer without running one of +/// the schedulers. Example use cases for this pass would be: +/// +/// - Targets that need the hazard recognizer to be run at -O0. +/// - Targets that want to guarantee that hazards at the beginning of +/// scheduling regions are handled correctly. The post-RA scheduler is +/// a top-down scheduler, but when there are multiple scheduling regions +/// in a basic block, it visits the regions in bottom-up order. This +/// makes it impossible for the scheduler to gauranttee it can correctly +/// handle hazards at the beginning of scheduling regions. +/// +/// This pass traverses all the instructions in a program in top-down order. +/// In contrast to the instruction scheduling passes, this pass never resets +/// the hazard recognizer to ensure it can correctly handles noop hazards at +/// the begining of blocks. +// +//===----------------------------------------------------------------------===// + +#include "llvm/ADT/Statistic.h" +#include "llvm/CodeGen/MachineFunctionPass.h" +#include "llvm/CodeGen/Passes.h" +#include "llvm/CodeGen/ScheduleHazardRecognizer.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Target/TargetInstrInfo.h" +#include "llvm/Target/TargetSubtargetInfo.h" +using namespace llvm; + +#define DEBUG_TYPE "post-RA-hazard-rec" + +STATISTIC(NumNoops, "Number of noops inserted"); + +namespace { + class PostRAHazardRecognizer : public MachineFunctionPass { + + public: + static char ID; + PostRAHazardRecognizer() : MachineFunctionPass(ID) {} + + void getAnalysisUsage(AnalysisUsage &AU) const override { + AU.setPreservesCFG(); + MachineFunctionPass::getAnalysisUsage(AU); + } + + bool runOnMachineFunction(MachineFunction &Fn) override; + + }; + char PostRAHazardRecognizer::ID = 0; + +} + +char &llvm::PostRAHazardRecognizerID = PostRAHazardRecognizer::ID; + +INITIALIZE_PASS(PostRAHazardRecognizer, DEBUG_TYPE, + "Post RA hazard recognizer", false, false) + +bool PostRAHazardRecognizer::runOnMachineFunction(MachineFunction &Fn) { + const TargetInstrInfo *TII = Fn.getSubtarget().getInstrInfo(); + std::unique_ptr HazardRec( + TII->CreateTargetPostRAHazardRecognizer(Fn)); + + // Return if the target has not implemented a hazard recognizer. + if (!HazardRec.get()) + return false; + + // Loop over all of the basic blocks + for (auto &MBB : Fn) { + // We do not call HazardRec->reset() here to make sure we are handling noop + // hazards at the start of basic blocks. + for (MachineInstr &MI : MBB) { + // If we need to emit noops prior to this instruction, then do so. + unsigned NumPreNoops = HazardRec->PreEmitNoops(&MI); + for (unsigned i = 0; i != NumPreNoops; ++i) { + HazardRec->EmitNoop(); + TII->insertNoop(MBB, MachineBasicBlock::iterator(MI)); + ++NumNoops; + } + + HazardRec->EmitInstruction(&MI); + if (HazardRec->atIssueLimit()) { + HazardRec->AdvanceCycle(); + } + } + } + return true; +} diff --git a/pool/shard011/C++/0121621_KoOasisSettings.cpp b/pool/shard011/C++/0121621_KoOasisSettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f982300d71f925c6e2dedf94a2eb2878c39bdf1e --- /dev/null +++ b/pool/shard011/C++/0121621_KoOasisSettings.cpp @@ -0,0 +1,224 @@ +/* This file is part of the KDE project + Copyright (C) 2004 Laurent Montel + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. +*/ + +#include "KoOasisSettings.h" +#include "KoXmlNS.h" +#include + +class KoOasisSettings::Private +{ +}; + +KoOasisSettings::KoOasisSettings(const KoXmlDocument& doc) + : m_settingsElement(KoXml::namedItemNS(doc.documentElement(), KoXmlNS::office, "settings")), + m_configNSURI(KoXmlNS::config) + , d(0) +{ + const KoXmlElement contents = doc.documentElement(); + if (m_settingsElement.isNull()) + kDebug(30003) << " document doesn't have tag 'office:settings'"; +} + +KoOasisSettings::KoOasisSettings(const KoXmlDocument& doc, const char* officeNSURI, const char* configNSURI) + : m_settingsElement(KoXml::namedItemNS(doc.documentElement(), officeNSURI, "settings")), + m_configNSURI(configNSURI) + , d(0) +{ + const KoXmlElement contents = doc.documentElement(); + if (m_settingsElement.isNull()) + kDebug(30003) << " document doesn't have tag 'office:settings'"; +} + +KoOasisSettings::~KoOasisSettings() +{ + delete d; +} + +KoOasisSettings::Items KoOasisSettings::itemSet(const QString& itemSetName) const +{ + KoXmlElement e; + forEachElement(e, m_settingsElement) { + if (e.localName() == "config-item-set" && + e.namespaceURI() == m_configNSURI && + e.attributeNS(m_configNSURI, "name", QString()) == itemSetName) { + return Items(e, this); + } + } + + return Items(KoXmlElement(), this); +} + +KoOasisSettings::IndexedMap KoOasisSettings::Items::indexedMap(const QString& itemMapName) const +{ + KoXmlElement configItem; + forEachElement(configItem, m_element) { + if (configItem.localName() == "config-item-map-indexed" && + configItem.namespaceURI() == m_settings->m_configNSURI && + configItem.attributeNS(m_settings->m_configNSURI, "name", QString()) == itemMapName) { + return IndexedMap(configItem, m_settings); + } + } + return IndexedMap(KoXmlElement(), m_settings); +} + +KoOasisSettings::NamedMap KoOasisSettings::Items::namedMap(const QString& itemMapName) const +{ + KoXmlElement configItem; + forEachElement(configItem, m_element) { + if (configItem.localName() == "config-item-map-named" && + configItem.namespaceURI() == m_settings->m_configNSURI && + configItem.attributeNS(m_settings->m_configNSURI, "name", QString()) == itemMapName) { + return NamedMap(configItem, m_settings); + } + } + return NamedMap(KoXmlElement(), m_settings); +} + +KoOasisSettings::Items KoOasisSettings::IndexedMap::entry(int entryIndex) const +{ + int i = 0; + KoXmlElement entry; + forEachElement(entry, m_element) { + if (entry.localName() == "config-item-map-entry" && + entry.namespaceURI() == m_settings->m_configNSURI) { + if (i == entryIndex) + return Items(entry, m_settings); + else + ++i; + } + } + return Items(KoXmlElement(), m_settings); +} + +KoOasisSettings::Items KoOasisSettings::NamedMap::entry(const QString& entryName) const +{ + KoXmlElement entry; + forEachElement(entry, m_element) { + if (entry.localName() == "config-item-map-entry" && + entry.namespaceURI() == m_settings->m_configNSURI && + entry.attributeNS(m_settings->m_configNSURI, "name", QString()) == entryName) { + return Items(entry, m_settings); + } + } + return Items(KoXmlElement(), m_settings); +} + +// helper method +QString KoOasisSettings::Items::findConfigItem(const KoXmlElement& element, + const QString& item, bool* ok) const +{ + KoXmlElement it; + forEachElement(it, element) { + if (it.localName() == "config-item" && + it.namespaceURI() == m_settings->m_configNSURI && + it.attributeNS(m_settings->m_configNSURI, "name", QString()) == item) { + *ok = true; + return it.text(); + } + } + *ok = false; + return QString(); +} + + +QString KoOasisSettings::Items::findConfigItem(const QString& item, bool* ok) const +{ + return findConfigItem(m_element, item, ok); +} + +#if 0 // does anyone need this one? passing a default value does the job, too +bool KoOasisSettings::Items::hasConfigItem(const QString& configName) const +{ + bool ok; + (void)findConfigItem(configName, &ok); + return ok; +} +#endif + +QString KoOasisSettings::Items::parseConfigItemString(const QString& configName, const QString& defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + return ok ? str : defValue; +} + +int KoOasisSettings::Items::parseConfigItemInt(const QString& configName, int defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + int value; + if (ok) { + value = str.toInt(&ok); + if (ok) + return value; + } + return defValue; +} + +qreal KoOasisSettings::Items::parseConfigItemDouble(const QString& configName, qreal defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + qreal value; + if (ok) { + value = str.toDouble(&ok); + if (ok) + return value; + } + return defValue; +} + +bool KoOasisSettings::Items::parseConfigItemBool(const QString& configName, bool defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + if (! ok) + return defValue; + if (str == "true") + return true; + else if (str == "false") + return false; + return defValue; +} + +short KoOasisSettings::Items::parseConfigItemShort(const QString& configName, short defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + short value; + if (ok) { + value = str.toShort(&ok); + if (ok) + return value; + } + return defValue; +} + +long KoOasisSettings::Items::parseConfigItemLong(const QString& configName, long defValue) const +{ + bool ok; + const QString str = findConfigItem(configName, &ok); + long value; + if (ok) { + value = str.toLong(&ok); + if (ok) + return value; + } + return defValue; +} diff --git a/pool/shard011/C++/0121623_campaign.cpp b/pool/shard011/C++/0121623_campaign.cpp new file mode 100644 index 0000000000000000000000000000000000000000..867cf1adabc26f259ebb5e724bd51aa0d46aeee3 --- /dev/null +++ b/pool/shard011/C++/0121623_campaign.cpp @@ -0,0 +1,237 @@ +/* xoreos - A reimplementation of BioWare's Aurora engine + * + * xoreos is the legal property of its developers, whose names + * can be found in the AUTHORS file distributed with this source + * distribution. + * + * xoreos 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. + * + * xoreos 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 xoreos. If not, see . + */ + +/** @file + * The context holding a Witcher campaign. + */ + +#include "src/common/util.h" +#include "src/common/error.h" +#include "src/common/readfile.h" +#include "src/common/filepath.h" +#include "src/common/filelist.h" +#include "src/common/configman.h" + +#include "src/aurora/gff3file.h" + +#include "src/engines/witcher/campaign.h" +#include "src/engines/witcher/console.h" + +namespace Engines { + +namespace Witcher { + +void CampaignDescription::clear() { + tag.clear(); + + name.clear(); + description.clear(); + + file.clear(); + directory.clear(); +} + + +Campaign::Campaign(::Engines::Console &console) : _running(false), + _module(console, this), _newCampaign(0) { + + findCampaigns(); +} + +Campaign::~Campaign() { + clear(); +} + +const std::list &Campaign::getCampaigns() const { + return _campaigns; +} + +void Campaign::findCampaigns() { + Common::UString moduleDir = ConfigMan.getString("WITCHER_moduleDir"); + if (moduleDir.empty()) + return; + + Common::FileList modules; + if (!modules.addDirectory(moduleDir, -1)) + return; + + Common::FileList mmdFiles; + if (!modules.getSubListGlob(".*\\.mmd", true, mmdFiles)) + return; + + for (Common::FileList::const_iterator c = mmdFiles.begin(); c != mmdFiles.end(); ++c) { + CampaignDescription desc; + + desc.directory = Common::FilePath::relativize(moduleDir, Common::FilePath::getDirectory(*c)); + if (!readCampaign(*c, desc)) + continue; + + _campaigns.push_back(desc); + } +} + +bool Campaign::readCampaign(const Common::UString &mmdFile, CampaignDescription &desc) { + Common::ReadFile *file = new Common::ReadFile; + if (!file->open(mmdFile)) { + delete file; + return false; + } + + Aurora::GFF3File *gff = 0; + try { + gff = new Aurora::GFF3File(file, MKTAG('M', 'M', 'D', ' ')); + } catch (...) { + return false; + } + + gff->getTopLevel().getLocString("Meta_Name", desc.name); + gff->getTopLevel().getLocString("Meta_Desc", desc.description); + + delete gff; + + desc.file = mmdFile; + desc.tag = Common::FilePath::getStem(mmdFile).toLower(); + + return true; +} + +void Campaign::clear() { + _module.clear(); + + _currentCampaign.clear(); + + _modules.clear(); + _startModule.clear(); + + _newCampaign = 0; +} + +void Campaign::load(const CampaignDescription &desc) { + if (isRunning()) { + // We are currently running a campaign. Schedule a safe change instead + + changeCampaign(desc); + return; + } + + // We are not currently running a campaign. Directly load the new campaign + loadCampaign(desc); +} + +void Campaign::loadCampaignFile(const CampaignDescription &desc) { + Common::ReadFile *file = 0; + Aurora::GFF3File *gff = 0; + try { + + try { + if (desc.file.empty()) + throw Common::Exception("Campaign file is empty"); + + file = new Common::ReadFile(desc.file); + gff = new Aurora::GFF3File(file, MKTAG('M', 'M', 'D', ' ')); + } catch (Common::Exception &UNUSED(e)) { + delete file; + throw; + } + + _startModule = gff->getTopLevel().getString("StartingMod"); + + const Aurora::GFF3List &modules = gff->getTopLevel().getList("Meta_Mod_list"); + for (Aurora::GFF3List::const_iterator m = modules.begin(); m != modules.end(); ++m) + _modules.push_back((*m)->getString("Mod_Name")); + + if (_startModule.empty()) + throw Common::Exception("No starting module"); + + } catch (Common::Exception &e) { + delete gff; + + e.add("Failed to load campaign \"%s\" (\"%s\")", desc.tag.c_str(), desc.name.getString().c_str()); + throw; + } + + delete gff; +} + +void Campaign::loadCampaign(const CampaignDescription &desc) { + clear(); + loadCampaignFile(desc); + + _currentCampaign = desc; + + try { + _module.load(_currentCampaign.directory + "/" + _startModule + ".mod"); + } catch (Common::Exception &e) { + clear(); + + e.add("Failed to load campaign's starting module"); + throw; + } +} + +void Campaign::run() { + _running = true; + + try { + _module.run(); + } catch (...) { + _running = false; + throw; + } + + _running = false; +} + +bool Campaign::isRunning() const { + return _running; +} + +void Campaign::changeCampaign(const CampaignDescription &desc) { + _newCampaign = &desc; +} + +void Campaign::replaceCampaign() { + if (!_newCampaign) + return; + + const CampaignDescription *campaign = _newCampaign; + + loadCampaign(*campaign); +} + +const Aurora::LocString&Campaign::getName() const { + return _currentCampaign.name; +} + +const Aurora::LocString &Campaign::getDescription() const { + return _currentCampaign.description; +} + +void Campaign::refreshLocalized() { + _module.refreshLocalized(); +} + +Module *Campaign::getModule() { + return &_module; +} + +} // End of namespace Witcher + +} // End of namespace Engines diff --git a/pool/shard011/C++/0121624_testParser.cpp b/pool/shard011/C++/0121624_testParser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4275711d8ee9573367fda8fd40d252026e7d03f0 --- /dev/null +++ b/pool/shard011/C++/0121624_testParser.cpp @@ -0,0 +1,47 @@ +//============================================================================// +// An example to test the performance of reconstruction methods // +// // +// Chao Peng // +// 11/12/2016 // +//============================================================================// + +#include "PRadBenchMark.h" +#include "ConfigParser.h" +#include +#include +#include +#include + +using namespace std; + +int main(int argc, char *argv[]) +{ + if(argc < 2) { + cout << "usage: " << argv[0] << " " << endl; + return -1; + } + + PRadBenchMark timer; + + ConfigParser parser; + int count = 100; + + for(int i = 1; i <= count; ++i) + { + parser.OpenFile(argv[1]); + while(parser.ParseLine()) {;} + + cout <<"------[ " << i << " ]---" + << "---[ " << timer.GetElapsedTimeStr() << " ]---" + << "---[ " << timer.GetElapsedTime()/(double)i << " ms/time ]------" + << "\r" << flush; + } + + cout <<"------[ ev " << count << " ]---" + << "---[ " << timer.GetElapsedTimeStr() << " ]---" + << "---[ " << timer.GetElapsedTime()/(double)count << " ms/time ]------" + << endl; + cout << "Finished." << endl; + + return 0; +} diff --git a/pool/shard011/C++/0121626_TrueTypeRasterizer.cpp b/pool/shard011/C++/0121626_TrueTypeRasterizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8fea1b645e15c284c0ec03eda91d29319ef86cf0 --- /dev/null +++ b/pool/shard011/C++/0121626_TrueTypeRasterizer.cpp @@ -0,0 +1,202 @@ +/** + * Copyright (c) 2006-2016 LOVE Development Team + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + **/ + +// LOVE +#include "TrueTypeRasterizer.h" + +#include "common/Exception.h" + +namespace love +{ +namespace font +{ +namespace freetype +{ + +TrueTypeRasterizer::TrueTypeRasterizer(FT_Library library, love::Data *data, int size, Hinting hinting) + : data(data) + , hinting(hinting) +{ + if (size <= 0) + throw love::Exception("Invalid TrueType font size: %d", size); + + FT_Error err = FT_Err_Ok; + err = FT_New_Memory_Face(library, + (const FT_Byte *)data->getData(), /* first byte in memory */ + data->getSize(), /* size in bytes */ + 0, /* face_index */ + &face); + + if (err != FT_Err_Ok) + throw love::Exception("TrueType Font loading error: FT_New_Face failed: 0x%x (problem with font file?)", err); + + err = FT_Set_Pixel_Sizes(face, size, size); + + if (err != FT_Err_Ok) + throw love::Exception("TrueType Font loading error: FT_Set_Pixel_Sizes failed: 0x%x (invalid size?)", err); + + // Set global metrics + FT_Size_Metrics s = face->size->metrics; + metrics.advance = (int) (s.max_advance >> 6); + metrics.ascent = (int) (s.ascender >> 6); + metrics.descent = (int) (s.descender >> 6); + metrics.height = (int) (s.height >> 6); +} + +TrueTypeRasterizer::~TrueTypeRasterizer() +{ + FT_Done_Face(face); +} + +int TrueTypeRasterizer::getLineHeight() const +{ + return (int)(getHeight() * 1.25); +} + +GlyphData *TrueTypeRasterizer::getGlyphData(uint32 glyph) const +{ + love::font::GlyphMetrics glyphMetrics = {}; + FT_Glyph ftglyph; + + FT_Error err = FT_Err_Ok; + FT_ULong loadoption = hintingToLoadOption(hinting); + + // Initialize + err = FT_Load_Glyph(face, FT_Get_Char_Index(face, glyph), FT_LOAD_DEFAULT | loadoption); + + if (err != FT_Err_Ok) + throw love::Exception("TrueType Font glyph error: FT_Load_Glyph failed (0x%x)", err); + + err = FT_Get_Glyph(face->glyph, &ftglyph); + + if (err != FT_Err_Ok) + throw love::Exception("TrueType Font glyph error: FT_Get_Glyph failed (0x%x)", err); + + FT_Render_Mode rendermode = FT_RENDER_MODE_NORMAL; + if (hinting == HINTING_MONO) + rendermode = FT_RENDER_MODE_MONO; + + err = FT_Glyph_To_Bitmap(&ftglyph, rendermode, 0, 1); + + if (err != FT_Err_Ok) + throw love::Exception("TrueType Font glyph error: FT_Glyph_To_Bitmap failed (0x%x)", err); + + FT_BitmapGlyph bitmap_glyph = (FT_BitmapGlyph) ftglyph; + FT_Bitmap &bitmap = bitmap_glyph->bitmap; //just to make things easier + + // Get metrics + glyphMetrics.bearingX = bitmap_glyph->left; + glyphMetrics.bearingY = bitmap_glyph->top; + glyphMetrics.height = bitmap.rows; + glyphMetrics.width = bitmap.width; + glyphMetrics.advance = (int) (ftglyph->advance.x >> 16); + + GlyphData *glyphData = new GlyphData(glyph, glyphMetrics, GlyphData::FORMAT_LUMINANCE_ALPHA); + + const uint8 *pixels = bitmap.buffer; + uint8 *dest = (uint8 *) glyphData->getData(); + + // We treat the luminance of the FreeType bitmap as alpha in the GlyphData. + if (bitmap.pixel_mode == FT_PIXEL_MODE_MONO) + { + for (int y = 0; y < (int) bitmap.rows; y++) + { + for (int x = 0; x < (int) bitmap.width; x++) + { + // Extract the 1-bit value and convert it to uint8. + uint8 v = ((pixels[x / 8]) & (1 << (7 - (x % 8)))) ? 255 : 0; + dest[2 * (y * bitmap.width + x) + 0] = 255; + dest[2 * (y * bitmap.width + x) + 1] = v; + } + + pixels += bitmap.pitch; + } + } + else if (bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) + { + for (int y = 0; y < (int) bitmap.rows; y++) + { + for (int x = 0; x < (int) bitmap.width; x++) + { + dest[2 * (y * bitmap.width + x) + 0] = 255; + dest[2 * (y * bitmap.width + x) + 1] = pixels[x]; + } + + pixels += bitmap.pitch; + } + } + else + { + delete glyphData; + FT_Done_Glyph(ftglyph); + throw love::Exception("Unknown TrueType glyph pixel mode."); + } + + // Having copied the data over, we can destroy the glyph. + FT_Done_Glyph(ftglyph); + + return glyphData; +} + +int TrueTypeRasterizer::getGlyphCount() const +{ + return (int) face->num_glyphs; +} + +bool TrueTypeRasterizer::hasGlyph(uint32 glyph) const +{ + return FT_Get_Char_Index(face, glyph) != 0; +} + +float TrueTypeRasterizer::getKerning(uint32 leftglyph, uint32 rightglyph) const +{ + FT_Vector kerning = {}; + FT_Get_Kerning(face, leftglyph, rightglyph, FT_KERNING_DEFAULT, &kerning); + return float(kerning.x >> 6); +} + +bool TrueTypeRasterizer::accepts(FT_Library library, love::Data *data) +{ + const FT_Byte *fbase = (const FT_Byte *) data->getData(); + FT_Long fsize = (FT_Long) data->getSize(); + + // Pasing in -1 for the face index lets us test if the data is valid. + return FT_New_Memory_Face(library, fbase, fsize, -1, nullptr) == 0; +} + +FT_ULong TrueTypeRasterizer::hintingToLoadOption(Hinting hint) +{ + switch (hint) + { + case HINTING_NORMAL: + default: + return FT_LOAD_TARGET_NORMAL; + case HINTING_LIGHT: + return FT_LOAD_TARGET_LIGHT; + case HINTING_MONO: + return FT_LOAD_TARGET_MONO; + case HINTING_NONE: + return FT_LOAD_NO_HINTING; + } +} + +} // freetype +} // font +} // love diff --git a/pool/shard011/C++/0121627_devtools_network_protocol_handler.cc b/pool/shard011/C++/0121627_devtools_network_protocol_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..de023c43e3a99b7644230d9dfdb0268c0ee7d13d --- /dev/null +++ b/pool/shard011/C++/0121627_devtools_network_protocol_handler.cc @@ -0,0 +1,114 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/devtools/devtools_network_protocol_handler.h" + +#include "base/values.h" +#include "chrome/browser/devtools/devtools_network_conditions.h" +#include "chrome/browser/devtools/devtools_network_controller_handle.h" +#include "chrome/browser/devtools/devtools_protocol_constants.h" +#include "chrome/browser/profiles/profile.h" +#include "content/public/browser/devtools_agent_host.h" +#include "content/public/browser/web_contents.h" + +DevToolsNetworkProtocolHandler::DevToolsNetworkProtocolHandler() { +} + +DevToolsNetworkProtocolHandler::~DevToolsNetworkProtocolHandler() { +} + +base::DictionaryValue* DevToolsNetworkProtocolHandler::HandleCommand( + content::DevToolsAgentHost* agent_host, + base::DictionaryValue* command_dict) { + int id = 0; + std::string method; + base::DictionaryValue* params = nullptr; + if (!DevToolsProtocol::ParseCommand(command_dict, &id, &method, ¶ms)) + return nullptr; + + namespace network = ::chrome::devtools::Network; + + if (method == network::emulateNetworkConditions::kName) + return EmulateNetworkConditions(agent_host, id, params).release(); + + if (method == network::canEmulateNetworkConditions::kName) + return CanEmulateNetworkConditions(agent_host, id, params).release(); + + return nullptr; +} + +scoped_ptr +DevToolsNetworkProtocolHandler::CanEmulateNetworkConditions( + content::DevToolsAgentHost* agent_host, + int command_id, + base::DictionaryValue* params) { + scoped_ptr result(new base::DictionaryValue()); + result->SetBoolean(chrome::devtools::kResult, true); + return DevToolsProtocol::CreateSuccessResponse(command_id, result.Pass()); +} + +scoped_ptr +DevToolsNetworkProtocolHandler::EmulateNetworkConditions( + content::DevToolsAgentHost* agent_host, + int command_id, + base::DictionaryValue* params) { + namespace names = ::chrome::devtools::Network::emulateNetworkConditions; + + bool offline = false; + if (!params || !params->GetBoolean(names::kParamOffline, &offline)) { + return DevToolsProtocol::CreateInvalidParamsResponse( + command_id, names::kParamOffline); + } + double latency = 0.0; + if (!params->GetDouble(names::kParamLatency, &latency)) { + return DevToolsProtocol::CreateInvalidParamsResponse( + command_id, names::kParamLatency); + } + if (latency < 0.0) + latency = 0.0; + + double download_throughput = 0.0; + if (!params->GetDouble(names::kParamDownloadThroughput, + &download_throughput)) { + return DevToolsProtocol::CreateInvalidParamsResponse( + command_id, names::kParamDownloadThroughput); + } + if (download_throughput < 0.0) + download_throughput = 0.0; + + double upload_throughput = 0.0; + if (!params->GetDouble(names::kParamUploadThroughput, &upload_throughput)) { + return DevToolsProtocol::CreateInvalidParamsResponse( + command_id, names::kParamUploadThroughput); + } + if (upload_throughput < 0.0) + upload_throughput = 0.0; + + scoped_ptr conditions( + new DevToolsNetworkConditions( + offline, latency, download_throughput, upload_throughput)); + + UpdateNetworkState(agent_host, conditions.Pass()); + return scoped_ptr(); +} + +void DevToolsNetworkProtocolHandler::UpdateNetworkState( + content::DevToolsAgentHost* agent_host, + scoped_ptr conditions) { + Profile* profile = Profile::FromBrowserContext( + agent_host->GetBrowserContext()); + if (!profile) + return; + profile->GetDevToolsNetworkControllerHandle()->SetNetworkState( + agent_host->GetId(), conditions.Pass()); +} + +void DevToolsNetworkProtocolHandler::DevToolsAgentStateChanged( + content::DevToolsAgentHost* agent_host, + bool attached) { + scoped_ptr conditions; + if (attached) + conditions.reset(new DevToolsNetworkConditions()); + UpdateNetworkState(agent_host, conditions.Pass()); +} diff --git a/pool/shard011/C++/0121628_GtPolylineF.cpp b/pool/shard011/C++/0121628_GtPolylineF.cpp new file mode 100644 index 0000000000000000000000000000000000000000..caa1a53ce02e9effb15f84cf71dd964cf3c9e1b8 --- /dev/null +++ b/pool/shard011/C++/0121628_GtPolylineF.cpp @@ -0,0 +1,193 @@ +/* +** This file is part of the TridentCAD +** This software was merged and developed by: +** +** Anthony Daniels +** +** TridentCAD is free software: you can redistribute it and/or modify +** it under the terms of the GNU Lesser General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** The United States of America Department of Defense has unlimited +** usage, redistribution, and modification rights to TridentCAD. +** +** TridentCAD 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 TridentCAD. If not, see . +*/ +#pragma once +#pragma warning(push) +#pragma warning (disable : 4005 ) /* macro redefinition */ +#define HTL_DLLEXPORT +#pragma warning(pop) + +#include ".\GtPolylineF.h" +#include + +namespace GT +{ + + namespace GtCore + { + GtPolylineF::GtPolylineF(void) + : HtlBase() + { + //HtlBase Initialization + m_strType = "GtPolylineF"; + //GtPolylineF Initialization//////////////////// + m_objNullPoint.Zero(); + return; + }; + + + GtPolylineF::GtPolylineF(GtPolylineF& rhs) + : HtlBase(rhs) + { + //HtlBase Initialization + m_strType = "GtPolylineF"; + //GtPolylineF Initialization//////////////////// + size_t i, intNumPts; + m_arrObjPoints.clear(); + intNumPts = rhs.Size(); + for(i = 0; i < intNumPts; i++) + { + this->m_arrObjPoints.push_back(rhs.m_arrObjPoints.at(i)); + }; + return; + }; + + GtPolylineF & GtPolylineF::operator = (GtPolylineF & rhs) + { + if(this == &rhs) + return *this; + + HtlBase::operator=(rhs); + + //ORSSerializable Initialization + m_strType = "GtPolylineF"; + //GtPolylineF Initialization//////////////////// + size_t i, intNumPts; + m_arrObjPoints.clear(); + intNumPts = rhs.Size(); + for(i = 0; i < intNumPts; i++) + { + this->m_arrObjPoints.push_back(rhs.m_arrObjPoints.at(i)); + }; + return *this; + }; + + GtPolylineF::~GtPolylineF(void) + { + return; + }; + + + bool GtPolylineF::operator == (GtPolylineF & rhs) + { + size_t i, intLHSNumPoints, intRHSNumPoints; + intLHSNumPoints = m_arrObjPoints.size(); + intRHSNumPoints = rhs.m_arrObjPoints.size(); + if(intLHSNumPoints != intRHSNumPoints){return false;}; + //if number of points same must compare all of them + for(i = 0; i < intLHSNumPoints; i++) + { + if(m_arrObjPoints.at(i) != rhs.m_arrObjPoints.at(i)){return false;}; + } + //made it this far without finding a difference, must be the same + return true; + }; + + bool GtPolylineF::operator != (GtPolylineF & rhs) + { + size_t i, intLHSNumPoints, intRHSNumPoints; + intLHSNumPoints = m_arrObjPoints.size(); + intRHSNumPoints = rhs.m_arrObjPoints.size(); + if(intLHSNumPoints != intRHSNumPoints){return true;}; + //if number of points same must compare all of them + for(i = 0; i < intLHSNumPoints; i++) + { + if(m_arrObjPoints.at(i) != rhs.m_arrObjPoints.at(i)){return true;}; + } + //made it this far without finding a difference, must be the same + return false; + }; + + void GtPolylineF::Clear(void) + { + m_arrObjPoints.clear(); + }; + size_t GtPolylineF::Size(void) + { + return m_arrObjPoints.size(); + }; + GtPoint3DF & GtPolylineF::At(size_t intIndex) + { + size_t intNumPoints; + intNumPoints = m_arrObjPoints.size(); + if((intIndex >= 0) && (intIndex < intNumPoints)) + { + return m_arrObjPoints.at(intIndex); + }else{ + return m_objNullPoint; + }; + }; + void GtPolylineF::PushBack(GtPoint3DF & objNewPoint) + { + m_arrObjPoints.push_back(objNewPoint); + return; + }; + void GtPolylineF::Round(int intNumDecimals) + { + size_t i, intNumPoints; + intNumPoints = m_arrObjPoints.size(); + if(intNumPoints <= 0){return;}; + for(i = 0; i < intNumPoints; i++) + { + m_arrObjPoints.at(i).Round(intNumDecimals); + }; + }; + + //Virtual Inheritance Serialization Engines + //SERIALIZATION ACCESSOR MACRO/////////////////////////////////////// + int GtPolylineF::Save(HTL::HtlElement * ptrCurrNode, std::string strMemVarName, bool blnWithSubObjects) + { + + int intReturn = 0; + //SAFETY CHECK //put at top of all Serialize Methods + if(!ptrCurrNode){return 0;}; + //CALL PARENT CLASS Serialize() + /*...*/ + HtlBase::Save(ptrCurrNode, strMemVarName, blnWithSubObjects); + //Standard Member Variables + intReturn &= SetHtlMemVar< StlVector ,STL_CONTAINER>(ptrCurrNode,"m_arrObjPoints",m_arrObjPoints,true); + + + return intReturn; + + + }; + + int GtPolylineF::Load(HTL::HtlElement * ptrCurrNode, std::string strMemVarName) + { + + int intReturn = 0; + //SAFETY CHECK //put at top of all Serialize Methods + if(!ptrCurrNode){return 0;}; + //CALL PARENT CLASS Serialize() + /*...*/ + HtlBase::Load(ptrCurrNode,strMemVarName); + //Standard Member Variables + //Standard Member Variables + intReturn &= GetHtlMemVar< StlVector ,STL_CONTAINER>(ptrCurrNode,"m_arrObjPoints",m_arrObjPoints); + return intReturn; + + }; + + };//end namespace GtCore + +};//end namespace GT \ No newline at end of file diff --git a/pool/shard011/C++/0121629_syscall_wrappers_unittest.cc b/pool/shard011/C++/0121629_syscall_wrappers_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8b48fe586f04677a4add441b47a5dd2f42986d4 --- /dev/null +++ b/pool/shard011/C++/0121629_syscall_wrappers_unittest.cc @@ -0,0 +1,65 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "sandbox/linux/services/syscall_wrappers.h" + +#include +#include +#include +#include + +#include "base/logging.h" +#include "base/posix/eintr_wrapper.h" +#include "base/third_party/valgrind/valgrind.h" +#include "build/build_config.h" +#include "sandbox/linux/tests/test_utils.h" +#include "sandbox/linux/tests/unit_tests.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace sandbox { + +namespace { + +TEST(SyscallWrappers, BasicSyscalls) { + EXPECT_EQ(getpid(), sys_getpid()); +} + +TEST(SyscallWrappers, CloneBasic) { + pid_t child = sys_clone(SIGCHLD); + TestUtils::HandlePostForkReturn(child); + EXPECT_LT(0, child); +} + +TEST(SyscallWrappers, CloneParentSettid) { + pid_t ptid = 0; + pid_t child = sys_clone(CLONE_PARENT_SETTID | SIGCHLD, nullptr, &ptid, + nullptr, nullptr); + TestUtils::HandlePostForkReturn(child); + EXPECT_LT(0, child); + EXPECT_EQ(child, ptid); +} + +TEST(SyscallWrappers, CloneChildSettid) { + pid_t ctid = 0; + pid_t pid = + sys_clone(CLONE_CHILD_SETTID | SIGCHLD, nullptr, nullptr, &ctid, nullptr); + + const int kSuccessExit = 0; + if (0 == pid) { + // In child. + if (sys_getpid() == ctid) + _exit(kSuccessExit); + _exit(1); + } + + ASSERT_NE(-1, pid); + int status = 0; + ASSERT_EQ(pid, HANDLE_EINTR(waitpid(pid, &status, 0))); + ASSERT_TRUE(WIFEXITED(status)); + EXPECT_EQ(kSuccessExit, WEXITSTATUS(status)); +} + +} // namespace + +} // namespace sandbox diff --git a/pool/shard011/C++/0121630_token_service_table_unittest.cc b/pool/shard011/C++/0121630_token_service_table_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..47391e4763742964c03cf0e600325bad4e11cdeb --- /dev/null +++ b/pool/shard011/C++/0121630_token_service_table_unittest.cc @@ -0,0 +1,112 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/files/scoped_temp_dir.h" +#include "base/macros.h" +#include "base/strings/string_number_conversions.h" +#include "base/time/time.h" +#include "build/build_config.h" +#include "components/os_crypt/os_crypt_mocker.h" +#include "components/signin/core/browser/webdata/token_service_table.h" +#include "components/webdata/common/web_database.h" +#include "testing/gtest/include/gtest/gtest.h" + +using base::Time; + +class TokenServiceTableTest : public testing::Test { + public: + TokenServiceTableTest() {} + ~TokenServiceTableTest() override {} + + protected: + void SetUp() override { + OSCryptMocker::SetUpWithSingleton(); + ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); + file_ = temp_dir_.GetPath().AppendASCII("TestWebDatabase"); + + table_.reset(new TokenServiceTable); + db_.reset(new WebDatabase); + db_->AddTable(table_.get()); + ASSERT_EQ(sql::INIT_OK, db_->Init(file_)); + } + + void TearDown() override { OSCryptMocker::TearDown(); } + + base::FilePath file_; + base::ScopedTempDir temp_dir_; + std::unique_ptr table_; + std::unique_ptr db_; + + private: + DISALLOW_COPY_AND_ASSIGN(TokenServiceTableTest); +}; + +TEST_F(TokenServiceTableTest, TokenServiceGetAllRemoveAll) { + std::map out_map; + std::string service; + std::string service2; + service = "testservice"; + service2 = "othertestservice"; + + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_TRUE(out_map.empty()); + + // Check that get all tokens works + EXPECT_TRUE(table_->SetTokenForService(service, "pepperoni")); + EXPECT_TRUE(table_->SetTokenForService(service2, "steak")); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ("pepperoni", out_map.find(service)->second); + EXPECT_EQ("steak", out_map.find(service2)->second); + out_map.clear(); + + // Purge + EXPECT_TRUE(table_->RemoveAllTokens()); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_TRUE(out_map.empty()); + + // Check that you can still add it back in + EXPECT_TRUE(table_->SetTokenForService(service, "cheese")); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ("cheese", out_map.find(service)->second); +} + +TEST_F(TokenServiceTableTest, TokenServiceGetSet) { + std::map out_map; + std::string service; + service = "testservice"; + + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_TRUE(out_map.empty()); + + EXPECT_TRUE(table_->SetTokenForService(service, "pepperoni")); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ("pepperoni", out_map.find(service)->second); + out_map.clear(); + + // try blanking it - won't remove it from the db though! + EXPECT_TRUE(table_->SetTokenForService(service, std::string())); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ("", out_map.find(service)->second); + out_map.clear(); + + // try mutating it + EXPECT_TRUE(table_->SetTokenForService(service, "ham")); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ("ham", out_map.find(service)->second); +} + +TEST_F(TokenServiceTableTest, TokenServiceRemove) { + std::map out_map; + std::string service; + std::string service2; + service = "testservice"; + service2 = "othertestservice"; + + EXPECT_TRUE(table_->SetTokenForService(service, "pepperoni")); + EXPECT_TRUE(table_->SetTokenForService(service2, "steak")); + EXPECT_TRUE(table_->RemoveTokenForService(service)); + EXPECT_TRUE(table_->GetAllTokens(&out_map)); + EXPECT_EQ(0u, out_map.count(service)); + EXPECT_EQ("steak", out_map.find(service2)->second); +} diff --git a/pool/shard011/C++/0121632_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_memmove_73b.cpp b/pool/shard011/C++/0121632_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_memmove_73b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c4f2a6e221d1921018ad8b5ac3868c906e4732c --- /dev/null +++ b/pool/shard011/C++/0121632_CWE195_Signed_to_Unsigned_Conversion_Error__fgets_memmove_73b.cpp @@ -0,0 +1,73 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__fgets_memmove_73b.cpp +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-73b.tmpl.cpp +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: fgets Read data from the console using fgets() + * GoodSource: Positive integer + * Sinks: memmove + * BadSink : Copy strings using memmove() with the length of data + * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +using namespace std; + +namespace CWE195_Signed_to_Unsigned_Conversion_Error__fgets_memmove_73 +{ + +#ifndef OMITBAD + +void badSink(list dataList) +{ + /* copy data out of dataList */ + int data = dataList.back(); + { + char source[100]; + char dest[100] = ""; + memset(source, 'A', 100-1); + source[100-1] = '\0'; + if (data < 100) + { + /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, + * the sign conversion could result in a very large number */ + memmove(dest, source, data); + dest[data] = '\0'; /* NULL terminate */ + } + printLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(list dataList) +{ + int data = dataList.back(); + { + char source[100]; + char dest[100] = ""; + memset(source, 'A', 100-1); + source[100-1] = '\0'; + if (data < 100) + { + /* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative, + * the sign conversion could result in a very large number */ + memmove(dest, source, data); + dest[data] = '\0'; /* NULL terminate */ + } + printLine(dest); + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard011/C++/0121633_CanvasRenderingContext.cpp b/pool/shard011/C++/0121633_CanvasRenderingContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cfc17cd00c18b8c9ba25af4c22c05f6e0ed5e508 --- /dev/null +++ b/pool/shard011/C++/0121633_CanvasRenderingContext.cpp @@ -0,0 +1,113 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "CanvasRenderingContext.h" + +#include "CachedImage.h" +#include "CanvasPattern.h" +#include "HTMLImageElement.h" +#include "HTMLVideoElement.h" +#include "Image.h" +#include "URL.h" +#include "SecurityOrigin.h" + +namespace WebCore { + +CanvasRenderingContext::CanvasRenderingContext(HTMLCanvasElement* canvas) + : m_canvas(canvas) +{ +} + +bool CanvasRenderingContext::wouldTaintOrigin(const CanvasPattern* pattern) +{ + if (canvas()->originClean() && pattern && !pattern->originClean()) + return true; + return false; +} + +bool CanvasRenderingContext::wouldTaintOrigin(const HTMLCanvasElement* sourceCanvas) +{ + if (canvas()->originClean() && sourceCanvas && !sourceCanvas->originClean()) + return true; + return false; +} + +bool CanvasRenderingContext::wouldTaintOrigin(const HTMLImageElement* image) +{ + if (!image || !canvas()->originClean()) + return false; + + CachedImage* cachedImage = image->cachedImage(); + if (!cachedImage->image()->hasSingleSecurityOrigin()) + return true; + + return wouldTaintOrigin(cachedImage->response().url()) && !cachedImage->passesAccessControlCheck(canvas()->securityOrigin()); +} + +bool CanvasRenderingContext::wouldTaintOrigin(const HTMLVideoElement* video) +{ +#if ENABLE(VIDEO) + // FIXME: This check is likely wrong when a redirect is involved. We need + // to test the finalURL. Please be careful when fixing this issue not to + // make currentSrc be the final URL because then the + // HTMLMediaElement.currentSrc DOM API would leak redirect destinations! + if (!video || !canvas()->originClean()) + return false; + + if (!video->hasSingleSecurityOrigin()) + return true; + + if (!(video->player() && video->player()->didPassCORSAccessCheck()) && wouldTaintOrigin(video->currentSrc())) + return true; + +#else + UNUSED_PARAM(video); +#endif + + return false; +} + +bool CanvasRenderingContext::wouldTaintOrigin(const URL& url) +{ + if (!canvas()->originClean()) + return false; + + if (canvas()->securityOrigin()->taintsCanvas(url)) + return true; + + if (url.protocolIsData()) + return false; + + return false; +} + +void CanvasRenderingContext::checkOrigin(const URL& url) +{ + if (wouldTaintOrigin(url)) + canvas()->setOriginTainted(); +} + +} // namespace WebCore diff --git a/pool/shard011/C++/0121635_del_source_formula_Equivalence_Normalize.cpp b/pool/shard011/C++/0121635_del_source_formula_Equivalence_Normalize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53d531aa6b2a439497599e4cb07bb74c9d8c0244 --- /dev/null +++ b/pool/shard011/C++/0121635_del_source_formula_Equivalence_Normalize.cpp @@ -0,0 +1,188 @@ +/*****************************************************************************/ +/* Project name: del - mathematics development language */ +/* File Name: del_source_formula_Equivalence_Normalize.cpp */ +/* Description: normalization subset formula routines */ +/* Copyright: (c) 2006-2009 Dmitri Vlasov */ +/* Author: Dmitri Yurievich Vlasov, Novosibirsk, Russia */ +/* Email: vlasov at academ.org */ +/* URL: http://mathdevlanguage.sourceforge.net */ +/* Modified by: */ +/* License: GNU General Public License Version 3 */ +/*****************************************************************************/ + +#pragma once + +#include "del/lexer/del_lexer.hpp" +#include "del/source/del_source.hpp" + +namespace del { +namespace source { +namespace formula { + + /**************************** + * Private members + ****************************/ + +using manipulator :: endLine; +using manipulator :: space; +using manipulator :: tab; + + // normalization routines + void + Equivalence :: transformIntersection (del :: Theory* theory) const + { + for (value :: Integer i = 0; i < term_2_->getSize(); ++ i) { + const del :: Term* const + conjTerm = Formula :: term_2_->getSubterm (i); + const del :: Formula* const formula = new Equivalence + ( + location_, + Formula :: term_1_->clone(), + conjTerm->clone(), + image_, + COMPLEX_KIND, + isRoot_ + ); + theory->addFormula (formula); + } + Del :: statistics().data()->incConjunctionRight(); + } + void + Equivalence :: transformComplexExists (del :: Theory* theory, const del :: Term* complexExists) const + { + const value :: Variable + var = Table :: variables()->fresh ("X"); + const del :: Term* const + term_1_1 = new term :: Variable (location_, var, complexExists->getSubterm()); + + const del :: Term* const + term_1_2 = complexExists->getSubterm()->clone(); + const del :: Term* const + term_2_1 = new term :: Variable (location_, var, complexExists->getSubterm()); + const del :: Term* const + term_2_2 = complexExists->getSubterm()->clone(); + + const del :: Formula* const first = new formula :: Equivalence + ( + location_, + term_1_1, + term_1_2, + image_ + ); + const del :: Formula* const second = new formula :: Equivalence + ( + location_, + term_2_2, + term_2_1, + image_ + ); + theory->addFormula (clone()); + theory->replace (complexExists->getSubterm(), term_1_1); + theory->addFormula (first); + theory->addFormula (second); + } + void + Equivalence :: transformRightExists + ( + del :: Theory* theory, + del :: Term*& term + ) const + { + /* If A1 ⊓ ··· ⊓ An ⊓ ∃r1.B1 ⊓ ··· ∃rm.Bm ⊑ ∃r.B in T, remove it, + * remove it, take a new concept names Z1...Zm and add + * A1 ⊓ ··· ⊓ An ⊓ Z1 ⊓ ... ⊓ Zm ⊑ X, ∃r1 .B1 ≡ Z1 ... ∃rm .Bm ≡ Zm + * and X ≡ ∃r.B to T */ + + const value :: Variable + var = Table :: variables()->fresh ("Y"); + const del :: Term* const + varTerm = new term :: Variable (location_, var, term); + + + const del :: Formula* const first = new formula :: Identity + ( + location_, + term, + varTerm, + image_ + ); + term = varTerm->clone(); + const del :: Formula* const + second = clone(); + theory->addFormula (first); + theory->addFormula (second); + } + void + Equivalence :: transformExisisVector (del :: Theory* theory, del :: Term* term) const + { + if (!term->isIntersection()) { + return; + } + term :: Intersect* + existsIntersection = dynamic_cast(term); + term :: Intersect* + intersection = dynamic_cast(const_cast(term_1_)); + + for (value :: Integer i = 0; i < existsIntersection->getSize(); ++ i) { + const value :: Variable + var = Table :: variables()->fresh ("U"); + const del :: Term* const + subterm = existsIntersection->getSubterm (i); + const del :: Term* const + varTerm = new term :: Variable (location_, var, subterm); + + intersection->addTerm (varTerm); + + const del :: Formula* const first = new formula :: Identity + ( + location_, + subterm->clone(), + varTerm->clone(), + image_ + ); + theory->addFormula (first); + } + existsIntersection->commitSuicide(); + } + void + Equivalence :: transformSingleExists (del :: Theory* theory) const + { + /* If ∃r1.B1 ⊑ ∃r2.B2 in T , remove it, + * take a new concept name X and add ∃r1.B1 ⊑ X + * and X ⊑ ∃r2.B2 to T */ + if (!term_1_->isExists() || !term_2_->isExists()) { + return; + } + const value :: Variable + var = Table :: variables()->fresh ("W"); + const del :: Term* const + term_1_1 = term_1_->clone(); + const del :: Term* const + term_1_2 = new term :: Variable (location_, var, term_1_1); + const del :: Term* const + term_2_1 = new term :: Variable (location_, var); + const del :: Term* const + term_2_2 = term_2_->clone(); + + const del :: Formula* const first = new formula :: Identity + ( + location_, + term_1_1, + term_1_2, + image_ + ); + const del :: Formula* const second = new formula :: Equivalence + ( + location_, + term_2_1, + term_2_2, + image_ + ); + theory->addFormula (first); + theory->addFormula (second); + } +} +} +} + + diff --git a/pool/shard011/C++/0121636_motion_event_web.cc b/pool/shard011/C++/0121636_motion_event_web.cc new file mode 100644 index 0000000000000000000000000000000000000000..bff45355ce09326a5d5c922e960673667626f451 --- /dev/null +++ b/pool/shard011/C++/0121636_motion_event_web.cc @@ -0,0 +1,180 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// MSVC++ requires this to be set before any other includes to get M_PI. +#define _USE_MATH_DEFINES + +#include "content/browser/renderer_host/input/motion_event_web.h" + +#include + +#include "base/logging.h" +#include "content/browser/renderer_host/input/web_input_event_util.h" +#include "content/common/input/web_touch_event_traits.h" + +using blink::WebInputEvent; +using blink::WebTouchEvent; +using blink::WebTouchPoint; + +namespace content { +namespace { + +ui::MotionEvent::Action GetActionFrom(const WebTouchEvent& event) { + DCHECK(event.touchesLength); + switch (event.type) { + case WebInputEvent::TouchStart: + if (WebTouchEventTraits::AllTouchPointsHaveState( + event, WebTouchPoint::StatePressed)) + return ui::MotionEvent::ACTION_DOWN; + else + return ui::MotionEvent::ACTION_POINTER_DOWN; + case WebInputEvent::TouchEnd: + if (WebTouchEventTraits::AllTouchPointsHaveState( + event, WebTouchPoint::StateReleased)) + return ui::MotionEvent::ACTION_UP; + else + return ui::MotionEvent::ACTION_POINTER_UP; + case WebInputEvent::TouchCancel: + DCHECK(WebTouchEventTraits::AllTouchPointsHaveState( + event, WebTouchPoint::StateCancelled)); + return ui::MotionEvent::ACTION_CANCEL; + case WebInputEvent::TouchMove: + return ui::MotionEvent::ACTION_MOVE; + default: + break; + }; + NOTREACHED() + << "Unable to derive a valid MotionEvent::Action from the WebTouchEvent."; + return ui::MotionEvent::ACTION_CANCEL; +} + +int GetActionIndexFrom(const WebTouchEvent& event) { + for (size_t i = 0; i < event.touchesLength; ++i) { + if (event.touches[i].state != WebTouchPoint::StateUndefined && + event.touches[i].state != WebTouchPoint::StateStationary) + return i; + } + return -1; +} + +} // namespace + +MotionEventWeb::MotionEventWeb(const WebTouchEvent& event) + : event_(event), + cached_action_(GetActionFrom(event)), + cached_action_index_(GetActionIndexFrom(event)) { + DCHECK_GT(GetPointerCount(), 0U); +} + +MotionEventWeb::~MotionEventWeb() {} + +int MotionEventWeb::GetId() const { + return 0; +} + +MotionEventWeb::Action MotionEventWeb::GetAction() const { + return cached_action_; +} + +int MotionEventWeb::GetActionIndex() const { return cached_action_index_; } + +size_t MotionEventWeb::GetPointerCount() const { return event_.touchesLength; } + +int MotionEventWeb::GetPointerId(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return event_.touches[pointer_index].id; +} + +float MotionEventWeb::GetX(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return event_.touches[pointer_index].position.x; +} + +float MotionEventWeb::GetY(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return event_.touches[pointer_index].position.y; +} + +float MotionEventWeb::GetRawX(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return event_.touches[pointer_index].screenPosition.x; +} + +float MotionEventWeb::GetRawY(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return event_.touches[pointer_index].screenPosition.y; +} + +float MotionEventWeb::GetTouchMajor(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return 2.f * std::max(event_.touches[pointer_index].radiusX, + event_.touches[pointer_index].radiusY); +} + +float MotionEventWeb::GetTouchMinor(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + return 2.f * std::min(event_.touches[pointer_index].radiusX, + event_.touches[pointer_index].radiusY); +} + +float MotionEventWeb::GetOrientation(size_t pointer_index) const { + DCHECK_LT(pointer_index, GetPointerCount()); + + float rotation_angle_rad = event_.touches[pointer_index].rotationAngle + * M_PI / 180.f; + DCHECK(0 <= rotation_angle_rad && rotation_angle_rad <= M_PI_2) + << "Unexpected touch rotation angle"; + + if (event_.touches[pointer_index].radiusX + > event_.touches[pointer_index].radiusY) { + // The case radiusX == radiusY is omitted from here on purpose: for circles, + // we want to pass the angle (which could be any value in such cases but + // always seem to be set to zero) unchanged. + rotation_angle_rad -= (float) M_PI_2; + } + + return rotation_angle_rad; +} + +float MotionEventWeb::GetPressure(size_t pointer_index) const { + return 0.f; +} + +base::TimeTicks MotionEventWeb::GetEventTime() const { + return base::TimeTicks() + + base::TimeDelta::FromMicroseconds(event_.timeStampSeconds * + base::Time::kMicrosecondsPerSecond); +} + +ui::MotionEvent::ToolType MotionEventWeb::GetToolType( + size_t pointer_index) const { + // TODO(jdduke): Plumb tool type from the platform event, crbug.com/404128. + DCHECK_LT(pointer_index, GetPointerCount()); + return TOOL_TYPE_UNKNOWN; +} + +int MotionEventWeb::GetButtonState() const { + NOTIMPLEMENTED(); + return 0; +} + +int MotionEventWeb::GetFlags() const { + return WebEventModifiersToEventFlags(event_.modifiers); +} + +scoped_ptr MotionEventWeb::Clone() const { + return scoped_ptr(new MotionEventWeb(event_)); +} + +scoped_ptr MotionEventWeb::Cancel() const { + WebTouchEvent cancel_event(event_); + WebTouchEventTraits::ResetTypeAndTouchStates( + blink::WebInputEvent::TouchCancel, + // TODO(rbyers): Shouldn't we use a fresh timestamp? + event_.timeStampSeconds, + &cancel_event); + return scoped_ptr(new MotionEventWeb(cancel_event)); +} + +} // namespace content diff --git a/pool/shard011/C++/0121637_SubspaceChat.cpp b/pool/shard011/C++/0121637_SubspaceChat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fe94f0c1cd8dbb098ba79c314d8e875188dac49f --- /dev/null +++ b/pool/shard011/C++/0121637_SubspaceChat.cpp @@ -0,0 +1,264 @@ +#include "SubspaceChat.h" + +#include + +#include "AsciiUtil.h" +#include "SubspaceSettings.h" + +#include "SubspacePlayer.h" + +const string SubspaceChat::defaultHeaderSeparator_ = "> "; +const string SubspaceChat::defaultName_ = ""; + +SubspaceChat::SubspaceChat() : + headerWidth_(defaultHeaderWidth_), + headerSeparator_(defaultHeaderSeparator_), + lineWidth_(defaultLineWidth_) + //players_(0) +{ + //headerSeparator_ = "> "; +} + +SubspaceChat::~SubspaceChat() +{ +} + +Uint SubspaceChat::countLines() const +{ + Uint lines = 0, msgLines = 0; + + MessageList::const_iterator i; + for(i = messages_.begin(); i != messages_.end(); ++i) + { + msgLines = countMessageLines(*i); + lines += msgLines; + } + + return lines; +} + +double SubspaceChat::getDisplayHeight() const +{ + Uint lines = min(linesDisplayed_, countLines()); + + return (double)lines * font_.getFontHeight(); +} + +const TextureFont& SubspaceChat::getFont() const +{ + return font_; +} + +Uint SubspaceChat::getHeaderWidth() const +{ + return headerWidth_; +} + +Uint SubspaceChat::getLinesDisplayed() const +{ + return linesDisplayed_; +} + +Uint SubspaceChat::getLineWidth() const +{ + return lineWidth_; +} + +Uint SubspaceChat::size() const +{ + return (Uint)messages_.size(); +} + + +void SubspaceChat::setFont(const TextureFont& font) +{ + font_ = font; +} + +void SubspaceChat::setHeaderWidth(Uint width) +{ + Uint w = min(width, lineWidth_ - headerSeparator_.size() - 1 - 1); + headerWidth_ = w; +} + +void SubspaceChat::setLineWidth(Uint width) +{ + lineWidth_ = width; +} + +void SubspaceChat::setLinesDisplayed(Uint lines) +{ + linesDisplayed_ = lines; + if(countLines() < linesDisplayed_) + { + linesDisplayOffset_ = 0; + } +} + +void SubspaceChat::setLineOffset(Uint offset) +{ + linesDisplayOffset_ = offset; +} + +/*void SubspaceChat::setPlayers(const SubspacePlayerMap* map) +{ + players_ = map; +}*/ + +void SubspaceChat::addMessage(const ChatMessage& m) +{ + Uint size = countLines(); + Uint newLines = countMessageLines(m); + if(size + newLines > linesDisplayed_) // if at the end of the buffer + linesDisplayOffset_ = size+newLines - linesDisplayed_; // scroll down + + messages_.push_back(m); +} + + +void SubspaceChat::clear() +{ + messages_.clear(); +} + +/*void SubspaceChat::doChat(Uint16 playerID, const string& message, Uint8 chatType, Uint8 soundByte) +{ + string name = defaultName_; + SubspacePlayerMap::const_iterator i; + if(players_) + { + i = players_->find(playerID); + if(i != players_->end()) + name = ((*i).second)->getName(); + } + + addMessage(ChatMessage(name, message, (ChatType)chatType, soundByte)); +}*/ + +/*void SubspaceChat::doChatOutbound(Uint16 playerID, const string& message, Uint8 chatType, Uint8 soundByte) +{ + doChat(playerID, message, chatType, soundByte); + + SubspaceChatCommands::Chat cmd; + cmd.playerID = playerID; + cmd.message = message; + cmd.type = (ChatType)chatType; + cmd.soundByte = soundByte; + + this->CommandGenerator::invokeCommand(&cmd); +}*/ + +void SubspaceChat::writeMessage(const string& sender, const string& text, ChatType chatType) +{ + this->messages_.push_back(ChatMessage(sender, text, chatType)); +} + +void SubspaceChat::draw() const +{ + Uint line = 0; + Uint msgLines = 0; + Uint msgNum = 0, msgLineOffset = 0; + + if(messages_.size() == 0) + return; + + findLine(linesDisplayOffset_, msgNum, msgLineOffset); + + // display offset message + /*for(msgNum; line < linesDisplayed_ && msgNum < messages_.size(); ++msgNum) + { + msgLines = drawMessage(messages_[msgNum], msgLineOffset, linesDisplayed_); + glTranslated(0, -(double)font_.getFontHeight() * msgLines, 0); + line += msgLines; + }*/ + + // display offset message + msgLines = drawMessage(messages_[msgNum], msgLineOffset, linesDisplayed_); + //glTranslated(0, -(double)font_.getFontHeight() * msgLines, 0); + line += msgLines; + ++msgNum; + + // display other messages + for(msgNum; line < linesDisplayed_ && msgNum < messages_.size(); ++msgNum) + { + msgLines = drawMessage(messages_[msgNum], 0, linesDisplayed_ - line); + //glTranslated(0, font_.getHeight() * msgLines, 0); + line += msgLines; + } +} + +void SubspaceChat::update(double time) +{ +} + +Uint SubspaceChat::countMessageLines(const ChatMessage& msg) const +{ + /* + <----------lineWidth--------> + Header Message + |-------|-------------------| + */ + + Uint messageWidth = lineWidth_ - headerWidth_; + return AsciiUtil::countWrapLines(msg.text, messageWidth); +} + +void SubspaceChat::findLine(Uint lineNum, Uint& msgNum, Uint& msgLineOffset) const +{ + Uint msgLines = 0; + Uint line = 0; + + msgNum = 0; + + msgLines = countMessageLines(messages_[msgNum]); + while(line + msgLines <= lineNum) + { + ++msgNum; + line += msgLines; + msgLines = countMessageLines(messages_[msgNum]); + } + + //msgLineOffset = line+(msgLines-1) - lineNum; + msgLineOffset = lineNum - line; +} + + +Uint SubspaceChat::drawMessage(const ChatMessage& msg, Uint lineOffset, Uint maxMsgLines) const +{ + assert(headerWidth_ >= headerSeparator_.size()); + + Uint senderWidth = headerWidth_ - headerSeparator_.size(); + Uint messageWidth = lineWidth_ - headerWidth_; + vector msgText = AsciiUtil::wordWrap(msg.text, messageWidth); + string headerString; + Uint linesDisplayed = 0; + + if(msg.sender.size() == 0) + headerString = ""; + else if(msg.sender.size() > senderWidth) + { + headerString = msg.sender.substr(0, senderWidth); + headerString += headerSeparator_; + } + else + { + headerString = AsciiUtil::fixedWidthString(msg.sender, senderWidth, AsciiUtil::rightJustified); + headerString += headerSeparator_; + } + + vector::iterator i; + for(i = msgText.begin() + lineOffset; i != msgText.end() && linesDisplayed < maxMsgLines; ++i) + { + glTranslated(0, -(double)font_.getFontHeight(), 0); + + font_.displayString(headerString.c_str(), msg.getNameColor()); + glTranslated(headerString.length() * font_.getFontWidth(), 0, 0); + + font_.displayString((*i).c_str(), msg.getTextColor()); + glTranslated(-(double)(headerString.length() * font_.getFontWidth()), 0, 0); + + ++linesDisplayed; + } + + return linesDisplayed; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121638_chain.cpp b/pool/shard011/C++/0121638_chain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a5bc56f6cd9e9b2bf69293a95635480290867f1a --- /dev/null +++ b/pool/shard011/C++/0121638_chain.cpp @@ -0,0 +1,198 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2017 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include + +#include "validation.h" + +/* Moved here from the header, because we need auxpow and the logic + becomes more involved. */ +CBlockHeader CBlockIndex::GetBlockHeader(const Consensus::Params& consensusParams) const +{ + CBlockHeader block; + + block.nVersion = nVersion; + + /* The CBlockIndex object's block header is missing the auxpow. + So if this is an auxpow block, read it from disk instead. We only + have to read the actual *header*, not the full block. */ + if (block.IsAuxpow()) + { + ReadBlockHeaderFromDisk(block, this, consensusParams); + return block; + } + + if (pprev) + block.hashPrevBlock = pprev->GetBlockHash(); + block.hashMerkleRoot = hashMerkleRoot; + block.nTime = nTime; + block.nBits = nBits; + block.nNonce = nNonce; + return block; +} + +/** + * CChain implementation + */ +void CChain::SetTip(CBlockIndex *pindex) { + if (pindex == nullptr) { + vChain.clear(); + return; + } + vChain.resize(pindex->nHeight + 1); + while (pindex && vChain[pindex->nHeight] != pindex) { + vChain[pindex->nHeight] = pindex; + pindex = pindex->pprev; + } +} + +CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { + int nStep = 1; + std::vector vHave; + vHave.reserve(32); + + if (!pindex) + pindex = Tip(); + while (pindex) { + vHave.push_back(pindex->GetBlockHash()); + // Stop when we have added the genesis block. + if (pindex->nHeight == 0) + break; + // Exponentially larger steps back, plus the genesis block. + int nHeight = std::max(pindex->nHeight - nStep, 0); + if (Contains(pindex)) { + // Use O(1) CChain index if possible. + pindex = (*this)[nHeight]; + } else { + // Otherwise, use O(log n) skiplist. + pindex = pindex->GetAncestor(nHeight); + } + if (vHave.size() > 10) + nStep *= 2; + } + + return CBlockLocator(vHave); +} + +const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { + if (pindex == nullptr) { + return nullptr; + } + if (pindex->nHeight > Height()) + pindex = pindex->GetAncestor(Height()); + while (pindex && !Contains(pindex)) + pindex = pindex->pprev; + return pindex; +} + +CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const +{ + std::vector::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, + [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); + return (lower == vChain.end() ? nullptr : *lower); +} + +/** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ +int static inline InvertLowestOne(int n) { return n & (n - 1); } + +/** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ +int static inline GetSkipHeight(int height) { + if (height < 2) + return 0; + + // Determine which height to jump back to. Any number strictly lower than height is acceptable, + // but the following expression seems to perform well in simulations (max 110 steps to go back + // up to 2**18 blocks). + return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); +} + +const CBlockIndex* CBlockIndex::GetAncestor(int height) const +{ + if (height > nHeight || height < 0) { + return nullptr; + } + + const CBlockIndex* pindexWalk = this; + int heightWalk = nHeight; + while (heightWalk > height) { + int heightSkip = GetSkipHeight(heightWalk); + int heightSkipPrev = GetSkipHeight(heightWalk - 1); + if (pindexWalk->pskip != nullptr && + (heightSkip == height || + (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && + heightSkipPrev >= height)))) { + // Only follow pskip if pprev->pskip isn't better than pskip->pprev. + pindexWalk = pindexWalk->pskip; + heightWalk = heightSkip; + } else { + assert(pindexWalk->pprev); + pindexWalk = pindexWalk->pprev; + heightWalk--; + } + } + return pindexWalk; +} + +CBlockIndex* CBlockIndex::GetAncestor(int height) +{ + return const_cast(static_cast(this)->GetAncestor(height)); +} + +void CBlockIndex::BuildSkip() +{ + if (pprev) + pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); +} + +arith_uint256 GetBlockProof(const CBlockIndex& block) +{ + arith_uint256 bnTarget; + bool fNegative; + bool fOverflow; + bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); + if (fNegative || fOverflow || bnTarget == 0) + return 0; + // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 + // as it's too large for an arith_uint256. However, as 2**256 is at least as large + // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, + // or ~bnTarget / (bnTarget+1) + 1. + return (~bnTarget / (bnTarget + 1)) + 1; +} + +int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) +{ + arith_uint256 r; + int sign = 1; + if (to.nChainWork > from.nChainWork) { + r = to.nChainWork - from.nChainWork; + } else { + r = from.nChainWork - to.nChainWork; + sign = -1; + } + r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); + if (r.bits() > 63) { + return sign * std::numeric_limits::max(); + } + return sign * r.GetLow64(); +} + +/** Find the last common ancestor two blocks have. + * Both pa and pb must be non-nullptr. */ +const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { + if (pa->nHeight > pb->nHeight) { + pa = pa->GetAncestor(pb->nHeight); + } else if (pb->nHeight > pa->nHeight) { + pb = pb->GetAncestor(pa->nHeight); + } + + while (pa != pb && pa && pb) { + pa = pa->pprev; + pb = pb->pprev; + } + + // Eventually all chain branches meet at the genesis block. + assert(pa == pb); + return pa; +} diff --git a/pool/shard011/C++/0121639_zip_reader_ctocpp.cc b/pool/shard011/C++/0121639_zip_reader_ctocpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..6d6502c05f9467f5b42ad9441d8c2931f14b9d60 --- /dev/null +++ b/pool/shard011/C++/0121639_zip_reader_ctocpp.cc @@ -0,0 +1,220 @@ +// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights +// reserved. Use of this source code is governed by a BSD-style license that +// can be found in the LICENSE file. +// +// --------------------------------------------------------------------------- +// +// This file was generated by the CEF translator tool. If making changes by +// hand only do so within the body of existing method and function +// implementations. See the translator.README.txt file in the tools directory +// for more information. +// + +#include "libcef_dll/ctocpp/stream_reader_ctocpp.h" +#include "libcef_dll/ctocpp/zip_reader_ctocpp.h" + + +// STATIC METHODS - Body may be edited by hand. + +CefRefPtr CefZipReader::Create( + CefRefPtr stream) { + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: stream; type: refptr_same + DCHECK(stream.get()); + if (!stream.get()) + return NULL; + + // Execute + cef_zip_reader_t* _retval = cef_zip_reader_create( + CefStreamReaderCToCpp::Unwrap(stream)); + + // Return type: refptr_same + return CefZipReaderCToCpp::Wrap(_retval); +} + + +// VIRTUAL METHODS - Body may be edited by hand. + +bool CefZipReaderCToCpp::MoveToFirstFile() { + if (CEF_MEMBER_MISSING(struct_, move_to_first_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_first_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::MoveToNextFile() { + if (CEF_MEMBER_MISSING(struct_, move_to_next_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->move_to_next_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::MoveToFile(const CefString& fileName, + bool caseSensitive) { + if (CEF_MEMBER_MISSING(struct_, move_to_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: fileName; type: string_byref_const + DCHECK(!fileName.empty()); + if (fileName.empty()) + return false; + + // Execute + int _retval = struct_->move_to_file(struct_, + fileName.GetStruct(), + caseSensitive); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::Close() { + if (CEF_MEMBER_MISSING(struct_, close)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->close(struct_); + + // Return type: bool + return _retval?true:false; +} + +CefString CefZipReaderCToCpp::GetFileName() { + if (CEF_MEMBER_MISSING(struct_, get_file_name)) + return CefString(); + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + cef_string_userfree_t _retval = struct_->get_file_name(struct_); + + // Return type: string + CefString _retvalStr; + _retvalStr.AttachToUserFree(_retval); + return _retvalStr; +} + +int64 CefZipReaderCToCpp::GetFileSize() { + if (CEF_MEMBER_MISSING(struct_, get_file_size)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->get_file_size(struct_); + + // Return type: simple + return _retval; +} + +time_t CefZipReaderCToCpp::GetFileLastModified() { + if (CEF_MEMBER_MISSING(struct_, get_file_last_modified)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + time_t _retval = struct_->get_file_last_modified(struct_); + + // Return type: simple + return _retval; +} + +bool CefZipReaderCToCpp::OpenFile(const CefString& password) { + if (CEF_MEMBER_MISSING(struct_, open_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Unverified params: password + + // Execute + int _retval = struct_->open_file(struct_, + password.GetStruct()); + + // Return type: bool + return _retval?true:false; +} + +bool CefZipReaderCToCpp::CloseFile() { + if (CEF_MEMBER_MISSING(struct_, close_file)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->close_file(struct_); + + // Return type: bool + return _retval?true:false; +} + +int CefZipReaderCToCpp::ReadFile(void* buffer, size_t bufferSize) { + if (CEF_MEMBER_MISSING(struct_, read_file)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Verify param: buffer; type: simple_byaddr + DCHECK(buffer); + if (!buffer) + return 0; + + // Execute + int _retval = struct_->read_file(struct_, + buffer, + bufferSize); + + // Return type: simple + return _retval; +} + +int64 CefZipReaderCToCpp::Tell() { + if (CEF_MEMBER_MISSING(struct_, tell)) + return 0; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int64 _retval = struct_->tell(struct_); + + // Return type: simple + return _retval; +} + +bool CefZipReaderCToCpp::Eof() { + if (CEF_MEMBER_MISSING(struct_, eof)) + return false; + + // AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING + + // Execute + int _retval = struct_->eof(struct_); + + // Return type: bool + return _retval?true:false; +} + + +#ifndef NDEBUG +template<> long CefCToCpp::DebugObjCt = 0; +#endif + diff --git a/pool/shard011/C++/0121641_PrimitiveTypeDeclaration.cpp b/pool/shard011/C++/0121641_PrimitiveTypeDeclaration.cpp new file mode 100644 index 0000000000000000000000000000000000000000..10e3c69a8e9684dd5ceb3edd44066770b43e2022 --- /dev/null +++ b/pool/shard011/C++/0121641_PrimitiveTypeDeclaration.cpp @@ -0,0 +1,93 @@ +#include + +#include +#include +#include + +namespace pddl +{ +namespace detail +{ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +// +// PrimitiveTypeDeclaration +// +//////////////////////////////////////////////////////////////////////////////////////////////////// + +std::experimental::optional findPrimitiveTypeDeclaration(ast::Domain &domain, const std::string &typeName) +{ + auto &types = domain.types; + + const auto matchingPrimitiveType = std::find_if(types.begin(), types.end(), + [&](const auto &primitiveType) + { + return primitiveType->name == typeName; + }); + + if (matchingPrimitiveType != types.end()) + return &*matchingPrimitiveType; + + return std::experimental::nullopt; +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +ast::PrimitiveTypeDeclarationPointer &parseAndAddUntypedPrimitiveTypeDeclaration(Context &context, ast::Domain &domain, std::vector &flaggedTypes) +{ + auto &tokenizer = context.tokenizer; + auto typeName = tokenizer.getIdentifier(); + + auto &types = domain.types; + + auto matchingPrimitiveTypeDeclaration = findPrimitiveTypeDeclaration(domain, typeName); + + if (matchingPrimitiveTypeDeclaration) + return *matchingPrimitiveTypeDeclaration.value(); + + types.emplace_back(std::make_unique(std::move(typeName))); + flaggedTypes.emplace_back(false); + + return types.back(); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +void parseAndAddPrimitiveTypeDeclarations(Context &context, ast::Domain &domain) +{ + auto &tokenizer = context.tokenizer; + tokenizer.skipWhiteSpace(); + + auto &types = domain.types; + assert(types.empty()); + + std::vector flaggedTypes; + + while (tokenizer.currentCharacter() != ')') + { + auto &childType = parseAndAddUntypedPrimitiveTypeDeclaration(context, domain, flaggedTypes); + flaggedTypes[&childType - &types.front()] = true; + + tokenizer.skipWhiteSpace(); + + if (!tokenizer.testAndSkip('-')) + continue; + + // Skip parent type information for now + auto &parentType = parseAndAddUntypedPrimitiveTypeDeclaration(context, domain, flaggedTypes); + + for (size_t i = 0; i < flaggedTypes.size(); i++) + if (flaggedTypes[i]) + { + flaggedTypes[i] = false; + types[i]->parentTypes.emplace_back(std::make_unique(parentType.get())); + } + + tokenizer.skipWhiteSpace(); + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// + +} +} diff --git a/pool/shard011/C++/0121642_MicroBenchmarksQ31.cpp b/pool/shard011/C++/0121642_MicroBenchmarksQ31.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4eeae2ba2be0daf254ebbe68ef0ea64d19dcb3c6 --- /dev/null +++ b/pool/shard011/C++/0121642_MicroBenchmarksQ31.cpp @@ -0,0 +1,105 @@ +#include "MicroBenchmarksQ31.h" +#include "Error.h" + +static void add_while_q31( + const q31_t * pSrcA, + const q31_t * pSrcB, + q31_t * pDst, + uint32_t blockSize) +{ + uint32_t blkCnt; + + blkCnt = blockSize; + + while (blkCnt > 0U) + { + /* C = A + B */ + + /* Add and store result in destination buffer. */ + *pDst++ = (*pSrcA++) + (*pSrcB++); + + /* Decrement loop counter */ + blkCnt--; + } +} + +static void add_for_q31( + const q31_t * pSrcA, + const q31_t * pSrcB, + q31_t * pDst, + uint32_t blockSize) +{ + uint32_t blkCnt; + int32_t i; + + blkCnt = blockSize; + + for(i=0; iinp1,this->inp2,this->outp,this->nbSamples); + } + + void MicroBenchmarksQ31::test_for_q31() + { + add_for_q31(this->inp1,this->inp2,this->outp,this->nbSamples); + } + + void MicroBenchmarksQ31::test_array_q31() + { + add_array_q31(this->inp1,this->inp2,this->outp,this->nbSamples); + } + + + void MicroBenchmarksQ31::setUp(Testing::testID_t id,std::vector& params,Client::PatternMgr *mgr) + { + + + std::vector::iterator it = params.begin(); + this->nbSamples = *it; + + input1.reload(MicroBenchmarksQ31::INPUT1_Q31_ID,mgr,this->nbSamples); + input2.reload(MicroBenchmarksQ31::INPUT2_Q31_ID,mgr,this->nbSamples); + + + output.create(this->nbSamples,MicroBenchmarksQ31::OUT_SAMPLES_Q31_ID,mgr); + + this->inp1=input1.ptr(); + this->inp2=input2.ptr(); + this->outp=output.ptr(); + + } + + void MicroBenchmarksQ31::tearDown(Testing::testID_t id,Client::PatternMgr *mgr) + { + } diff --git a/pool/shard011/C++/0121643_FirstPass.cpp b/pool/shard011/C++/0121643_FirstPass.cpp new file mode 100644 index 0000000000000000000000000000000000000000..576ad849cb0f02b6a676f13084d30c27bdb399bb --- /dev/null +++ b/pool/shard011/C++/0121643_FirstPass.cpp @@ -0,0 +1,22 @@ +#include "llvm/Pass.h" +#include "llvm/IR/Function.h" +#include "llvm/Support/raw_ostream.h" + +using namespace llvm; + +namespace { + struct FirstPass : public FunctionPass { + static char ID; + FirstPass() : FunctionPass(ID) {} + + bool runOnFunction(Function &F) override { + errs() << "Function recognized: "; + errs().write_escaped(F.getName()); + errs() << '\n'; + return false; + } + }; +} + +char FirstPass::ID = 0; +static RegisterPass X("FirstPass", "Function printer pass", false, false); diff --git a/pool/shard011/C++/0121645_addatodialog_funcs.cpp b/pool/shard011/C++/0121645_addatodialog_funcs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf75d510dde408456d0ea63ca64d43ae6e89988d --- /dev/null +++ b/pool/shard011/C++/0121645_addatodialog_funcs.cpp @@ -0,0 +1,109 @@ +#include "addatodialog.h" +#include "epsrproject.h" + +#include + +AddAtoDialog::AddAtoDialog(MainWindow *parent) : QDialog(parent) +{ + ui.setupUi(this); + + mainWindow_ = parent; + + ui.atoComboBox->clear(); + ui.atoTable->clearContents(); + + QStringList atoFileList = mainWindow_->listAtoFiles(); + QString boxAtoFileName = mainWindow_->atoFileName(); + + for (int i = 0; i < atoFileList.count(); i++) + { + ui.atoComboBox->addItem(atoFileList.at(i)); + ui.atoList->addItem(atoFileList.at(i)); + } + if (!boxAtoFileName.isEmpty()) + { + ui.atoComboBox->addItem(boxAtoFileName); + } + + ui.atoTable->setSelectionBehavior(QAbstractItemView::SelectRows); + ui.atoTable->setSelectionMode(QAbstractItemView::SingleSelection); + + connect(ui.okButton, SIGNAL(clicked()), this, SLOT(checkEntries())); + connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(reject())); +} + +void AddAtoDialog::on_okButton_clicked(bool checked) +{ + +} + +void AddAtoDialog::on_cancelButton_clicked(bool checked) +{ + +} + +void AddAtoDialog::checkEntries() +{ + QList twi = ui.atoTable->findItems("0", Qt::MatchExactly); + if (ui.atoTable->rowCount() < 1 || twi.isEmpty() == false) + { + QMessageBox::warning(this, tr("No .ato files to add"), + tr("Add ato files to the right hand table and input the number of these molecules to add.")); + } + else + { + accept(); + } +} + +void AddAtoDialog::on_addAtoButton_clicked(bool checked) +{ + if (ui.atoList->currentRow() == -1) + { + return; + } + + QString atoFileName = ui.atoList->currentItem()->text(); + int lastAtoFile = ui.atoTable->rowCount(); + ui.atoTable->setRowCount(lastAtoFile+1); + QTableWidgetItem *item = new QTableWidgetItem(atoFileName); + item->setFlags(item->flags() & ~Qt::ItemIsEditable); + ui.atoTable->setItem(lastAtoFile,0, item); + ui.atoTable->setItem(lastAtoFile,1, new QTableWidgetItem("0")); +} + +void AddAtoDialog::on_removeAtoButton_clicked(bool checked) +{ + if (ui.atoTable->rowCount() != 0) + { + int row = ui.atoTable->currentRow(); + ui.atoTable->removeRow(row); + } +} + +QString AddAtoDialog::getContainer() +{ + return ui.atoComboBox->currentText(); +} + +QStringList AddAtoDialog::getAtoFiles() +{ + QStringList selectedAtoFiles; + + for (int i = 0; i < ui.atoTable->rowCount(); i++) + { + selectedAtoFiles.append(ui.atoTable->item(i,0)->text()); + } + return selectedAtoFiles; +} + +QStringList AddAtoDialog::getNumberMols() +{ + QStringList numberMols; + + for (int i = 0; i < ui.atoTable->rowCount(); i++) + { + numberMols.append(ui.atoTable->item(i,1)->text()); + } + return numberMols; +} diff --git a/pool/shard011/C++/0121646_dlguser.cpp b/pool/shard011/C++/0121646_dlguser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47fb981de61c4321e1c17adfd2623f982f1d8446 --- /dev/null +++ b/pool/shard011/C++/0121646_dlguser.cpp @@ -0,0 +1,136 @@ +//---------------------------------------------------------------------------------------- +// Name: DlgUser.cpp +// Purpose: Dialog mit Variable Gestaltung durch DlgUser.wxr +// Author: Mark Johnson +// Modified by: 19991105.mj10777 +// Created: 19991105 +// Copyright: (c) Mark Johnson +// Licence: wxWindows license +// RCS-ID: $Id: dlguser.cpp 44499 2007-02-13 23:22:24Z VZ $ +//---------------------------------------------------------------------------------------- + +// For compilers that support precompilation, includes "wx/wx.h". +#include "wx/wxprec.h" +//---------------------------------------------------------------------------------------- +#ifdef __BORLANDC__ +#pragma hdrstop +#endif +//---------------------------------------------------------------------------------------- +#ifndef WX_PRECOMP +#include "wx/wx.h" +#endif + + +//---------------------------------------------------------------------------------------- +//-- all #includes that every .cpp needs ----19990807.mj10777 ---------------- +//---------------------------------------------------------------------------------------- +#include "std.h" + +//---------------------------------------------------------------------------------------- +DlgUser::DlgUser(wxWindow *parent, MainDoc *p_Doc, const wxString& title) : + wxDialog(parent, ID_DIALOG_DSN, title) +{ + int chSize; // Height of Font * 1.4 = Height of wxTextCtrl + + float ratio = (float)1.4; +#ifdef __WXMOTIF__ + ratio = (float)2.1; +#endif + + SetBackgroundColour(_T("wheat")); + pDoc = p_Doc; + wxLayoutConstraints* layout; + SetAutoLayout(true); + + m_Label1 = new wxStaticText(this, wxID_ANY, _("User ID:")); + m_Label1->SetFont(* pDoc->ft_Doc); + layout = new wxLayoutConstraints; + layout->left.SameAs(this, wxLeft, 10); + layout->top.SameAs(this, wxTop, 10); + layout->height.AsIs(); + layout->width.Absolute(75); + m_Label1->SetConstraints(layout); + + int w; + m_Label1->GetSize(&w, &chSize); + + m_UserName = new wxTextCtrl(this, wxID_ANY, wxEmptyString); + m_UserName->SetFont(* pDoc->ft_Doc); + chSize = (int) (m_UserName->GetCharHeight()*ratio); + + layout = new wxLayoutConstraints; + layout->left.SameAs(m_Label1, wxRight, 10); + layout->centreY.SameAs(m_Label1,wxCentreY); + layout->width.Absolute(200); + layout->height.Absolute(chSize); + // layout->height.AsIs(); + m_UserName->SetConstraints(layout); + + + m_Label2 = new wxStaticText(this, wxID_ANY, _("Password:")); + m_Label2->SetFont(* pDoc->ft_Doc); + layout = new wxLayoutConstraints; + layout->left.SameAs(m_Label1, wxLeft); + layout->top.SameAs(m_Label1, wxBottom, 10); + layout->height.AsIs(); + layout->width.SameAs(m_Label1, wxWidth); + m_Label2->SetConstraints(layout); + + m_Password = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxTE_PASSWORD); + m_Password->SetFont(* pDoc->ft_Doc); + layout = new wxLayoutConstraints; + layout->left.SameAs(m_UserName, wxLeft); + layout->width.SameAs(m_UserName, wxWidth); + layout->centreY.SameAs(m_Label2,wxCentreY); + layout->height.Absolute(chSize); + //layout->height.AsIs(); + m_Password->SetConstraints(layout); + + m_OK = new wxButton(this, wxID_OK); + m_OK->SetFont(* pDoc->ft_Doc); + layout = new wxLayoutConstraints; + layout->left.SameAs(this, wxLeft, 10); + layout->top.SameAs(m_Label2, wxBottom,10); + layout->height.AsIs(); + layout->width.Absolute(75); + m_OK->SetConstraints(layout); + + m_Cancel = new wxButton(this, wxID_CANCEL); + m_Cancel->SetFont(* pDoc->ft_Doc); + layout = new wxLayoutConstraints; + layout->left.SameAs(m_OK, wxRight, 10); + layout->top.SameAs(m_OK, wxTop); + layout->height.AsIs(); + layout->width.SameAs(m_OK, wxWidth); + m_Cancel->SetConstraints(layout); + + m_OK->SetDefault(); + m_UserName->SetFocus(); + + s_User = wxEmptyString; + s_Password = wxEmptyString; + Layout(); +} + +//---------------------------------------------------------------------------------------- +void DlgUser::OnInit() +{ + wxString Temp; Temp.Printf(_T(">>> %s <<<"),s_DSN.c_str()); + SetTitle(Temp); + m_UserName->SetLabel(s_User); + m_Password->SetLabel(s_Password); +} + +//---------------------------------------------------------------------------------------- +BEGIN_EVENT_TABLE(DlgUser, wxDialog) + EVT_BUTTON(wxID_OK, DlgUser::OnOk) +END_EVENT_TABLE() + +//---------------------------------------------------------------------------------------- +void DlgUser::OnOk(wxCommandEvent& WXUNUSED(event) ) +{ + s_User = m_UserName->GetValue(); + s_Password = m_Password->GetValue(); + EndModal(wxID_OK); +} + diff --git a/pool/shard011/C++/0121647_renumber_component_wise_01.cc b/pool/shard011/C++/0121647_renumber_component_wise_01.cc new file mode 100644 index 0000000000000000000000000000000000000000..07491dcad406769ad7310bba1b6e5120939bd77a --- /dev/null +++ b/pool/shard011/C++/0121647_renumber_component_wise_01.cc @@ -0,0 +1,75 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2005 - 2017 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +// test DoFRenumbering::component_wise for codim=1 + +#include "../tests.h" +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +std::ofstream logfile("output"); + +template +void test(std::string filename) +{ + Triangulation tria; + GridIn gi; + gi.attach_triangulation (tria); + std::ifstream in (filename.c_str()); + gi.read_ucd (in); + + deallog << tria.n_active_cells() << " active cells" << std::endl; + + FESystem fe(FE_Q (2), spacedim); + DoFHandler dof_handler (tria); + dof_handler.distribute_dofs (fe); + + deallog << dof_handler.n_dofs() << " degrees of freedom" << std::endl; + DoFRenumbering::component_wise (dof_handler); + + for (typename DoFHandler::active_cell_iterator + cell = dof_handler.begin_active(); cell!=dof_handler.end(); ++cell) + { + std::vector x (cell->get_fe().dofs_per_cell); + cell->get_dof_indices (x); + + deallog << cell << std::endl; + for (unsigned int i=0; i(SOURCE_DIR "/grids/square.inp"); + test<2,3>(SOURCE_DIR "/grids/sphere_1.inp"); + + return 0; +} + diff --git a/pool/shard011/C++/0121648_help_app_launcher.cc b/pool/shard011/C++/0121648_help_app_launcher.cc new file mode 100644 index 0000000000000000000000000000000000000000..2dfce22fc9c068664cc2c9ebcea54b75a89bd5f8 --- /dev/null +++ b/pool/shard011/C++/0121648_help_app_launcher.cc @@ -0,0 +1,89 @@ +// 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 "chrome/browser/chromeos/login/help_app_launcher.h" + +#include + +#include "base/strings/stringprintf.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/chromeos/login/ui/login_web_dialog.h" +#include "chrome/browser/chromeos/profiles/profile_helper.h" +#include "chrome/browser/profiles/profile.h" +#include "chrome/grit/generated_resources.h" +#include "chrome/grit/locale_settings.h" +#include "content/public/browser/browser_thread.h" +#include "extensions/browser/extension_registry.h" +#include "ui/base/l10n/l10n_util.h" +#include "ui/gfx/geometry/rect.h" +#include "ui/gfx/geometry/size.h" +#include "url/gurl.h" + +using content::BrowserThread; +using extensions::ExtensionRegistry; + +namespace { + +// Official HelpApp extension id. +const char kExtensionId[] = "honijodknafkokifofgiaalefdiedpko"; + +const char kHelpAppFormat[] = "chrome-extension://%s/oobe.html?id=%d"; + +const char* g_extension_id_for_test = nullptr; + +} // namespace + +namespace chromeos { + +/////////////////////////////////////////////////////////////////////////////// +// HelpApp, public: + +HelpAppLauncher::HelpAppLauncher(gfx::NativeWindow parent_window) + : parent_window_(parent_window) {} + +void HelpAppLauncher::ShowHelpTopic(HelpTopic help_topic_id) { + Profile* profile = ProfileHelper::GetSigninProfile(); + ExtensionRegistry* registry = ExtensionRegistry::Get(profile); + + DCHECK(registry); + if (!registry) + return; + + const char* extension_id = kExtensionId; + if (g_extension_id_for_test && *g_extension_id_for_test != '\0') { + extension_id = g_extension_id_for_test; + } + + GURL url(base::StringPrintf(kHelpAppFormat, extension_id, + static_cast(help_topic_id))); + // HelpApp component extension presents only in official builds so we can + // show help only when the extensions is installed. + if (registry->enabled_extensions().GetByID(url.host())) + ShowHelpTopicDialog(profile, GURL(url)); +} + +// static +void HelpAppLauncher::SetExtensionIdForTest(const char* extension_id) { + g_extension_id_for_test = extension_id; +} + +/////////////////////////////////////////////////////////////////////////////// +// HelpApp, protected: + +HelpAppLauncher::~HelpAppLauncher() {} + +/////////////////////////////////////////////////////////////////////////////// +// HelpApp, private: + +void HelpAppLauncher::ShowHelpTopicDialog(Profile* profile, + const GURL& topic_url) { + DCHECK_CURRENTLY_ON(BrowserThread::UI); + LoginWebDialog* dialog = new LoginWebDialog( + profile, NULL, parent_window_, + l10n_util::GetStringUTF16(IDS_LOGIN_OOBE_HELP_DIALOG_TITLE), topic_url); + dialog->Show(); + // The dialog object will be deleted on dialog close. +} + +} // namespace chromeos diff --git a/pool/shard011/C++/0121650_FourierTransformationTest.cpp b/pool/shard011/C++/0121650_FourierTransformationTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89ccdf1f4e0fc349d9ad43c02768cc931f7e3513 --- /dev/null +++ b/pool/shard011/C++/0121650_FourierTransformationTest.cpp @@ -0,0 +1,140 @@ +// ************************************************************************** // +// +// BornAgain: simulate and fit scattering at grazing incidence +// +//! @file Tests/Functional/Core/CoreSpecial/FourierTransformationTest.cpp +//! @brief Implements FourierTransformationTest class. +//! +//! @homepage http://www.bornagainproject.org +//! @license GNU General Public License v3 or higher (see COPYING) +//! @copyright Forschungszentrum Jülich GmbH 2018 +//! @authors Scientific Computing Group at MLZ (see CITATION, AUTHORS) +// +// ************************************************************************** // + +#include "FourierTransformationTest.h" +#include "FileSystemUtils.h" +#include "IntensityDataFunctions.h" +#include "IntensityDataIOFactory.h" +#include "OutputData.h" +#include "TestUtils.h" +#include "BATesting.h" +#include +#include +#include + +namespace +{ + +const double threshold = 1e-10; + +//! Returns file names to test fft. +std::vector inputImages() { + return {"CylindersAndPrisms.int.gz", "RectDetectorGeneric.int.gz"}; +} + +//! Returns location of images to test fft. +std::string inputImageDir(); + +//! Returns file names with paths to test fft. +std::vector inputImageNames(); + +//! Returns name of directory with fft images for reference. +std::string fftReferenceDir(); + +//! Returns name of fft image based on given image name. +std::string fftReferenceImage(const std::string& input_image); + +//! Returns name of directory for output fft images. +std::string outputDir(); + +} + +bool FourierTransformationTest::runTest() +{ + bool success(true); + + for (auto inputImage : inputImageNames()) + success &= test_fft(inputImage, fftReferenceImage(inputImage)); + + return success; +} + +bool FourierTransformationTest::test_fft(const std::string& input_image_name, + const std::string& reference_fft_name) +{ + std::cout << "\nFourierTransformationTest::test_fft()" + << "\n"; + std::cout << "Input image: " << input_image_name << "\n"; + std::cout << "Reference fft: " << reference_fft_name << "\n"; + + // loading input image + std::unique_ptr> input_image; + try { + input_image.reset(IntensityDataIOFactory::readOutputData(input_image_name)); + } catch (const std::exception&) { + std::cout << "Error: no input image.\n"; + return false; + } + + // making fourier transformation + std::unique_ptr> fft = + IntensityDataFunctions::createFFT(*input_image.get()); + + // loading reference fft + std::unique_ptr> reference_fft; + try { + reference_fft.reset(IntensityDataIOFactory::readOutputData(reference_fft_name)); + } catch (const std::exception&) { + std::cout << "Error: no reference fft image. Creating new one.\n"; + } + + // comparing new fft against reference fft, if exist + bool success(false); + if (reference_fft) + success = TestUtils::isTheSame(*fft, *reference_fft, threshold) ? true : false; + + if (!success) { + FileSystemUtils::createDirectory(outputDir()); + std::string out_fname = FileSystemUtils::jointPath( + outputDir(), FileSystemUtils::filename(reference_fft_name)); + IntensityDataIOFactory::writeOutputData(*fft, out_fname); + std::cout << "New fft image stored in " << out_fname << "\n"; + } + + return success; +} + +namespace +{ +std::string inputImageDir() +{ + return std::string(BATesting::CoreReferenceDir()); +} + +std::vector inputImageNames() +{ + std::vector result; + for (auto name : inputImages()) + result.push_back(FileSystemUtils::jointPath(inputImageDir(), name)); + + return result; +} + +std::string fftReferenceDir() +{ + return BATesting::CoreReferenceDir(); +} + +std::string fftReferenceImage(const std::string& input_image) +{ + auto filename = FileSystemUtils::filename(input_image); + return FileSystemUtils::jointPath(fftReferenceDir(), "FourierTransformation_" + filename); +} + +std::string outputDir() +{ + return std::string(BATesting::CoreOutputDir()); +} + +} diff --git a/pool/shard011/C++/0121651_ProcessList.cpp b/pool/shard011/C++/0121651_ProcessList.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61b25222f24e49a2111cee6dbf178917e0630de3 --- /dev/null +++ b/pool/shard011/C++/0121651_ProcessList.cpp @@ -0,0 +1,95 @@ +// Copyright (c) 2020 The Orbit Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ProcessService/ProcessList.h" + +#include +#include +#include + +#include +#include + +#include "OrbitBase/Logging.h" +#include "OrbitBase/Result.h" +#include "OrbitBase/ThreadUtils.h" +#include "ProcessServiceUtils.h" + +namespace orbit_process_service_internal { + +ErrorMessageOr ProcessList::Refresh() { + absl::flat_hash_map updated_processes{}; + + // TODO(b/161423785): This for loop should be refactored. For example, when + // parts are in a separate function, OUTCOME_TRY could be used to simplify + // error handling. + std::error_code error; + auto directory_iterator = std::filesystem::directory_iterator("/proc", error); + if (error) { + return ErrorMessage(absl::StrFormat("Unable to iterate /proc directory: %s", error.message())); + } + + for (auto it = begin(directory_iterator); it != end(directory_iterator); it.increment(error)) { + if (error) { + return ErrorMessage( + absl::StrFormat("Unable to iterate /proc directory: %s", error.message())); + } + + bool is_directory = it->is_directory(error); + if (error) { + ORBIT_ERROR("Unable to stat \"%s\" directory entry: %s", it->path(), error.message()); + continue; + } + + if (!is_directory) continue; + + const std::filesystem::path& path = it->path(); + std::string folder_name = path.filename().string(); + + uint32_t pid; + if (!absl::SimpleAtoi(folder_name, &pid)) continue; + + const auto iter = processes_.find(pid); + + if (iter != processes_.end()) { + auto process = processes_.extract(iter); + + const auto total_cpu_time = orbit_process_service::GetCumulativeTotalCpuTime(); + const auto cpu_time = orbit_process_service::GetCumulativeCpuTimeFromProcess(process.key()); + if (cpu_time && total_cpu_time) { + process.mapped().UpdateCpuUsage(cpu_time.value(), total_cpu_time.value()); + } else { + // We don't fail in this case. This could be a permission problem which might occur when not + // running as root. + ORBIT_ERROR("Could not update the CPU usage of process %d", process.key()); + } + + updated_processes.insert(std::move(process)); + continue; + } + + auto process_or_error = Process::FromPid(pid); + + if (process_or_error.has_error()) { + // We don't fail in this case. This could be a permission problem which is restricted to a + // small amount of processes. + ORBIT_ERROR("Could not create process list entry for pid %u: %s", pid, + process_or_error.error().message()); + continue; + } + + updated_processes.emplace(pid, std::move(process_or_error.value())); + } + + processes_ = std::move(updated_processes); + + if (processes_.empty()) { + return ErrorMessage{ + "Could not determine a single process from the proc-filesystem. Something seems to wrong."}; + } + + return outcome::success(); +} + +} // namespace orbit_process_service_internal diff --git a/pool/shard011/C++/0121653_sensor_comparator_component.cc b/pool/shard011/C++/0121653_sensor_comparator_component.cc new file mode 100644 index 0000000000000000000000000000000000000000..c4575bd754a915a75319f54749312f657555c460 --- /dev/null +++ b/pool/shard011/C++/0121653_sensor_comparator_component.cc @@ -0,0 +1,66 @@ +#include +#include +#include "../memory.h" +#include "sensor_comparator_component.h" + +/* THIS FILE IS AUTOGENERATED BY gen/gen_component_impl.py; DO NOT HAND-MODIFY */ + +void +sensor_comparator_component_manager::create_component_instance_data(unsigned count) { + if (count <= buffer.allocated) + return; + + component_buffer new_buffer; + instance_data new_pool; + + size_t size = sizeof(c_entity) * count; + size = sizeof(float) * count + align_size(size); + size = sizeof(float) * count + align_size(size); + size += 16; // for worst-case misalignment of initial ptr + + new_buffer.buffer = malloc(size); + new_buffer.num = buffer.num; + new_buffer.allocated = count; + memset(new_buffer.buffer, 0, size); + + new_pool.entity = align_ptr((c_entity *)new_buffer.buffer); + new_pool.compare_result = align_ptr((float *)(new_pool.entity + count)); + new_pool.compare_epsilon = align_ptr((float *)(new_pool.compare_result + count)); + + memcpy(new_pool.entity, instance_pool.entity, buffer.num * sizeof(c_entity)); + memcpy(new_pool.compare_result, instance_pool.compare_result, buffer.num * sizeof(float)); + memcpy(new_pool.compare_epsilon, instance_pool.compare_epsilon, buffer.num * sizeof(float)); + + free(buffer.buffer); + buffer = new_buffer; + + instance_pool = new_pool; +} + +void +sensor_comparator_component_manager::destroy_instance(instance i) { + auto last_index = buffer.num - 1; + auto last_entity = instance_pool.entity[last_index]; + auto current_entity = instance_pool.entity[i.index]; + + instance_pool.entity[i.index] = instance_pool.entity[last_index]; + instance_pool.compare_result[i.index] = instance_pool.compare_result[last_index]; + instance_pool.compare_epsilon[i.index] = instance_pool.compare_epsilon[last_index]; + + entity_instance_map[last_entity] = i.index; + entity_instance_map.erase(current_entity); + + --buffer.num; +} + +void +sensor_comparator_component_manager::entity(c_entity e) { + if (buffer.num >= buffer.allocated) { + printf("Increasing size of sensor_comparator buffer. Please adjust\n"); + create_component_instance_data(std::max(1u, buffer.allocated) * 2); + } + + auto inst = lookup(e); + + instance_pool.entity[inst.index] = e; +} diff --git a/pool/shard011/C++/0121655_pet_dk.cpp b/pool/shard011/C++/0121655_pet_dk.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8be43292a0e836814beda25729ff482234379164 --- /dev/null +++ b/pool/shard011/C++/0121655_pet_dk.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2008-2014 TrinityCore + * Copyright (C) 2011-2015 ArkCORE + * + * 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 . + */ + +/* + * Ordered alphabetically using scriptname. + * Scriptnames of files in this file should be prefixed with "npc_pet_dk_". + */ + +#include "ScriptMgr.h" +#include "ScriptedCreature.h" +#include "CombatAI.h" +#include "Cell.h" +#include "CellImpl.h" +#include "GridNotifiers.h" +#include "GridNotifiersImpl.h" + +enum DeathKnightSpells +{ + SPELL_DK_SUMMON_GARGOYLE_1 = 49206, + SPELL_DK_SUMMON_GARGOYLE_2 = 50514, + SPELL_DK_DISMISS_GARGOYLE = 50515, + SPELL_DK_SANCTUARY = 54661 +}; + +class npc_pet_dk_ebon_gargoyle : public CreatureScript +{ + public: + npc_pet_dk_ebon_gargoyle() : CreatureScript("npc_pet_dk_ebon_gargoyle") { } + + struct npc_pet_dk_ebon_gargoyleAI : CasterAI + { + npc_pet_dk_ebon_gargoyleAI(Creature* creature) : CasterAI(creature) { } + + void InitializeAI() override + { + // Not needed to be despawned now + _despawnTimer = 0; + + CasterAI::InitializeAI(); + uint64 ownerGuid = me->GetOwnerGUID(); + if (!ownerGuid) + return; + + // Find victim of Summon Gargoyle spell + std::list targets; + Trinity::AnyUnfriendlyUnitInObjectRangeCheck u_check(me, me, 30.0f); + Trinity::UnitListSearcher searcher(me, targets, u_check); + me->VisitNearbyObject(30.0f, searcher); + for (std::list::const_iterator iter = targets.begin(); iter != targets.end(); ++iter) + if ((*iter)->GetAura(SPELL_DK_SUMMON_GARGOYLE_1, ownerGuid)) + { + me->Attack((*iter), false); + break; + } + } + + void JustDied(Unit* /*killer*/) override + { + // Stop Feeding Gargoyle when it dies + if (Unit* owner = me->GetOwner()) + owner->RemoveAurasDueToSpell(SPELL_DK_SUMMON_GARGOYLE_2); + } + + // Fly away when dismissed + void SpellHit(Unit* source, SpellInfo const* spell) override + { + if (spell->Id != SPELL_DK_DISMISS_GARGOYLE || !me->IsAlive()) + return; + + Unit* owner = me->GetOwner(); + if (!owner || owner != source) + return; + + // Stop Fighting + me->ApplyModFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE, true); + + // Sanctuary + me->CastSpell(me, SPELL_DK_SANCTUARY, true); + me->SetReactState(REACT_PASSIVE); + + //! HACK: Creature's can't have MOVEMENTFLAG_FLYING + // Fly Away + me->SetCanFly(true); + me->SetSpeed(MOVE_FLIGHT, 0.75f, true); + me->SetSpeed(MOVE_RUN, 0.75f, true); + float x = me->GetPositionX() + 20 * std::cos(me->GetOrientation()); + float y = me->GetPositionY() + 20 * std::sin(me->GetOrientation()); + float z = me->GetPositionZ() + 40; + me->GetMotionMaster()->Clear(false); + me->GetMotionMaster()->MovePoint(0, x, y, z); + + // Despawn as soon as possible + _despawnTimer = 4 * IN_MILLISECONDS; + } + + void UpdateAI(uint32 diff) override + { + if (_despawnTimer > 0) + { + if (_despawnTimer > diff) + _despawnTimer -= diff; + else + me->DespawnOrUnsummon(); + return; + } + + CasterAI::UpdateAI(diff); + } + + private: + uint32 _despawnTimer; + }; + + CreatureAI* GetAI(Creature* creature) const override + { + return new npc_pet_dk_ebon_gargoyleAI(creature); + } +}; + +void AddSC_deathknight_pet_scripts() +{ + new npc_pet_dk_ebon_gargoyle(); +} diff --git a/pool/shard011/C++/0121656_glut_win.cpp b/pool/shard011/C++/0121656_glut_win.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e11747435eba8ef008f0587a947e2ff313e96345 --- /dev/null +++ b/pool/shard011/C++/0121656_glut_win.cpp @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2012, Frederic Dubouchet + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the CERN nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY Frederic Dubouchet ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL Frederic DUBOUCHEDT BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#ifdef __linux__ +#include +#endif +#ifdef __APPLE__ +#include +#endif + +#include "glut_win.hpp" + +static void init() { + glut_win::instance()->pwin_->init(); +} + +static void finish() { + glut_win::instance()->pwin_->finish(); +} + +static void display() { + static bool s_first = true; + if (s_first) { + s_first = false; + init(); + } else { + glut_win::instance()->pwin_->display(); + } + glutSwapBuffers(); +} + +static void keyboard(unsigned char key, int x, int y) { + switch(key) { + case 27 : + finish(); + exit(0); + break; + } + glut_win::instance()->pwin_->keyboard(key, x, y); +} + +static void reshape(int w, int h) { + glut_win::instance()->pwin_->reshape(w, h); +} + +static void idle() { + glut_win::instance()->pwin_->idle(); + glutPostRedisplay(); +} + +static void mouse_move(int x, int y) { + glut_win::instance()->pwin_->mouse_move(x, y); +} + +static void mouse_event(int button, int state, int x, int y) { + glut_win::instance()->pwin_->mouse_event(button, state, x, y); +} + +glut_win* glut_win::instance_ = NULL; + +glut_win* glut_win::instance( + const std::string& name, + const std::pair& range, + i_win* windesc, + bool fullscreen) + throw(std::exception) +{ + if (!instance_) + instance_ = new glut_win(name, range, windesc, fullscreen); + return instance_; +} + +glut_win* glut_win::instance() throw(std::exception) { + if (instance_) return instance_; + else throw std::runtime_error(std::string("glut_win was not initialized!")); +} + +glut_win::glut_win( + const std::string& name, + const std::pair& range, + i_win* windesc, + bool fullscreen) + throw(std::exception) : + fullscreen_(fullscreen), + pwin_(windesc) +{ + if (!pwin_) throw std::runtime_error(std::string("Window class == NULL")); + int ac = 0; + glutInit(&ac, NULL); + glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH); + if (!fullscreen_) + glutInitWindowSize(range.first, range.second); + glutCreateWindow(name.c_str()); + if (fullscreen_) + glutFullScreen(); +} + +glut_win::~glut_win() { } + +void glut_win::run() + throw(std::exception) +{ + glutDisplayFunc(display); + glutKeyboardFunc(keyboard); + glutReshapeFunc(reshape); + glutMotionFunc(mouse_move); + glutMouseFunc(mouse_event); + glutIdleFunc(idle); + glutMainLoop(); +} + diff --git a/pool/shard011/C++/0121658_main.cpp b/pool/shard011/C++/0121658_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2efa281bad58608d9dd58391be8f088c3d7c9cf0 --- /dev/null +++ b/pool/shard011/C++/0121658_main.cpp @@ -0,0 +1,40 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* main.cpp :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: ncharret +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2015/06/16 17:15:24 by ncharret #+# #+# */ +/* Updated: 2015/06/16 17:29:35 by ncharret ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "ZombieEvent.hpp" +#include "Zombie.hpp" + +void pitiZomb() { + + Zombie piti("petit", "Pony"); + piti.announce(); + piti.announce(); +} + +int main() +{ + ZombieEvent factory; + factory.setZombieType("rebelz"); + for (int i = 0; i < 3; i++) { + + Zombie *zomb = factory.randomChump(); + delete zomb; + } + factory.setZombieType("pasrebelz"); + for (int i = 0; i < 3; i++) { + + Zombie *zomb = factory.randomChump(); + delete zomb; + } + pitiZomb(); + return (0); +} diff --git a/pool/shard011/C++/0121660_checkpoints.cpp b/pool/shard011/C++/0121660_checkpoints.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4700cd1ced77bd30b79c08f1eaa264fad05edfda --- /dev/null +++ b/pool/shard011/C++/0121660_checkpoints.cpp @@ -0,0 +1,87 @@ +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include // for 'map_list_of()' +#include + +#include "checkpoints.h" + +#include "txdb.h" +#include "main.h" +#include "uint256.h" + + +static const int nCheckpointSpan = 500; + +namespace Checkpoints +{ + typedef std::map MapCheckpoints; + + // + // What makes a good checkpoint block? + // + Is surrounded by blocks with reasonable timestamps + // (no blocks before with a timestamp after, none after with + // timestamp before) + // + Contains no strange transactions + // + static MapCheckpoints mapCheckpoints = + boost::assign::map_list_of + ( 0, uint256("0x00000068ea1bda5d79b59679d475024f8bc3344a5571a2c00bed231c7495fae6") ) // genesis + ; + + // TestNet has no checkpoints + static MapCheckpoints mapCheckpointsTestnet; + + bool CheckHardened(int nHeight, const uint256& hash) + { + MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); + + MapCheckpoints::const_iterator i = checkpoints.find(nHeight); + if (i == checkpoints.end()) return true; + return hash == i->second; + } + + int GetTotalBlocksEstimate() + { + MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); + + if (checkpoints.empty()) + return 0; + return checkpoints.rbegin()->first; + } + + CBlockIndex* GetLastCheckpoint(const std::map& mapBlockIndex) + { + MapCheckpoints& checkpoints = (TestNet() ? mapCheckpointsTestnet : mapCheckpoints); + + BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints) + { + const uint256& hash = i.second; + std::map::const_iterator t = mapBlockIndex.find(hash); + if (t != mapBlockIndex.end()) + return t->second; + } + return NULL; + } + + // Automatically select a suitable sync-checkpoint + const CBlockIndex* AutoSelectSyncCheckpoint() + { + const CBlockIndex *pindex = pindexBest; + // Search backward for a block within max span and maturity window + while (pindex->pprev && pindex->nHeight + nCheckpointSpan > pindexBest->nHeight) + pindex = pindex->pprev; + return pindex; + } + + // Check against synchronized checkpoint + bool CheckSync(int nHeight) + { + const CBlockIndex* pindexSync = AutoSelectSyncCheckpoint(); + + if (nHeight <= pindexSync->nHeight) + return false; + return true; + } +} diff --git a/pool/shard011/C++/0121661_kis_deform_paintop_settings_widget.cpp b/pool/shard011/C++/0121661_kis_deform_paintop_settings_widget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd085dac4ff2b23a492d944388a695e5481945f4 --- /dev/null +++ b/pool/shard011/C++/0121661_kis_deform_paintop_settings_widget.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (c) 2008,2009,2010 Lukáš Tvrdý + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ +#include "kis_deform_paintop_settings.h" +#include "kis_deform_paintop_settings_widget.h" +#include "kis_deform_option.h" + +#include +#include + +#include +#include +#include +#include +#include +#include + +KisDeformPaintOpSettingsWidget::KisDeformPaintOpSettingsWidget(QWidget* parent) + : KisPaintOpOptionsWidget(parent) +{ + m_deformOption = new KisDeformOption(); + m_brushSizeOption = new KisBrushSizeOption(); + m_brushSizeOption->setDiameter(200); + + addPaintOpOption(m_brushSizeOption); + addPaintOpOption(m_deformOption); + addPaintOpOption(new KisCompositeOpOption(true)); + addPaintOpOption(new KisCurveOptionWidget(new KisPressureOpacityOption())); + addPaintOpOption(new KisCurveOptionWidget(new KisPressureSizeOption())); + addPaintOpOption(new KisCurveOptionWidget(new KisPressureRotationOption())); + addPaintOpOption(new KisAirbrushOption()); +} + +KisDeformPaintOpSettingsWidget::~ KisDeformPaintOpSettingsWidget() +{ +} + + +void KisDeformPaintOpSettingsWidget::changePaintOpSize(qreal x, qreal y) +{ + // if the movement is more left<->right then up<->down + if (qAbs(x) > qAbs(y)) { + m_brushSizeOption->setDiameter(m_brushSizeOption->diameter() + qRound(x)); + } + else { // vice-versa + // we can do something different, e.g. change deform mode or ... + } +} + + +QSizeF KisDeformPaintOpSettingsWidget::paintOpSize() const +{ + qreal height = m_brushSizeOption->diameter() * m_brushSizeOption->brushAspect(); + return QSizeF(m_brushSizeOption->diameter(), height); +} + + +KisPropertiesConfiguration* KisDeformPaintOpSettingsWidget::configuration() const +{ + KisDeformPaintOpSettings* config = new KisDeformPaintOpSettings(); + config->setOptionsWidget(const_cast(this)); + config->setProperty("paintop", "deformBrush"); + writeConfiguration(config); + return config; +} + diff --git a/pool/shard011/C++/0121664_codec.cpp b/pool/shard011/C++/0121664_codec.cpp new file mode 100644 index 0000000000000000000000000000000000000000..71045a5127c78b16379afa0ea5c27e8be27cafa8 --- /dev/null +++ b/pool/shard011/C++/0121664_codec.cpp @@ -0,0 +1,254 @@ + +#include +#include +#include +#include "scrambler.h" +#include "base64.h" +#include "codec.h" +#include "easylog.hpp" +#include "libstr.h" +#include "key.h" + +#define MAX_CODEC_LENGTH 20480000 +#define MOD 13 + +BOOL Encode(const char* exe_file_path, const char* txt_file_path) +{ + FILE* in = NULL; + FILE* out = NULL; + int rc = -1; + + do + { + in = fopen(exe_file_path, "rb"); + if (in == NULL) + { + // "encode file fail, open exe file %s error\n" + EasyLog::Format(GetLibStrById(401), exe_file_path); + break; + } + + out = fopen(txt_file_path, "w"); + if (out == NULL) + { + // "encode file fail, open txt file %s error\n" + EasyLog::Format(GetLibStrById(402), txt_file_path); + break; + } + + // Write KEY at fist line + // "%d\n" + fprintf(out, GetLibStrById(552), KEY); + + char ibuffer[BLOCK_SIZE]; + char obuffer[2*BLOCK_SIZE]; + + rc = 0; + while (!feof(in) && rc >= 0) + { + memset(ibuffer, 0, sizeof ibuffer); + memset(obuffer, 0, sizeof obuffer); + + size_t len = fread(ibuffer, 1, BLOCK_SIZE, in); + if (len > 0) + { + // encrypt + for (size_t i = 0; i < len; i++) + { + ibuffer[i] = ibuffer[i] ^ (i % MOD) ^ KEY; + } + + // convert to base64 + rc = encode64(obuffer, sizeof obuffer, ibuffer, len); + if (rc > 0) + { + // write into txt file + // "%s\n" + fprintf(out, GetLibStrById(403), obuffer); + } + else if (rc == 0) + { + // "encode file, encode64 rc %d\n" + EasyLog::Format(GetLibStrById(404), rc); + } + else + { + // "encode file fails, encode64 rc %d < 0\n" + EasyLog::Format(GetLibStrById(405), rc); + break; + } + } + } + } + while (FALSE); + + // close files + if (in != NULL) fclose(in); + if (out != NULL) + { + _commit(_fileno(out)); + fclose(out); + } + + return rc >= 0; +} + +BOOL Decode(const char* txt_file_path, const char* exe_file_path) +{ + FILE* in = NULL; + FILE* out = NULL; + char* cache = NULL; // cache + int total_length = 0; + int key = 0; + + do + { + in = fopen(txt_file_path, "r"); + if (in == NULL) + { + // "decode file fail, open txt file %s error\n" + EasyLog::Format(GetLibStrById(406), txt_file_path); + break; + } + + out = fopen(exe_file_path, "wb"); + if (out == NULL) + { + // "decode file fail, open exe file %s error\n" + EasyLog::Format(GetLibStrById(407), exe_file_path); + break; + } + + char ibuffer[2*BLOCK_SIZE]; + char obuffer[2*BLOCK_SIZE]; + cache = new char [MAX_CODEC_LENGTH]; + + // Read key from first line + bool keyFound = false; + if (!feof(in)) + { + memset(ibuffer, 0, sizeof ibuffer); + char* str = fgets(ibuffer, sizeof ibuffer, in); + if (str != NULL) + { + size_t len2 = strlen(ibuffer); + + // remove the line feed + ibuffer[len2 - 1] = '\0'; + + key = atoi(ibuffer); + } + } + + if (key == 0) + { + // "decode fails, key not fould\n" + EasyLog::Format(GetLibStrById(553)); + } + + while (!feof(in) && total_length < MAX_CODEC_LENGTH) + { + memset(ibuffer, 0, sizeof ibuffer); + memset(obuffer, 0, sizeof obuffer); + + char* str = fgets(ibuffer, sizeof ibuffer, in); + if (str != NULL) + { + size_t len2 = strlen(ibuffer); + + // remove the line feed + ibuffer[len2 - 1] = '\0'; + + // revert base64 + int rc = decode64(obuffer, sizeof obuffer, ibuffer, strlen(ibuffer)); + if (rc > 0) + { + memcpy(cache + total_length, obuffer, rc); + total_length += rc; + + // Decrypt + for (size_t i = 0; i < rc; i++) + { + obuffer[i] = obuffer[i] ^ (i % MOD) ^ (key & 0xff); + } + + fwrite(obuffer, 1, rc, out); + } + else if (rc == 0) + { + // "decode file, decode64 rc %d\n" + EasyLog::Format(GetLibStrById(408), rc); + } + else + { + // "decode file fails, decode64 rc %d < 0\n" + EasyLog::Format(GetLibStrById(409), rc); + break; + } + } + } + } + while (FALSE); + + if (cache != NULL) + { + delete []cache; + } + + // close files + if (in != NULL) fclose(in); + if (out != NULL) + { + fflush(out); + _commit(_fileno(out)); + fclose(out); + } + + return total_length > 0 && total_length < MAX_CODEC_LENGTH; +} + +BOOL DecodePHP(std::string szSrcLine, std::string& szDstLine) +{ + char buffer[1024] = {0}; + char buffer2[1024] = {0}; + + // Decode base64 + memset(buffer, 0, sizeof buffer); + int rc = decode64(buffer, sizeof buffer, szSrcLine.c_str(), szSrcLine.size()); + if (rc <= 6) + { + // prefix + suffix + return FALSE; + } + + // Remove prefix and suffix + memset(buffer2, 0, sizeof buffer2); + memcpy(buffer2, buffer + 3, rc - 6); + + // Decode base64 + memset(buffer, 0, sizeof buffer); + rc = decode64(buffer, sizeof buffer, buffer2, rc - 6); + if (rc <= 6) + { + // prefix + suffix + return FALSE; + } + + // Remove prefix and suffix + memset(buffer2, 0, sizeof buffer2); + memcpy(buffer2, buffer + 3, rc - 6); + + // Decode base64 + memset(buffer, 0, sizeof buffer); + rc = decode64(buffer, sizeof buffer, buffer2, rc - 6); + if (rc <= 0) + { + // prefix + suffix + return FALSE; + } + + // Output + szDstLine = buffer; + + return TRUE; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121666_CascadeButton.cpp b/pool/shard011/C++/0121666_CascadeButton.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df7f8c2add3b32ce9c6a7e1ba9d2ffa1b6a8e33f --- /dev/null +++ b/pool/shard011/C++/0121666_CascadeButton.cpp @@ -0,0 +1,281 @@ +/*********************************************************************** +CascadeButton - Class for buttons that pop up secondary top-level +GLMotif UI components. +Copyright (c) 2001-2010 Oliver Kreylos + +This file is part of the GLMotif Widget Library (GLMotif). + +The GLMotif Widget 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 2 of the +License, or (at your option) any later version. + +The GLMotif Widget Library is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License along +with the GLMotif Widget Library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +***********************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace GLMotif { + +/****************************** +Methods of class CascadeButton: +******************************/ + +void CascadeButton::setArmed(bool newArmed) + { + /* Call the base class widget's setArmed method: */ + DecoratedButton::setArmed(newArmed); + + /* Pop the secondary top level widget up or down: */ + if(isArmed&&!isPopped&&popup!=0) + { + /* Calculate the popup's transformation: */ + Vector offset=getExterior().getCorner(3); + Vector popupHotSpot=popup->getChild()->getExterior().getCorner(2); + offset[0]-=popupHotSpot[0]; + offset[1]-=popupHotSpot[1]; + offset[2]-=popupHotSpot[2]; + offset[2]+=getZRange().second-popup->getChild()->getZRange().first; + getManager()->popupSecondaryWidget(this,popup,offset); + isPopped=true; + + /* Calculate the extended "hit box" around the popup: */ + popupHitBox=popup->getExterior(); + ZRange popupZRange=popup->getZRange(); + popupHitBox.origin[2]=popupZRange.first; + popupHitBox.size[2]=popupZRange.second-popupZRange.first; + popupHitBox.doOffset(offset); + popupHitBox.doOutset(Vector(popupExtrudeSize,popupExtrudeSize,popupExtrudeSize)); + } + else if(!isArmed&&isPopped) + { + popup->getManager()->popdownWidget(popup); + isPopped=false; + } + } + +void CascadeButton::drawDecoration(GLContextData& contextData) const + { + /* Draw the cascade button arrow: */ + glColor(backgroundColor); + arrow.draw(contextData); + } + +CascadeButton::CascadeButton(const char* sName,Container* sParent,const char* sLabel,const GLFont* sFont,bool sManageChild) + :DecoratedButton(sName,sParent,sLabel,sFont,false), + popup(0),isPopped(false), + foundChild(0),armedChild(0), + arrow(GlyphGadget::FANCY_ARROW_RIGHT,GlyphGadget::IN,0.0f) + { + /* Get the style sheet: */ + const StyleSheet* ss=getStyleSheet(); + + /* Set the arrow sizes: */ + arrow.setGlyphSize(ss->size*0.25f); + arrow.setBevelSize(ss->size*0.25f); + arrow.setGlyphColor(backgroundColor); + popupExtrudeSize=ss->size*4.0f; + + /* Set the decoration position and size: */ + setDecorationPosition(DecoratedButton::DECORATION_RIGHT); + GLfloat width=arrow.getPreferredBoxSize(); + setDecorationSize(Vector(width,width,0.0f)); + + /* Manage me: */ + if(sManageChild) + manageChild(); + } + +CascadeButton::CascadeButton(const char* sName,Container* sParent,const char* sLabel,bool sManageChild) + :DecoratedButton(sName,sParent,sLabel,false), + popup(0),isPopped(false), + foundChild(0),armedChild(0), + arrow(GlyphGadget::FANCY_ARROW_RIGHT,GlyphGadget::IN,0.0f) + { + /* Get the style sheet: */ + const StyleSheet* ss=getStyleSheet(); + + /* Set the arrow sizes: */ + arrow.setGlyphSize(ss->size*0.25f); + arrow.setBevelSize(ss->size*0.25f); + arrow.setGlyphColor(backgroundColor); + popupExtrudeSize=ss->size*4.0f; + + /* Set the decoration position and size: */ + setDecorationPosition(DecoratedButton::DECORATION_RIGHT); + GLfloat width=arrow.getPreferredBoxSize(); + setDecorationSize(Vector(width,width,0.0f)); + + /* Manage me: */ + if(sManageChild) + manageChild(); + } + +CascadeButton::~CascadeButton(void) + { + delete popup; + } + +ZRange CascadeButton::calcZRange(void) const + { + /* Calculate the parent class widget's z range: */ + ZRange myZRange=DecoratedButton::calcZRange(); + + /* Adjust for the cascade arrow: */ + myZRange+=arrow.calcZRange(); + + return myZRange; + } + +void CascadeButton::resize(const Box& newExterior) + { + /* Resize the parent class widget: */ + DecoratedButton::resize(newExterior); + + /* Position the cascade arrow: */ + arrow.setGlyphBox(decorationBox); + } + +void CascadeButton::setBackgroundColor(const Color& newBackgroundColor) + { + /* Call the base class method: */ + DecoratedButton::setBackgroundColor(newBackgroundColor); + + /* Let the arrow glyph track the background color: */ + arrow.setGlyphColor(newBackgroundColor); + } + +bool CascadeButton::findRecipient(Event& event) + { + bool result=false; + + /* Find the event's point in our coordinate system: */ + Event::WidgetPoint wp=event.calcWidgetPoint(this); + + /* If the point is inside our bounding box, put us down as recipient: */ + if(isInside(wp.getPoint())) + result=event.setTargetWidget(this,wp); + + /* If the popup is popped up, redirect the question: */ + foundChild=0; + if(isPopped) + { + bool popupResult=popup->findRecipient(event); + if(popupResult) + { + foundChild=event.getTargetWidget(); + event.overrideTargetWidget(this); + result=true; + } + else if(popupHitBox.isInside(Vector(wp.getPoint().getComponents()))) + result|=event.setTargetWidget(this,wp); + } + + return result; + } + +void CascadeButton::pointerButtonDown(Event& event) + { + /* "Repair" the incoming event: */ + event.overrideTargetWidget(foundChild); + + /* Arm the button: */ + setArmed(true); + + /* Find a potential event recipient in the popup: */ + if(popup->findRecipient(event)) + { + armedChild=event.getTargetWidget(); + armedChild->pointerButtonDown(event); + } + else + armedChild=0; + } + +void CascadeButton::pointerButtonUp(Event& event) + { + /* "Repair" the incoming event: */ + event.overrideTargetWidget(foundChild); + + /* Disarm the armed child: */ + if(armedChild!=0) + { + armedChild->pointerButtonUp(event); + armedChild=0; + } + + setArmed(false); + } + +void CascadeButton::pointerMotion(Event& event) + { + /* "Repair" the incoming event: */ + event.overrideTargetWidget(foundChild); + + /* Arm/disarm children as we go by sending fake button events: */ + if(foundChild!=armedChild) + { + if(armedChild!=0) + armedChild->pointerButtonUp(event); + armedChild=foundChild; + if(armedChild!=0) + armedChild->pointerButtonDown(event); + } + else if(armedChild!=0) + armedChild->pointerMotion(event); + } + +void CascadeButton::setPopup(Popup* newPopup) + { + if(isPopped) + { + popup->getManager()->popdownWidget(popup); + isPopped=false; + } + delete popup; + popup=newPopup; + } + +void CascadeButton::setArrowBorderSize(GLfloat newArrowBorderSize) + { + /* Adjust the arrow glyph: */ + arrow.setBevelSize(newArrowBorderSize); + + /* Set the decoration width: */ + GLfloat width=arrow.getPreferredBoxSize(); + setDecorationSize(Vector(width,width,0.0f)); + } + +void CascadeButton::setArrowSize(GLfloat newArrowSize) + { + /* Adjust the arrow glyph: */ + arrow.setGlyphSize(newArrowSize); + + /* Set the decoration width: */ + GLfloat width=arrow.getPreferredBoxSize(); + setDecorationSize(Vector(width,width,0.0f)); + } + +void CascadeButton::setPopupExtrudeSize(GLfloat newPopupExtrudeSize) + { + popupExtrudeSize=newPopupExtrudeSize; + } + +} diff --git a/pool/shard011/C++/0121672_FSProvider.cpp b/pool/shard011/C++/0121672_FSProvider.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5d1434bf6f0bf1673bd23f890c2f1de4a9a5a60e --- /dev/null +++ b/pool/shard011/C++/0121672_FSProvider.cpp @@ -0,0 +1,84 @@ +//===--- FSProvider.cpp - VFS provider for ClangdServer -------------------===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "FSProvider.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/VirtualFileSystem.h" +#include + +namespace clang { +namespace clangd { + +namespace { +/// Always opens files in the underlying filesystem as "volatile", meaning they +/// won't be memory-mapped. This avoid locking the files on Windows. +class VolatileFileSystem : public llvm::vfs::ProxyFileSystem { +public: + explicit VolatileFileSystem(llvm::IntrusiveRefCntPtr FS) + : ProxyFileSystem(std::move(FS)) {} + + llvm::ErrorOr> + openFileForRead(const llvm::Twine &InPath) override { + llvm::SmallString<128> Path; + InPath.toVector(Path); + + auto File = getUnderlyingFS().openFileForRead(Path); + if (!File) + return File; + // Try to guess preamble files, they can be memory-mapped even on Windows as + // clangd has exclusive access to those. + llvm::StringRef FileName = llvm::sys::path::filename(Path); + if (FileName.startswith("preamble-") && FileName.endswith(".pch")) + return File; + return std::unique_ptr(new VolatileFile(std::move(*File))); + } + +private: + class VolatileFile : public llvm::vfs::File { + public: + VolatileFile(std::unique_ptr Wrapped) + : Wrapped(std::move(Wrapped)) { + assert(this->Wrapped); + } + + virtual llvm::ErrorOr> + getBuffer(const llvm::Twine &Name, int64_t FileSize, + bool RequiresNullTerminator, bool /*IsVolatile*/) override { + return Wrapped->getBuffer(Name, FileSize, RequiresNullTerminator, + /*IsVolatile=*/true); + } + + llvm::ErrorOr status() override { + return Wrapped->status(); + } + llvm::ErrorOr getName() override { return Wrapped->getName(); } + std::error_code close() override { return Wrapped->close(); } + + private: + std::unique_ptr Wrapped; + }; +}; +} // namespace + +llvm::IntrusiveRefCntPtr +clang::clangd::RealFileSystemProvider::getFileSystem() const { +// Avoid using memory-mapped files on Windows, they cause file locking issues. +// FIXME: Try to use a similar approach in Sema instead of relying on +// propagation of the 'isVolatile' flag through all layers. +#ifdef _WIN32 + return new VolatileFileSystem( + llvm::vfs::createPhysicalFileSystem().release()); +#else + return llvm::vfs::createPhysicalFileSystem().release(); +#endif +} +} // namespace clangd +} // namespace clang diff --git a/pool/shard011/C++/0121674_datetimectrl.cpp b/pool/shard011/C++/0121674_datetimectrl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..408feab3eb864e271590f7f3a5ed1f5750f59988 --- /dev/null +++ b/pool/shard011/C++/0121674_datetimectrl.cpp @@ -0,0 +1,159 @@ +/////////////////////////////////////////////////////////////////////////////// +// Name: src/msw/datetimectrl.cpp +// Purpose: Implementation of wxDateTimePickerCtrl for MSW. +// Author: Vadim Zeitlin +// Created: 2011-09-22 (extracted from src/msw/datectrl.cpp) +// Copyright: (c) 2005-2011 Vadim Zeitlin +// Licence: wxWindows licence +/////////////////////////////////////////////////////////////////////////////// + +// ============================================================================ +// declarations +// ============================================================================ + +// ---------------------------------------------------------------------------- +// headers +// ---------------------------------------------------------------------------- + +// for compilers that support precompilation, includes "wx.h". +#include "wx/wxprec.h" + +#ifdef __BORLANDC__ + #pragma hdrstop +#endif + +#include "wx/datetimectrl.h" + +#ifdef wxNEEDS_DATETIMEPICKCTRL + +#ifndef WX_PRECOMP + #include "wx/msw/wrapwin.h" + #include "wx/msw/wrapcctl.h" // include "properly" + #include "wx/msw/private.h" + #include "wx/dcclient.h" +#endif // WX_PRECOMP + +#include "wx/msw/private/datecontrols.h" + +// apparently some versions of mingw define these macros erroneously +#ifndef DateTime_GetSystemtime + #define DateTime_GetSystemtime DateTime_GetSystemTime +#endif + +#ifndef DateTime_SetSystemtime + #define DateTime_SetSystemtime DateTime_SetSystemTime +#endif + +// ============================================================================ +// wxDateTimePickerCtrl implementation +// ============================================================================ + +bool +wxDateTimePickerCtrl::MSWCreateDateTimePicker(wxWindow *parent, + wxWindowID id, + const wxDateTime& dt, + const wxPoint& pos, + const wxSize& size, + long style, + const wxValidator& validator, + const wxString& name) +{ + if ( !wxMSWDateControls::CheckInitialization() ) + return false; + + // initialize the base class + if ( !CreateControl(parent, id, pos, size, style, validator, name) ) + return false; + + // create the native control + if ( !MSWCreateControl(DATETIMEPICK_CLASS, wxString(), pos, size) ) + return false; + + if ( dt.IsValid() || MSWAllowsNone() ) + SetValue(dt); + else + SetValue(wxDateTime::Now()); + + return true; +} + +void wxDateTimePickerCtrl::SetValue(const wxDateTime& dt) +{ + wxCHECK_RET( dt.IsValid() || MSWAllowsNone(), + wxT("this control requires a valid date") ); + + SYSTEMTIME st; + if ( dt.IsValid() ) + dt.GetAsMSWSysTime(&st); + + if ( !DateTime_SetSystemtime(GetHwnd(), + dt.IsValid() ? GDT_VALID : GDT_NONE, + &st) ) + { + // The only expected failure is when the date is out of range but we + // already checked for this above. + wxFAIL_MSG( wxT("Setting the calendar date unexpectedly failed.") ); + + // In any case, skip updating m_date below. + return; + } + + m_date = dt; +} + +wxDateTime wxDateTimePickerCtrl::GetValue() const +{ + return m_date; +} + +wxSize wxDateTimePickerCtrl::DoGetBestSize() const +{ + wxClientDC dc(const_cast(this)); + + // Use the same native format as the underlying native control. +#if wxUSE_INTL + wxString s = wxDateTime::Now().Format(wxLocale::GetInfo(MSWGetFormat())); +#else // !wxUSE_INTL + wxString s("XXX-YYY-ZZZZ"); +#endif // wxUSE_INTL/!wxUSE_INTL + + // the best size for the control is bigger than just the string + // representation of the current value because the control must accommodate + // any date and while the widths of all digits are usually about the same, + // the width of the month string varies a lot, so try to account for it + s += wxT("WW"); + + int x, y; + dc.GetTextExtent(s, &x, &y); + + // account for the drop-down arrow or spin arrows + x += wxSystemSettings::GetMetric(wxSYS_HSCROLL_ARROW_X); + + // and for the checkbox if we have it + if ( MSWAllowsNone() ) + x += 3*GetCharWidth(); + + wxSize best(x, EDIT_HEIGHT_FROM_CHAR_HEIGHT(y)); + CacheBestSize(best); + return best; +} + +bool +wxDateTimePickerCtrl::MSWOnNotify(int idCtrl, WXLPARAM lParam, WXLPARAM *result) +{ + NMHDR* hdr = (NMHDR *)lParam; + switch ( hdr->code ) + { + case DTN_DATETIMECHANGE: + if ( MSWOnDateTimeChange(*(NMDATETIMECHANGE*)(hdr)) ) + { + *result = 0; + return true; + } + break; + } + + return wxDateTimePickerCtrlBase::MSWOnNotify(idCtrl, lParam, result); +} + +#endif // wxNEEDS_DATETIMEPICKCTRL diff --git a/pool/shard011/C++/0121675_commandlocator.cpp b/pool/shard011/C++/0121675_commandlocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9090c05a632a2a789cfa69b217a27ac0e6b0b91 --- /dev/null +++ b/pool/shard011/C++/0121675_commandlocator.cpp @@ -0,0 +1,128 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** +** GNU Lesser General Public License Usage +** +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this file. +** Please review the following information to ensure the GNU Lesser General +** Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** Other Usage +** +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** +**************************************************************************/ + +#include "commandlocator.h" + +#include +#include + +#include + +#include + +namespace Locator { + +struct CommandLocatorPrivate { + CommandLocatorPrivate(const QString &prefix, + const QString &displayName) : + m_prefix(prefix), m_displayName(displayName) {} + + const QString m_prefix; + const QString m_displayName; + + QList commands; +}; + +CommandLocator::CommandLocator(const QString &prefix, + const QString &displayName, + const QString &shortCutString, + QObject *parent) : + Locator::ILocatorFilter(parent), + d(new CommandLocatorPrivate(prefix, displayName)) +{ + setShortcutString(shortCutString); +} + +CommandLocator::~CommandLocator() +{ + delete d; +} + +void CommandLocator::appendCommand(Core::Command *cmd) +{ + d->commands.push_back(cmd); +} + +QString CommandLocator::displayName() const +{ + return d->m_displayName; +} + +QString CommandLocator::id() const +{ + return d->m_prefix; +} + +ILocatorFilter::Priority CommandLocator::priority() const +{ + return Medium; +} + +QList CommandLocator::matchesFor(QFutureInterface &future, const QString &entry) +{ + QList filters; + // Get active, enabled actions matching text, store in list. + // Reference via index in extraInfo. + const QChar ampersand = QLatin1Char('&'); + const int count = d->commands.size(); + for (int i = 0; i < count; i++) { + if (future.isCanceled()) + break; + if (d->commands.at(i)->isActive()) { + if (QAction *action = d->commands.at(i)->action()) + if (action->isEnabled()) { + QString text = action->text(); + text.remove(ampersand); + if (text.contains(entry, Qt::CaseInsensitive)) { + filters.append(FilterEntry(this, text, QVariant(i))); + } + } + } + } + return filters; +} + +void CommandLocator::accept(Locator::FilterEntry entry) const +{ + // Retrieve action via index. + const int index = entry.internalData.toInt(); + QTC_ASSERT(index >= 0 && index < d->commands.size(), return); + QAction *action = d->commands.at(index)->action(); + QTC_ASSERT(action->isEnabled(), return); + action->trigger(); +} + +void CommandLocator::refresh(QFutureInterface &) +{ +} + +} // namespace Locator diff --git a/pool/shard011/C++/0121677_insert_node.cpp b/pool/shard011/C++/0121677_insert_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b45de34ccb7ba436bf4659a94ebf8fe281e7171b --- /dev/null +++ b/pool/shard011/C++/0121677_insert_node.cpp @@ -0,0 +1,35 @@ +#include "insert_node.hpp" + +#include +#include +#include +#include +#include + +#include "utils/assert.hpp" + +namespace opossum { + +InsertNode::InsertNode(const std::string& init_table_name) + : AbstractNonQueryNode(LQPNodeType::Insert), table_name(init_table_name) {} + +std::string InsertNode::description(const DescriptionMode mode) const { + std::ostringstream desc; + + desc << "[Insert] Into table '" << table_name << "'"; + + return desc.str(); +} + +size_t InsertNode::_on_shallow_hash() const { return boost::hash_value(table_name); } + +std::shared_ptr InsertNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const { + return InsertNode::make(table_name); +} + +bool InsertNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const { + const auto& insert_node_rhs = static_cast(rhs); + return table_name == insert_node_rhs.table_name; +} + +} // namespace opossum diff --git a/pool/shard011/C++/0121679_vpMomentAlpha.cpp b/pool/shard011/C++/0121679_vpMomentAlpha.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9e4927ba7cc8eb64184ac6094922aaf44fc8bdcf --- /dev/null +++ b/pool/shard011/C++/0121679_vpMomentAlpha.cpp @@ -0,0 +1,172 @@ +/**************************************************************************** + * + * This file is part of the ViSP software. + * Copyright (C) 2005 - 2017 by Inria. All rights reserved. + * + * This software 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. + * See the file LICENSE.txt at the root directory of this source + * distribution for additional information about the GNU GPL. + * + * For using ViSP with software that can not be combined with the GNU + * GPL, please contact Inria about acquiring a ViSP Professional + * Edition License. + * + * See http://visp.inria.fr for more information. + * + * This software was developed at: + * Inria Rennes - Bretagne Atlantique + * Campus Universitaire de Beaulieu + * 35042 Rennes Cedex + * France + * + * If you have questions regarding the use of this file, please contact + * Inria at visp@inria.fr + * + * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE + * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + * + * Description: + * Alpha moment descriptor for in-plane orientation. + * + * Authors: + * Filip Novotny + * + *****************************************************************************/ + +#include +#include +#include +#include + +/*! + Empty constructor. Initializes alpha moment as a reference alpha with a + value in \f$[-\pi/2..\pi/2]\f$. A default-constructed alpha moment may be + used as a reference information for other alphas. A reference alpha is a + class harbouring an alpha value computed for a \f$[-\pi/2..\pi/2]\f$ portion + of the circle. + */ +vpMomentAlpha::vpMomentAlpha() : isRef(true), symmetric(false), ref(), alphaRef(0.) { values.resize(1); } + +/*! + Common constructor. Initializes alpha moment as a non-reference alpha with a + value computed in \f$[-\pi..\pi]\f$. \param ref_ : vector of 3rd order + centered moments corresponding to the reference alpha in the following + order: \f$\mu_{30},\mu_{21},\mu_{12},\mu_{03}\f$. \param alpha_ref : value + of the reference alpha. +*/ +vpMomentAlpha::vpMomentAlpha(const std::vector &ref_, double alpha_ref) + : vpMoment(), isRef(false), symmetric(false), ref(ref_), alphaRef(alpha_ref) +{ + for (std::vector::const_iterator it = ref_.begin(); it != ref_.end(); ++it) + if (std::fabs(*it) <= 1e-4) + symmetric = true; + + values.resize(1); +} + +/*! + Compute the value of the alpha-moment. + Depends on vpMomentCentered. + */ +void vpMomentAlpha::compute() +{ + // symmetric = symmetric | this->getObject().isSymmetric(); + bool found_moment_centered; + + const vpMomentCentered &momentCentered = + (static_cast(getMoments().get("vpMomentCentered", found_moment_centered))); + + if (!found_moment_centered) + throw vpException(vpException::notInitialized, "vpMomentCentered not found"); + + double t = 2.0 * momentCentered.get(1, 1) / (momentCentered.get(2, 0) - momentCentered.get(0, 2)); + // double alpha = 0.5 * atan2(2.0 * momentCentered.get(1, 1), + // (momentCentered.get(2, 0) - momentCentered.get(0, 2))); + double alpha = 0.5 * atan(t); + + std::vector rotMu(4); + // std::vector realMu(4); + + if (isRef) { + alphaRef = alpha; + } else { + if (!symmetric) { + double r11 = cos(alpha - alphaRef); + double r12 = sin(alpha - alphaRef); + double r21 = -r12; + double r22 = r11; + unsigned int idx = 0; + unsigned int order = 4; + for (unsigned int c = 0; c < (order) * (order); c++) { + unsigned int i = c % order; + unsigned int j = c / order; + + if (i + j == 3) { + double r11_k = 1.; + for (unsigned int k = 0; k <= i; k++) { + double r12_i_k = pow(r12, (int)(i - k)); + double comb_i_k = static_cast(vpMath::comb(i, k)); + for (unsigned int l = 0; l <= j; l++) { + rotMu[idx] += static_cast(comb_i_k * vpMath::comb(j, l) * r11_k * pow(r21, (int)l) * r12_i_k * + pow(r22, (int)(j - l)) * + momentCentered.get(k + l, (unsigned int)(int)(i + j - k - l))); + } + r11_k *= r11; + } + // realMu[idx] = momentCentered.get(i, j); + idx++; + } + } + + double sum = 0.; + bool signChange = true; + for (unsigned int i = 0; i < 4; i++) { + if (std::fabs(rotMu[i]) > 1e10 * std::numeric_limits::epsilon() && + std::fabs(ref[i]) > 1e10 * std::numeric_limits::epsilon() && rotMu[i] * ref[i] > 0) + signChange = false; + sum += std::fabs(rotMu[i] * ref[i]); + } + + if (sum < 1e4 * std::numeric_limits::epsilon()) + signChange = false; + if (signChange) { + // alpha = alpha + M_PI; + if (alpha < 0) + alpha += M_PI; + else + alpha -= M_PI; + } + } + } + values[0] = alpha; +} + +/*! + Prints the value of the major-axis orientation in degrees and rad + */ +VISP_EXPORT std::ostream &operator<<(std::ostream &os, const vpMomentAlpha &c) +{ + os << (__FILE__) << std::endl; + os << "Alpha = " << c.values[0] << "rad = " << vpMath::deg(c.values[0]) << "deg " << std::endl; + return os; +} + +/*! +Prints the dependencies of alpha, namely centered moments mu11, mu20 ad mu02 +*/ +void vpMomentAlpha::printDependencies(std::ostream &os) const +{ + os << (__FILE__) << std::endl; + bool found_moment_centered; + const vpMomentCentered &momentCentered = + (static_cast(getMoments().get("vpMomentCentered", found_moment_centered))); + if (!found_moment_centered) + throw vpException(vpException::notInitialized, "vpMomentCentered not found"); + + os << "mu11 = " << momentCentered.get(1, 1) << "\t"; + os << "mu20 = " << momentCentered.get(2, 0) << "\t"; + os << "mu02 = " << momentCentered.get(0, 2) << std::endl; +} diff --git a/pool/shard011/C++/0121681_SearchClientMain.cpp b/pool/shard011/C++/0121681_SearchClientMain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9633bb6d53d08b5538f133d52869c6855897cc59 --- /dev/null +++ b/pool/shard011/C++/0121681_SearchClientMain.cpp @@ -0,0 +1,40 @@ +#include "firtex/extension/util/Application.h" +#include "firtex/utility/Path.h" +#include "firtex/config/XMLConfigurator.h" +#include "RPCSearchClientAppRunner.h" + + +FX_NS_USE(app); + +using namespace std; +FX_NS_USE(util); +FX_NS_USE(common); +FX_NS_USE(config); +FX_NS_USE(utility); + +#define LOGGER_CONF_FILE_NAME "logger_conf.xml" + + +int main(int argc,char* argv[]) +{ + + Path logFilePath(Path::current()); + logFilePath.makeDirectory(); + logFilePath.setFileName(LOGGER_CONF_FILE_NAME); + + string sLogConf = logFilePath.toString(); + File confFile(sLogConf); + if (confFile.exists()) + { + cout << "[INFO] Load logger configure file: [" << sLogConf << "]" << endl; + LoggerBuilder::instance()->configure(sLogConf); + } + + Application app("RPCSearchClient", "FirteX search client."); + app.addAppRunner(new RPCSearchClientAppRunner); + if (app.parse(argc, (const char**)argv)) + { + return app.run(); + } + return 0; +} diff --git a/pool/shard011/C++/0121683_cspace_tools.cpp b/pool/shard011/C++/0121683_cspace_tools.cpp new file mode 100644 index 0000000000000000000000000000000000000000..45e8e3d94b581fd3c84c7736e19c8f040562aeaf --- /dev/null +++ b/pool/shard011/C++/0121683_cspace_tools.cpp @@ -0,0 +1,90 @@ +#include "cspace_tools.h" + +#include "obstacle_map.h" + +#include +#include + +using namespace std; + +namespace cspace { + +typedef cgal_kernel K; +typedef K::Segment_3 Segment_3; +typedef K::Point_2 Point_2; +typedef K::Point_3 Point_3; +typedef K::Iso_rectangle_2 Iso_rectangle_2; +typedef K::Vector_2 Vector_2; +typedef CGAL::Polygon_2 Polygon_2; +typedef CGAL::Polygon_with_holes_2 Polygon_with_holes_2_exact; +typedef CGAL::Point_2 Point_2_exact; +typedef CGAL::Polygon_2 Polygon_2_exact; + + +void GetCSpaceObstacle2d(const Polygon_2 &poly, const int rotInd, + Polygon_2 *cspoly) { + double rad = ObstacleMap::IdToRad(rotInd); + Polygon_2_exact reflected_robot = GetReflectedRobotRepresentation(rad); + Polygon_2_exact poly_exact; + for (int i = 0; i < poly.size(); ++i) { + poly_exact.insert(poly_exact.vertices_end(), Point_2_exact(poly[i].x(), poly[i].y())); + } + Polygon_with_holes_2_exact sum = minkowski_sum_2(reflected_robot, poly_exact); + Polygon_2_exact cspoly_exact = sum.outer_boundary(); + cspoly->clear(); + for (int i = 0; i < cspoly_exact.size(); ++i) { + cspoly->insert(cspoly->vertices_end(), Point_2(CGAL::to_double(cspoly_exact[i].x()), CGAL::to_double(cspoly_exact[i].y()))); + } +} + +Polygon_2_exact GetReflectedRobotRepresentation(double rad) { + /* + double pForward = 0.20, pBackward = -0.34, + pLeft = 0.24, pRight = -0.24; + */ + vector points; +/* points.push_back( + Point_2_exact( + -(pForward*cos(rad)-pLeft*sin(rad)), + -(pForward*sin(rad)+pLeft*cos(rad)))); + points.push_back( + Point_2_exact( + -(pForward*cos(rad)-pRight*sin(rad)), + -(pForward*sin(rad)+pRight*cos(rad)))); + points.push_back( + Point_2_exact( + -(pBackward*cos(rad)-pLeft*sin(rad)), + -(pBackward*sin(rad)+pLeft*cos(rad)))); + points.push_back( + Point_2_exact( + -(pBackward*cos(rad)-pRight*sin(rad)), + -(pBackward*sin(rad)+pRight*cos(rad)))); + */ + points.push_back(Point_2_exact(-0.27, 0.10)); + points.push_back(Point_2_exact(-0.27+0.15, 0.10+0.15)); + points.push_back(Point_2_exact(+0.27-0.14, 0.10+0.15)); + points.push_back(Point_2_exact(+0.27, 0.10)); + points.push_back(Point_2_exact(+0.27, -0.11)); + points.push_back(Point_2_exact(+0.23, -0.11)); + points.push_back(Point_2_exact(+0.23, -0.37)); + points.push_back(Point_2_exact(-0.23, -0.37)); + points.push_back(Point_2_exact(-0.23, -0.11)); + points.push_back(Point_2_exact(-0.27, -0.11)); + // Reflect and rotate + for (int i = 0; i < points.size(); ++i) { + double nx = CGAL::to_double(points[i].y()); + double ny = -CGAL::to_double(points[i].x()); + points[i] = Point_2_exact(-(nx*cos(rad)-ny*sin(rad)), -(nx*sin(rad)+ny*cos(rad))); + } + + vector hull; + CGAL::ch_graham_andrew(points.begin(), points.end(), back_inserter(hull)); + + Polygon_2_exact reflected_robot; + for (Point_2_exact p : hull) { + reflected_robot.insert(reflected_robot.vertices_end(), p); + } + return reflected_robot; +} + +} // namespace cspace diff --git a/pool/shard011/C++/0121684_MaterialInstance.cpp b/pool/shard011/C++/0121684_MaterialInstance.cpp new file mode 100644 index 0000000000000000000000000000000000000000..db705186c8adc2527f2107d844c3b81206fafa62 --- /dev/null +++ b/pool/shard011/C++/0121684_MaterialInstance.cpp @@ -0,0 +1,152 @@ +/* +Copied from the Ogre3d wiki: Article "Per renderable transparency" +Edited to fit the usage in open dark engine + +$Id$ + +*/ + +#include "MaterialInstance.h" +#include + +using namespace Ogre; + +MaterialInstance::MaterialInstance() { + mCurrentTransparency = 0.0f; + mCurrentZBias = 0.0f; + + mCopyMat.reset(); + + mSBT = SBT_TRANSPARENT_ALPHA; +} + +MaterialInstance::~MaterialInstance() { clearCopyMaterial(); } + +void MaterialInstance::setSceneBlending(SceneBlendType sbt) { + mSBT = sbt; + + if (mCopyMat) { + Material::TechniqueIterator techniqueIt = + mCopyMat->getTechniqueIterator(); + while (techniqueIt.hasMoreElements()) { + Technique *t = techniqueIt.getNext(); + Technique::PassIterator passIt = t->getPassIterator(); + while (passIt.hasMoreElements()) { + passIt.getNext()->setSceneBlending(mSBT); + } + } + } +} + +void MaterialInstance::setTransparency(Real transparency) { + mCurrentTransparency = transparency; + if (mCurrentTransparency > 0.0f) { + if (mCurrentTransparency > 1.0f) + mCurrentTransparency = 1.0f; + + if (!mCopyMat) { + createCopyMaterial(); + } + + unsigned short i = 0, j; + ColourValue sc, dc; // Source colur, destination colour + Material::TechniqueIterator techniqueIt = + mCopyMat->getTechniqueIterator(); + while (techniqueIt.hasMoreElements()) { + Technique *t = techniqueIt.getNext(); + Technique::PassIterator passIt = t->getPassIterator(); + j = 0; + while (passIt.hasMoreElements()) { + sc = mOriginalMat->getTechnique(i)->getPass(j)->getDiffuse(); + + switch (mSBT) { + case SBT_ADD: + dc = sc; + dc.r -= sc.r * mCurrentTransparency; + dc.g -= sc.g * mCurrentTransparency; + dc.b -= sc.b * mCurrentTransparency; + passIt.peekNext()->setAmbient(ColourValue::Black); + break; + case SBT_TRANSPARENT_ALPHA: + default: + dc = sc; + dc.a = sc.a * (1.0f - mCurrentTransparency); + passIt.peekNext()->setAmbient(mOriginalMat->getTechnique(i) + ->getPass(j) + ->getAmbient()); + break; + } + passIt.peekNext()->setDiffuse(dc); + passIt.peekNext()->setAlphaRejectFunction(CMPF_ALWAYS_PASS); + + passIt.moveNext(); + + ++j; + } + + ++i; + } + } else { + mCurrentTransparency = 0.0f; + } +} + +void MaterialInstance::setZBias(Ogre::Real zbias) { + mCurrentZBias = zbias; + + if (mCurrentZBias != 0.0f) { + if (!mCopyMat) { + createCopyMaterial(); + } + + Material::TechniqueIterator techniqueIt = + mCopyMat->getTechniqueIterator(); + + while (techniqueIt.hasMoreElements()) { + Technique *t = techniqueIt.getNext(); + + Technique::PassIterator passIt = t->getPassIterator(); + while (passIt.hasMoreElements()) { + Pass *p = passIt.getNext(); + + // change the depth bias + p->setDepthBias(mCurrentZBias, mCurrentZBias); + } + } + } +} + +MaterialPtr MaterialInstance::getCopyMaterial() { return mCopyMat; } + +void MaterialInstance::createCopyMaterial() { + String name; + // Avoid name collision + do { + name = mOriginalMat->getName() + + StringConverter::toString(Math::UnitRandom()); + } while (MaterialManager::getSingleton().resourceExists(name)); + + mCopyMat = mOriginalMat->clone(name); + + Material::TechniqueIterator techniqueIt = mCopyMat->getTechniqueIterator(); + while (techniqueIt.hasMoreElements()) { + Technique *t = techniqueIt.getNext(); + Technique::PassIterator passIt = t->getPassIterator(); + while (passIt.hasMoreElements()) { + passIt.peekNext()->setDepthWriteEnabled(false); + passIt.peekNext()->setSceneBlending(mSBT); + passIt.moveNext(); + } + } +} + +void MaterialInstance::clearCopyMaterial() { + if (mCopyMat) + MaterialManager::getSingleton().remove(mCopyMat->getName()); + + mCopyMat.reset(); +} + +bool MaterialInstance::hasOverrides(void) { + return (mCurrentTransparency != 0.0f) || (mCurrentZBias != 0.0f); +} diff --git a/pool/shard011/C++/0121686_SimpleStreamHandler.cpp b/pool/shard011/C++/0121686_SimpleStreamHandler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..89fd23d05e33678dd07b3f85c0117d5f5d6fcdc4 --- /dev/null +++ b/pool/shard011/C++/0121686_SimpleStreamHandler.cpp @@ -0,0 +1,126 @@ +/* + Copyright 2002-2013 CEA LIST + + This file is part of LIMA. + + LIMA is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + LIMA is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with LIMA. If not, see +*/ +/*************************************************************************** + * Copyright (C) 2004-2012 by CEA LIST * + * * + ***************************************************************************/ +#include "SimpleStreamHandler.h" +#include "common/AbstractFactoryPattern/SimpleFactory.h" +#include "common/Data/genericDocumentProperties.h" + +namespace Lima +{ + +namespace LinguisticProcessing +{ + SimpleFactory simpleStreamHandlerFactory(SIMPLESTREAMHANDLER_CLASSID); + +class SimpleStreamHandlerPrivate +{ + friend class SimpleStreamHandler; + + SimpleStreamHandlerPrivate(); + + SimpleStreamHandlerPrivate(const SimpleStreamHandlerPrivate& sshp); + + virtual ~SimpleStreamHandlerPrivate(); + + std::ostream* m_out; +}; + +SimpleStreamHandlerPrivate::SimpleStreamHandlerPrivate(): + m_out(0) +{} + +SimpleStreamHandlerPrivate::SimpleStreamHandlerPrivate(const SimpleStreamHandlerPrivate& sshp): + m_out(0) +{ + LIMA_UNUSED(sshp); +} + + +SimpleStreamHandlerPrivate::~SimpleStreamHandlerPrivate() +{} + + +SimpleStreamHandler::SimpleStreamHandler() + : AbstractTextualAnalysisHandler(), m_d(new SimpleStreamHandlerPrivate()) +{} + +SimpleStreamHandler::SimpleStreamHandler(const SimpleStreamHandler& ssh) + : AbstractTextualAnalysisHandler(), m_d(new SimpleStreamHandlerPrivate(*ssh.m_d)) +{} + + +SimpleStreamHandler::~SimpleStreamHandler() +{ + delete m_d; +} + +void SimpleStreamHandler::startDocument(const Common::Misc::GenericDocumentProperties& /*props*/) +{} + +void SimpleStreamHandler::endDocument() +{} + +void SimpleStreamHandler::endAnalysis() +{ + DUMPERLOGINIT; + LDEBUG << "SimpleStreamHandler::endAnalysis"; + if (m_d->m_out != 0) m_d->m_out->flush(); +} + +void SimpleStreamHandler::startAnalysis() +{} + + +void SimpleStreamHandler::handle(const char* buf,int length) +{ + DUMPERLOGINIT; + LDEBUG << "SimpleStreamHandler::handle"; + + if (m_d->m_out != 0) m_d->m_out->write(buf,length); +} + +void SimpleStreamHandler::startNode( const std::string& /*elementName*/, bool /*forIndexing*/ ) +{} + +void SimpleStreamHandler::endNode( const Common::Misc::GenericDocumentProperties& /*props*/ ) +{ +} + +void SimpleStreamHandler::setOut(std::ostream* out) +{ + m_d->m_out = out; +} + +// void SimpleStreamHandler::handleProc( +// const std::string& tagName, +// const std::string& content, +// const std::map& metaData, +// const std::string& pipeline, +// const std::set& inactiveUnits) +// { +// getAnalysisClient("fre")->analyze(content, metaData,pipeline,inactiveUnits); +// +// } + +} // closing namespace LinguisticProcessing + +} // closing namespace Lima diff --git a/pool/shard011/C++/0121687_pepper_file_system_browser_host_unittest.cc b/pool/shard011/C++/0121687_pepper_file_system_browser_host_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..30353a1cd2fa01424463feecda60d8c936b9fd34 --- /dev/null +++ b/pool/shard011/C++/0121687_pepper_file_system_browser_host_unittest.cc @@ -0,0 +1,84 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/browser/renderer_host/pepper/pepper_file_system_browser_host.h" + +#include +#include + +#include "base/macros.h" +#include "content/browser/renderer_host/pepper/browser_ppapi_host_test.h" +#include "content/public/test/browser_task_environment.h" +#include "ppapi/c/pp_instance.h" +#include "ppapi/c/pp_resource.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace content { + +class PepperFileSystemBrowserHostTest : public testing::Test, + public BrowserPpapiHostTest { + public: + PepperFileSystemBrowserHostTest() {} + + PepperFileSystemBrowserHostTest(const PepperFileSystemBrowserHostTest&) = + delete; + PepperFileSystemBrowserHostTest& operator=( + const PepperFileSystemBrowserHostTest&) = delete; + + ~PepperFileSystemBrowserHostTest() override {} + + void SetUp() override { + PP_Instance pp_instance = 12345; + PP_Resource pp_resource = 67890; + host_ = std::make_unique( + GetBrowserPpapiHost(), pp_instance, pp_resource, + PP_FILESYSTEMTYPE_ISOLATED); + } + + void TearDown() override { host_.reset(); } + + protected: + std::string GeneratePluginId(const std::string& mime_type) { + return host_->GeneratePluginId(mime_type); + } + + private: + // Needed because |host_| has checks for UI/IO threads. + BrowserTaskEnvironment task_environment_; + std::unique_ptr host_; +}; + +TEST_F(PepperFileSystemBrowserHostTest, GeneratePluginId) { + // Should not contain wild card characters. + EXPECT_TRUE(GeneratePluginId("*").empty()); + EXPECT_TRUE(GeneratePluginId("*/*").empty()); + + // Should contain only one slash. + EXPECT_TRUE(GeneratePluginId(".").empty()); + EXPECT_TRUE(GeneratePluginId("..").empty()); + EXPECT_TRUE(GeneratePluginId("application").empty()); + EXPECT_TRUE(GeneratePluginId("application/mime/type").empty()); + + // Should start with "legal_top_level_types" + // (ex. "application", "audio", "x-"). See "mime_util.cc" for more details. + EXPECT_TRUE(GeneratePluginId("/mime").empty()); + EXPECT_TRUE(GeneratePluginId("./mime").empty()); + EXPECT_TRUE(GeneratePluginId("../mime").empty()); + EXPECT_TRUE(GeneratePluginId("app/mime").empty()); + + // Should not contain characters other than alphanumeric or "._-". + EXPECT_TRUE(GeneratePluginId("application/mime+type").empty()); + EXPECT_TRUE(GeneratePluginId("application/mime:type").empty()); + EXPECT_TRUE(GeneratePluginId("application/mime;type").empty()); + + // Valid cases. + EXPECT_EQ("application_mime", GeneratePluginId("application/mime")); + EXPECT_EQ("x-app_mime", GeneratePluginId("x-app/mime")); + EXPECT_EQ("application_mime.type", GeneratePluginId("application/mime.type")); + EXPECT_EQ("application_mime_type", GeneratePluginId("application/mime_type")); + EXPECT_EQ("application_mime-type", GeneratePluginId("application/mime-type")); + EXPECT_EQ("application_..", GeneratePluginId("application/..")); +} + +} // namespace content diff --git a/pool/shard011/C++/0121691_death.cpp b/pool/shard011/C++/0121691_death.cpp new file mode 100644 index 0000000000000000000000000000000000000000..005e717426beac0ab9039ff96063c5b7d76d720d --- /dev/null +++ b/pool/shard011/C++/0121691_death.cpp @@ -0,0 +1,149 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +#include "ultima/ultima4/game/death.h" +#include "ultima/ultima4/game/context.h" +#include "ultima/ultima4/game/game.h" +#include "ultima/ultima4/game/player.h" +#include "ultima/ultima4/game/portal.h" +#include "ultima/ultima4/views/stats.h" +#include "ultima/ultima4/controllers/wait_controller.h" +#include "ultima/ultima4/core/settings.h" +#include "ultima/ultima4/events/event_handler.h" +#include "ultima/ultima4/gfx/screen.h" +#include "ultima/ultima4/map/map.h" +#include "ultima/ultima4/map/annotation.h" +#include "ultima/ultima4/map/city.h" +#include "ultima/ultima4/map/location.h" +#include "ultima/ultima4/map/mapmgr.h" +#include "ultima/ultima4/sound/music.h" +#include "ultima/ultima4/ultima4.h" +#include "common/system.h" + +namespace Ultima { +namespace Ultima4 { + +Death *g_death; + +#define REVIVE_WORLD_X 86 +#define REVIVE_WORLD_Y 107 +#define REVIVE_CASTLE_X 19 +#define REVIVE_CASTLE_Y 8 + +const struct { + int _timeout; ///< pause in seconds + const char *_text; ///< text of message +} DEATH_MSGS[] = { + { 5, "\n\n\nAll is Dark...\n" }, + { 5, "\nBut wait...\n" }, + { 5, "Where am I?...\n" }, + { 5, "Am I dead?...\n" }, + { 5, "Afterlife?...\n" }, + { 5, "You hear:\n %s\n" }, + { 5, "I feel motion...\n" }, + { 5, "\nLord British says: I have pulled thy spirit and some possessions from the void. Be more careful in the future!\n\n\020" } +}; + +#define N_MSGS (sizeof(DEATH_MSGS) / sizeof(DEATH_MSGS[0])) + +Death::Death() : timerCount(0), timerMsg(0), deathSequenceRunning(false) { + g_death = this; +} + +Death::~Death() { + g_death = nullptr; +} + +void Death::start(int delay) { + if (deathSequenceRunning) + return; + + // stop playing music + g_music->fadeOut(1000); + + deathSequenceRunning = 1; + timerCount = 0; + timerMsg = 0; + + WaitController waitCtrl(delay * settings._gameCyclesPerSecond); + eventHandler->pushController(&waitCtrl); + waitCtrl.wait(); + + gameSetViewMode(VIEW_DEAD); + + eventHandler->pushKeyHandler(&KeyHandler::ignoreKeys); + g_screen->screenDisableCursor(); + + eventHandler->getTimer()->add(&deathTimer, settings._gameCyclesPerSecond); +} + +void Death::deathTimer(void *data) { + g_death->timerCount++; + if ((g_death->timerMsg < N_MSGS) && (g_death->timerCount > DEATH_MSGS[g_death->timerMsg]._timeout)) { + + g_screen->screenMessage(DEATH_MSGS[g_death->timerMsg]._text, g_context->_party->member(0)->getName().c_str()); + g_screen->screenHideCursor(); + + g_death->timerCount = 0; + g_death->timerMsg++; + + if (g_death->timerMsg >= N_MSGS) { + eventHandler->getTimer()->remove(&deathTimer); + g_death->revive(); + } + } +} + +void Death::revive() { + while (!g_context->_location->_map->isWorldMap() && g_context->_location->_prev != nullptr) { + g_game->exitToParentMap(); + } + + eventHandler->setController(g_game); + + deathSequenceRunning = false; + gameSetViewMode(VIEW_NORMAL); + + // Move our world map location to Lord British's Castle + g_context->_location->_coords = g_context->_location->_map->_portals[0]->_coords; + + // Now, move the avatar into the castle and put him in front of Lord British + g_game->setMap(mapMgr->get(100), 1, nullptr); + g_context->_location->_coords.x = REVIVE_CASTLE_X; + g_context->_location->_coords.y = REVIVE_CASTLE_Y; + g_context->_location->_coords.z = 0; + + g_context->_aura->set(); + g_context->_horseSpeed = 0; + g_context->_lastCommandTime = g_system->getMillis(); + g_music->playMapMusic(); + + g_context->_party->reviveParty(); + + g_screen->screenEnableCursor(); + g_screen->screenShowCursor(); + g_context->_stats->setView(STATS_PARTY_OVERVIEW); + g_screen->update(); +} + +} // End of namespace Ultima4 +} // End of namespace Ultima diff --git a/pool/shard011/C++/0121692_glShader.cpp b/pool/shard011/C++/0121692_glShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0a9389845e69d71b533911bebaa02b68c6aadde --- /dev/null +++ b/pool/shard011/C++/0121692_glShader.cpp @@ -0,0 +1,129 @@ +#include "glShader.h" + +#include + +namespace Freya { + + void glShader::bind() + { + glUseProgram(this->ID); + } + + void glShader::unbind() + { + glUseProgram(0); + } + + bool glShader::compile(const char* vertexSource, const char* fragmentSource, const char* geometrySource) + { + GLuint sVertex, sFragment, gShader; + // Vertex Shader + sVertex = glCreateShader(GL_VERTEX_SHADER); + glShaderSource(sVertex, 1, &vertexSource, NULL); + glCompileShader(sVertex); + if (!checkCompileErrors(sVertex, "VERTEX")) + return false; + // Fragment Shader + sFragment = glCreateShader(GL_FRAGMENT_SHADER); + glShaderSource(sFragment, 1, &fragmentSource, NULL); + glCompileShader(sFragment); + if (!checkCompileErrors(sFragment, "FRAGMENT")) + return false; + // If geometry shader source code is given, also compile geometry shader + if (geometrySource != nullptr) + { + gShader = glCreateShader(GL_GEOMETRY_SHADER); + glShaderSource(gShader, 1, &geometrySource, NULL); + glCompileShader(gShader); + if (!checkCompileErrors(gShader, "GEOMETRY")) + return false; + } + // Shader Program + this->ID = glCreateProgram(); + glAttachShader(this->ID, sVertex); + glAttachShader(this->ID, sFragment); + if (geometrySource != nullptr) + glAttachShader(this->ID, gShader); + glLinkProgram(this->ID); + if (!checkCompileErrors(this->ID, "PROGRAM")) + return false; + // Delete the shaders as they're linked into our program now and no longer necessery + glDeleteShader(sVertex); + glDeleteShader(sFragment); + if (geometrySource != nullptr) + glDeleteShader(gShader); + + return true; + } + + void glShader::setFloat(const char *name, float value) + { + glUniform1f(glGetUniformLocation(this->ID, name), value); + } + void glShader::setInteger(const char *name, int value) + { + glUniform1i(glGetUniformLocation(this->ID, name), value); + } + void glShader::setVector2f(const char *name, float x, float y) + { + glUniform2f(glGetUniformLocation(this->ID, name), x, y); + } + void glShader::setVector2f(const char *name, const glm::vec2 &value) + { + glUniform2f(glGetUniformLocation(this->ID, name), value.x, value.y); + } + void glShader::setVector3f(const char *name, float x, float y, float z) + { + glUniform3f(glGetUniformLocation(this->ID, name), x, y, z); + } + void glShader::setVector3f(const char *name, const glm::vec3 &value) + { + glUniform3f(glGetUniformLocation(this->ID, name), value.x, value.y, value.z); + } + void glShader::setVector4f(const char *name, float x, float y, float z, float w) + { + glUniform4f(glGetUniformLocation(this->ID, name), x, y, z, w); + } + void glShader::setVector4f(const char *name, const glm::vec4 &value) + { + glUniform4f(glGetUniformLocation(this->ID, name), value.x, value.y, value.z, value.w); + } + void glShader::setMatrix4(const char *name, const glm::mat4 &matrix) + { + glUniformMatrix4fv(glGetUniformLocation(this->ID, name), 1, GL_FALSE, glm::value_ptr(matrix)); + } + + + bool glShader::checkCompileErrors(GLuint object, std::string type) + { + GLint success; + GLchar infoLog[1024]; + if (type != "PROGRAM") + { + glGetShaderiv(object, GL_COMPILE_STATUS, &success); + if (!success) + { + glGetShaderInfoLog(object, 1024, NULL, infoLog); + std::cout << "| ERROR::SHADER: Compile-time error: Type: " << type << "\n" + << infoLog << "\n -- --------------------------------------------------- -- " + << std::endl; + return false; + } + } + else + { + glGetProgramiv(object, GL_LINK_STATUS, &success); + if (!success) + { + glGetProgramInfoLog(object, 1024, NULL, infoLog); + std::cout << "| ERROR::Shader: Link-time error: Type: " << type << "\n" + << infoLog << "\n -- --------------------------------------------------- -- " + << std::endl; + return false; + } + } + + return true; + } + +} \ No newline at end of file diff --git a/pool/shard011/C++/0121693_CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64a.cpp b/pool/shard011/C++/0121693_CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d07cccdd7fa28fd1e39e92fb426f06e3b6afa63e --- /dev/null +++ b/pool/shard011/C++/0121693_CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64a.cpp @@ -0,0 +1,104 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64a.cpp +Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_array_delete.label.xml +Template File: sources-sinks-64a.tmpl.cpp +*/ +/* + * @description + * CWE: 762 Mismatched Memory Management Routines + * BadSource: Allocate data using new [] + * GoodSource: Allocate data using new + * Sinks: + * GoodSink: Deallocate data using delete [] + * BadSink : Deallocate data using delete + * Flow Variant: 64 Data flow: void pointer to data passed from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(void * dataVoidPtr); + +void bad() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ + data = new TwoIntsClass[100]; + badSink(&data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(void * dataVoidPtr); + +static void goodG2B() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + /* FIX: Allocate memory from the heap using new */ + data = new TwoIntsClass; + goodG2BSink(&data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void goodB2GSink(void * dataVoidPtr); + +static void goodB2G() +{ + TwoIntsClass * data; + /* Initialize data*/ + data = NULL; + /* POTENTIAL FLAW: Allocate memory with a function that requires delete [] to free the memory */ + data = new TwoIntsClass[100]; + goodB2GSink(&data); +} + +void good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +using namespace CWE762_Mismatched_Memory_Management_Routines__new_array_delete_class_64; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C++/0121695_cxx_abi.cpp b/pool/shard011/C++/0121695_cxx_abi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26217e89728a02150afe1d7371e62fb0e308bcad --- /dev/null +++ b/pool/shard011/C++/0121695_cxx_abi.cpp @@ -0,0 +1,213 @@ + +#include +#include +#include +#include +#include +#include +#include + +/** + * This header is for instantiating and implementing + * missing functionality gluing libc++ to the kernel + * + **/ + +extern "C" +{ + + int __isnan(double val) + { + return std::isnan(val); + } + + int __isnanf(float val) + { + return std::isnan(val); + } + + /// Linux standard base (locale) + size_t __mbrlen (const char*, size_t, mbstate_t*) + { + printf("WARNING: mbrlen was called - which we don't currently support - returning bogus value\n"); + return (size_t) 1; + } + + char _IO_getc() + { + /// NOTE: IMPLEMENT ME + printf("_IO_getc(): returning bogus character as input from stdin\n"); + return 'x'; + } + + struct source_location { + const char *file_name; + struct { + uint32_t line; + uint32_t column; + }; + }; + struct type_descriptor { + uint16_t type_kind; + uint16_t type_info; + char type_name[1]; + }; + const char* type_kind_string[] = { + "load of", "store to", "reference binding to", "member access within", + "member call on", "constructor call on", "downcast of", "downcast of" + }; + + struct out_of_bounds { + source_location src; + type_descriptor* array_type; + type_descriptor* index_type; + }; + struct overflow { + source_location src; + }; + struct mismatch { + source_location src; + type_descriptor& type; + unsigned char log_align; + unsigned char type_kind; + }; + struct function_type_mismatch { + const source_location src; + const type_descriptor& type; + }; + struct nonnull_return { + source_location src; + source_location attr; + }; + struct unreachable { + source_location src; + }; + using ub_error = std::runtime_error; + void print_src_location(const source_location& src) { + printf("ubsan: %s at line %u col %u\n", + src.file_name, src.line, src.column); + } + void undefined_throw(const char* error) { + kprintf("ubsan: %s", error); + os::print_backtrace(); + kprintf("\n"); + } + + /// Undefined-behavior sanitizer + void __ubsan_handle_out_of_bounds(struct out_of_bounds* data) + { + print_src_location(data->src); + undefined_throw("Out-of-bounds access"); + } + void __ubsan_handle_missing_return() + { + undefined_throw("Missing return"); + } + void __ubsan_handle_nonnull_return(struct nonnull_return* data) + { + print_src_location(data->src); + undefined_throw("Non-null return"); + } + + void __ubsan_handle_add_overflow() + { + undefined_throw("Overflow on addition"); + } + void __ubsan_handle_sub_overflow() + { + undefined_throw("Overflow on subtraction"); + } + void __ubsan_handle_mul_overflow() + { + undefined_throw("Overflow on multiplication"); + } + void __ubsan_handle_negate_overflow() + { + undefined_throw("Overflow on negation"); + } + void __ubsan_handle_pointer_overflow() + { + undefined_throw("Pointer overflow"); + } + void __ubsan_handle_divrem_overflow(struct overflow* data, + unsigned long lhs, + unsigned long rhs) + { + print_src_location(data->src); + printf("ubsan: LHS %lu / RHS %lu\n", lhs, rhs); + undefined_throw("Division remainder overflow"); + } + void __ubsan_handle_float_cast_overflow() + { + undefined_throw("Float-cast overflow"); + } + void __ubsan_handle_shift_out_of_bounds() + { + undefined_throw("Shift out-of-bounds"); + } + + void __ubsan_handle_type_mismatch_v1(struct mismatch* data, unsigned long ptr) + { + print_src_location(data->src); + char sbuf[1024]; + auto res = Elf::safe_resolve_symbol((void*) ptr, sbuf, sizeof(sbuf)); + + const char* reason = "Type mismatch"; + const long alignment = 1 << data->log_align; + + if (alignment && (ptr & (alignment-1)) != 0) { + reason = "Misaligned access"; + } + else if (ptr == 0) { + reason = "Null-pointer access"; + } + char buffer[2048]; + snprintf(buffer, sizeof(buffer), + "%s on ptr %p (aligned %lu)\n" + "ubsan: type name %s\n" + "ubsan: symbol %s", + reason, + (void*) ptr, + alignment, + data->type.type_name, + res.name); + undefined_throw(buffer); + } + void __ubsan_handle_function_type_mismatch( + struct function_type_mismatch* data, + unsigned long ptr) + { + print_src_location(data->src); + char sbuf[1024]; + auto res = Elf::safe_resolve_symbol((void*) ptr, sbuf, sizeof(sbuf)); + + char buffer[2048]; + snprintf(buffer, sizeof(buffer), + "Function type mismatch on ptr %p\n" + "ubsan: type name %s\n" + "ubsan: function %s", + (void*) ptr, + data->type.type_name, + res.name); + undefined_throw(buffer); + } + void __ubsan_handle_nonnull_arg() + { + undefined_throw("Non-null argument violated"); + } + + void __ubsan_handle_invalid_builtin() + { + undefined_throw("Invalid built-in function"); + } + void __ubsan_handle_load_invalid_value() + { + undefined_throw("Load of invalid value"); + } + [[noreturn]] + void __ubsan_handle_builtin_unreachable(struct unreachable* data) + { + print_src_location(data->src); + os::panic("Unreachable code reached"); + } +} diff --git a/pool/shard011/C++/0121696_abstractapi.cpp b/pool/shard011/C++/0121696_abstractapi.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9cb99f406b7ba9b758c047b630c7d3464b9a682f --- /dev/null +++ b/pool/shard011/C++/0121696_abstractapi.cpp @@ -0,0 +1,254 @@ +/* Copyright (c) 2012 Silk Project. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Silk nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL SILK BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "abstractapi.h" + +#include "qaccount.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +QNetworkAccessManager *AbstractApi::networkAccessManager = 0; + +class AbstractApi::Private +{ +public: + Private(AbstractApi *parent); + + void exec(QNetworkRequest request, QNetworkAccessManager::Operation operation, const QByteArray &data); + +private: + QByteArray toString(const QDateTime &dt) const; + QByteArray toString(QNetworkAccessManager::Operation operation) const; + QByteArray toString(const QUrl &url) const; + +private: + AbstractApi *q; + +public: + QAccount *account; + bool loading; + int progress; +}; + +AbstractApi::Private::Private(AbstractApi *parent) + : q(parent) + , account(0) + , loading(false) + , progress(0) +{ +} + +QByteArray AbstractApi::Private::toString(const QDateTime &dt) const +{ + QDateTime utc(dt); + utc.setTimeSpec(Qt::UTC); + int timezoneSeconds = dt.secsTo(utc); + QChar sign = (timezoneSeconds >=0 ? QLatin1Char('+') : QLatin1Char('-')); + if (timezoneSeconds < 0) + timezoneSeconds = -timezoneSeconds; + int timezoneMinutes = (timezoneSeconds % 3600) / 60; + int timezoneHours = (timezoneSeconds / 3600); + + QLocale locale(QStringLiteral("C")); + return QStringLiteral("%1 %2%3").arg(locale.toString(dt, QStringLiteral("ddd, dd MMM yyyy hh:mm:ss"))).arg(sign).arg(timezoneHours * 100 + timezoneMinutes, 4, 10, QLatin1Char('0')).toLatin1(); +} + +QByteArray AbstractApi::Private::toString(QNetworkAccessManager::Operation operation) const +{ + static QMap map; + if (map.isEmpty()) { + map.insert(QNetworkAccessManager::HeadOperation, "HEAD"); + map.insert(QNetworkAccessManager::GetOperation, "GET"); + map.insert(QNetworkAccessManager::PostOperation, "POST"); + map.insert(QNetworkAccessManager::PutOperation, "PUT"); + map.insert(QNetworkAccessManager::DeleteOperation, "DELETE"); + } + return map.value(operation); +} + +QByteArray AbstractApi::Private::toString(const QUrl &url) const +{ + QByteArray ret; + QRegularExpression bucket(QStringLiteral("^([a-z0-9\\-]+)\\.s3[a-z0-9\\-]*\\.amazonaws\\.com$")); + QRegularExpressionMatch match = bucket.match(url.host()); + if (match.hasMatch()) { + ret.append("/"); + ret.append(match.captured(1).toUtf8()); + } + ret.append(url.path().toUtf8()); + QString query = url.query(); + if (query.indexOf('&') < query.indexOf('=')) { + ret.append(QStringLiteral("?%1").arg(query.left(query.indexOf(QStringLiteral("&")))).toUtf8()); + } + return ret; +} + +void AbstractApi::Private::exec(QNetworkRequest request, QNetworkAccessManager::Operation operation, const QByteArray &data) +{ + if (!account) { + qWarning() << "account is not set."; + return; + } + q->setLoading(true); + QNetworkReply *reply = 0; + + QByteArray httpVerb = toString(operation); + QByteArray contentMd5; + if (!data.isEmpty()) + contentMd5 = QCryptographicHash::hash(data, QCryptographicHash::Md5).toHex(); +// qDebug() << Q_FUNC_INFO << __LINE__ << contentMd5; + QByteArray contentType = request.header(QNetworkRequest::ContentTypeHeader).toByteArray(); +// qDebug() << Q_FUNC_INFO << __LINE__ << contentType; + QByteArray date = toString(QDateTime::currentDateTime()); +// qDebug() << Q_FUNC_INFO << __LINE__ << date; +// QMap xamzHeaders; +// foreach (const QString &key, qSort(xamzHeaders.keys())) { + +// } + QByteArray canonicalizedAmzHeaders; + QByteArray canonicalizedResource = toString(request.url()); +// qDebug() << Q_FUNC_INFO << __LINE__ << canonicalizedResource; + + QByteArray stringToSign = httpVerb + "\n" + + contentMd5 + "\n" + + contentType + "\n" + + date + "\n" + + canonicalizedAmzHeaders + + canonicalizedResource; +// qDebug() << q; +// qDebug() << Q_FUNC_INFO << __LINE__ << account->awsSecretAccessKey() << stringToSign; + QByteArray signature = QMessageAuthenticationCode::hash(stringToSign, account->awsSecretAccessKey(), QCryptographicHash::Sha1); + signature = signature.toBase64(); + QByteArray authorization("AWS "); + authorization.append(account->awsAccessKeyId()); + authorization.append(":"); + authorization.append(signature); + + request.setRawHeader("Date", date); + request.setRawHeader("Authorization", authorization); + + if (!networkAccessManager) + setNetworkAccessManager(new QNetworkAccessManager); + + switch (operation) { + case QNetworkAccessManager::HeadOperation: + reply = networkAccessManager->head(request); + break; + case QNetworkAccessManager::GetOperation: + reply = networkAccessManager->get(request); + break; + case QNetworkAccessManager::PostOperation: + reply = networkAccessManager->post(request, ""); + break; + case QNetworkAccessManager::PutOperation: + reply = networkAccessManager->put(request, ""); + break; + case QNetworkAccessManager::DeleteOperation: + reply = networkAccessManager->deleteResource(request); + break; + default: + break; + } + + q->setProgress(0); + + connect(reply, &QNetworkReply::finished, [this, reply]() { + q->done(reply); + reply->deleteLater(); + q->setLoading(false); + }); + connect(reply, static_cast(&QNetworkReply::error), [this, reply](QNetworkReply::NetworkError error) { + qDebug() << Q_FUNC_INFO << __LINE__ << error << reply->errorString(); + }); + connect(reply, &QNetworkReply::downloadProgress, [this](qint64 bytesReceived, qint64 bytesTotal) { + if (bytesTotal > 0) + q->setProgress(bytesReceived * 100 / bytesTotal); + }); +} + +AbstractApi::AbstractApi(QObject *parent) + : QObject(parent) + , d(new Private(this)) +{ + connect(this, &AbstractApi::destroyed, [d]() { delete d; }); +} + +QAccount *AbstractApi::account() const +{ + return d->account; +} + +void AbstractApi::setAccount(QAccount *account) +{ + if (d->account == account) return; + d->account = account; + emit accountChanged(account); +} + +bool AbstractApi::loading() const +{ + return d->loading; +} + +void AbstractApi::setLoading(bool loading) +{ + if (d->loading == loading) return; + d->loading = loading; + emit loadingChanged(loading); +} + +int AbstractApi::progress() const +{ + return d->progress; +} + +void AbstractApi::setProgress(int progress) +{ + if (d->progress == progress) return; + d->progress = progress; + emit progressChanged(progress); +} + +void AbstractApi::setNetworkAccessManager(QNetworkAccessManager *nam) +{ + if (networkAccessManager && !networkAccessManager->parent()) + networkAccessManager->deleteLater(); + networkAccessManager = nam; +} + +void AbstractApi::exec(QNetworkRequest request, QNetworkAccessManager::Operation operation, const QByteArray &data) +{ + d->exec(request, operation, data); +} diff --git a/pool/shard011/C++/0121697_BatchGetDeploymentTargetsRequest.cpp b/pool/shard011/C++/0121697_BatchGetDeploymentTargetsRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c0ee8951d77444c7b3d3a549f1700495befa64c --- /dev/null +++ b/pool/shard011/C++/0121697_BatchGetDeploymentTargetsRequest.cpp @@ -0,0 +1,65 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include + +#include + +using namespace Aws::CodeDeploy::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +BatchGetDeploymentTargetsRequest::BatchGetDeploymentTargetsRequest() : + m_deploymentIdHasBeenSet(false), + m_targetIdsHasBeenSet(false) +{ +} + +Aws::String BatchGetDeploymentTargetsRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_deploymentIdHasBeenSet) + { + payload.WithString("deploymentId", m_deploymentId); + + } + + if(m_targetIdsHasBeenSet) + { + Array targetIdsJsonList(m_targetIds.size()); + for(unsigned targetIdsIndex = 0; targetIdsIndex < targetIdsJsonList.GetLength(); ++targetIdsIndex) + { + targetIdsJsonList[targetIdsIndex].AsString(m_targetIds[targetIdsIndex]); + } + payload.WithArray("targetIds", std::move(targetIdsJsonList)); + + } + + return payload.View().WriteReadable(); +} + +Aws::Http::HeaderValueCollection BatchGetDeploymentTargetsRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodeDeploy_20141006.BatchGetDeploymentTargets")); + return headers; + +} + + + + diff --git a/pool/shard011/C++/0121698_function_declaration_expression_builder.cpp b/pool/shard011/C++/0121698_function_declaration_expression_builder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..679c6b304f34339aac97545a32e42d0e6e8c95b3 --- /dev/null +++ b/pool/shard011/C++/0121698_function_declaration_expression_builder.cpp @@ -0,0 +1,82 @@ +#include "function_declaration_expression_builder.h" + +#include "../vm_expression_visitor.h" + +namespace elsa { + namespace compiler { + + void FunctionDeclarationExpressionBuilder::build(VMProgram* program, VMExpressionVisitor* visitor, FuncDeclarationExpression* expression) + { + build_internal(program, visitor, expression); + } + + const FunctionInfo* FunctionDeclarationExpressionBuilder::build_member(VMProgram* program, VMExpressionVisitor* visitor, FuncDeclarationExpression* expression) + { + return build_internal(program, visitor, expression); + } + + const FunctionInfo* FunctionDeclarationExpressionBuilder::build_internal(VMProgram* program, VMExpressionVisitor* visitor, FuncDeclarationExpression* expression) + { + if (expression->built()) + { + auto function_info = program->get_func(expression->get_name()); + + if (expression->anonymous()) + { + program->emit(OpCode::null); + program->emit(OpCode::fnconst); + program->emit(static_cast(function_info->get_addr())); + } + + return function_info; + } + + for (auto nested_function_expression : expression->get_nested_functions()) + { + build_internal(program, visitor, nested_function_expression); + } + + auto fi = std::make_unique(expression->get_name()); + fi->set_num_args(expression->get_num_args()); + auto is_main = expression->get_name() == L"main"; + + if (is_main) + { + if (program->get_entry_point() != -1) + throw CodeGenException("An entry point has alredy been defined"); + + program->set_entry_point(static_cast(program->get_next_instruction_index())); + } + + fi->set_addr(static_cast(program->get_next_instruction_index())); + + visitor->push_new_scope(expression); + + for (auto& exp : expression->get_body()) + { + exp->accept(visitor); + } + + if (is_main) + { + program->emit(OpCode::halt); + } + else + { + program->emit(OpCode::ret); + } + + fi->set_num_locals(expression->get_num_locals()); + + auto fi_ptr = fi.get(); + + program->add_func(std::move(fi)); + + visitor->pop_current_scope(); + expression->set_built(true); + + return fi_ptr; + } + + } +} diff --git a/pool/shard011/C++/0121699_ODComputeSummaryTask.cpp b/pool/shard011/C++/0121699_ODComputeSummaryTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8d967d65e6deb8a84d9656ff933e5c9c90924276 --- /dev/null +++ b/pool/shard011/C++/0121699_ODComputeSummaryTask.cpp @@ -0,0 +1,284 @@ +/********************************************************************** + + Audacity: A Digital Audio Editor + + ODComputeSummaryTask.cpp + + Created by Michael Chinen (mchinen) on 6/8/08. + Audacity(R) is copyright (c) 1999-2008 Audacity Team. + License: GPL v2. See License.txt. + +******************************************************************//** + +\class ODComputeSummaryTask +\brief Computes the summary data for a PCM (WAV) file and writes it to disk, +updating the ODPCMAliasBlockFile and the GUI of the newly available data. + +*//*******************************************************************/ + + + +#include "ODComputeSummaryTask.h" +#include "../blockfile/ODPCMAliasBlockFile.h" +#include + +//36 blockfiles > 3 minutes stereo 44.1kHz per ODTask::DoSome +#define kNumBlockFilesPerDoSome 36 + +///Creates a new task that computes summaries for a wavetrack that needs to be specified through SetWaveTrack() +ODComputeSummaryTask::ODComputeSummaryTask() +{ + mMaxBlockFiles = 0; + mComputedBlockFiles = 0; + mHasUpdateRan=false; +} + +ODTask* ODComputeSummaryTask::Clone() +{ + ODComputeSummaryTask* clone = new ODComputeSummaryTask; + clone->mDemandSample=GetDemandSample(); + return clone; +} + + +///releases memory that the ODTask owns. Subclasses should override. +void ODComputeSummaryTask::Terminate() +{ + //The terminate block won't allow DoSomeInternal and this method to be run async, so this is thread-safe. + //Deref the block files since they are ref'ed when put into the array. + mBlockFilesMutex.Lock(); + for(unsigned int i=0;iDeref(); + mBlockFiles.clear(); + mBlockFilesMutex.Unlock(); +} + +///Computes and writes the data for one BlockFile if it still has a refcount. +void ODComputeSummaryTask::DoSomeInternal() +{ + if(mBlockFiles.size()<=0) + { + mPercentCompleteMutex.Lock(); + mPercentComplete = 1.0; + mPercentCompleteMutex.Unlock(); + return; + } + + ODPCMAliasBlockFile* bf; + sampleCount blockStartSample = 0; + sampleCount blockEndSample = 0; + bool success =false; + + mBlockFilesMutex.Lock(); + for(size_t i=0; i < mWaveTracks.size() && mBlockFiles.size();i++) + { + bf = mBlockFiles[0]; + + //first check to see if the ref count is at least 2. It should have one + //from when we added it to this instance's mBlockFiles array, and one from + //the Wavetrack/sequence. If it doesn't it has been deleted and we should forget it. + if(bf->RefCount()>=2) + { + bf->DoWriteSummary(); + success = true; + blockStartSample = bf->GetStart(); + blockEndSample = blockStartSample + bf->GetLength(); + mComputedBlockFiles++; + } + else + { + //the waveform in the wavetrack now is shorter, so we need to update mMaxBlockFiles + //because now there is less work to do. + mMaxBlockFiles--; + } + + //Release the refcount we placed on it. + bf->Deref(); + //take it out of the array - we are done with it. + mBlockFiles.erase(mBlockFiles.begin()); + + //This is a bit of a convenience in case someone tries to terminate the task by closing the trackpanel or window. + //ODComputeSummaryTask::Terminate() uses this lock to remove everything, and we don't want it to wait since the UI is being blocked. + mBlockFilesMutex.Unlock(); + wxThread::This()->Yield(); + mBlockFilesMutex.Lock(); + + //upddate the gui for all associated blocks. It doesn't matter that we're hitting more wavetracks then we should + //because this loop runs a number of times equal to the number of tracks, they probably are getting processed in + //the next iteration at the same sample window. + mWaveTrackMutex.Lock(); + for(size_t i=0;iAddInvalidRegion(blockStartSample,blockEndSample); + } + mWaveTrackMutex.Unlock(); + } + + mBlockFilesMutex.Unlock(); + + //update percentage complete. + CalculatePercentComplete(); +} + +///compute the next time we should take a break in terms of overall percentage. +///We want to do a constant number of blockfiles. +float ODComputeSummaryTask::ComputeNextWorkUntilPercentageComplete() +{ + if(mMaxBlockFiles==0) + return 1.0; + + float nextPercent; + mPercentCompleteMutex.Lock(); + nextPercent=mPercentComplete + ((float)kNumBlockFilesPerDoSome/(mMaxBlockFiles+1)); + mPercentCompleteMutex.Unlock(); + + return nextPercent; +} + +void ODComputeSummaryTask::MarkUpdateRan() +{ + mHasUpdateRanMutex.Lock(); + mHasUpdateRan=true; + mHasUpdateRanMutex.Unlock(); +} + +bool ODComputeSummaryTask::HasUpdateRan() +{ + bool ret; + mHasUpdateRanMutex.Lock(); + ret = mHasUpdateRan; + mHasUpdateRanMutex.Unlock(); + return ret; +} + +void ODComputeSummaryTask::CalculatePercentComplete() +{ + bool hasUpdateRan; + hasUpdateRan = HasUpdateRan(); + mPercentCompleteMutex.Lock(); + if(hasUpdateRan) + mPercentComplete = (float) 1.0 - ((float)mBlockFiles.size() / (mMaxBlockFiles+1)); + else + mPercentComplete =0.0; + mPercentCompleteMutex.Unlock(); +} + +///creates the order of the wavetrack to load. +///by default left to right, or frome the point the user has clicked. +void ODComputeSummaryTask::Update() +{ + std::vector tempBlocks; + + mWaveTrackMutex.Lock(); + + for(size_t j=0;jGetClipIterator(); + + while(node) { + clip = node->GetData(); + seq = clip->GetSequence(); + //This lock may be way too big since the whole file is one sequence. + //TODO: test for large files and find a way to break it down. + seq->LockDeleteUpdateMutex(); + + //See Sequence::Delete() for why need this for now.. + //We don't need the mBlockFilesMutex here because it is only for the vector list. + //These are existing blocks, and its wavetrack or blockfiles won't be deleted because + //of the respective mWaveTrackMutex lock and LockDeleteUpdateMutex() call. + blocks = clip->GetSequenceBlockArray(); + int i; + int insertCursor; + + insertCursor =0;//OD TODO:see if this works, removed from inner loop (bfore was n*n) + + for(i=0; i<(int)blocks->GetCount(); i++) + { + //if there is data but no summary, this blockfile needs summarizing. + if(blocks->Item(i)->f->IsDataAvailable() && !blocks->Item(i)->f->IsSummaryAvailable()) + { + blocks->Item(i)->f->Ref(); + ((ODPCMAliasBlockFile*)blocks->Item(i)->f)->SetStart(blocks->Item(i)->start); + ((ODPCMAliasBlockFile*)blocks->Item(i)->f)->SetClipOffset((sampleCount)(clip->GetStartTime()*clip->GetRate())); + + //these will always be linear within a sequence-lets take advantage of this by keeping a cursor. + while(insertCursor<(int)tempBlocks.size()&& + (sampleCount)(tempBlocks[insertCursor]->GetStart()+tempBlocks[insertCursor]->GetClipOffset()) < + (sampleCount)(((ODPCMAliasBlockFile*)blocks->Item(i)->f)->GetStart()+((ODPCMAliasBlockFile*)blocks->Item(i)->f)->GetClipOffset())) + insertCursor++; + + tempBlocks.insert(tempBlocks.begin()+insertCursor++,(ODPCMAliasBlockFile*)blocks->Item(i)->f); + } + } + seq->UnlockDeleteUpdateMutex(); + node = node->GetNext(); + } + } + } + mWaveTrackMutex.Unlock(); + + //get the new order. + mBlockFilesMutex.Lock(); + OrderBlockFiles(tempBlocks); + mBlockFilesMutex.Unlock(); + + MarkUpdateRan(); +} + + + +///Computes the summary calculation queue order of the blockfiles +void ODComputeSummaryTask::OrderBlockFiles(std::vector &unorderedBlocks) +{ + //we are going to take things out of the array. But first deref them since we ref them when we put them in. + for(unsigned int i=0;iDeref(); + mBlockFiles.clear(); + //Order the blockfiles into our queue in a fancy convenient way. (this could be user-prefs) + //for now just put them in linear. We start the order from the first block that includes the ondemand sample + //(which the user sets by clicking.) + //Note that this code assumes that the array is sorted in time. + + //find the startpoint + sampleCount processStartSample = GetDemandSample(); + for(int i= ((int)unorderedBlocks.size())-1;i>= 0;i--) + { + //check to see if the refcount is at least two before we add it to the list. + //There should be one Ref() from the one added by this ODTask, and one from the track. + //If there isn't, then the block was deleted for some reason and we should ignore it. + if(unorderedBlocks[i]->RefCount()>=2) + { + //test if the blockfiles are near the task cursor. we use the last mBlockFiles[0] as our point of reference + //and add ones that are closer. + if(mBlockFiles.size() && + unorderedBlocks[i]->GetGlobalEnd() >= processStartSample && + ( mBlockFiles[0]->GetGlobalEnd() < processStartSample || + unorderedBlocks[i]->GetGlobalStart() <= mBlockFiles[0]->GetGlobalStart()) + ) + { + //insert at the front of the list if we get blockfiles that are after the demand sample + mBlockFiles.insert(mBlockFiles.begin()+0,unorderedBlocks[i]); + } + else + { + //otherwise no priority + mBlockFiles.push_back(unorderedBlocks[i]); + } + if(mMaxBlockFiles< (int) mBlockFiles.size()) + mMaxBlockFiles = mBlockFiles.size(); + } + else + { + //Otherwise, let it be deleted and forget about it. + unorderedBlocks[i]->Deref(); + } + } +} diff --git a/pool/shard011/C++/0121701_AddBinary.cpp b/pool/shard011/C++/0121701_AddBinary.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6603c5f33177ce73012e73a00012b5ff46a827a4 --- /dev/null +++ b/pool/shard011/C++/0121701_AddBinary.cpp @@ -0,0 +1,41 @@ +/* + * Filename: AddBinary.cpp + * Author: fishpj + * Date: 09/03/2014 + */ + +#include "leetCode.h" +#include +using std::string; + +class Solution +{ + public: + string addBinary(string a, string b) + { + string::size_type sa = a.size(); + string::size_type sb = b.size(); + string result = sa > sb ? a:b; + int overFlow = 0; + + for (string::size_type i = 0; i != result.size(); ++i) + { + char ca = i < sa ? a[sa-i-1] : '0'; + char cb = i < sb ? b[sb-i-1] : '0'; + int bit = (ca-'0') + (cb-'0') + overFlow; + overFlow = bit/2; + result[result.size()-i-1] = bit%2 + '0'; + } + if (overFlow) + result = '1' + result; + return result; + } +}; + +int main(int argc, char *argv[]) +{ + string a = "1010"; + string b = "1111"; + Solution so; + std::cout << so.addBinary(a, b) << std::endl; +} diff --git a/pool/shard011/C++/0121703_InflatingIStream.cpp b/pool/shard011/C++/0121703_InflatingIStream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b190e0d68278e684be16a6aa3d3c0f90b762ff7 --- /dev/null +++ b/pool/shard011/C++/0121703_InflatingIStream.cpp @@ -0,0 +1,135 @@ +/// inflatingistream +// An istream filter for inflating data. +// @module inflatingistream +#include "InflatingIStream.h" +#include +#include + +int luaopen_poco_inflatingistream(lua_State* L) +{ + LuaPoco::InflatingIStreamUserdata::registerInflatingIStream(L); + return LuaPoco::loadConstructor(L, LuaPoco::InflatingIStreamUserdata::InflatingIStream); +} + +namespace LuaPoco +{ + +const char* POCO_INFLATINGISTREAM_METATABLE_NAME = "Poco.InflatingIStream.metatable"; + +InflatingIStreamUserdata::InflatingIStreamUserdata(std::istream& istream + , Poco::InflatingStreamBuf::StreamType type + , int ref) + : mInflatingInputStream(istream, type) + , mUdReference(ref) +{ +} + +InflatingIStreamUserdata::InflatingIStreamUserdata(std::istream& istream + , int windowBits + , int ref) + : mInflatingInputStream(istream, windowBits) + , mUdReference(ref) +{ +} + +InflatingIStreamUserdata::~InflatingIStreamUserdata() +{ +} + +std::istream& InflatingIStreamUserdata::istream() +{ + return mInflatingInputStream; +} + +// register metatable for this class +bool InflatingIStreamUserdata::registerInflatingIStream(lua_State* L) +{ + struct CFunctions methods[] = + { + { "__gc", metamethod__gc }, + { "__tostring", metamethod__tostring }, + { "read", read }, + { "lines", lines }, + { "seek", seek }, + { "reset", reset}, + { NULL, NULL} + }; + + setupUserdataMetatable(L, POCO_INFLATINGISTREAM_METATABLE_NAME, methods); + return true; +} + +/// Constructs a new inflatingistream userdata. +// inflatingistream holds a reference to another istream userdata to prevent the userdata from +// being garbage collected while the inflatingistream is still trying to use it. +// @param istream userdata. +// @param val a number for windowBits or a string for algorithm type. +// +// "STREAM_ZLIB", "STREAM_GZIP", "STREAM_ZIP" (same as STREAM_ZLIB but no checksum is performed.) +// @return userdata or nil. (error) +// @return error message. +// @function new +// @see istream +int InflatingIStreamUserdata::InflatingIStream(lua_State* L) +{ + int rv = 0; + int firstArg = lua_istable(L, 1) ? 2 : 1; + IStream* is = checkPrivateUserdata(L, firstArg); + + lua_pushvalue(L, firstArg); + int ref = luaL_ref(L, LUA_REGISTRYINDEX); + + InflatingIStreamUserdata* iisud = NULL; + if (lua_isnumber(L, firstArg + 1)) + { + int num = static_cast(luaL_checkinteger(L, firstArg + 1)); + iisud = new(lua_newuserdata(L, sizeof *iisud)) InflatingIStreamUserdata(is->istream(), num, ref); + } + else + { + Poco::InflatingStreamBuf::StreamType type = Poco::InflatingStreamBuf::STREAM_ZLIB; + const char* mode = luaL_checkstring(L, firstArg + 1); + + if (std::strcmp(mode, "STREAM_ZLIB") == 0) type = Poco::InflatingStreamBuf::STREAM_ZLIB; + else if (std::strcmp(mode, "STREAM_GZIP") == 0) type = Poco::InflatingStreamBuf::STREAM_GZIP; + else if (std::strcmp(mode, "STREAM_GZIP") == 0) type = Poco::InflatingStreamBuf::STREAM_ZIP; + + iisud = new(lua_newuserdata(L, sizeof *iisud)) InflatingIStreamUserdata(is->istream(), type, ref); + } + setupPocoUserdata(L, iisud, POCO_INFLATINGISTREAM_METATABLE_NAME); + + return 1; +} + +int InflatingIStreamUserdata::metamethod__gc(lua_State* L) +{ + InflatingIStreamUserdata* iisud = checkPrivateUserdata(L, 1); + + luaL_unref(L, LUA_REGISTRYINDEX, iisud->mUdReference); + iisud->~InflatingIStreamUserdata(); + + return 0; +} + +// metamethod infrastructure +int InflatingIStreamUserdata::metamethod__tostring(lua_State* L) +{ + InflatingIStreamUserdata* iisud = checkPrivateUserdata(L, 1); + lua_pushfstring(L, "Poco.InflatingIStream (%p)", static_cast(iisud)); + + return 1; +} + +// methods + +/// Resets the zlib machinery so that another zlib stream can be read from the same underlying input stream. +// @function reset +int InflatingIStreamUserdata::reset(lua_State* L) +{ + InflatingIStreamUserdata* iisud = checkPrivateUserdata(L, 1); + iisud->mInflatingInputStream.reset(); + + return 0; +} + +} // LuaPoco diff --git a/pool/shard011/C++/0121705_imageinfo.cpp b/pool/shard011/C++/0121705_imageinfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..62020d80638f0d4cf6ce5e55dd781677f96d28a7 --- /dev/null +++ b/pool/shard011/C++/0121705_imageinfo.cpp @@ -0,0 +1,54 @@ +#include "imageinfo.h" +#include "ui_imageinfo.h" +#include +#include "csbigimg.h" +#include "csbigcam.h" +#include "iostream" +//Prova + +imageInfo::imageInfo(QWidget *parent) : + QWidget(parent), + ui(new Ui::imageInfo) +{ + ui->setupUi(this); + this->setFixedSize(400,320); +} + +imageInfo::~imageInfo() +{ + delete ui; +} + +void imageInfo::loadHeader(){ + struct tm tym; + + QString *Head = new QString(pSbigImage->GetCameraModel().c_str()); + QString wpix, hpix, timeEXp, filter, year, mounth, day; + wpix.setNum(double(pSbigImage->GetWidth()), '%f',0); + hpix.setNum(double(pSbigImage->GetHeight()), '%f',0); + filter = pSbigImage->GetFilter().c_str(); + + //Questa cosa non fa quello che dovrebbe. + /*tym= pSbigImage->GetImageStartTime(); + year.setNum(double(tym.tm_year+1900), 'f', 0); + mounth.setNum(double(tym.tm_mon+1), 'f',0); + day.setNum(double(tym.tm_mday), 'f', 0); + */ + timeEXp.setNum(double(pSbigImage->GetExposureTime()), 'f', 3); + *Head += "
Dimensione in Pixel: " + wpix.toAscii() + "x" + hpix.toAscii(); + *Head += "
Tempo di esposizione: "+ timeEXp.toAscii() + " sec."; + *Head += "
Filtro: " + filter.toAscii(); + + //*Head += "\nData inizio posa: " + day.toAscii() + "/" + mounth.toAscii() + "/" + year.toAscii(); + + ui->textEdit->setHtml(Head->toAscii()); + //ui->label->setText(Head->toAscii()); + + +} + + +void imageInfo::setImage(CSBIGImg *image){ + pSbigImage = image; + loadHeader(); +} diff --git a/pool/shard011/C++/0121707_funccasts.cpp b/pool/shard011/C++/0121707_funccasts.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6552b018c5b66d8517c95a3f602aafd1475d164f --- /dev/null +++ b/pool/shard011/C++/0121707_funccasts.cpp @@ -0,0 +1,25 @@ +//===---------------------------------------------------------------------===// +// Copyright 2019 Leaning Technlogies +//===----------------------------------------------------------------------===// + +#include + +#include +#include + +int foo(int a, int b, int c, int d) +{ + return a+b+c+d; +} +int bar(int a, int b, int c, int d, int e) +{ + return a+b+c+d+e; +} + +typedef int (*fptr)(int, int, int, int, int); +void webMain() +{ + fptr f = unitBlackBox(1) ? (fptr)foo : bar; + int r = f(1,2,3,4,5); + assertEqual(r, 10, "FixFunctionCasts 1/1"); +} diff --git a/pool/shard011/C++/0121708_bgp_show_ribout_statistics.cc b/pool/shard011/C++/0121708_bgp_show_ribout_statistics.cc new file mode 100644 index 0000000000000000000000000000000000000000..7933af1ffe636eab885a181974d2abc7269be507 --- /dev/null +++ b/pool/shard011/C++/0121708_bgp_show_ribout_statistics.cc @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2016 Juniper Networks, Inc. All rights reserved. + */ + +#include "bgp/bgp_show_handler.h" + +#include "bgp/bgp_peer_internal_types.h" +#include "bgp/bgp_server.h" +#include "bgp/bgp_table.h" +#include "bgp/routing-instance/routing_instance.h" + +using std::string; +using std::vector; + +// +// Specialization of BgpShowHandler<>::CallbackCommon. +// +// Note that we check the page and iteration limits only after examining all +// ribouts in all tables for a given routing instance. This simplifies things +// and requires to only keep track of the next instance rather than the next +// instance and next table. +// +template <> +bool BgpShowHandler::CallbackCommon( + const BgpSandeshContext *bsc, Data *data) { + uint32_t page_limit = bsc->page_limit() ? bsc->page_limit() : kPageLimit; + uint32_t iter_limit = bsc->iter_limit() ? bsc->iter_limit() : kIterLimit; + RoutingInstanceMgr *rim = bsc->bgp_server->routing_instance_mgr(); + + RoutingInstanceMgr::const_name_iterator it1 = + rim->name_clower_bound(data->next_entry); + for (uint32_t iter_count = 0; it1 != rim->name_cend(); ++it1) { + const RoutingInstance *rtinstance = it1->second; + for (RoutingInstance::RouteTableList::const_iterator it2 = + rtinstance->GetTables().begin(); + it2 != rtinstance->GetTables().end(); ++it2, ++iter_count) { + const BgpTable *table = it2->second; + if (!data->search_string.empty() && + (table->name().find(data->search_string) == string::npos)) { + continue; + } + table->FillRibOutStatisticsInfo(&data->show_list); + } + if (data->show_list.size() >= page_limit) + break; + if (iter_count >= iter_limit) + break; + } + + // All done if we've looked at all instances. + if (it1 == rim->name_cend() || ++it1 == rim->name_end()) + return true; + + // Return true if we've reached the page limit, false if we've reached the + // iteration limit. + bool done = data->show_list.size() >= page_limit; + SaveContextToData(it1->second->name(), done, data); + return done; +} + +// +// Specialization of BgpShowHandler<>::FillShowList. +// +template <> +void BgpShowHandler::FillShowList( + ShowRibOutStatisticsResp *resp, + const vector &show_list) { + resp->set_ribouts(show_list); +} + +// +// Handler for ShowRibOutStatisticsReq. +// +void ShowRibOutStatisticsReq::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + ShowRibOutStatisticsReq, + ShowRibOutStatisticsReqIterate, + ShowRibOutStatisticsResp, + ShowRibOutStatistics>::Callback, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + ShowRibOutStatisticsReq, + ShowRibOutStatisticsReqIterate, + ShowRibOutStatisticsResp, + ShowRibOutStatistics>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} + +// +// Handler for ShowRibOutStatisticsReqIterate. +// +void ShowRibOutStatisticsReqIterate::HandleRequest() const { + RequestPipeline::PipeSpec ps(this); + RequestPipeline::StageSpec s1; + TaskScheduler *scheduler = TaskScheduler::GetInstance(); + + s1.taskId_ = scheduler->GetTaskId("bgp::ShowCommand"); + s1.cbFn_ = boost::bind(&BgpShowHandler< + ShowRibOutStatisticsReq, + ShowRibOutStatisticsReqIterate, + ShowRibOutStatisticsResp, + ShowRibOutStatistics>::CallbackIterate, _1, _2, _3, _4, _5); + s1.allocFn_ = BgpShowHandler< + ShowRibOutStatisticsReq, + ShowRibOutStatisticsReqIterate, + ShowRibOutStatisticsResp, + ShowRibOutStatistics>::CreateData; + s1.instances_.push_back(0); + ps.stages_.push_back(s1); + RequestPipeline rp(ps); +} diff --git a/pool/shard011/C++/0121710_complex_vector_equality_6.cc b/pool/shard011/C++/0121710_complex_vector_equality_6.cc new file mode 100644 index 0000000000000000000000000000000000000000..aeb836c92aaaada856c67fd7f31aedca1bd08969 --- /dev/null +++ b/pool/shard011/C++/0121710_complex_vector_equality_6.cc @@ -0,0 +1,82 @@ +// --------------------------------------------------------------------- +// +// Copyright (C) 2004 - 2016 by the deal.II authors +// +// This file is part of the deal.II library. +// +// The deal.II library is free software; you can use it, redistribute +// it, and/or modify it under the terms of the GNU Lesser General +// Public License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full text of the license can be found in the file LICENSE at +// the top level of the deal.II distribution. +// +// --------------------------------------------------------------------- + + + +// check Vector >::operator==(Vector >) for vectors that are +// equal and different template arguments + +#include "../tests.h" +#include +#include + + +void test (Vector > &v, + Vector > &w) +{ + // set only certain elements of each + // vector + for (unsigned int i=0; i (i, i+1.); + if (i%3 == 0) + w(i) = std::complex (i+1., i+2.); + } + // but then copy elements and make sure the + // vectors are actually equal + v = w; + AssertThrow (v==w, ExcInternalError()); + AssertThrow (w==v, ExcInternalError()); + + deallog << "OK" << std::endl; +} + + + +int main () +{ + initlog(); + + try + { + Vector > v (100); + Vector > w (100); + test (v,w); + } + catch (std::exception &exc) + { + deallog << std::endl << std::endl + << "----------------------------------------------------" + << std::endl; + deallog << "Exception on processing: " << std::endl + << exc.what() << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + + return 1; + } + catch (...) + { + deallog << std::endl << std::endl + << "----------------------------------------------------" + << std::endl; + deallog << "Unknown exception!" << std::endl + << "Aborting!" << std::endl + << "----------------------------------------------------" + << std::endl; + return 1; + }; +} diff --git a/pool/shard011/C++/0121711_consolidated_consent_screen_handler.cc b/pool/shard011/C++/0121711_consolidated_consent_screen_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..468244fe060f5546da78c0ae3145513ed2e99cbc --- /dev/null +++ b/pool/shard011/C++/0121711_consolidated_consent_screen_handler.cc @@ -0,0 +1,188 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/login/consolidated_consent_screen_handler.h" + +#include "ash/constants/ash_switches.h" +#include "base/command_line.h" +#include "chrome/browser/ash/login/oobe_screen.h" +#include "chrome/browser/ash/login/screens/consolidated_consent_screen.h" +#include "chrome/grit/chromium_strings.h" +#include "chrome/grit/generated_resources.h" +#include "components/login/localized_values_builder.h" + +namespace chromeos { + +ConsolidatedConsentScreenView::ScreenConfig::ScreenConfig() = default; + +ConsolidatedConsentScreenView::ScreenConfig::~ScreenConfig() = default; + +constexpr StaticOobeScreenId ConsolidatedConsentScreenView::kScreenId; + +ConsolidatedConsentScreenHandler::ConsolidatedConsentScreenHandler( + JSCallsContainer* js_calls_container) + : BaseScreenHandler(kScreenId, js_calls_container) { + set_user_acted_method_path("login.ConsolidatedConsentScreen.userActed"); +} + +ConsolidatedConsentScreenHandler::~ConsolidatedConsentScreenHandler() { + if (screen_) + screen_->OnViewDestroyed(this); +} + +void ConsolidatedConsentScreenHandler::DeclareLocalizedValues( + ::login::LocalizedValuesBuilder* builder) { + builder->Add("consolidatedConsentHeader", IDS_CONSOLIDATED_CONSENT_HEADER); + builder->Add("consolidatedConsentHeaderChild", + IDS_CONSOLIDATED_CONSENT_HEADER_CHILD); + builder->Add("consolidatedConsentHeaderManaged", + IDS_CONSOLIDATED_CONSENT_HEADER_MANAGED); + builder->Add("consolidatedConsentSubheader", + IDS_CONSOLIDATED_CONSENT_SUBHEADER); + builder->Add("consolidatedConsentSubheaderArcDisabled", + IDS_CONSOLIDATED_CONSENT_SUBHEADER_ARC_DISABLED); + builder->Add("consolidatedConsentTermsDescriptionTitle", + IDS_CONSOLIDATED_CONSENT_TERMS_TITLE); + builder->Add("consolidatedConsentTermsDescription", + IDS_CONSOLIDATED_CONSENT_TERMS); + builder->Add("consolidatedConsentTermsDescriptionArcDisabled", + IDS_CONSOLIDATED_CONSENT_TERMS_ARC_DISABLED); + builder->Add("consolidatedConsentUsageOptInTitle", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_TITLE); + builder->Add("consolidatedConsentUsageOptIn", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN); + builder->Add("consolidatedConsentUsageOptInChild", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_CHILD); + builder->Add("consolidatedConsentUsageOptInArcDisabled", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_ARC_DISABLED); + builder->Add("consolidatedConsentBackupOptInTitle", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_TITLE); + builder->Add("consolidatedConsentBackupOptIn", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN); + builder->Add("consolidatedConsentBackupOptInChild", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_CHILD); + builder->Add("consolidatedConsentLocationOptInTitle", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_TITLE); + builder->Add("consolidatedConsentLocationOptIn", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN); + builder->Add("consolidatedConsentLocationOptInChild", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_CHILD); + builder->Add("consolidatedConsentFooter", IDS_CONSOLIDATED_CONSENT_FOOTER); + builder->Add("consolidatedConsentFooterChild", + IDS_CONSOLIDATED_CONSENT_FOOTER_CHILD); + builder->Add("consolidatedConsentUsageOptInLearnMore", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE); + builder->Add("consolidatedConsentUsageOptInLearnMoreChild", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_CHILD); + builder->Add("consolidatedConsentUsageOptInLearnMoreArcDisabled", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED); + builder->Add( + "consolidatedConsentUsageOptInLearnMoreArcDisabledChild", + IDS_CONSOLIDATED_CONSENT_USAGE_OPT_IN_LEARN_MORE_ARC_DISABLED_CHILD); + builder->Add("consolidatedConsentBackupOptInLearnMore", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE); + builder->Add("consolidatedConsentBackupOptInLearnMoreChild", + IDS_CONSOLIDATED_CONSENT_BACKUP_OPT_IN_LEARN_MORE_CHILD); + builder->Add("consolidatedConsentLocationOptInLearnMore", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE); + builder->Add("consolidatedConsentLocationOptInLearnMoreChild", + IDS_CONSOLIDATED_CONSENT_LOCATION_OPT_IN_LEARN_MORE_CHILD); + builder->Add("consolidatedConsentFooterLearnMore", + IDS_CONSOLIDATED_CONSENT_FOOTER_LEARN_MORE); + builder->Add("consolidatedConsentLearnMore", + IDS_CONSOLIDATED_CONSENT_LEARN_MORE); + builder->Add("consolidatedConsentAcceptAndContinue", + IDS_CONSOLIDATED_CONSENT_ACCEPT_AND_CONTINUE); + builder->Add("consolidatedConsentLoading", IDS_CONSOLIDATED_CONSENT_LOADING); + builder->Add("consolidatedConsentErrorTitle", + IDS_OOBE_GENERIC_FATAL_ERROR_TITLE); + builder->Add("consolidatedConsentErrorMessage", + IDS_CONSOLIDATED_CONSENT_TERMS_LOAD_ERROR); + builder->Add("consolidatedConsentRetry", IDS_CONSOLIDATED_CONSENT_RETRY); + builder->Add("consolidatedConsentOK", IDS_CONSOLIDATED_CONSENT_OK); + builder->Add("consolidatedConsentGoogleEulaTitle", + IDS_CONSOLIDATED_CONSENT_GOOGLE_EULA_TITLE); + builder->Add("consolidatedConsentCrosEulaTitle", + IDS_CONSOLIDATED_CONSENT_CROS_EULA_TITLE); + builder->Add("consolidatedConsentArcTermsTitle", + IDS_CONSOLIDATED_CONSENT_ARC_TITLE); + builder->Add("consolidatedConsentPrivacyTitle", + IDS_CONSOLIDATED_CONSENT_PRIVACY_POLICY_TITLE); + + if (base::CommandLine::ForCurrentProcess()->HasSwitch( + switches::kArcTosHostForTests)) { + builder->Add("consolidatedConsentArcTosHostNameForTesting", + base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( + switches::kArcTosHostForTests)); + } +} + +void ConsolidatedConsentScreenHandler::Initialize() {} + +void ConsolidatedConsentScreenHandler::Show(const ScreenConfig& config) { + base::DictionaryValue data; + // If ARC is enabled, show the ARC ToS and the related opt-ins. + data.SetBoolean("isArcEnabled", config.is_arc_enabled); + // In demo mode, don't show any opt-ins related to ARC and allow showing the + // offline ARC ToS if the online version failed to load. + data.SetBoolean("isDemo", config.is_demo); + // Child accounts have alternative strings for the opt-ins. + data.SetBoolean("isChildAccount", config.is_child_account); + // Managed account will not be shown any terms of service, and the title + // string will be updated. + data.SetBoolean("isEnterpriseManagedAccount", + config.is_enterprise_managed_account); + // Country code is needed to load the ARC ToS. + data.SetString("countryCode", config.country_code); + // URL for EULA, the URL should include the locale. + data.SetString("googleEulaUrl", config.google_eula_url); + // URL for Chrome and ChromeOS additional terms of service, the URL should + // include the locale. + data.SetString("crosEulaUrl", config.cros_eula_url); + ShowScreenWithData(kScreenId, &data); +} + +void ConsolidatedConsentScreenHandler::Bind(ConsolidatedConsentScreen* screen) { + screen_ = screen; + BaseScreenHandler::SetBaseScreen(screen_); +} + +void ConsolidatedConsentScreenHandler::Unbind() { + screen_ = nullptr; + BaseScreenHandler::SetBaseScreen(nullptr); +} + +void ConsolidatedConsentScreenHandler::RegisterMessages() { + BaseScreenHandler::RegisterMessages(); + + AddCallback("ToSAccept", &ConsolidatedConsentScreenHandler::HandleAccept); +} + +void ConsolidatedConsentScreenHandler::HandleAccept( + bool enable_stats_usage, + bool enable_backup_restore, + bool enable_location_services, + const std::string& tos_content) { + if (screen_) { + screen_->OnAccept(enable_stats_usage, enable_backup_restore, + enable_location_services, tos_content); + } +} + +void ConsolidatedConsentScreenHandler::SetUsageMode(bool enabled, + bool managed) { + CallJS("login.ConsolidatedConsentScreen.setUsageMode", enabled, managed); +} + +void ConsolidatedConsentScreenHandler::SetBackupMode(bool enabled, + bool managed) { + CallJS("login.ConsolidatedConsentScreen.setBackupMode", enabled, managed); +} + +void ConsolidatedConsentScreenHandler::SetLocationMode(bool enabled, + bool managed) { + CallJS("login.ConsolidatedConsentScreen.setLocationMode", enabled, managed); +} + +} // namespace chromeos diff --git a/pool/shard011/C++/0121714_wtf_map_unittest.cc b/pool/shard011/C++/0121714_wtf_map_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..dc40143168f62646fb14a1fac3d36a810c2a39b3 --- /dev/null +++ b/pool/shard011/C++/0121714_wtf_map_unittest.cc @@ -0,0 +1,41 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "mojo/public/cpp/bindings/tests/rect_blink.h" +#include "mojo/public/interfaces/bindings/tests/rect.mojom-blink.h" +#include "mojo/public/interfaces/bindings/tests/test_structs.mojom-blink.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace mojo { +namespace test { +namespace { + +TEST(WTFMapTest, StructKey) { + WTF::HashMap map; + map.insert(blink::Rect::New(1, 2, 3, 4), 123); + + blink::RectPtr key = blink::Rect::New(1, 2, 3, 4); + ASSERT_NE(map.end(), map.find(key)); + ASSERT_EQ(123, map.find(key)->value); + + map.erase(key); + ASSERT_EQ(0u, map.size()); +} + +TEST(WTFMapTest, TypemappedStructKey) { + WTF::HashMap map; + map.insert(blink::ContainsHashable::New(RectBlink(1, 2, 3, 4)), 123); + + blink::ContainsHashablePtr key = + blink::ContainsHashable::New(RectBlink(1, 2, 3, 4)); + ASSERT_NE(map.end(), map.find(key)); + ASSERT_EQ(123, map.find(key)->value); + + map.erase(key); + ASSERT_EQ(0u, map.size()); +} + +} // namespace +} // namespace test +} // namespace mojo diff --git a/pool/shard011/C++/0121717_qmlostplugin.cpp b/pool/shard011/C++/0121717_qmlostplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bcf93324f94a373c241d1af5fa1cb250554767c3 --- /dev/null +++ b/pool/shard011/C++/0121717_qmlostplugin.cpp @@ -0,0 +1,149 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmlostplugin.h" +#include "qostdevice.h" + +#include +#include + +QT_BEGIN_NAMESPACE + +static const TInt KQmlOstProtocolId = 0x94; + +class QmlOstPluginPrivate { +public: + QmlOstPluginPrivate(); + + QOstDevice *ost; + QPacketProtocol *protocol; + QDeclarativeDebugServer *debugServer; +}; + +QmlOstPluginPrivate::QmlOstPluginPrivate() : + ost(0), + protocol(0), + debugServer(0) +{ +} + +QmlOstPlugin::QmlOstPlugin() : + d_ptr(new QmlOstPluginPrivate) +{ +} + +QmlOstPlugin::~QmlOstPlugin() +{ + delete d_ptr; +} + +void QmlOstPlugin::setServer(QDeclarativeDebugServer *server) +{ + Q_D(QmlOstPlugin); + d->debugServer = server; +} + +bool QmlOstPlugin::isConnected() const +{ + Q_D(const QmlOstPlugin); + return d->ost && d->ost->isOpen(); +} + +void QmlOstPlugin::send(const QByteArray &message) +{ + Q_D(QmlOstPlugin); + + if (!isConnected()) + return; + + QPacket pack; + pack.writeRawData(message.data(), message.length()); + + d->protocol->send(pack); + //d->socket->flush(); +} + +void QmlOstPlugin::disconnect() +{ + Q_D(QmlOstPlugin); + + delete d->protocol; + d->protocol = 0; +} + +bool QmlOstPlugin::waitForMessage() +{ + Q_D(QmlOstPlugin); + return d->protocol->waitForReadyRead(-1); +} + +void QmlOstPlugin::setPort(int port, bool block) +{ + Q_UNUSED(port); + Q_UNUSED(block); + + Q_D(QmlOstPlugin); + + d->ost = new QOstDevice(this); + bool ok = d->ost->open(KQmlOstProtocolId); + if (!ok) { + if (d->ost->errorString().length()) + qDebug("Error from QOstDevice: %s", qPrintable(d->ost->errorString())); + qWarning("QDeclarativeDebugServer: Unable to listen on OST"); // This message is part of the signalling - do not change the format! + return; + } + d->protocol = new QPacketProtocol(d->ost, this); + QObject::connect(d->protocol, SIGNAL(readyRead()), this, SLOT(readyRead())); + qWarning("QDeclarativeDebugServer: Waiting for connection via OST"); // This message is part of the signalling - do not change the format! +} + +void QmlOstPlugin::readyRead() +{ + Q_D(QmlOstPlugin); + QPacket packet = d->protocol->read(); + + QByteArray content = packet.data(); + d->debugServer->receiveMessage(content); +} + +Q_EXPORT_PLUGIN2(qmlostplugin, QmlOstPlugin) + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0121718_fieldpath_fuzzer.cc b/pool/shard011/C++/0121718_fieldpath_fuzzer.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b09a8cf40bf0768e10ce0dedd0a09b8b9e0a119 --- /dev/null +++ b/pool/shard011/C++/0121718_fieldpath_fuzzer.cc @@ -0,0 +1,37 @@ +/* + * Copyright 2018 Google + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "Firestore/core/src/model/field_path.h" +#include "Firestore/core/src/util/statusor.h" + +using firebase::firestore::model::FieldPath; +using firebase::firestore::util::StatusOr; + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + const char* str_ptr = reinterpret_cast(data); + std::string str{str_ptr, size}; + + try { + StatusOr fp = FieldPath::FromServerFormat(str); + } catch (...) { + // Ignore caught exceptions. + } + return 0; +} diff --git a/pool/shard011/C++/0121719_i2c_bus.cpp b/pool/shard011/C++/0121719_i2c_bus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd0b7d10c0897d781d6efde77444f476cb9dcd9f --- /dev/null +++ b/pool/shard011/C++/0121719_i2c_bus.cpp @@ -0,0 +1,94 @@ +#include "i2c_bus.h" +#include "Wire.h" +#include + +#if !defined(ESP32) +#define Serial_print +#define Serial_println +#else +#define Serial_print Serial.print +#define Serial_println Serial.println +#endif + +void I2CBus::scan(void) +{ + uint8_t err, addr; + int nDevices = 0; + for (addr = 1; addr < 127; addr++) { + _port->beginTransmission(addr); + err = _port->endTransmission(); + if (err == 0) { + Serial_print("I2C device found at address 0x"); + if (addr < 16) + Serial_print("0"); + Serial_print(addr, HEX); + Serial_println(" !"); + nDevices++; + } else if (err == 4) { + Serial_print("Unknow error at address 0x"); + if (addr < 16) + Serial_print("0"); + Serial_println(addr, HEX); + } + } + if (nDevices == 0) + Serial_println("No I2C devices found\n"); + else + Serial_println("done\n"); +} + + +uint16_t I2CBus::readBytes(uint8_t addr, uint8_t *data, uint16_t len, uint16_t delay_ms) +{ + uint16_t ret = 0; + xSemaphoreTakeRecursive(_i2c_mux, portMAX_DELAY); + uint8_t cnt = _port->requestFrom(addr, (uint8_t)len, (uint8_t)1); + if (!cnt) { + ret = 1 << 13; + } + uint16_t index = 0; + while (_port->available()) { + if (index > len)return 1 << 14; + if (delay_ms)delay(delay_ms); + data[index++] = _port->read(); + } + xSemaphoreGiveRecursive(_i2c_mux); + return ret; +} + + +uint16_t I2CBus::readBytes(uint8_t addr, uint8_t reg, uint8_t *data, uint16_t len) +{ + uint16_t ret = 0; + xSemaphoreTakeRecursive(_i2c_mux, portMAX_DELAY); + _port->beginTransmission(addr); + _port->write(reg); + _port->endTransmission(false); + uint8_t cnt = _port->requestFrom(addr, (uint8_t)len, (uint8_t)1); + if (!cnt) { + ret = 1 << 13; + } + uint16_t index = 0; + while (_port->available()) { + if (index > len)return 1 << 14; + data[index++] = _port->read(); + } + xSemaphoreGiveRecursive(_i2c_mux); + return ret; +} + +uint16_t I2CBus::writeBytes(uint8_t addr, uint8_t reg, uint8_t *data, uint16_t len) +{ + uint16_t ret = 0; + char *err = NULL; + xSemaphoreTakeRecursive(_i2c_mux, portMAX_DELAY); + _port->beginTransmission(addr); + _port->write(reg); + for (uint16_t i = 0; i < len; i++) { + _port->write(data[i]); + } + ret = _port->endTransmission(); + xSemaphoreGiveRecursive(_i2c_mux); + return ret ? 1 << 12 : ret; +} + diff --git a/pool/shard011/C++/0121721_B.cpp b/pool/shard011/C++/0121721_B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..81f7a22cd6488053593e4fff3283a7d09ad6947c --- /dev/null +++ b/pool/shard011/C++/0121721_B.cpp @@ -0,0 +1,23 @@ +#include +using namespace std; + +int main() { + int array[5]; + for(int i = 0; i < 5; i++) + scanf("%d", &array[i]); + bool C = true; + bool D = true; + for(int i = 0; i < 4; i++) { + if (array[i] > array[i + 1]) + C = false; + if (array[i] < array[i + 1]) + D = false; + } + if (C) + printf("C\n"); + else if (D) + printf("D\n"); + else + printf("N\n"); + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121722_connector.cpp b/pool/shard011/C++/0121722_connector.cpp new file mode 100644 index 0000000000000000000000000000000000000000..926e05ae7d296146b964eb1209f4fb27a8fbf793 --- /dev/null +++ b/pool/shard011/C++/0121722_connector.cpp @@ -0,0 +1,110 @@ +// Copyright (c) Torrox GmbH & Co KG. All rights reserved. +// Please note that the content of this file is confidential or protected by law. +// Any unauthorised copying or unauthorised distribution of the information contained herein is prohibited. + +#include "proxy/connector.h" + +namespace proxy { + +////////////////////////////// +// class proxy_connection_limit_reached +connection_limit_reached::connection_limit_reached(const std::string& s) + : std::runtime_error(s) +{ +} + +////////////////////////////// +// class configuration + +configuration::configuration() + : max_connections_(20u) + , max_idle_time_(boost::posix_time::seconds(5 * 60)) + , connect_timeout_(boost::posix_time::seconds(5)) + , orgin_timeout_(boost::posix_time::seconds(1)) +{ +} + +unsigned configuration::max_connections() const +{ + return max_connections_; +} + +void configuration::max_connections(unsigned val) +{ + max_connections_ = val; +} + +boost::posix_time::time_duration configuration::max_idle_time() const +{ + return max_idle_time_; +} + +void configuration::max_idle_time(const boost::posix_time::time_duration& val) +{ + max_idle_time_ = val; +} + +boost::posix_time::time_duration configuration::connect_timeout() const +{ + return connect_timeout_; +} + +void configuration::connect_timeout(const boost::posix_time::time_duration& val) +{ + connect_timeout_ = val; +} + +boost::posix_time::time_duration configuration::orgin_timeout() const +{ + return orgin_timeout_; +} + +void configuration::orgin_timeout(const boost::posix_time::time_duration& val) +{ + orgin_timeout_ = val; +} + +////////////////////////////// +// class configurator +configurator::configurator() + : config_(new configuration()) +{ +} + +const configurator& configurator::max_connections(unsigned val) const +{ + config_->max_connections(val); + + return *this; +} + +const configurator& configurator::max_idle_time(const boost::posix_time::time_duration& val) const +{ + config_->max_idle_time(val); + + return *this; +} + +const configurator& configurator::connect_timeout(const boost::posix_time::time_duration& val) const +{ + config_->connect_timeout(val); + + return *this; +} + +const configurator& configurator::orgin_timeout(const boost::posix_time::time_duration& val) const +{ + config_->orgin_timeout(val); + + return *this; +} + +configurator::operator const configuration&() const +{ + return *config_; +} + + + +} // namespace server + diff --git a/pool/shard011/C++/0121724_StackWithMin.cpp b/pool/shard011/C++/0121724_StackWithMin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..35f30cf31e5c0d35734f12d83954eaebe62ea40b --- /dev/null +++ b/pool/shard011/C++/0121724_StackWithMin.cpp @@ -0,0 +1,66 @@ +#include +#include + +using namespace std; + +class NodeWithMin +{ + public: + int data; + int min; + NodeWithMin(){data=0; min=0;} + NodeWithMin(int value, int m){data=value; min=m;} +}; + +class StackWithMin +{ + private: + stack source; + public: + void push(int value) + { + int min = value; + if(!source.empty()) + { + min = source.top().min; + min = value +#include +#include +#include +#include + +struct Naive { +private: + Naive(const Naive&); + void operator=(const Naive&); +public: + const std::vector& v_; + explicit Naive(const std::vector& v) + : v_(v) + { + } + size_t get(size_t pos) const + { + return v_[pos]; + } + size_t rank(uint32_t val, size_t pos) const + { + return std::count(v_.begin(), v_.begin() + pos, val); + } + size_t rankLt(uint32_t val, size_t pos) const + { + size_t ret = 0; + for (size_t i = 0, n = pos; i < n; i++) { + if (v_[i] < val) ret++; + } + return ret; + } + size_t select(uint32_t val, size_t n) const + { + const size_t N = v_.size(); + n++; + for (size_t i = 0; i < N; i++) { + if (v_[i] == val) n--; + if (n == 0) return i; + } + return cybozu::NotFound; + } +}; + +void add(size_t& ret, size_t x) +{ + ret += x; +} + +template +void bench_get(const T& wm, RG& rg, size_t N) +{ + size_t ret = 0; + printf("get "); + CYBOZU_BENCH("", add, ret, wm.get(rg() & (N - 1))); + printf(" ret=%u\n", (int)ret); +} + +template +void bench_rank(const T& wm, RG& rg, size_t N) +{ + size_t ret = 0; + printf("rank "); + CYBOZU_BENCH("", add, ret, wm.rank(uint8_t(rg()), rg() & (N - 1))); + printf(" ret=%u\n", (int)ret); +} + +template +void bench_rankLt(const T& wm, RG& rg, size_t N) +{ + size_t ret = 0; + printf("rank "); + CYBOZU_BENCH("", add, ret, wm.rankLt(uint8_t(rg()), rg() & (N - 1))); + printf(" ret=%u\n", (int)ret); +} + +template +void oneSelect(size_t& ret, const T& wm, RG& rg, const std::vector& maxTbl) +{ + uint8_t c = uint8_t(rg()); + size_t pos = rg() % maxTbl[c]; + ret += wm.select(c, pos); +} + +template +void bench_select(const T& wm, const Vec8& v, RG& rg) +{ + size_t ret = 0; + std::vector maxTbl; + maxTbl.resize(256); + for (int i = 0; i < 256; i++) { + maxTbl[i] = (int)wm.size(i) + 1; + } + printf("select"); + CYBOZU_BENCH("", oneSelect, ret, wm, rg, maxTbl); + printf(" ret=%u\n", (int)ret); + Naive nv(v); +/* + over pos=67108805, i=1024, v=58 +over pos=67108841, i=1026, v=35 +*/ + const struct { + uint8_t v; + uint64_t pos; + } tbl[] = { + { 58, 1024 }, + { 35, 1026 }, + }; + for (size_t i = 0; i < CYBOZU_NUM_OF_ARRAY(tbl); i++) { + uint8_t c = tbl[i].v; + uint64_t pos = tbl[i].pos; + uint64_t a = nv.select(c, pos); + uint64_t b = wm.select(c, pos); + if (a != b) { + printf("ERR c=%d, pos=%d, a=%d, b=%d\n", (int)c, (int)pos, (int)a, (int)b); + exit(1); + } + } + puts("select ok"); +} + +template +void bench(const cybozu::WaveletMatrix& wm, const Vec8& v, size_t N) +{ + cybozu::XorShift rg; + puts("wm"); + bench_get(wm, rg, N); + bench_rank(wm, rg, N); + bench_rankLt(wm, rg, N); + bench_select(wm, v, rg); +#if 0 + bench_get(nv, "nv", 1000000, N); + bench_rank(nv, "nv", 10, N); + bench_rank_lt(nv, "nv", 10, N); + bench_select(nv, "nv", 10); +#endif +} + +void run(size_t bitLen) +{ + cybozu::XorShift rg; + cybozu::WaveletMatrix wm; + const size_t N = size_t(1) << bitLen; + printf("%09llx\n", (long long)N); + puts("init"); + std::vector v; + v.resize(N); + for (size_t i = 0; i < N; i++) { + v[i] = uint8_t(rg()); + } +#if 0 + printf("v\n"); + for (size_t i = 0; i < N; i++) { + printf("%d ", v[i]); + } + printf("\n"); +#endif + wm.init(v, 8); + puts("start"); + bench(wm, v, N); +} + +int main(int argc, char *argv[]) + try +{ + size_t bitLen = 26; + argc--, argv++; + while (argc > 0) { + if (argc > 1 && strcmp(*argv, "-b") == 0) { + argc--, argv++; + bitLen = atoi(*argv); + } else + { + printf("usage wm_bench_smpl.exe [-b bitLen]\n"); + return 1; + } + argc--, argv++; + } + run(bitLen); +} catch (std::exception& e) { + printf("err %s\n", e.what()); +} diff --git a/pool/shard011/C++/0121732_bind_to_task_runner_unittest.cc b/pool/shard011/C++/0121732_bind_to_task_runner_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..20f21c278bc2313082a53c6492c0f174684da852 --- /dev/null +++ b/pool/shard011/C++/0121732_bind_to_task_runner_unittest.cc @@ -0,0 +1,170 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chromecast/base/bind_to_task_runner.h" + +#include + +#include "base/message_loop/message_loop.h" +#include "base/synchronization/waitable_event.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chromecast { + +void BoundBoolSet(bool* var, bool val) { + *var = val; +} + +void BoundBoolSetFromScopedPtr(bool* var, scoped_ptr val) { + *var = *val; +} + +void BoundBoolSetFromScopedPtrFreeDeleter( + bool* var, + scoped_ptr val) { + *var = *val; +} + +void BoundBoolSetFromScopedArray(bool* var, scoped_ptr val) { + *var = val[0]; +} + +void BoundBoolSetFromConstRef(bool* var, const bool& val) { + *var = val; +} + +void BoundIntegersSet(int* a_var, int* b_var, int a_val, int b_val) { + *a_var = a_val; + *b_var = b_val; +} + +// Various tests that check that the bound function is only actually executed +// on the message loop, not during the original Run. +class BindToTaskRunnerTest : public ::testing::Test { + protected: + base::MessageLoop loop_; +}; + +TEST_F(BindToTaskRunnerTest, Closure) { + // Test the closure is run inside the loop, not outside it. + base::WaitableEvent waiter(false, false); + base::Closure cb = BindToCurrentThread( + base::Bind(&base::WaitableEvent::Signal, Unretained(&waiter))); + cb.Run(); + EXPECT_FALSE(waiter.IsSignaled()); + loop_.RunUntilIdle(); + EXPECT_TRUE(waiter.IsSignaled()); +} + +TEST_F(BindToTaskRunnerTest, Bool) { + bool bool_var = false; + base::Callback cb = + BindToCurrentThread(base::Bind(&BoundBoolSet, &bool_var)); + cb.Run(true); + EXPECT_FALSE(bool_var); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_var); +} + +TEST_F(BindToTaskRunnerTest, BoundScopedPtrBool) { + bool bool_val = false; + scoped_ptr scoped_ptr_bool(new bool(true)); + base::Closure cb = BindToCurrentThread(base::Bind( + &BoundBoolSetFromScopedPtr, &bool_val, base::Passed(&scoped_ptr_bool))); + cb.Run(); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, PassedScopedPtrBool) { + bool bool_val = false; + scoped_ptr scoped_ptr_bool(new bool(true)); + base::Callback)> cb = + BindToCurrentThread(base::Bind(&BoundBoolSetFromScopedPtr, &bool_val)); + cb.Run(std::move(scoped_ptr_bool)); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, BoundScopedArrayBool) { + bool bool_val = false; + scoped_ptr scoped_array_bool(new bool[1]); + scoped_array_bool[0] = true; + base::Closure cb = + BindToCurrentThread(base::Bind(&BoundBoolSetFromScopedArray, &bool_val, + base::Passed(&scoped_array_bool))); + cb.Run(); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, PassedScopedArrayBool) { + bool bool_val = false; + scoped_ptr scoped_array_bool(new bool[1]); + scoped_array_bool[0] = true; + base::Callback)> cb = + BindToCurrentThread(base::Bind(&BoundBoolSetFromScopedArray, &bool_val)); + cb.Run(std::move(scoped_array_bool)); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, BoundScopedPtrFreeDeleterBool) { + bool bool_val = false; + scoped_ptr scoped_ptr_free_deleter_bool( + static_cast(malloc(sizeof(bool)))); + *scoped_ptr_free_deleter_bool = true; + base::Closure cb = BindToCurrentThread( + base::Bind(&BoundBoolSetFromScopedPtrFreeDeleter, &bool_val, + base::Passed(&scoped_ptr_free_deleter_bool))); + cb.Run(); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, PassedScopedPtrFreeDeleterBool) { + bool bool_val = false; + scoped_ptr scoped_ptr_free_deleter_bool( + static_cast(malloc(sizeof(bool)))); + *scoped_ptr_free_deleter_bool = true; + base::Callback)> cb = + BindToCurrentThread( + base::Bind(&BoundBoolSetFromScopedPtrFreeDeleter, &bool_val)); + cb.Run(std::move(scoped_ptr_free_deleter_bool)); + EXPECT_FALSE(bool_val); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_val); +} + +TEST_F(BindToTaskRunnerTest, BoolConstRef) { + bool bool_var = false; + bool true_var = true; + const bool& true_ref = true_var; + base::Closure cb = BindToCurrentThread( + base::Bind(&BoundBoolSetFromConstRef, &bool_var, true_ref)); + cb.Run(); + EXPECT_FALSE(bool_var); + loop_.RunUntilIdle(); + EXPECT_TRUE(bool_var); +} + +TEST_F(BindToTaskRunnerTest, Integers) { + int a = 0; + int b = 0; + base::Callback cb = + BindToCurrentThread(base::Bind(&BoundIntegersSet, &a, &b)); + cb.Run(1, -1); + EXPECT_EQ(a, 0); + EXPECT_EQ(b, 0); + loop_.RunUntilIdle(); + EXPECT_EQ(a, 1); + EXPECT_EQ(b, -1); +} + +} // namespace chromecast diff --git a/pool/shard011/C++/0121733_test_bitcoin.cpp b/pool/shard011/C++/0121733_test_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b5a5c4e711d31e724fc1a415e0ba20d192a0f67a --- /dev/null +++ b/pool/shard011/C++/0121733_test_bitcoin.cpp @@ -0,0 +1,66 @@ +#define BOOST_TEST_MODULE Mobilecash Test Suite +#include +#include + +#include "db.h" +#include "txdb.h" +#include "main.h" +#include "wallet.h" +#include "util.h" + +CWallet* pwalletMain; +CClientUIInterface uiInterface; + +extern bool fPrintToConsole; +extern void noui_connect(); + +struct TestingSetup { + CCoinsViewDB *pcoinsdbview; + boost::filesystem::path pathTemp; + boost::thread_group threadGroup; + + TestingSetup() { + fPrintToDebugger = true; // don't want to write to debug.log file + noui_connect(); + bitdb.MakeMock(); + pathTemp = GetTempPath() / strprintf("test_mobilecash_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); + boost::filesystem::create_directories(pathTemp); + mapArgs["-datadir"] = pathTemp.string(); + pblocktree = new CBlockTreeDB(1 << 20, true); + pcoinsdbview = new CCoinsViewDB(1 << 23, true); + pcoinsTip = new CCoinsViewCache(*pcoinsdbview); + InitBlockIndex(); + bool fFirstRun; + pwalletMain = new CWallet("wallet.dat"); + pwalletMain->LoadWallet(fFirstRun); + RegisterWallet(pwalletMain); + nScriptCheckThreads = 3; + for (int i=0; i < nScriptCheckThreads-1; i++) + threadGroup.create_thread(&ThreadScriptCheck); + } + ~TestingSetup() + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + delete pwalletMain; + pwalletMain = NULL; + delete pcoinsTip; + delete pcoinsdbview; + delete pblocktree; + bitdb.Flush(true); + boost::filesystem::remove_all(pathTemp); + } +}; + +BOOST_GLOBAL_FIXTURE(TestingSetup); + +void Shutdown(void* parg) +{ + exit(0); +} + +void StartShutdown() +{ + exit(0); +} + diff --git a/pool/shard011/C++/0121734_qrcodedialog.cpp b/pool/shard011/C++/0121734_qrcodedialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..50465c80c0ae83668119454520357f34ef631814 --- /dev/null +++ b/pool/shard011/C++/0121734_qrcodedialog.cpp @@ -0,0 +1,171 @@ +#include "qrcodedialog.h" +#include "ui_qrcodedialog.h" + +#include "bitcoinunits.h" +#include "guiconstants.h" +#include "guiutil.h" +#include "optionsmodel.h" + +#include +#include + +#include + +QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : + QDialog(parent), + ui(new Ui::QRCodeDialog), + model(0), + address(addr) +{ + ui->setupUi(this); + + setWindowTitle(QString("%1").arg(address)); + + ui->chkReqPayment->setVisible(enableReq); + ui->lblAmount->setVisible(enableReq); + ui->lnReqAmount->setVisible(enableReq); + + ui->lnLabel->setText(label); + + ui->btnSaveAs->setEnabled(false); + + genCode(); +} + +QRCodeDialog::~QRCodeDialog() +{ + delete ui; +} + +void QRCodeDialog::setModel(OptionsModel *model) +{ + this->model = model; + + if (model) + connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + // update the display unit, to not use the default ("BTC") + updateDisplayUnit(); +} + +void QRCodeDialog::genCode() +{ + QString uri = getURI(); + + if (uri != "") + { + ui->lblQRCode->setText(""); + + QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); + if (!code) + { + ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); + return; + } + myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); + myImage.fill(0xffffff); + unsigned char *p = code->data; + for (int y = 0; y < code->width; y++) + { + for (int x = 0; x < code->width; x++) + { + myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); + p++; + } + } + QRcode_free(code); + + ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); + + ui->outUri->setPlainText(uri); + } +} + +QString QRCodeDialog::getURI() +{ + QString ret = QString("recyclingcoin:%1").arg(address); + int paramCount = 0; + + ui->outUri->clear(); + + if (ui->chkReqPayment->isChecked()) + { + if (ui->lnReqAmount->validate()) + { + // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) + ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); + paramCount++; + } + else + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); + return QString(""); + } + } + + if (!ui->lnLabel->text().isEmpty()) + { + QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); + ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); + paramCount++; + } + + if (!ui->lnMessage->text().isEmpty()) + { + QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); + ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); + paramCount++; + } + + // limit URI length to prevent a DoS against the QR-Code dialog + if (ret.length() > MAX_URI_LENGTH) + { + ui->btnSaveAs->setEnabled(false); + ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); + return QString(""); + } + + ui->btnSaveAs->setEnabled(true); + return ret; +} + +void QRCodeDialog::on_lnReqAmount_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnLabel_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_lnMessage_textChanged() +{ + genCode(); +} + +void QRCodeDialog::on_btnSaveAs_clicked() +{ + QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); + if (!fn.isEmpty()) + myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); +} + +void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) +{ + if (!fChecked) + // if chkReqPayment is not active, don't display lnReqAmount as invalid + ui->lnReqAmount->setValid(true); + + genCode(); +} + +void QRCodeDialog::updateDisplayUnit() +{ + if (model) + { + // Update lnReqAmount with the current unit + ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); + } +} diff --git a/pool/shard011/C++/0121735_foldershortcutdialog.cpp b/pool/shard011/C++/0121735_foldershortcutdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3cb1e8f5f9d0d91a692fe5e772f46133a7ffd627 --- /dev/null +++ b/pool/shard011/C++/0121735_foldershortcutdialog.cpp @@ -0,0 +1,98 @@ +/******************************************************************************* +** +** Filename : foldershortcutdialog.cpp +** Created on : 09 October, 2004 +** Copyright : (c) 2004 Till Adam +** Email : adam@kde.org +** +*******************************************************************************/ + +/******************************************************************************* +** +** This program is free software; you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation; either version 2 of the License, or +** (at your option) any later version. +** +** This program is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with this program; if not, write to the Free Software +** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +** +** In addition, as a special exception, the copyright holders give +** permission to link the code of this program with any edition of +** the Qt library by Trolltech AS, Norway (or with modified versions +** of Qt that use the same license as Qt), and distribute linked +** combinations including the two. You must obey the GNU General +** Public License in all respects for all of the code used other than +** Qt. If you modify this file, you may extend this exception to +** your version of the file, but you are not obligated to do so. If +** you do not wish to do so, delete this exception statement from +** your version. +** +*******************************************************************************/ + +#include "foldershortcutdialog.h" + +#include +#include + +#include +#include +#include +#include + +#include "kmmainwidget.h" +#include "kmfolder.h" + +#include + +using namespace KMail; + +FolderShortcutDialog::FolderShortcutDialog( KMFolder *folder, + KMMainWidget *mainwidget, + QWidget *parent ) +: KDialog( parent ), + mFolder( folder ), mMainWidget( mainwidget ) +{ + setCaption( i18n( "Shortcut for Folder %1", folder->label() ) ); + setButtons( Ok | Cancel ); + QFrame *box = new KVBox( this ); + setMainWidget( box ); + QGroupBox *gb = new QGroupBox(i18n("Select Shortcut for Folder"),box ); + QHBoxLayout *layout = new QHBoxLayout; + gb->setWhatsThis( i18n( "To choose a key or a combination " + "of keys which select the current folder, " + "click the button below and then press the key(s) " + "you wish to associate with this folder." ) ); + gb->setLayout( layout ); + KHBox *hb = new KHBox; + layout->addWidget( hb ); + new QWidget(hb); + mKeySeqWidget = new KKeySequenceWidget( hb ); + mKeySeqWidget->setObjectName( "FolderShortcutSelector" ); + new QWidget(hb); + + connect( this, SIGNAL( okClicked() ), SLOT( slotOk() ) ); + mKeySeqWidget->setKeySequence( folder->shortcut().primary(), + KKeySequenceWidget::NoValidate ); + mKeySeqWidget->setCheckActionCollections( mMainWidget->actionCollections() ); +} + +FolderShortcutDialog::~FolderShortcutDialog() +{ +} + +void FolderShortcutDialog::slotOk() +{ + mKeySeqWidget->applyStealShortcut(); + mFolder->setShortcut( KShortcut(mKeySeqWidget->keySequence(), QKeySequence()) ); +} + +#include "foldershortcutdialog.moc" + + diff --git a/pool/shard011/C++/0121736_InsertChildTest.cpp b/pool/shard011/C++/0121736_InsertChildTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e523ad9cd1a356373b4929b5396d01d995df5044 --- /dev/null +++ b/pool/shard011/C++/0121736_InsertChildTest.cpp @@ -0,0 +1,89 @@ +/* Copyright 2013 David Axmark + +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. +*/ + +/* + * InsertChildTest.cpp + * + * Contains general tests for maWidgetInsertChild. + * + * Created on: Mar 29, 2011 + * Author: fmattias + */ +#include + +#include + +#include + +/** + * Tests a valid insert at the beginning of list view. + */ +void testValidInsert() +{ + int listView = maWidgetCreate( MAW_LIST_VIEW ); + TESTIFY_ASSERT( listView > 0 ); + + int firstChild = maWidgetCreate( MAW_LABEL ); + TESTIFY_ASSERT( firstChild > 0 ); + TESTIFY_ASSERT_EQUAL( maWidgetInsertChild( listView, firstChild, 0 ), MAW_RES_OK ); + + int secondChild = maWidgetCreate( MAW_LABEL ); + TESTIFY_ASSERT( secondChild > 0 ); + TESTIFY_ASSERT_EQUAL( maWidgetInsertChild( listView, secondChild, 0 ), MAW_RES_OK ); + + maWidgetDestroy( listView ); +} + +/** + * Tests to insert an element at the end of a list. + */ +void testInsertLast() +{ + int listView = maWidgetCreate( MAW_LIST_VIEW ); + TESTIFY_ASSERT( listView > 0 ); + + int firstChild = maWidgetCreate( MAW_LABEL ); + TESTIFY_ASSERT( firstChild > 0 ); + TESTIFY_ASSERT_EQUAL( maWidgetInsertChild( listView, firstChild, 0 ), MAW_RES_OK ); + + int secondChild = maWidgetCreate( MAW_LABEL ); + TESTIFY_ASSERT( secondChild > 0 ); + TESTIFY_ASSERT_EQUAL( maWidgetInsertChild( listView, secondChild, -1 ), MAW_RES_OK ); + + maWidgetDestroy( listView ); +} + +/** + * Tests to insert an element at a bad index. + */ +void testBadInsert() +{ + int listView = maWidgetCreate( MAW_LIST_VIEW ); + TESTIFY_ASSERT( listView > 0 ); + + int firstChild = maWidgetCreate( MAW_LABEL ); + TESTIFY_ASSERT( firstChild > 0 ); + TESTIFY_ASSERT_EQUAL( maWidgetInsertChild( listView, firstChild, -515 ), MAW_RES_INVALID_INDEX ); + + maWidgetDestroy( listView ); +} + +static Testify::Test *tests[] = +{ + Testify::Test::create( Testify::bind( testValidInsert ), "Testing insert at 0." ), + Testify::Test::create( Testify::bind( testInsertLast ), "Testing insert last." ), + Testify::Test::create( Testify::bind( testBadInsert ), "Testing bad insert." ) +}; +static Testify::TestHook hook( tests, "maWidgetInsertChild tests" ); diff --git a/pool/shard011/C++/0121737_port_tests.cpp b/pool/shard011/C++/0121737_port_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18efa4bd43523085b2c707efccec15fcb967ea5b --- /dev/null +++ b/pool/shard011/C++/0121737_port_tests.cpp @@ -0,0 +1,182 @@ +/* The MIT License (MIT) + * + * Copyright (c) 2020 Cynara Krewe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software, hardware and associated documentation files (the "Solution"), to deal + * in the Solution without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Solution, and to permit persons to whom the Solution is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Solution. + * + * THE SOLUTION IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOLUTION OR THE USE OR OTHER DEALINGS IN THE + * SOLUTION. + */ + +#include +#include + +#include "CppUTest/TestHarness.h" + +#include "flow.h" + +#include "data.h" + +using Flow::Connection; +using Flow::OutPort; +using Flow::InPort; +using Flow::connect; + +const static unsigned int CONNECTION_FIFO_SIZE = 10; + +TEST_GROUP(Port_TestBench) +{ + Connection* connection; + OutPort* outUnitUnderTest; + InPort* inUnitUnderTest; + + void setup() + { + outUnitUnderTest = new OutPort; + inUnitUnderTest = new InPort{ nullptr }; + CHECK(!inUnitUnderTest->full()); + connection = connect(outUnitUnderTest, inUnitUnderTest, + CONNECTION_FIFO_SIZE); + } + + void teardown() + { + disconnect(connection); + delete inUnitUnderTest; + delete outUnitUnderTest; + } +}; + +TEST(Port_TestBench, IsEmptyAfterCreation) +{ + CHECK(!inUnitUnderTest->peek()); + Data response; + CHECK(!inUnitUnderTest->receive(response)); + CHECK(!outUnitUnderTest->full()); +} + +TEST(Port_TestBench, SendReceiveItem) +{ + CHECK(!inUnitUnderTest->peek()); + Data stimulus = Data(123, true); + CHECK(outUnitUnderTest->send(stimulus)); + CHECK(inUnitUnderTest->peek()); + Data response; + CHECK(inUnitUnderTest->receive(response)); + CHECK(stimulus == response); + CHECK(!inUnitUnderTest->peek()); + CHECK(!inUnitUnderTest->receive(response)); +} + +TEST(Port_TestBench, FullConnection) +{ + // Port should be empty. + CHECK(!inUnitUnderTest->peek()); + + for (unsigned int c = 0; c < (CONNECTION_FIFO_SIZE - 1); c++) + { + Data stimulus = Data(c, true); + + // Port should accept another item. + CHECK(outUnitUnderTest->send(stimulus)); + + // Port should not be empty. + CHECK(inUnitUnderTest->peek()); + } + + Data lastStimulus = Data(CONNECTION_FIFO_SIZE, false); + CHECK(!inUnitUnderTest->full()); + // Port should accept another item. + CHECK(outUnitUnderTest->send(lastStimulus)); + + // Port should not be empty. + CHECK(inUnitUnderTest->peek()); + CHECK(inUnitUnderTest->full()); + CHECK(outUnitUnderTest->full()); + + // Port shouldn't accept any more items. + CHECK(!outUnitUnderTest->send(lastStimulus)); + + Data response; + + for (unsigned int c = 0; c < (CONNECTION_FIFO_SIZE - 1); c++) + { + // Should get another item from the Port. + CHECK(inUnitUnderTest->receive(response)); + + // Item should be the expected. + Data expectedResponse = Data(c, true); + CHECK(response == expectedResponse); + + // Port should not be empty. + CHECK(inUnitUnderTest->peek()); + CHECK(!outUnitUnderTest->full()); + } + + // Should get another item from the Port. + CHECK(inUnitUnderTest->receive(response)); + + // Item should be the expected. + CHECK(lastStimulus == response); + + // Port should be empty. + CHECK(!inUnitUnderTest->peek()); + CHECK(!outUnitUnderTest->full()); + + // Shouldn't get another item from the Port. + CHECK(!inUnitUnderTest->receive(response)); +} + +static void producer(OutPort* _unitUnderTest, + const unsigned long long count) +{ + for (unsigned long long c = 0; c <= count; c++) + { + while (!_unitUnderTest->send(Data(c, ((c % 2) == 0)))) + ; + } +} + +static void consumer(InPort* _unitUnderTest, + const unsigned long long count, bool* success) +{ + unsigned long long c = 0; + + while (c <= count) + { + Data response; + if (_unitUnderTest->receive(response)) + { + Data expected = Data(c, ((c % 2) == 0)); + *success = *success && (response == expected); + c++; + } + } +} + +TEST(Port_TestBench, Threadsafe) +{ + const unsigned long long count = 1000000; + bool success = true; + + std::thread producerThread(producer, outUnitUnderTest, count); + std::thread consumerThread(consumer, inUnitUnderTest, count, &success); + + producerThread.join(); + consumerThread.join(); + + CHECK(success); +} diff --git a/pool/shard011/C++/0121740_manifest_feature.cc b/pool/shard011/C++/0121740_manifest_feature.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d36d5278d161f4eb8ff2ec9da5e99da50c73802 --- /dev/null +++ b/pool/shard011/C++/0121740_manifest_feature.cc @@ -0,0 +1,37 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/common/features/manifest_feature.h" + +#include "extensions/common/manifest.h" + +namespace extensions { + +ManifestFeature::ManifestFeature() { +} + +ManifestFeature::~ManifestFeature() { +} + +Feature::Availability ManifestFeature::IsAvailableToContext( + const Extension* extension, + Feature::Context context, + const GURL& url, + Feature::Platform platform) const { + Availability availability = SimpleFeature::IsAvailableToContext(extension, + context, + url, + platform); + if (!availability.is_available()) + return availability; + + // We know we can skip manifest()->GetKey() here because we just did the same + // validation it would do above. + if (extension && !extension->manifest()->value()->HasKey(name())) + return CreateAvailability(NOT_PRESENT, extension->GetType()); + + return CreateAvailability(IS_AVAILABLE); +} + +} // namespace extensions diff --git a/pool/shard011/C++/0121741_test_registry_util.cc b/pool/shard011/C++/0121741_test_registry_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..608620165956c0b1cd934433f940d145a6e5a694 --- /dev/null +++ b/pool/shard011/C++/0121741_test_registry_util.cc @@ -0,0 +1,121 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/chrome_cleaner/test/test_registry_util.h" + +#include "base/check_op.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace chrome_cleaner { + +namespace { +constexpr unsigned int kInitialRegistryValueSize = 256; +} // namespace + +void ExpectRegistryFootprint(const PUPData::PUP& pup, + const RegKeyPath& key_path, + const base::char16* value_name, + const base::char16* value_substring, + RegistryMatchRule rule) { + DCHECK(value_name); + DCHECK(value_substring); + for (const auto& footprint : pup.expanded_registry_footprints) { + bool same_path = footprint.key_path == key_path || + footprint.key_path.IsEquivalent(key_path); + if (same_path && footprint.value_name == value_name && + footprint.value_substring == value_substring && + footprint.rule == rule) { + return; + } + } + ADD_FAILURE() << "Expected registry not found: " << key_path.FullPath() + << "' value_name='" << value_name << "' value_substring='" + << value_substring << "' rule=" << rule; +} + +void ExpectRegistryFootprintAbsent(const PUPData::PUP& pup, + const RegKeyPath& key_path, + const base::char16* value_name, + const base::char16* value_substring, + RegistryMatchRule rule) { + DCHECK(value_name); + DCHECK(value_substring); + for (const auto& footprint : pup.expanded_registry_footprints) { + if (footprint.key_path == key_path && footprint.value_name == value_name && + footprint.value_substring == value_substring && + footprint.rule == rule) { + ADD_FAILURE() << "Unexpected registry found: " << key_path.FullPath() + << "' value_name='" << value_name << "' value_substring='" + << value_substring << "' rule=" << rule; + return; + } + } +} + +ScopedRegistryValue::ScopedRegistryValue(HKEY rootkey, + const base::char16* subkey, + REGSAM access, + const base::char16* value_name, + const base::char16* content, + uint32_t value_type) + : value_name_(value_name) { + DCHECK(subkey); + DCHECK(value_name); + DCHECK(content); + + LONG result = key_.Create(rootkey, subkey, access); + DCHECK_EQ(result, ERROR_SUCCESS); + DCHECK(key_.Valid()); + + old_value_.resize(kInitialRegistryValueSize); + + // Save the previous registry value content. + if (key_.HasValue(value_name)) { + has_value_ = true; + old_value_size_ = old_value_.size(); + while (true) { + result = key_.ReadValue(value_name, &old_value_[0], &old_value_size_, + &old_value_type_); + if (result == ERROR_SUCCESS) + break; + CHECK_EQ(result, ERROR_MORE_DATA); + DCHECK_GT(old_value_size_, old_value_.size()); + old_value_.resize(old_value_size_); + } + } + + // Store the new registry value content. + result = + key_.WriteValue(value_name, content, + ::wcslen(content) * sizeof(base::char16), value_type); + DCHECK_EQ(result, ERROR_SUCCESS); +} + +ScopedRegistryValue::~ScopedRegistryValue() { + DCHECK(key_.Valid()); + if (has_value_) { + LONG result = key_.WriteValue(value_name_, &old_value_[0], old_value_size_, + old_value_type_); + DCHECK_EQ(result, ERROR_SUCCESS); + } else { + if (key_.HasValue(value_name_)) { + LONG result = key_.DeleteValue(value_name_); + DCHECK_EQ(result, ERROR_SUCCESS); + } + } +} + +ScopedTempRegistryKey::ScopedTempRegistryKey(HKEY key, + const base::char16* key_path, + REGSAM access) { + DCHECK(key_path); + key_.Create(key, key_path, access); +} + +ScopedTempRegistryKey::~ScopedTempRegistryKey() { + if (Valid()) + key_.DeleteKey(L""); +} + +} // namespace chrome_cleaner diff --git a/pool/shard011/C++/0121742_fog_map.cpp b/pool/shard011/C++/0121742_fog_map.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1467b41573b4c5584cf8e87589a4d55e21d3cfd --- /dev/null +++ b/pool/shard011/C++/0121742_fog_map.cpp @@ -0,0 +1,255 @@ +// Ryzom - MMORPG Framework +// Copyright (C) 2010 Winch Gate Property Limited +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + + + + + +#include "stdpch.h" +#include "nel/misc/file.h" +#include "zone_util.h" +#include "fog_map.h" +#include "client_cfg.h" +#include "nel/3d/u_driver.h" +#include +// +#include "interface_v3/interface_manager.h" +#include "interface_v3/group_map.h" +#include "client_cfg.h" +#include "global.h" + +using namespace NLMISC; + +H_AUTO_DECL(RZ_FogMap) + +//=================================================================== +void CFogState::setupInDriver(NL3D::UDriver &drv) +{ + H_AUTO_USE(RZ_FogMap) + // Are we in wireframe ? + bool filled = (drv.getPolygonMode() == NL3D::UDriver::Filled); + + if (FogEnabled && filled && ClientCfg.Fog) + { + drv.enableFog(true); + drv.setupFog(FogStartDist, FogEndDist, FogColor); + } + else + { + drv.enableFog(false); + } +} + +//=================================================================== +CFogMap::CFogMap() : _MinCoord(0, 0), _MaxCoord(0, 0) +{ +} + +//=================================================================== +void CFogMap::worldPosToMapPos(float inX, float inY, float &outX, float &outY) const +{ + H_AUTO_USE(RZ_FogMap) + outX = _MinCoord.x != _MaxCoord.x ? (inX - _MinCoord.x) / (_MaxCoord.x - _MinCoord.x) : _MinCoord.x; + outY = _MinCoord.y != _MaxCoord.y ? 1.f - (inY - _MinCoord.y) / (_MaxCoord.y - _MinCoord.y) : 1.f - _MinCoord.y; +} + +//=================================================================== +void CFogMap::getFogParams(float startDist, float endDist, float x, float y, float dayNight, float duskRatio, CLightCycleManager::TLightState lightState, CFogState &result) +{ + H_AUTO_USE(RZ_FogMap) + NLMISC::clamp(dayNight, 0.f, 1.f); + // + float mx, my; + worldPosToMapPos(x, y, mx, my); + // tmp patch for ring island : lookup dist / depth ahead of current pos -> in matis cliffs, avoids to have too thick + // fog when looking inside the lands + float ddMx = x; + float ddMy = y; + CInterfaceManager *im = CInterfaceManager::getInstance(); + CGroupMap *gm = dynamic_cast(CWidgetManager::getInstance()->getElementFromId("ui:interface:map:content:map_content:actual_map")); + if (gm && gm->isIsland()) + { + CVector front = MainCam.getMatrix().getJ(); + ddMx += ClientCfg.FogDistAndDepthLookupBias * front.x; + ddMy += ClientCfg.FogDistAndDepthLookupBias * front.y; + } + // + worldPosToMapPos(ddMx, ddMy, ddMx, ddMy); + // + NLMISC::CRGBAF col0; + NLMISC::CRGBAF col1; + float blendFactor; + switch(lightState) + { + case CLightCycleManager::DayToNight: + // See which transition it is : day->dusk or dusk->night ? + if (dayNight < duskRatio) + { + col0 = getMapValueFromMapCoord(CFogMapBuild::Day, mx, my, CRGBAF(1.f, 1.f, 1.f)); + col1 = getMapValueFromMapCoord(CFogMapBuild::Dusk, mx, my, CRGBAF(1.f, 1.f, 1.f)); + blendFactor = duskRatio != 0.f ? dayNight / duskRatio : 0.f; + } + else + { + col0 = getMapValueFromMapCoord(CFogMapBuild::Dusk, mx, my, CRGBAF(1.f, 1.f, 1.f)); + col1 = getMapValueFromMapCoord(CFogMapBuild::Night, mx, my, CRGBAF(1.f, 1.f, 1.f)); + blendFactor = duskRatio != 1.f ? (dayNight - duskRatio) / (1.f - duskRatio) : 0.f; + } + break; + default: + col0 = getMapValueFromMapCoord(CFogMapBuild::Day, mx, my, CRGBAF(1.f, 1.f, 1.f)); + col1 = getMapValueFromMapCoord(CFogMapBuild::Night, mx, my, CRGBAF(1.f, 1.f, 1.f)); + blendFactor = dayNight; + break; + } + NLMISC::CRGBAF fogColor = col1 * blendFactor + (1.f - blendFactor) * col0; + // + result.FogColor = fogColor; + // + NLMISC::CRGBAF distanceCol = getMapValueFromMapCoord(CFogMapBuild::Distance, ddMx, ddMy, CRGBAF(0.f, 0.f, 0.f)); + result.FogStartDist = (distanceCol.R * (endDist - startDist)) + startDist; + // + NLMISC::CRGBAF depthCol = getMapValueFromMapCoord(CFogMapBuild::Depth,ddMx, ddMy, CRGBAF(1.f, 1.f, 1.f)); + result.FogEndDist = std::min(result.FogStartDist + depthCol.R * (endDist - startDist), endDist); + result.FogEnabled = true; +} + + +//=================================================================== +NLMISC::CRGBAF CFogMap::getMapValue(TMapType type, float x, float y, NLMISC::CRGBAF defaultValue) const +{ + H_AUTO_USE(RZ_FogMap) + nlassert(type < CFogMapBuild::NumMap); + if (_Map[type].getWidth() == 0) return defaultValue; + float mx, my; + worldPosToMapPos(x, y, mx, my); + return _Map[type].getColor(mx, my); +} + +//=================================================================== +NLMISC::CRGBAF CFogMap::getMapValueFromMapCoord(TMapType type, float x, float y, NLMISC::CRGBAF defaultValue) const +{ + H_AUTO_USE(RZ_FogMap) + nlassert(type < CFogMapBuild::NumMap); + if (_Map[type].getWidth() == 0) return defaultValue; + return _Map[type].getColor(x, y); +} + +//=================================================================== +void CFogMap::release() +{ + H_AUTO_USE(RZ_FogMap) + for(uint k = 0; k < CFogMapBuild::NumMap; ++k) + { + _Map[k].reset(); + } + _MinCoord.set(0.f, 0.f); + _MaxCoord.set(0.f, 0.f); +} + +//=================================================================== +bool CFogMap::init(const CFogMapBuild &desc) +{ + H_AUTO_USE(RZ_FogMap) + release(); + CVector2f minCoord, maxCoord; + if (!getPosFromZoneName(desc.ZoneMin, minCoord) || !getPosFromZoneName(desc.ZoneMax, maxCoord)) + { + release(); + return false; + } + return init(desc, minCoord, maxCoord); +} + +//=================================================================== +bool CFogMap::init(const CFogMapBuild &desc, const NLMISC::CVector &minCoord, const NLMISC::CVector &maxCoord) +{ + _MinCoord = minCoord; + _MaxCoord = maxCoord; + if (_MinCoord.x > _MaxCoord.x) std::swap(_MinCoord.x, _MaxCoord.x); + if (_MinCoord.y > _MaxCoord.y) std::swap(_MinCoord.y, _MaxCoord.y); + _MaxCoord.set(_MaxCoord.x + 160.f, _MaxCoord.y + 160.f); + for(uint k = 0; k < CFogMapBuild::NumMap; ++k) + { + _Map[k].resize(0, 0); + if (!desc.Map[k].empty()) + { + load(_Map[k], desc.Map[k]); + } + } + // Exception for dusk map : it has been added later, so if the filename is empty, we use the day and night map to get the dusk map + if (desc.Map[CFogMapBuild::Dusk].empty()) + { + if (_Map[CFogMapBuild::Day].getWidth() != 0 && + _Map[CFogMapBuild::Day].getHeight() != 0 && + _Map[CFogMapBuild::Night].getWidth() != 0 && + _Map[CFogMapBuild::Night].getHeight() != 0) + { + _Map[CFogMapBuild::Dusk].blend(_Map[CFogMapBuild::Day], _Map[CFogMapBuild::Night], 127); + } + } + return true; +} + +//=================================================================== +void CFogMap::load(NLMISC::CBitmap &bm, const std::string &filename) +{ + H_AUTO_USE(RZ_FogMap) + std::string lookupName = NLMISC::CPath::lookup(filename, false, true); + if (lookupName.empty()) + { + nlwarning("couldn't find %s", filename.c_str()); + return; + } + NLMISC::CIFile inputFile; + inputFile.open(lookupName); + try + { + if (!bm.load(inputFile)) + { + nlwarning ("Error while loading fog map %s (bitmap size is multiple of 4?)", lookupName.c_str()); + inputFile.close(); + } + } + catch(const NLMISC::EStream &e) + { + nlwarning(e.what()); + inputFile.close(); + } +} + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pool/shard011/C++/0121743_Test_PHP_mt19937.cpp b/pool/shard011/C++/0121743_Test_PHP_mt19937.cpp new file mode 100644 index 0000000000000000000000000000000000000000..06bca6aa5f4ac655f411c20ba81e1df427a8706d --- /dev/null +++ b/pool/shard011/C++/0121743_Test_PHP_mt19937.cpp @@ -0,0 +1,57 @@ +/* + Copyright Bishop Fox, 2014 + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "Test_PHP_mt19937.h" + +void Test_PHP_Mt19937::setUp() +{ + +} + +void Test_PHP_Mt19937::tearDown() +{ + +} + +void Test_PHP_Mt19937::initalizationTest() +{ + PHP_mt19937 *mt = new PHP_mt19937(); + CPPUNIT_ASSERT(mt != NULL); + delete mt; +} + +void Test_PHP_Mt19937::seedTest() +{ + PHP_mt19937 *mt = new PHP_mt19937(); + mt->seed(31337); + CPPUNIT_ASSERT(mt->getSeed() == 31337); + delete mt; +} + +void Test_PHP_Mt19937::randomTest() +{ + PHP_mt19937 *mt = new PHP_mt19937(); + mt->seed(31337); + CPPUNIT_ASSERT(mt->random() == 590238509); + CPPUNIT_ASSERT(mt->random() == 418805881); + CPPUNIT_ASSERT(mt->random() == 83861629); + mt->seed(31337); + CPPUNIT_ASSERT(mt->random() == 590238509); + CPPUNIT_ASSERT(mt->random() == 418805881); + CPPUNIT_ASSERT(mt->random() == 83861629); + delete mt; +} diff --git a/pool/shard011/C++/0121745_qgeomapcustomobject.cpp b/pool/shard011/C++/0121745_qgeomapcustomobject.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97a0c4eee66b89ce378d6360938eaeee47e53521 --- /dev/null +++ b/pool/shard011/C++/0121745_qgeomapcustomobject.cpp @@ -0,0 +1,305 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qgeomapcustomobject.h" +#include "qgeomapcustomobject_p.h" +#include "qgeoboundingbox.h" + +#include + +QTM_BEGIN_NAMESPACE + +/*! + \class QGeoMapCustomObject + \brief The QGeoMapCustomObject class is a QGeoMapObject used to draw + a QGraphicsItem on a map. + + \inmodule QtLocation + + \ingroup maps-mapping-objects + \since 1.2 + + Any arbitrary QGraphicsItem can be associated with a QGeoMapCustomObject, and to + this end it contains support for interpreting the coordinates of the + QGraphicsItem in a variety of different ways. + + For example, the following code creates a QGraphicsEllipseItem and a + QGeoMapCustomObject to display it. The EllipseItem extends from the origin point, + out 20 meters to the east and 30 metres south. + + \code + QGraphicsEllipseItem *ellipseItem = new QGraphicsEllipseItem; + ellipseItem->setRect(0, 0, 20, 30); + + QGeoMapCustomObject *mapObject = new QGeoMapCustomObject; + mapObject->setGraphicsItem(ellipseItem); + mapObject->setUnits(QGeoMapObject::MeterUnit); + mapObject->setOrigin(QGeoCoordinate(-27.5796, 153.1)); + \endcode + + \section2 Units and coordinates + + The local units and coordinates of the QGraphicsItem are transformed + onto the map based on the \a units, \a origin, \a transformType and + \a transform properties. Several systems are available, including + pixels, meters and seconds of arc. + + It should be noted that both pixel and meter coordinate systems are south- + oriented (ie, positive Y axis faces south on the map). However, the + RelativeArcSeconds unit system faces north to align with the standard + latitude grid. The Y axis can be flipped if necessary by making use of the + GraphicsItem's \a transform property + + \code + QTransform northFlip; + northFlip.scale(0, -1); + + ellipseItem->setTransform(northFlip); + \endcode + + \section2 Transform methods + + Normally, the GraphicsItem will be transformed into map coordinates using + a bilinear interpolation. Another option is the ExactTransform, which + converts the GraphicsItem exactly into map coordinates, but is only available + for certain subclasses of QGraphicsItem. Other interpolation methods may + be provided in future for greater accuracy near poles and in different + map projections, without the limitations of ExactTransform. + + Calling setUnits() or setting the units property will result in the + default value of transformType being restored. See QGeoMapObject::transformType + for more details. + + \section2 Caveats + + Other than the coordinate system features, there are a few differences + with using QGraphicsItems on a map compared to using them on a standard + QGraphicsScene. One of the most important of these is the use of the + \a update() function. When an application changes anything that has an + effect upon the appearance, size, shape etc of the QGraphicsItem, it + must call \a QGeoMapCustomObject::update() to ensure that the map is updated. + + Another is the use of child items of a QGraphicsItem. These are supported + in more or less the same manner as in QGraphicsScene, with the exception + of use in concert with \a ExactTransform -- any object with transformType + set to \a ExactTransform will not have children of its QGraphicsItem drawn + on the map. +*/ + +/*! + Constructs a new custom object. +*/ +QGeoMapCustomObject::QGeoMapCustomObject() + : d_ptr(new QGeoMapCustomObjectPrivate()) +{ +} + +/*! + Constructs a new custom object which will draw a QGraphicsItem at an + offset of \a offset pixels from the coordinate \a coordinate. + \since 1.2 +*/ +QGeoMapCustomObject::QGeoMapCustomObject(const QGeoCoordinate &coordinate, const QPoint &offset) + : d_ptr(new QGeoMapCustomObjectPrivate()) +{ + setOrigin(coordinate); + d_ptr->offset = offset; +} + +/*! + Destroys this custom object. +*/ +QGeoMapCustomObject::~QGeoMapCustomObject() +{ + delete d_ptr; +} + +/*! + \reimp + \since 1.2 +*/ +QGeoMapObject::Type QGeoMapCustomObject::type() const +{ + return QGeoMapObject::CustomType; +} + +/*! + If the graphics item is modified this + method should be called immediately afterwards to inform + the map that an update is required. . + + This method causes the triggerUpdate() signal to be emitted. + \since 1.2 +*/ +void QGeoMapCustomObject::update() +{ + emit triggerUpdate(); +} + +/*! +\fn void QGeoMapCustomObject::triggerUpdate() + + This signal indicates that the graphics item has + changed and that the map needs to be updated. + \since 1.2 +*/ + +/*! + \property QGeoMapCustomObject::graphicsItem + \brief the graphics item which will + be drawn by this custom object. + + If the graphics item is 0 then nothing will be drawn. + \since 1.2 +*/ + +QGraphicsItem* QGeoMapCustomObject::graphicsItem() const +{ + return d_ptr->graphicsItem; +} + +void QGeoMapCustomObject::setGraphicsItem(QGraphicsItem *graphicsItem) +{ + if (d_ptr->graphicsItem == graphicsItem) + return; + + d_ptr->graphicsItem = graphicsItem; + + emit graphicsItemChanged(graphicsItem); +} + +/*! +\fn void QGeoMapCustomObject::graphicsItemChanged(QGraphicsItem *graphicsItem) + + This signal is emitted when the graphics item which this custom object + draws is changed. + + The new value will be \a graphicsItem. + \since 1.2 +*/ + +/*! + \property QGeoMapCustomObject::offset + \brief the offset in pixels at which the graphics + item will be drawn by this custom object. + + The default value of this property is QPoint(0, 0). If this value is not + changed the upper left coordinate of the graphics item will be drawn at the + coordinate specified by QGeoMapCustomObject::coordinate. + + The offset is in pixels and is independent of the zoom level of the map. + \since 1.2 +*/ +QPoint QGeoMapCustomObject::offset() const +{ + return d_ptr->offset; +// QPointF pt = d_ptr->offset; +// +// QPoint rounded; +// rounded.setX(int(pt.x() > 0 ? pt.x() + 0.5 : pt.x() - 0.5)); +// rounded.setY(int(pt.y() > 0 ? pt.y() + 0.5 : pt.y() - 0.5)); +// +// return rounded; +} + +void QGeoMapCustomObject::setOffset(const QPoint &offset) +{ + if (d_ptr->offset != offset) { + d_ptr->offset = offset; + emit offsetChanged(offset); + } +} + +/*! +\fn void QGeoMapCustomObject::offsetChanged(const QPoint &offset) + + This signal is emitted when the on-screen offset from the coordinate + at which this custom object should be drawn has changed. + + The new value will be \a offset. + \since 1.2 +*/ + +/*! + Sets the origin of the object to \a origin. + \since 1.2 +*/ +void QGeoMapCustomObject::setOrigin(const QGeoCoordinate &origin) +{ + QGeoMapObject::setOrigin(origin); +} + +/*! + Sets the coordinate units of the object to \a unit. + + Note that setting this property will reset the transformType property to + the default for the units given. For PixelUnit, this is ExactTransform, + and for all others, BilinearTransform. + \since 1.2 +*/ +void QGeoMapCustomObject::setUnits(const CoordinateUnit &unit) +{ + QGeoMapObject::setUnits(unit); +} + +/*! + Sets the transform type of the object to \a type. + \since 1.2 +*/ +void QGeoMapCustomObject::setTransformType(const TransformType &type) +{ + QGeoMapObject::setTransformType(type); +} + +/******************************************************************************* +*******************************************************************************/ + +QGeoMapCustomObjectPrivate::QGeoMapCustomObjectPrivate() + : graphicsItem(0) {} + +QGeoMapCustomObjectPrivate::~QGeoMapCustomObjectPrivate() +{ +} + +#include "moc_qgeomapcustomobject.cpp" + +QTM_END_NAMESPACE + diff --git a/pool/shard011/C++/0121746_main.cpp b/pool/shard011/C++/0121746_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0dd6856859951304a35883b2b97178721edb12c2 --- /dev/null +++ b/pool/shard011/C++/0121746_main.cpp @@ -0,0 +1,297 @@ +#include +#include +#include + +using namespace std; // uso del espacio de nombres estandar +typedef string nomArch; // declaracion del tipo nomArchi + + +void leerArchivoBinario( string ); // lee y muestra contenido de archivos binarios +void mezclaDirecta( nomArch ); // controla la mezcla +int cuentaReg( nomArch ); // cuenta el numero de registros +void distribuir( nomArch, nomArch, nomArch, int longSubSec, int numReg ); // separa secuencias ordenadas +void subSecuencia( nomArch, nomArch, int, int ); // toma subSecuencias y las escribe +void mezclar(nomArch, nomArch, nomArch, int&, int ); // mezcla pares de subsecuencias + + + +// funcion principal del programa +int main(int argc, char** argv) +{ + leerArchivoBinario( "numeros1.dat" ); +// mezclaDirecta( "numeros1.dat" ); +// cout << endl << endl; +// leerArchivoBinario( "numeros1.dat" ); +} // fin de main + + +/** + * @brief ee el archivo binario y muestra su contenido +*/ +void leerArchivoBinario( string nomFile ) +{ + int buffer; + ifstream file( nomFile.c_str(), ifstream::binary ); + + + while( file ) + { + file.read( (char*)&buffer, sizeof(int) ); + + if( file.eof() ) + break; + + cout << buffer << endl; + } // fin del while + + + file.close(); +} // fin de leerArchivoBinario + + + +//-------------------------------------------- mezcla ----------------------------------------------------------// +/** + * @brief función que controla el algoritmo de ordenación + * @param nomArch nombre del archivo original a ordenar +*/ +void mezclaDirecta( nomArch f ) +{ + int longSubSec; // longitud de las SubSecuencias + int numReg; // numero de registros en el archivo + + nomArch f1 = "auxiliar1.dat"; // archivo auxiliar1 + nomArch f2 = "auxiliar2.dat"; // archivo auxiliar2 + numReg = cuentaReg(f); // determina número de registros + longSubSec = 1; // la longitud de las secuencias inicia en uno( cada registro) + + + // mientras la longitud de las secuencias sea menor al numero de registro + // se realizan pasadas de separación y mezcla + while ( longSubSec < numReg ) + { + distribuir( f, f1, f2, longSubSec, numReg ); // separacion + mezclar( f1, f2, f, longSubSec, numReg ); // mezcla + } // fin del while +} // fin de mezclaDirecta + + + +// variables globales para distribuir-------------------------------------------- + ifstream f; // flujo para el archivo original + ofstream f1; // flujo para el archivo auxiliar1 + ofstream f2; // flujo para el archivo auxiliar2 + +/** + * @brief separa secuencias ordenadas de registros + * @param nomArch nombre del archivo original a ordenar + * @param nomArch nombre del archivo auxiliar1 + * @param nomArch nombre del archivo auxiliar2 + * @param int longitud de las secuencias + * @param int numero de registros en el archivo +*/ +void distribuir( nomArch nf, nomArch nf1, nomArch nf2, int longSubSec, int numReg ) +{ + int numSec; // numero de secuencias(siendo las secuencias pares de subsecuencias de igual longitud) + int resto; // registros no tomados en cuenta( fuera de las secuencias) + numSec = numReg / ( 2 * longSubSec ); // calculo del numero de secuencias + resto = numReg % ( 2 * longSubSec ); // calculo de los registros restantes +/* + ifstream f( nf.c_str(), ifstream::binary ); // abro archivo original para leer + ofstream f1( nf1.c_str(), ofstream::binary ); // abro archivo auxiliar1 para escribir + ofstream f2( nf2.c_str(), ofstream::binary ); // abro archivo auxiliar1 para escribir +*/ + f.open( nf.c_str(), ifstream::binary ); // abro archivo original para leer + f1.open( nf1.c_str(), ofstream::binary ); // abro archivo auxiliar1 para escribir + f2.open( nf2.c_str(), ofstream::binary ); // abro archivo auxiliar1 para escribir + + + // compruebo la correcta apertura de los archivos + if ( f.fail() || f1.fail() || f2.fail() ) + throw " Error en el proceso de separación "; + + + // llamo a subsecuencia para escribir las SubSecuencias en + // los archivos auxiliares y formar las secuencias + for ( int i = 1; i <= numSec; ++i ) + { + subSecuencia( nf, nf1, longSubSec, 1 ); + subSecuencia( nf, nf2, longSubSec, 2 ); + } // fin del for + + + /* + Se procesa el resto de registros que no se tomaron en cuenta, + es decir, que no entraron en ninguna secuencia + */ + // si la cantidad de registros restante es mayor a la + // longitud de las subsecuencias + if ( resto > longSubSec ) + resto -= longSubSec; + else + { + longSubSec = resto; + resto = 0; + } // fin del if..else + + + subSecuencia( nf, nf1, longSubSec, 1 ); + subSecuencia( nf, nf2, resto, 2 ); + f1.close(); f2.close(); f.close(); +} // fin de distribuir + + +/** + * @brief lee una subSecuencia del archivo original y la escribe + * en un archivo auxiliar + * @param nomArch nombre del archivo original a ordenar + * @param nomArch nombre del archivo auxiliar + * @param int longitud de las secuencias +*/ +void subSecuencia( nomArch nf, nomArch nfAux, int longSubSec, int aux ) +{ + int buffer; // almacena registros +// ifstream f( nf.c_str(), ifstream::binary ); // abro archivo original para leer +// ofstream fAux( nfAux.c_str(), ofstream::binary ); // abro archivo auxiliar para escribir + + + // lee un registro a la vez del archivo original y lo escribe + // en el archivo auxiliar hasta completar una subSecuencia + for (int j = 1; j <= longSubSec; j++) + { + f.read( (char*)&buffer, sizeof(int) ); +// fAux.write( (char*)&buffer, sizeof(int) ); + + if( aux == 1 ) + f1.write( (char*)&buffer, sizeof(int) ); + else + f2.write( (char*)&buffer, sizeof(int) ); + } // fin del for +} // fin de subSecuencia + + +/** + * @brief mezcla pares de subsecuencias ordenadas en una secuencia + * @param nomArch nombre del archivo original a ordenar + * @param nomArch nombre del archivo auxiliar + * @param int longitud de las secuencias +*/ +void mezclar(nomArch nf1, nomArch nf2, nomArch nf, int& longSubSec, int numReg) +{ + int numSec; // numero de secuencias(siendo las secuencias pares de subsecuencias de igual longitud) + int resto; // registros no tomados en cuenta( fuera de las secuencias) + int i, j; // cuenta la cantidad de registros procesado para los auxiliares 1 y 2 respectivamente + int n1, n2; // longitudes de las subSecuencias para los auxiliares 1 y 2 respectivamente + int reg1, reg2; // registros a comparar + int actual; // buffer para guardar el registro a ser escrito es el archivo original + + + numSec = numReg / ( 2 * longSubSec ); // calculo del numero de secuencias + resto = numReg % ( 2 * longSubSec ); // calculo de los registros restantes + ofstream f( nf.c_str(), ofstream::binary ); // abro archivo original para escribir + ifstream f1( nf1.c_str(), ifstream::binary ); // abro archivo auxiliar1 para leer + ifstream f2( nf2.c_str(), ifstream::binary ); // abro archivo auxiliar1 para leer + + + f1.read( (char*)®1, sizeof(int) ); // leo un registro del archivo auxiliar1 + f2.read( (char*)®2, sizeof(int) ); // leo un registro del archivo auxiliar2 + + + // mezcla las Secuencias formando las nuevas subSecuencias + for( int s = 1; s <= numSec + 1; ++s ) + { + n1 = n2 = longSubSec; // las longitudes de n1 y n2 empiezan iguales + + + // procesa los registros de la subsecuencia incompleta, + // es decir, la subsecuencia que no formo una secuencia + if ( s == numSec + 1 ) + { + // si el resto es mayor a la longitud de las subSecuencias + if ( resto > longSubSec ) + n2 = resto - longSubSec; // longitud de la subSecuencia de Aux2 + else + { + n1 = resto; // longitud de la subSecuencia de aux1 son los registros restantes + n2 = 0; // Aux2 no tiene resgitros restantes + } // fin del if...else + } // fin del fi + + + i = j = 1; // contamos el primer registro de ambos auxiliares + + + // mientras aun no procese la cantidad de registros + // de las subsecuencias + while ( i <= n1 && j <= n2 ) + { + // si el resgitro en el archivo auxiliar1 es menor + if ( reg1 < reg2 ) + { + actual = reg1; // almaceno el registro del auxiliar1 + f1.read( (char*)®1, sizeof(int) ); // leo el siguiente registro del auxiliar1 + i++; // paso a precesar un registro más del auxiliar1 + } + else + { + actual = reg2; // almaceno el registro del auxiliar2 + f2.read( (char*)®2, sizeof(int) ); // leo el siguiente registro del auxiliar2 + j++; // paso a precesar un registro más del auxiliar2 + } // fin del if...else + + // escreibo en el archivo original el registro de menor valor + f.write( (char*)&actual, sizeof(int) ); + } // fin del while + + + + /* + Los registros no procesados se escriben directamente, + */ + // procesa los registros sin procesar del auxiliar1 + for ( int k = i; k <= n1; k++) + { + f.write( (char*)®1, sizeof(int) ); + f1.read( (char*)®1, sizeof(int) ); + } // fin del for + + + // procesa los registros sin procesar del auxiliar1 + for ( int k = j; k <= n2; k++ ) + { + f.write( (char*)®2, sizeof(int) ); + f2.read( (char*)®2, sizeof(int) ); + } // fin del for + } // fin del for + + + longSubSec *= 2; // aumento la longitud de las subSecuencias en un factor de 2 + f.close(); f1.close();f2.close(); // cierro todos los flujos +} // fin de mezclar + + +/** + * @brief determinar el número de registros ene la archivo + * @param nomArch nombre del archivo original a ordenar +*/ +int cuentaReg( nomArch nomFile ) +{ + int registros = 0; + int buffer; + ifstream file( nomFile.c_str(), ifstream::binary ); + + + while ( file ) + { + file.read( (char*)&buffer, sizeof(int) ); + + if( file.eof() ) + break; + + ++registros; + } // fin del while + + + file.close(); + return registros; +} // fin de cuentaReg diff --git a/pool/shard011/C++/0121749_ShipBlockPacket.cpp b/pool/shard011/C++/0121749_ShipBlockPacket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8480ccf03a0227ef5b09ffab5c7aa6febbdfb1dc --- /dev/null +++ b/pool/shard011/C++/0121749_ShipBlockPacket.cpp @@ -0,0 +1,30 @@ +#include +#include "ShipBlockPacket.h" + +ShipBlockPacket::ShipBlockPacket(uint8_t ip1, uint8_t ip2, uint8_t ip3, uint8_t ip4, uint16_t port) +{ + uint8_t ipBits[] = { ip1, ip2, ip3, ip4 }; + memcpy(this->ipaddr, ipBits, sizeof(ipBits)); + this->port = port; +} + +ShipBlockPacket::~ShipBlockPacket() {} + +PacketData ShipBlockPacket::build() +{ + PacketData data(0x90); + PacketHeader header(0x90, 0x11, 0x2C, 0x0, 0x0); + data.appendData(&header, sizeof(header)); + + data.appendBytes(0, 0x64 - sizeof(header)); + + // Offset 0x64 + data.appendData(&ipaddr, 4); + + // Offset 0x68 + data.appendData(&port, 2); + + data.appendBytes(0, 0x90 - 0x6A); + + return data; +} diff --git a/pool/shard011/C++/0121750_IfcClassificationNotationSelect.cpp b/pool/shard011/C++/0121750_IfcClassificationNotationSelect.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ff92bb167295794f7e11996cab6abfc64786e9c --- /dev/null +++ b/pool/shard011/C++/0121750_IfcClassificationNotationSelect.cpp @@ -0,0 +1,170 @@ +// IFC SDK : IFC2X3 C++ Early Classes +// Copyright (C) 2009 CSTB +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// The full license is in Licence.txt file included with this +// distribution or is available at : +// http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html +// +// 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. + + + +#include + +#include +#include +#include +#include +#include + + + +#include "precompiled.h" + +using namespace ifc2x3; + +IfcClassificationNotationSelect::IfcClassificationNotationSelect() : Step::BaseObject(0) { + m_type = UNSET; +} + +IfcClassificationNotationSelect::IfcClassificationNotationSelect(Step::SPFData *args) : Step::BaseObject(args) { + m_type = UNSET; +} + +IfcClassificationNotationSelect::~IfcClassificationNotationSelect() { + deleteUnion(); +} + +bool IfcClassificationNotationSelect::acceptVisitor(Step::BaseVisitor *visitor) { + return static_cast< Visitor * > (visitor)->visitIfcClassificationNotationSelect(this); +} + +bool IfcClassificationNotationSelect::init() { + return false; +} + +const std::string &IfcClassificationNotationSelect::type() const { + return IfcClassificationNotationSelect::s_type.getName(); +} + +const Step::ClassType &IfcClassificationNotationSelect::getClassType() { + return IfcClassificationNotationSelect::s_type; +} + +const Step::ClassType &IfcClassificationNotationSelect::getType() const { + return IfcClassificationNotationSelect::s_type; +} + +bool IfcClassificationNotationSelect::isOfType(const Step::ClassType &t) const { + return IfcClassificationNotationSelect::s_type == t ? true : Step::BaseObject::isOfType(t); +} + +void IfcClassificationNotationSelect::copy(const IfcClassificationNotationSelect &obj, const CopyOp ©op) { + switch(obj.m_type) { + case IFCCLASSIFICATIONNOTATION: + setIfcClassificationNotation((IfcClassificationNotation *) (copyop(obj.m_IfcClassificationNotationSelect_union.m_IfcClassificationNotation))); + break; + case IFCCLASSIFICATIONREFERENCE: + setIfcClassificationReference((IfcClassificationReference *) (copyop(obj.m_IfcClassificationNotationSelect_union.m_IfcClassificationReference))); + break; + default: + break; + } +} + +std::string IfcClassificationNotationSelect::currentTypeName() const { + switch(m_type) { + case IFCCLASSIFICATIONNOTATION: + return "IfcClassificationNotation"; + break; + case IFCCLASSIFICATIONREFERENCE: + return "IfcClassificationReference"; + break; + default: + return "UNSET"; + } +} + +IfcClassificationNotationSelect::IfcClassificationNotationSelect_select IfcClassificationNotationSelect::currentType() const { + return m_type; +} + +void IfcClassificationNotationSelect::deleteUnion() { + switch(m_type) { + case IFCCLASSIFICATIONNOTATION: + m_IfcClassificationNotationSelect_union.m_IfcClassificationNotation->unref(); + break; + case IFCCLASSIFICATIONREFERENCE: + m_IfcClassificationNotationSelect_union.m_IfcClassificationReference->unref(); + break; + default: + break; + } + m_type = UNSET; +} + +IfcClassificationNotation *IfcClassificationNotationSelect::getIfcClassificationNotation() const { + if (m_type == IFCCLASSIFICATIONNOTATION) { + return m_IfcClassificationNotationSelect_union.m_IfcClassificationNotation; + } + else { + return NULL; + } +} + +void IfcClassificationNotationSelect::setIfcClassificationNotation(IfcClassificationNotation *value) { + if (m_type != UNSET) { + deleteUnion(); + } + m_IfcClassificationNotationSelect_union.m_IfcClassificationNotation = value; + if (value) { + value->ref(); + m_type = IFCCLASSIFICATIONNOTATION; + } + else { + m_type = UNSET; + } + m_type = IFCCLASSIFICATIONNOTATION; +} + +IfcClassificationReference *IfcClassificationNotationSelect::getIfcClassificationReference() const { + if (m_type == IFCCLASSIFICATIONREFERENCE) { + return m_IfcClassificationNotationSelect_union.m_IfcClassificationReference; + } + else { + return NULL; + } +} + +void IfcClassificationNotationSelect::setIfcClassificationReference(IfcClassificationReference *value) { + if (m_type != UNSET) { + deleteUnion(); + } + m_IfcClassificationNotationSelect_union.m_IfcClassificationReference = value; + if (value) { + value->ref(); + m_type = IFCCLASSIFICATIONREFERENCE; + } + else { + m_type = UNSET; + } + m_type = IFCCLASSIFICATIONREFERENCE; +} + +void IfcClassificationNotationSelect::set(Step::BaseObject *v) { + if (v && v->isOfType(IfcClassificationNotation::getClassType())) { + setIfcClassificationNotation(static_cast< IfcClassificationNotation* > (v)); + } + else if (v && v->isOfType(IfcClassificationReference::getClassType())) { + setIfcClassificationReference(static_cast< IfcClassificationReference* > (v)); + } +} + +IFC2X3_EXPORT Step::ClassType IfcClassificationNotationSelect::s_type("IfcClassificationNotationSelect"); diff --git a/pool/shard011/C++/0121751_keyframedata.cpp b/pool/shard011/C++/0121751_keyframedata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..73f6bae9b0226b012a21b9cd31c9609a8c297d0c --- /dev/null +++ b/pool/shard011/C++/0121751_keyframedata.cpp @@ -0,0 +1,128 @@ + + +#include "keyframedata.h" +#include "tapp.h" +#include "toonzqt/tselectionhandle.h" +#include "keyframeselection.h" +#include "xsheetviewer.h" + +#include "toonz/txsheet.h" +#include "toonz/tstageobjecttree.h" +#include "toonz/tstageobjectkeyframe.h" +#include "toonz/txshcolumn.h" + +#include + +//============================================================================= +// TKeyframeData +//----------------------------------------------------------------------------- + +TKeyframeData::TKeyframeData() {} + +//----------------------------------------------------------------------------- + +TKeyframeData::TKeyframeData(const TKeyframeData *src) + : m_keyData(src->m_keyData) + , m_isPegbarsCycleEnabled(src->m_isPegbarsCycleEnabled) {} + +//----------------------------------------------------------------------------- + +TKeyframeData::~TKeyframeData() {} + +//----------------------------------------------------------------------------- +// data <- xsheet +void TKeyframeData::setKeyframes(std::set positions, TXsheet *xsh) { + if (positions.empty()) return; + + TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId(); + + std::set::iterator it = positions.begin(); + int r0 = it->first; + int c0 = it->second; + int r1 = it->first; + int c1 = it->second; + for (++it; it != positions.end(); ++it) { + r0 = std::min(r0, it->first); + c0 = std::min(c0, it->second); + r1 = std::max(r1, it->first); + c1 = std::max(c1, it->second); + } + + m_columnSpanCount = c1 - c0 + 1; + m_rowSpanCount = r1 - r0 + 1; + + for (it = positions.begin(); it != positions.end(); ++it) { + int row = it->first; + int col = it->second; + TStageObject *pegbar = xsh->getStageObject( + col >= 0 ? TStageObjectId::ColumnId(col) : cameraId); + assert(pegbar); + m_isPegbarsCycleEnabled[col] = pegbar->isCycleEnabled(); + if (pegbar->isKeyframe(row)) { + Position p(row - r0, col - c0); + TStageObject::Keyframe k = pegbar->getKeyframe(row); + m_keyData[p] = k; + } + } +} + +//----------------------------------------------------------------------------- + +// data -> xsh +bool TKeyframeData::getKeyframes(std::set &positions, + TXsheet *xsh) const { + std::set::iterator it2 = positions.begin(); + int r0 = it2->first; + int c0 = it2->second; + for (++it2; it2 != positions.end(); ++it2) { + r0 = std::min(r0, it2->first); + c0 = std::min(c0, it2->second); + } + + XsheetViewer *viewer = TApp::instance()->getCurrentXsheetViewer(); + + positions.clear(); + TStageObjectId cameraId = xsh->getStageObjectTree()->getCurrentCameraId(); + Iterator it; + bool keyFrameChanged = false; + for (it = m_keyData.begin(); it != m_keyData.end(); ++it) { + Position pos = it->first; + int row = r0 + pos.first; + int col = c0 + pos.second; + positions.insert(std::make_pair(row, col)); + TXshColumn *column = xsh->getColumn(col); + if (column && column->getSoundColumn()) continue; + TStageObject *pegbar = xsh->getStageObject( + col >= 0 ? TStageObjectId::ColumnId(col) : cameraId); + if (pegbar->getId().isColumn() && xsh->getColumn(col) && + xsh->getColumn(col)->isLocked()) + continue; + keyFrameChanged = true; + assert(pegbar); + pegbar->setKeyframeWithoutUndo(row, it->second); + } + if (!keyFrameChanged) return false; + + for (auto const pegbar : m_isPegbarsCycleEnabled) { + int const col = pegbar.first; + TStageObjectId objectId = + (col >= 0) ? TStageObjectId::ColumnId(col) : cameraId; + xsh->getStageObject(objectId)->enableCycle(pegbar.second); + } + return true; +} + +//----------------------------------------------------------------------------- + +void TKeyframeData::getKeyframes(std::set &positions) const { + int r0 = positions.begin()->first; + int c0 = positions.begin()->second; + positions.clear(); + + TKeyframeData::KeyData::const_iterator it; + for (it = m_keyData.begin(); it != m_keyData.end(); ++it) { + TKeyframeData::Position pos(it->first); + positions.insert( + TKeyframeSelection::Position(pos.first + r0, pos.second + c0)); + } +} diff --git a/pool/shard011/C++/0121752_beamrenderercomponent.cpp b/pool/shard011/C++/0121752_beamrenderercomponent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8fb058c60e046061fb7ea19e7a2610c9382861f --- /dev/null +++ b/pool/shard011/C++/0121752_beamrenderercomponent.cpp @@ -0,0 +1,266 @@ +/****************************************************************************** + * This file is part of the Gluon Development Platform + * Copyright (c) 2010 Arjen Hiemstra + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "beamrenderercomponent.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +REGISTER_OBJECTTYPE( GluonEngine, BeamRendererComponent ) + +using namespace GluonEngine; + +class BeamRendererComponent::Private +{ + public: + Private() + : baseItem( 0 ) + , beamItem( 0 ) + , tipItem( 0 ) + , baseMaterial( 0 ) + , beamMaterial( 0 ) + , tipMaterial( 0 ) + , size( QSizeF( 1.0f, 1.0f ) ) + { + } + + void loadMaterial( GluonGraphics::MaterialInstance* material ); + void acquireReleaseMaterial( GluonGraphics::MaterialInstance* acquire, GluonGraphics::MaterialInstance* release ); + + GluonGraphics::Item* baseItem; + GluonGraphics::Item* beamItem; + GluonGraphics::Item* tipItem; + + GluonGraphics::MaterialInstance* baseMaterial; + GluonGraphics::MaterialInstance* beamMaterial; + GluonGraphics::MaterialInstance* tipMaterial; + + QSizeF size; +}; + +BeamRendererComponent::BeamRendererComponent( QObject* parent ) + : Component( parent ), d( new Private ) +{ + +} + +BeamRendererComponent::~BeamRendererComponent() +{ + d->acquireReleaseMaterial( 0, d->baseMaterial ); + d->acquireReleaseMaterial( 0, d->beamMaterial ); + d->acquireReleaseMaterial( 0, d->tipMaterial ); + delete d; +} + +QString BeamRendererComponent::category() const +{ + return QString( "Graphics Rendering" ); +} + +void BeamRendererComponent::initialize() +{ + if( !d->baseItem ) + { + d->baseItem = GluonGraphics::Engine::instance()->createItem( "default" ); + } + if( !d->beamItem ) + { + d->beamItem = GluonGraphics::Engine::instance()->createItem( "default" ); + } + if( !d->tipItem ) + { + d->tipItem = GluonGraphics::Engine::instance()->createItem( "default" ); + } + + + if( d->baseMaterial ) + { + d->loadMaterial( d->baseMaterial ); + d->baseItem->setMaterialInstance( d->baseMaterial ); + } + + if( d->beamMaterial ) + { + d->loadMaterial( d->beamMaterial ); + d->beamItem->setMaterialInstance( d->beamMaterial ); + } + + if( d->tipMaterial ) + { + d->loadMaterial( d->tipMaterial ); + d->tipItem->setMaterialInstance( d->tipMaterial ); + } +} + +void BeamRendererComponent::start() +{ +} + +void BeamRendererComponent::draw( int /* timeLapse */ ) +{ + QMatrix4x4 transform = gameObject()->transform(); + transform.translate( 0, 0, 0.01f ); + transform.scale( d->size.width() / 2, d->size.width() / 2 ); + d->baseItem->setTransform( transform ); + + transform = gameObject()->transform(); + transform.translate( 0, d->size.height() / 2 ); + transform.scale( d->size.width() / 2, d->size.height() / 2 ); + d->beamItem->setTransform( transform ); + + transform = gameObject()->transform(); + transform.translate( 0, d->size.height(), 0.01f ); + transform.scale( d->size.width() / 2, d->size.width() / 2 ); + d->tipItem->setTransform( transform ); +} + +void BeamRendererComponent::cleanup() +{ + if( d->baseItem ) + { + GluonGraphics::Engine::instance()->destroyItem( d->baseItem ); + d->baseItem = 0; + } + + if( d->beamItem ) + { + GluonGraphics::Engine::instance()->destroyItem( d->beamItem ); + d->beamItem = 0; + } + + if( d->tipItem ) + { + GluonGraphics::Engine::instance()->destroyItem( d->tipItem ); + d->tipItem = 0; + } +} + +void BeamRendererComponent::setSize( const QSizeF& size ) +{ + d->size = size; +} + +QSizeF BeamRendererComponent::size() +{ + return d->size; +} + +GluonGraphics::MaterialInstance* +BeamRendererComponent::baseMaterial() +{ + return d->baseMaterial; +} + +void BeamRendererComponent::setBaseMaterial( GluonGraphics::MaterialInstance* material ) +{ + d->acquireReleaseMaterial( material, d->baseMaterial ); + d->baseMaterial = material; + + if( d->baseItem ) + d->baseItem->setMaterialInstance( material ); +} + +void BeamRendererComponent::setBaseMaterial( const QString& path ) +{ + setBaseMaterial( qobject_cast( Game::instance()->gameProject()->findItemByName( path ) ) ); +} + +GluonGraphics::MaterialInstance* +BeamRendererComponent::beamMaterial() +{ + return d->beamMaterial; +} + +void BeamRendererComponent::setBeamMaterial( GluonGraphics::MaterialInstance* material ) +{ + d->acquireReleaseMaterial( material, d->beamMaterial ); + d->beamMaterial = material; + + if( d->beamItem ) + d->beamItem->setMaterialInstance( material ); +} + +void BeamRendererComponent::setBeamMaterial( const QString& path ) +{ + setBeamMaterial( qobject_cast( Game::instance()->gameProject()->findItemByName( path ) ) ); +} + +GluonGraphics::MaterialInstance* +BeamRendererComponent::tipMaterial() +{ + return d->tipMaterial; +} + +void BeamRendererComponent::setTipMaterial( GluonGraphics::MaterialInstance* material ) +{ + d->acquireReleaseMaterial( material, d->tipMaterial ); + d->tipMaterial = material; + + if( d->tipItem ) + d->tipItem->setMaterialInstance( material ); +} + +void BeamRendererComponent::setTipMaterial( const QString& path ) +{ + setTipMaterial( qobject_cast( Game::instance()->gameProject()->findItemByName( path ) ) ); +} + +void BeamRendererComponent::Private::loadMaterial( GluonGraphics::MaterialInstance* material ) +{ + Asset* materialAsset = qobject_cast( material->parent() ); + if( materialAsset ) + materialAsset->load(); + + Asset* texture = Game::instance()->gameProject()->findChild( material->property( "texture0" ).toString() ); + if( texture ) + texture->load(); +} + +void BeamRendererComponent::Private::acquireReleaseMaterial( GluonGraphics::MaterialInstance* acquire, GluonGraphics::MaterialInstance* release ) +{ + if( release ) + { + release->deref(); + Asset* materialAsset = qobject_cast( release->parent() ); + if( materialAsset ) + materialAsset->deref(); + } + if( acquire ) + { + acquire->ref(); + Asset* materialAsset = qobject_cast( acquire->parent() ); + if( materialAsset ) + materialAsset->ref(); + } +} + +Q_EXPORT_PLUGIN2( gluon_component_beamrenderer, GluonEngine::BeamRendererComponent ) + +#include "beamrenderercomponent.moc" diff --git a/pool/shard011/C++/0121756_noui.cpp b/pool/shard011/C++/0121756_noui.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e563c5fc78f68badf36c434cfc7873895c61783a --- /dev/null +++ b/pool/shard011/C++/0121756_noui.cpp @@ -0,0 +1,52 @@ +// Copyright (c) 2010 Satoshi Nakamoto +// Copyright (c) 2009-2014 The Bitcoin developers +// Copyright (c) 2013-2017 The Anoncoin Core developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "noui.h" + +#include "ui_interface.h" +#include "util.h" + +#include +#include + +static bool noui_ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + bool fSecure = style & CClientUIInterface::SECURE; + style &= ~CClientUIInterface::SECURE; + + std::string strCaption; + // Check for usage of predefined caption + switch (style) { + case CClientUIInterface::MSG_ERROR: + strCaption += _("Error"); + break; + case CClientUIInterface::MSG_WARNING: + strCaption += _("Warning"); + break; + case CClientUIInterface::MSG_INFORMATION: + strCaption += _("Information"); + break; + default: + strCaption += caption; // Use supplied caption (can be empty) + } + + if (!fSecure) + LogPrintf("%s: %s\n", strCaption, message); + fprintf(stderr, "%s: %s\n", strCaption.c_str(), message.c_str()); + return false; +} + +static void noui_InitMessage(const std::string &message) +{ + LogPrintf("init message: %s\n", message); +} + +void noui_connect() +{ + // Connect anoncoind signal handlers + uiInterface.ThreadSafeMessageBox.connect(noui_ThreadSafeMessageBox); + uiInterface.InitMessage.connect(noui_InitMessage); +} diff --git a/pool/shard011/C++/0121757_clangstring-test.cpp b/pool/shard011/C++/0121757_clangstring-test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fb59daef22defd78826788dc1ce8fd69a88db9c --- /dev/null +++ b/pool/shard011/C++/0121757_clangstring-test.cpp @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2016 The Qt Company Ltd. +** Contact: https://www.qt.io/licensing/ +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3 as published by the Free Software +** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-3.0.html. +** +****************************************************************************/ + +#include "googletest.h" + +#include + +#include + +#include +#include + +namespace { + +using ::testing::StrEq; + +using ClangBackEnd::ClangString; + +TEST(ClangString, ConvertToUtf8String) +{ + const CXString cxString = { "text", 0}; + + ASSERT_THAT(Utf8String(ClangString(cxString)), Utf8StringLiteral("text")); +} + +TEST(ClangString, ConvertNullStringToUtf8String) +{ + const CXString cxString = { 0, 0}; + + ASSERT_THAT(Utf8String(ClangString(cxString)), Utf8String()); +} + +TEST(ClangString, MoveContructor) +{ + ClangString text(CXString{ "text", 0}); + + const ClangString text2 = std::move(text); + + ASSERT_TRUE(text.isNull()); + ASSERT_FALSE(text2.isNull()); +} + +TEST(ClangString, MoveAssigment) +{ + ClangString text(CXString{ "text", 0}); + + ClangString text2 = std::move(text); + text = std::move(text2); + + ASSERT_TRUE(text2.isNull()); + ASSERT_FALSE(text.isNull()); +} + +TEST(ClangString, MoveSelfAssigment) +{ + ClangString text(CXString{ "text", 0}); + + text = std::move(text); + + ASSERT_FALSE(text.isNull()); +} + +TEST(ClangString, SpellingAsCString) +{ + ClangString text(CXString{"text", 0}); + + ASSERT_THAT(text.cString(), StrEq("text")); +} +} diff --git a/pool/shard011/C++/0121758_solution.cpp b/pool/shard011/C++/0121758_solution.cpp new file mode 100644 index 0000000000000000000000000000000000000000..142a0d111bd8d10be0300ef92edf4f2ea19a87da --- /dev/null +++ b/pool/shard011/C++/0121758_solution.cpp @@ -0,0 +1,47 @@ +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ +struct Compare +{ + bool operator()(const ListNode*p, const ListNode* q)const{ + return p->val > q->val; + } +}; + +class Solution +{ +public: + ListNode* mergeKLists(vector& lists) + { + int length = lists.size(); + ListNode *head = new ListNode(0); + ListNode *pointer = head; + priority_queue, Compare> listQueue; + + for (int i=0; i 0) + { + ListNode* tempNode = listQueue.top(); + listQueue.pop(); + pointer->next = tempNode; + pointer = pointer->next; + if (tempNode->next) + listQueue.push(tempNode->next); + } + pointer->next = NULL; + return head->next; + } +}; + + + diff --git a/pool/shard011/C++/0121759_psroi_pooling_op.cpp b/pool/shard011/C++/0121759_psroi_pooling_op.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a0f7278056bcd97258e221264c681904db31122 --- /dev/null +++ b/pool/shard011/C++/0121759_psroi_pooling_op.cpp @@ -0,0 +1,51 @@ +#include "core/operator.hpp" + +#include "kernels/psroi_pooling.hpp" + +namespace Shadow { + +class PSROIPoolingOp : public Operator { + public: + PSROIPoolingOp(const shadow::OpParam& op_param, Workspace* ws) + : Operator(op_param, ws) { + pooled_h_ = get_single_argument("pooled_h", 0); + pooled_w_ = get_single_argument("pooled_w", 0); + CHECK_GT(pooled_h_, 0) << "pooled_h must be > 0"; + CHECK_GT(pooled_w_, 0) << "pooled_w must be > 0"; + spatial_scale_ = get_single_argument("spatial_scale", 1.f / 16); + + kernel_ = std::dynamic_pointer_cast( + CreateKernel(op_param.type(), ws_->Ctx()->device_type())); + CHECK_NOTNULL(kernel_); + } + + void Run(const std::vector>& inputs, + std::vector>& outputs) override { + CHECK_EQ(inputs.size(), 2); + + const auto& input = inputs[0]; + const auto& roi = inputs[1]; + auto& output = outputs[0]; + + CHECK_NE(input, output); + + int in_c = input->shape(1), out_spatial_dim = pooled_h_ * pooled_w_; + + CHECK_EQ(in_c % out_spatial_dim, 0); + + output->reshape( + {roi->shape(0), in_c / out_spatial_dim, pooled_h_, pooled_w_}); + + kernel_->Run(input, roi, output, ws_, spatial_scale_); + } + + private: + int pooled_h_, pooled_w_; + float spatial_scale_; + + std::shared_ptr kernel_ = nullptr; +}; + +REGISTER_OPERATOR(PSROIPooling, PSROIPoolingOp); + +} // namespace Shadow diff --git a/pool/shard011/C++/0121760_convert_stereo_calib.cpp b/pool/shard011/C++/0121760_convert_stereo_calib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..243d4b751f1790c1ffb48bec9296656f4cea78b2 --- /dev/null +++ b/pool/shard011/C++/0121760_convert_stereo_calib.cpp @@ -0,0 +1,106 @@ +#include +#include + +using namespace cvt; + +void dump( const cvt::String& camName, + const CameraCalibration& calib, + const Matrix3f& Rrect, + const Matrix4f& projection, + size_t w, size_t h ) +{ + std::ofstream out; + String fName; + fName.sprintf( "%s.yaml", camName.c_str() ); + + out.open( fName.c_str() ); + + const Matrix3f& K = calib.intrinsics(); + const Vector3f& rad = calib.radialDistortion(); + const Vector2f& tang = calib.tangentialDistortion(); + + out << "image_width: " << w << "\n"; + out << "image_height: " << h << "\n"; + out << "camera_name: " << camName << "\n"; + out << "camera_matrix:\n"; + out << " rows: 3\n"; + out << " cols: 3\n"; + out << " data: ["; + out << K[ 0 ][ 0 ] << ", " << K[ 0 ][ 1 ] << ", " << K[ 0 ][ 2 ] << ", " + << K[ 1 ][ 0 ] << ", " << K[ 1 ][ 1 ] << ", " << K[ 1 ][ 2 ] << ", " + << K[ 2 ][ 0 ] << ", " << K[ 2 ][ 1 ] << ", " << K[ 2 ][ 2 ] << "]\n"; + out << "distortion_model: plumb_bob\n"; + out << "distortion_coefficients:\n"; + out << " rows: 1\n"; + out << " cols: 5\n"; + out << " cols: 5\n"; + out << " data: ["; + out << rad[ 0 ] << ", " + << rad[ 1 ] << ", " + << tang[ 0 ] << ", " + << tang[ 1 ] << ", " + << rad[ 2 ] << "]\n"; + + out << "rectification_matrix:\n"; + out << " rows: 3\n"; + out << " cols: 3\n"; + out << " data: ["; + out << Rrect[ 0 ][ 0 ] << ", " << Rrect[ 0 ][ 1 ] << ", " << Rrect[ 0 ][ 2 ] << ", " + << Rrect[ 1 ][ 0 ] << ", " << Rrect[ 1 ][ 1 ] << ", " << Rrect[ 1 ][ 2 ] << ", " + << Rrect[ 2 ][ 0 ] << ", " << Rrect[ 2 ][ 1 ] << ", " << Rrect[ 2 ][ 2 ] << "]\n"; + + out << "projection_matrix:\n"; + out << " rows: 3\n"; + out << " cols: 4\n"; + out << " data: ["; + out << projection[ 0 ][ 0 ] << ", " << projection[ 0 ][ 1 ] << ", " << projection[ 0 ][ 2 ] << ", " << projection[ 0 ][ 3 ] << ", " + << projection[ 1 ][ 0 ] << ", " << projection[ 1 ][ 1 ] << ", " << projection[ 1 ][ 2 ] << ", " << projection[ 1 ][ 3 ] << ", " + << projection[ 2 ][ 0 ] << ", " << projection[ 2 ][ 1 ] << ", " << projection[ 2 ][ 2 ] << ", " << projection[ 2 ][ 3 ] << "]\n"; + + out.close(); +} + +int main( int argc, char* argv[] ){ + try { + if( argc < 5 ){ + std::cout << "usage: " << argv[ 0 ] << " " << std::endl; + return 0; + } + + String file0( argv[ 1 ] ); + String file1( argv[ 2 ] ); + + String s; + s = argv[ 3 ]; + size_t w = s.toInteger(); + s = argv[ 4 ]; + size_t h = s.toInteger(); + + CameraCalibration c0, c1; + c0.load( file0 ); + c1.load( file1 ); + + StereoCameraCalibration sCalib( c0, c1 ), tmp; + + Image il( w, h, IFormat::GRAYALPHA_FLOAT ), ir( w, h, IFormat::GRAYALPHA_FLOAT ); + sCalib.undistortRectify( tmp, il, ir, w, h, false ); + + Matrix3f rl, rr; + sCalib.rectificationMatrices( rl, rr ); + + file0 = file0.substring( 0, file0.rfind( '.' ) ); + std::cout << "Writing file: " << file0 << std::endl; + dump( file0, c0, rl, tmp.firstCamera().projectionMatrix(), w, h ); + + file1 = file1.substring( 0, file1.rfind( '.' ) ); + std::cout << "Writing file: " << file1 << std::endl; + dump( file1, c1, rr, tmp.secondCamera().projectionMatrix(), w, h ); + + } catch ( Exception& e ){ + std::cout << e.what() << std::endl; + } + + return 0; + + +} diff --git a/pool/shard011/C++/0121761_ReaderWriterFFmpeg.cpp b/pool/shard011/C++/0121761_ReaderWriterFFmpeg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba20b83b862a4d12da4720fbb0145d9f7fb93aeb --- /dev/null +++ b/pool/shard011/C++/0121761_ReaderWriterFFmpeg.cpp @@ -0,0 +1,176 @@ +/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2010 Robert Osfield + * + * This library is open source and may be redistributed and/or modified under + * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or + * (at your option) any later version. The full license is in LICENSE file + * included with this distribution, and on the openscenegraph.org website. + * + * 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 + * OpenSceneGraph Public License for more details. +*/ + +#include "FFmpegHeaders.hpp" +#include "FFmpegImageStream.hpp" +#include "FFmpegParameters.hpp" + +#include +#include +#include + + +#if LIBAVCODEC_VERSION_MAJOR >= 53 || \ + (LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR>=30) || \ + (LIBAVCODEC_VERSION_MAJOR==52 && LIBAVCODEC_VERSION_MINOR==20 && LIBAVCODEC_VERSION_MICRO >= 1) + #define USE_AV_LOCK_MANAGER +#endif + + + +/** Implementation heavily inspired by http://www.dranger.com/ffmpeg/ */ + +class ReaderWriterFFmpeg : public osgDB::ReaderWriter +{ +public: + + ReaderWriterFFmpeg() + { + supportsProtocol("http","Read video/audio from http using ffmpeg."); + supportsProtocol("rtsp","Read video/audio from rtsp using ffmpeg."); + + supportsExtension("ffmpeg", ""); + supportsExtension("avi", ""); + supportsExtension("flv", "Flash video"); + supportsExtension("mov", "Quicktime"); + supportsExtension("ogg", "Theora movie format"); + supportsExtension("mpg", "Mpeg movie format"); + supportsExtension("mpv", "Mpeg movie format"); + supportsExtension("wmv", "Windows Media Video format"); + supportsExtension("mkv", "Matroska"); + supportsExtension("mjpeg", "Motion JPEG"); + supportsExtension("mp4", "MPEG-4"); + supportsExtension("m4v", "MPEG-4"); + supportsExtension("sav", "Unknown"); + supportsExtension("3gp", "3G multi-media format"); + supportsExtension("sdp", "Session Description Protocol"); + supportsExtension("m2ts", "MPEG-2 Transport Stream"); + + supportsOption("format", "Force setting input format (e.g. vfwcap for Windows webcam)"); + supportsOption("pixel_format", "Set pixel format"); + supportsOption("frame_size", "Set frame size (e.g. 320x240)"); + supportsOption("frame_rate", "Set frame rate (e.g. 25)"); + supportsOption("audio_sample_rate", "Set audio sampling rate (e.g. 44100)"); + +#ifdef USE_AV_LOCK_MANAGER + // enable thread locking + av_lockmgr_register(&lockMgr); +#endif + // Register all FFmpeg formats/codecs + av_register_all(); + } + + virtual ~ReaderWriterFFmpeg() + { + } + + virtual const char * className() const + { + return "ReaderWriterFFmpeg"; + } + + virtual ReadResult readImage(const std::string & filename, const osgDB::ReaderWriter::Options* options) const + { + const std::string ext = osgDB::getLowerCaseFileExtension(filename); + if (ext=="ffmpeg") return readImage(osgDB::getNameLessExtension(filename),options); + + if (filename.compare(0, 5, "/dev/")==0) + { + return readImageStream(filename, NULL); + } + + osg::ref_ptr parameters(new osgFFmpeg::FFmpegParameters); + parseOptions(parameters.get(), options); + if (parameters->isFormatAvailable()) + { + return readImageStream(filename, parameters.get()); + } + + if (! acceptsExtension(ext)) + return ReadResult::FILE_NOT_HANDLED; + + const std::string path = osgDB::containsServerAddress(filename) ? + filename : + osgDB::findDataFile(filename, options); + + if (path.empty()) + return ReadResult::FILE_NOT_FOUND; + + return readImageStream(path, parameters.get()); + } + + ReadResult readImageStream(const std::string& filename, osgFFmpeg::FFmpegParameters* parameters) const + { + OSG_INFO << "ReaderWriterFFmpeg::readImage " << filename << std::endl; + + osg::ref_ptr image_stream(new osgFFmpeg::FFmpegImageStream); + + if (! image_stream->open(filename, parameters)) + return ReadResult::FILE_NOT_HANDLED; + + return image_stream.release(); + } + +private: + + void parseOptions(osgFFmpeg::FFmpegParameters* parameters, const osgDB::ReaderWriter::Options * options) const + { + if (options && options->getNumPluginStringData()>0) + { + const FormatDescriptionMap& supportedOptList = supportedOptions(); + for (FormatDescriptionMap::const_iterator itr = supportedOptList.begin(); + itr != supportedOptList.end(); ++itr) + { + const std::string& name = itr->first; + parameters->parse(name, options->getPluginStringData(name)); + } + } + } + +#ifdef USE_AV_LOCK_MANAGER + static int lockMgr(void **mutex, enum AVLockOp op) + { + // returns are 0 success + OpenThreads::Mutex **m=(OpenThreads::Mutex**)mutex; + if (op==AV_LOCK_CREATE) + { + *m=new OpenThreads::Mutex; + return !*m; + } + else if (op==AV_LOCK_DESTROY) + { + delete *m; + return 0; + } + else if (op==AV_LOCK_OBTAIN) + { + (*m)->lock(); + return 0; + } + else if (op==AV_LOCK_RELEASE) + { + (*m)->unlock(); + return 0; + } + else + { + return -1; + } + } +#endif + +}; + + + +REGISTER_OSGPLUGIN(ffmpeg, ReaderWriterFFmpeg) diff --git a/pool/shard011/C++/0121762_backendscenedata.cpp b/pool/shard011/C++/0121762_backendscenedata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..131f313b0d101a12bae1231e1715b06658ebdba6 --- /dev/null +++ b/pool/shard011/C++/0121762_backendscenedata.cpp @@ -0,0 +1,312 @@ +//****************************************************************************** +/// +/// @file backend/scene/backendscenedata.cpp +/// +/// @todo What's in here? +/// +/// @copyright +/// @parblock +/// +/// Persistence of Vision Ray Tracer ('POV-Ray') version 3.7. +/// Copyright 1991-2015 Persistence of Vision Raytracer Pty. Ltd. +/// +/// POV-Ray is free software: you can redistribute it and/or modify +/// it under the terms of the GNU Affero General Public License as +/// published by the Free Software Foundation, either version 3 of the +/// License, or (at your option) any later version. +/// +/// POV-Ray is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/// GNU Affero General Public License for more details. +/// +/// You should have received a copy of the GNU Affero General Public License +/// along with this program. If not, see . +/// +/// ---------------------------------------------------------------------------- +/// +/// POV-Ray is based on the popular DKB raytracer version 2.12. +/// DKBTrace was originally written by David K. Buck. +/// DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins. +/// +/// @endparblock +/// +//****************************************************************************** + +#include + +#include +#include + +// frame.h must always be the first POV file included (pulls in platform config) +#include "backend/frame.h" +#include "backend/scene/backendscenedata.h" + +#include "base/fileutil.h" + +#include "povms/povmsid.h" + +// this must be the last file included +#include "base/povdebug.h" + +namespace pov +{ + +BackendSceneData::BackendSceneData() : + SceneData(), + gammaMode(kPOVList_GammaMode_None) // default setting for 3.62, which in turn is the default for the language +{} + +UCS2String BackendSceneData::FindFile(POVMSContext ctx, const UCS2String& filename, unsigned int stype) +{ + vector filenames; + UCS2String foundfile; + bool tryExactFirst; + + // if filename extension, matches one of the standard ones, try the exact name first + // (otherwise, try it last) + UCS2String::size_type pos = filename.find_last_of('.'); + tryExactFirst = false; + if (pos != UCS2String::npos) + { + for (size_t i = 0; i < POV_FILE_EXTENSIONS_PER_TYPE; i++) + { + if ( ( strlen(gPOV_File_Extensions[stype].ext[i]) > 0 ) && + ( filename.compare(pos,filename.length()-pos, ASCIItoUCS2String(gPOV_File_Extensions[stype].ext[i])) == 0 ) ) + { + // match + tryExactFirst = true; + break; + } + } + } + + // build list of files to search for + if (tryExactFirst) + filenames.push_back(filename); + + // add filename with extension variants to list of files to search for + for (size_t i = 0; i < POV_FILE_EXTENSIONS_PER_TYPE; i++) + { + if (strlen(gPOV_File_Extensions[stype].ext[i]) > 0) + { + UCS2String fn(filename); + fn += ASCIItoUCS2String(gPOV_File_Extensions[stype].ext[i]); + filenames.push_back(fn); + } + } + + if (!tryExactFirst) + filenames.push_back(filename); + +#ifdef USE_SCENE_FILE_MAPPING + // see if the file is available locally + for(vector::const_iterator i(filenames.begin()); i != filenames.end(); i++) + { + FilenameToFilenameMap::iterator ilocalfile(scene2LocalFiles.find(*i)); + + if(ilocalfile != scene2LocalFiles.end()) + return *i; + } + + // see if the file is available as temporary file + for(vector::const_iterator i(filenames.begin()); i != filenames.end(); i++) + { + FilenameToFilenameMap::iterator itempfile(scene2TempFiles.find(*i)); + + if(itempfile != scene2TempFiles.end()) + return *i; + } +#endif + + // otherwise, request to find the file + RenderBackend::SendFindFile(ctx, sceneId, frontendAddress, filenames, foundfile); + + return foundfile; +} + +IStream *BackendSceneData::ReadFile(POVMSContext ctx, const UCS2String& origname, const UCS2String& filename, unsigned int stype) +{ + UCS2String scenefile(filename); + UCS2String localfile; + UCS2String fileurl; + +#ifdef USE_SCENE_FILE_MAPPING + // see if the file is available locally + FilenameToFilenameMap::iterator ilocalfile(scene2LocalFiles.find(scenefile)); + + // if available locally, open it end return + if(ilocalfile != scene2LocalFiles.end()) + return NewIStream(ilocalfile->second.c_str(), stype); + + // now try the original name as given in the scene + if((ilocalfile = scene2LocalFiles.find(origname)) != scene2LocalFiles.end()) + return NewIStream(ilocalfile->second.c_str(), stype); + + // see if the file is available as temporary file + FilenameToFilenameMap::iterator itempfile(scene2TempFiles.find(scenefile)); + + // if available as temporary file, open it end return + if(itempfile != scene2TempFiles.end()) + return NewIStream(itempfile->second.c_str(), stype); + + // otherwise, request the file + RenderBackend::SendReadFile(ctx, sceneId, frontendAddress, scenefile, localfile, fileurl); + + // if it is available locally, add it to the map and then open it + if(localfile.length() > 0) + { + scene2LocalFiles[scenefile] = localfile; + local2SceneFiles[localfile] = scenefile; + + // yes this is a hack + scene2LocalFiles[origname] = localfile; + + return NewIStream(localfile.c_str(), stype); + } + + // if it is available remotely ... + if(fileurl.length() > 0) + { + // create a temporary file + UCS2String tempname = POV_PLATFORM_BASE.CreateTemporaryFile(); + OStream *tempfile = NewOStream(tempname.c_str(), stype, false); + + if(tempfile == NULL) + { + POV_PLATFORM_BASE.DeleteTemporaryFile(tempname); + throw POV_EXCEPTION_CODE(kCannotOpenFileErr); + } + + // download the file from the URL + // TODO - handle referrer + if(POV_PLATFORM_BASE.ReadFileFromURL(tempfile, fileurl) == false) + { + delete tempfile; + POV_PLATFORM_BASE.DeleteTemporaryFile(tempname); + throw POV_EXCEPTION_CODE(kNetworkConnectionErr); + } + + delete tempfile; + + // add the temporary file to the map + scene2TempFiles[scenefile] = tempname; + temp2SceneFiles[tempname] = scenefile; + + return NewIStream(tempname.c_str(), stype); + } + + // file not found + return NULL; +#else + return NewIStream(filename.c_str(), stype); +#endif +} + +/* TODO FIXME - this is the correct code but it has a bug. The code above is just a hack [trf] +IStream *BackendSceneData::ReadFile(POVMSContext ctx, const UCS2String& filename, unsigned int stype) +{ + UCS2String scenefile(filename); + UCS2String localfile; + UCS2String fileurl; + + // see if the file is available locally + FilenameToFilenameMap::iterator ilocalfile(scene2LocalFiles.find(scenefile)); + + // if available locally, open it end return + if(ilocalfile != scene2LocalFiles.end()) + return NewIStream(ilocalfile->second.c_str(), stype); + + // see if the file is available as temporary file + FilenameToFilenameMap::iterator itempfile(scene2TempFiles.find(scenefile)); + + // if available as temporary file, open it end return + if(itempfile != scene2TempFiles.end()) + return NewIStream(itempfile->second.c_str(), stype); + + // otherwise, request the file + RenderBackend::SendReadFile(ctx, sceneId, frontendAddress, scenefile, localfile, fileurl); + + // if it is available locally, add it to the map and then open it + if(localfile.length() > 0) + { + scene2LocalFiles[scenefile] = localfile; + local2SceneFiles[localfile] = scenefile; + + return NewIStream(localfile.c_str(), stype); + } + + // if it is available remotely ... + if(fileurl.length() > 0) + { + // create a temporary file + UCS2String tempname = POV_PLATFORM_BASE.CreateTemporaryFile(); + OStream *tempfile = NewOStream(tempname.c_str(), stype, false); + + if(tempfile == NULL) + { + POV_PLATFORM_BASE.DeleteTemporaryFile(tempname); + throw POV_EXCEPTION_CODE(kCannotOpenFileErr); + } + + // download the file from the URL + // TODO - handle referrer + if(POV_PLATFORM_BASE.ReadFileFromURL(tempfile, fileurl) == false) + { + delete tempfile; + POV_PLATFORM_BASE.DeleteTemporaryFile(tempname); + throw POV_EXCEPTION_CODE(kNetworkConnectionErr); + } + + delete tempfile; + + // add the temporary file to the map + scene2TempFiles[scenefile] = tempname; + temp2SceneFiles[tempname] = scenefile; + + return NewIStream(tempname.c_str(), stype); + } + + // file not found + return NULL; +} +*/ +OStream *BackendSceneData::CreateFile(POVMSContext ctx, const UCS2String& filename, unsigned int stype, bool append) +{ + UCS2String scenefile(filename); + +#ifdef USE_SCENE_FILE_MAPPING + // see if the file is available as temporary file + FilenameToFilenameMap::iterator itempfile(scene2TempFiles.find(scenefile)); + + // if available as temporary file, open it end return + if(itempfile != scene2TempFiles.end()) + return NewOStream(itempfile->second.c_str(), stype, append); + + // otherwise, create a temporary file ... + UCS2String tempname = POV_PLATFORM_BASE.CreateTemporaryFile(); + OStream *tempfile = NewOStream(tempname.c_str(), stype, append); + + // failed to open file + if(tempfile == NULL) + return NULL; + + // add the temporary file to the map + scene2TempFiles[scenefile] = tempname; + temp2SceneFiles[tempname] = scenefile; +#else + // this is a workaround for the incomplete scene temp file support + // until someone has time to finish it. + + OStream *tempfile = NewOStream(scenefile.c_str(), stype, append); + if (tempfile == NULL) + return NULL; +#endif + + // let the frontend know that a new file was created + RenderBackend::SendCreatedFile(ctx, sceneId, frontendAddress, scenefile); + + return tempfile; +} + +} diff --git a/pool/shard011/C++/0121763_overviewpage.cpp b/pool/shard011/C++/0121763_overviewpage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e62a3657c669a5ca1b6a150e0850a4e64eb65101 --- /dev/null +++ b/pool/shard011/C++/0121763_overviewpage.cpp @@ -0,0 +1,200 @@ +#include "overviewpage.h" +#include "ui_overviewpage.h" + +#include "walletmodel.h" +#include "bitcoinunits.h" +#include "optionsmodel.h" +#include "transactiontablemodel.h" +#include "transactionfilterproxy.h" +#include "guiutil.h" +#include "guiconstants.h" + +#include +#include + +#define DECORATION_SIZE 64 +#define NUM_ITEMS 3 + +class TxViewDelegate : public QAbstractItemDelegate +{ + Q_OBJECT +public: + TxViewDelegate(): QAbstractItemDelegate(), unit(BitcoinUnits::BTC) + { + + } + + inline void paint(QPainter *painter, const QStyleOptionViewItem &option, + const QModelIndex &index ) const + { + painter->save(); + + QIcon icon = qvariant_cast(index.data(Qt::DecorationRole)); + QRect mainRect = option.rect; + QRect decorationRect(mainRect.topLeft(), QSize(DECORATION_SIZE, DECORATION_SIZE)); + int xspace = DECORATION_SIZE + 8; + int ypad = 6; + int halfheight = (mainRect.height() - 2*ypad)/2; + QRect amountRect(mainRect.left() + xspace, mainRect.top()+ypad, mainRect.width() - xspace, halfheight); + QRect addressRect(mainRect.left() + xspace, mainRect.top()+ypad+halfheight, mainRect.width() - xspace, halfheight); + icon.paint(painter, decorationRect); + + QDateTime date = index.data(TransactionTableModel::DateRole).toDateTime(); + QString address = index.data(Qt::DisplayRole).toString(); + qint64 amount = index.data(TransactionTableModel::AmountRole).toLongLong(); + bool confirmed = index.data(TransactionTableModel::ConfirmedRole).toBool(); + QVariant value = index.data(Qt::ForegroundRole); + QColor foreground = option.palette.color(QPalette::Text); + if(qVariantCanConvert(value)) + { + foreground = qvariant_cast(value); + } + + painter->setPen(foreground); + painter->drawText(addressRect, Qt::AlignLeft|Qt::AlignVCenter, address); + + if(amount < 0) + { + foreground = COLOR_NEGATIVE; + } + else if(!confirmed) + { + foreground = COLOR_UNCONFIRMED; + } + else + { + foreground = option.palette.color(QPalette::Text); + } + painter->setPen(foreground); + QString amountText = BitcoinUnits::formatWithUnit(unit, amount, true); + if(!confirmed) + { + amountText = QString("[") + amountText + QString("]"); + } + painter->drawText(amountRect, Qt::AlignRight|Qt::AlignVCenter, amountText); + + painter->setPen(option.palette.color(QPalette::Text)); + painter->drawText(amountRect, Qt::AlignLeft|Qt::AlignVCenter, GUIUtil::dateTimeStr(date)); + + painter->restore(); + } + + inline QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const + { + return QSize(DECORATION_SIZE, DECORATION_SIZE); + } + + int unit; + +}; +#include "overviewpage.moc" + +OverviewPage::OverviewPage(QWidget *parent) : + QWidget(parent), + ui(new Ui::OverviewPage), + currentBalance(-1), + currentUnconfirmedBalance(-1), + currentImmatureBalance(-1), + txdelegate(new TxViewDelegate()), + filter(0) +{ + ui->setupUi(this); + + // Recent transactions + ui->listTransactions->setItemDelegate(txdelegate); + ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); + ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); + ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); + + connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); + + // init "out of sync" warning labels + ui->labelWalletStatus->setText("(" + tr("Out of sync") + ")"); + ui->labelTransactionsStatus->setText("(" + tr("Out of sync") + ")"); + + // start with displaying the "out of sync" warnings + showOutOfSyncWarning(true); +} + +void OverviewPage::handleTransactionClicked(const QModelIndex &index) +{ + if(filter) + emit transactionClicked(filter->mapToSource(index)); +} + +OverviewPage::~OverviewPage() +{ + delete ui; +} + +void OverviewPage::setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance) +{ + int unit = model->getOptionsModel()->getDisplayUnit(); + currentBalance = balance; + currentUnconfirmedBalance = unconfirmedBalance; + currentImmatureBalance = immatureBalance; + ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); + ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); + ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); + + // only show immature (newly mined) balance if it's non-zero, so as not to complicate things + // for the non-mining users + bool showImmature = immatureBalance != 0; + ui->labelImmature->setVisible(showImmature); + ui->labelImmatureText->setVisible(showImmature); +} + +void OverviewPage::setNumTransactions(int count) +{ + ui->labelNumTransactions->setText(QLocale::system().toString(count)); +} + +void OverviewPage::setModel(WalletModel *model) +{ + this->model = model; + if(model && model->getOptionsModel()) + { + // Set up transaction list + filter = new TransactionFilterProxy(); + filter->setSourceModel(model->getTransactionTableModel()); + filter->setLimit(NUM_ITEMS); + filter->setDynamicSortFilter(true); + filter->setSortRole(Qt::EditRole); + filter->sort(TransactionTableModel::Status, Qt::DescendingOrder); + + ui->listTransactions->setModel(filter); + ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); + + // Keep up to date with wallet + setBalance(model->getBalance(), model->getUnconfirmedBalance(), model->getImmatureBalance()); + connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64))); + + setNumTransactions(model->getNumTransactions()); + connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int))); + + connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + } + + // update the display unit, to not use the default ("ZMB") + updateDisplayUnit(); +} + +void OverviewPage::updateDisplayUnit() +{ + if(model && model->getOptionsModel()) + { + if(currentBalance != -1) + setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance); + + // Update txdelegate->unit with the current unit + txdelegate->unit = model->getOptionsModel()->getDisplayUnit(); + + ui->listTransactions->update(); + } +} + +void OverviewPage::showOutOfSyncWarning(bool fShow) +{ + ui->labelWalletStatus->setVisible(fShow); + ui->labelTransactionsStatus->setVisible(fShow); +} diff --git a/pool/shard011/C++/0121764_net_export_ui.cc b/pool/shard011/C++/0121764_net_export_ui.cc new file mode 100644 index 0000000000000000000000000000000000000000..4980c2bcbe9bcef7bc3db3c8fe036d931cdd5193 --- /dev/null +++ b/pool/shard011/C++/0121764_net_export_ui.cc @@ -0,0 +1,176 @@ +// Copyright 2021 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 "weblayer/browser/webui/net_export_ui.h" + +#include "base/memory/raw_ptr.h" +#include "base/scoped_observation.h" +#include "base/strings/utf_string_conversions.h" +#include "components/net_log/net_export_file_writer.h" +#include "components/net_log/net_export_ui_constants.h" +#include "content/public/browser/browser_context.h" +#include "content/public/browser/storage_partition.h" +#include "content/public/browser/web_contents.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" +#include "content/public/browser/web_ui_message_handler.h" +#include "weblayer/browser/system_network_context_manager.h" +#include "weblayer/grit/weblayer_resources.h" + +#if defined(OS_ANDROID) +#include "components/browser_ui/share/android/intent_helper.h" +#endif + +namespace weblayer { + +namespace { + +class NetExportMessageHandler + : public content::WebUIMessageHandler, + public net_log::NetExportFileWriter::StateObserver { + public: + NetExportMessageHandler() + : file_writer_(SystemNetworkContextManager::GetInstance() + ->GetNetExportFileWriter()) { + file_writer_->Initialize(); + } + + NetExportMessageHandler(const NetExportMessageHandler&) = delete; + NetExportMessageHandler& operator=(const NetExportMessageHandler&) = delete; + + ~NetExportMessageHandler() override { file_writer_->StopNetLog(nullptr); } + + // content::WebUIMessageHandler implementation. + void RegisterMessages() override { + web_ui()->RegisterDeprecatedMessageCallback( + net_log::kEnableNotifyUIWithStateHandler, + base::BindRepeating(&NetExportMessageHandler::OnEnableNotifyUIWithState, + base::Unretained(this))); + web_ui()->RegisterDeprecatedMessageCallback( + net_log::kStartNetLogHandler, + base::BindRepeating(&NetExportMessageHandler::OnStartNetLog, + base::Unretained(this))); + web_ui()->RegisterDeprecatedMessageCallback( + net_log::kStopNetLogHandler, + base::BindRepeating(&NetExportMessageHandler::OnStopNetLog, + base::Unretained(this))); + web_ui()->RegisterDeprecatedMessageCallback( + net_log::kSendNetLogHandler, + base::BindRepeating(&NetExportMessageHandler::OnSendNetLog, + base::Unretained(this))); + } + + // Messages + void OnEnableNotifyUIWithState(const base::ListValue* list) { + AllowJavascript(); + if (!state_observation_manager_.IsObserving()) { + state_observation_manager_.Observe(file_writer_.get()); + } + NotifyUIWithState(file_writer_->GetState()); + } + + void OnStartNetLog(const base::ListValue* list) { + base::Value::ConstListView params = list->GetList(); + + // Determine the capture mode. + if (!params.empty() && params[0].is_string()) { + capture_mode_ = net_log::NetExportFileWriter::CaptureModeFromString( + params[0].GetString()); + } + + // Determine the max file size. + if (params.size() > 1 && params[1].is_int() && params[1].GetInt() > 0) + max_log_file_size_ = params[1].GetInt(); + + StartNetLog(base::FilePath()); + } + + void OnStopNetLog(const base::ListValue* list) { + file_writer_->StopNetLog(nullptr); + } + + void OnSendNetLog(const base::ListValue* list) { + file_writer_->GetFilePathToCompletedLog( + base::BindOnce(&NetExportMessageHandler::SendEmail)); + } + + // net_log::NetExportFileWriter::StateObserver implementation. + void OnNewState(const base::DictionaryValue& state) override { + NotifyUIWithState(state.CreateDeepCopy()); + } + + private: + // Send NetLog data via email. + static void SendEmail(const base::FilePath& file_to_send) { +#if defined(OS_ANDROID) + if (file_to_send.empty()) + return; + std::string email; + std::string subject = "WebLayer net_internals_log"; + std::string title = "Issue number: "; + std::string body = + "Please add some informative text about the network issues."; + base::FilePath::StringType file_to_attach(file_to_send.value()); + browser_ui::SendEmail(base::ASCIIToUTF16(email), + base::ASCIIToUTF16(subject), base::ASCIIToUTF16(body), + base::ASCIIToUTF16(title), + base::ASCIIToUTF16(file_to_attach)); +#endif + } + + void StartNetLog(const base::FilePath& path) { + file_writer_->StartNetLog( + path, capture_mode_, max_log_file_size_, + base::CommandLine::ForCurrentProcess()->GetCommandLineString(), + std::string(), + web_ui() + ->GetWebContents() + ->GetBrowserContext() + ->GetDefaultStoragePartition() + ->GetNetworkContext()); + } + + // Fires net-log-info-changed event to update the JavaScript UI in the + // renderer. + void NotifyUIWithState(std::unique_ptr state) { + FireWebUIListener(net_log::kNetLogInfoChangedEvent, *state); + } + + // Cached pointer to SystemNetworkContextManager's NetExportFileWriter. + raw_ptr file_writer_; + + base::ScopedObservation + state_observation_manager_{this}; + + // The capture mode and file size bound that the user chose in the UI when + // logging started is cached here and is read after a file path is chosen in + // the save dialog. Their values are only valid while the save dialog is open + // on the desktop UI. + net::NetLogCaptureMode capture_mode_ = net::NetLogCaptureMode::kDefault; + uint64_t max_log_file_size_ = net_log::NetExportFileWriter::kNoLimit; +}; + +} // namespace + +const char kChromeUINetExportHost[] = "net-export"; + +NetExportUI::NetExportUI(content::WebUI* web_ui) : WebUIController(web_ui) { + web_ui->AddMessageHandler(std::make_unique()); + + content::WebUIDataSource* source = + content::WebUIDataSource::Create(kChromeUINetExportHost); + source->UseStringsJs(); + source->AddResourcePath(net_log::kNetExportUICSS, IDR_NET_LOG_NET_EXPORT_CSS); + source->AddResourcePath(net_log::kNetExportUIJS, IDR_NET_LOG_NET_EXPORT_JS); + source->SetDefaultResource(IDR_NET_LOG_NET_EXPORT_HTML); + content::WebUIDataSource::Add(web_ui->GetWebContents()->GetBrowserContext(), + source); +} + +NetExportUI::~NetExportUI() = default; + +WEB_UI_CONTROLLER_TYPE_IMPL(NetExportUI) + +} // namespace weblayer diff --git a/pool/shard011/C++/0121765_FixJointBoxes.cpp b/pool/shard011/C++/0121765_FixJointBoxes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51cd1842d15fadccf70fdbe282844395a1a5a121 --- /dev/null +++ b/pool/shard011/C++/0121765_FixJointBoxes.cpp @@ -0,0 +1,172 @@ +#include "FixJointBoxes.h" + +#include "../CommonInterfaces/CommonGraphicsAppInterface.h" +#include "Bullet3Common/b3AlignedObjectArray.h" +#include "../CommonInterfaces/CommonRenderInterface.h" +#include "../CommonInterfaces/CommonExampleInterface.h" +#include "../CommonInterfaces/CommonGUIHelperInterface.h" +#include "../SharedMemory/PhysicsServerSharedMemory.h" +#include "../SharedMemory/PhysicsClientC_API.h" +#include "../SharedMemory/SharedMemoryPublic.h" +#include "../CommonInterfaces/CommonParameterInterface.h" +#include +#include +#include "../RobotSimulator/b3RobotSimulatorClientAPI.h" + +static btScalar numSolverIterations = 1000; +static btScalar solverId = 0; + +class FixJointBoxes : public CommonExampleInterface +{ + GUIHelperInterface* m_guiHelper; + b3RobotSimulatorClientAPI m_robotSim; + int m_options; + b3RobotSimulatorSetPhysicsEngineParameters physicsArgs; + int solver; + + const size_t numCubes; + std::vector cubeIds; + +public: + FixJointBoxes(GUIHelperInterface* helper, int options) + : m_guiHelper(helper), + m_options(options), + numCubes(30), + cubeIds(numCubes, 0), + solver(solverId) + { + } + + virtual ~FixJointBoxes() + { + } + + virtual void physicsDebugDraw(int debugDrawMode) + { + m_robotSim.debugDraw(debugDrawMode); + } + virtual void initPhysics() + { + int mode = eCONNECT_EXISTING_EXAMPLE_BROWSER; + m_robotSim.setGuiHelper(m_guiHelper); + bool connected = m_robotSim.connect(mode); + + b3Printf("robotSim connected = %d", connected); + + m_robotSim.configureDebugVisualizer(COV_ENABLE_RGB_BUFFER_PREVIEW, 0); + m_robotSim.configureDebugVisualizer(COV_ENABLE_DEPTH_BUFFER_PREVIEW, 0); + m_robotSim.configureDebugVisualizer(COV_ENABLE_SEGMENTATION_MARK_PREVIEW, 0); + + { + b3RobotSimulatorLoadUrdfFileArgs args; + b3RobotSimulatorChangeDynamicsArgs dynamicsArgs; + + for (int i = 0; i < numCubes; i++) + { + args.m_forceOverrideFixedBase = (i == 0); + args.m_startPosition.setValue(0, i * 0.05, 1); + cubeIds[i] = m_robotSim.loadURDF("cube_small.urdf", args); + + b3RobotJointInfo jointInfo; + + jointInfo.m_parentFrame[1] = -0.025; + jointInfo.m_childFrame[1] = 0.025; + + if (i > 0) + { + m_robotSim.createConstraint(cubeIds[i], -1, cubeIds[i - 1], -1, &jointInfo); + m_robotSim.setCollisionFilterGroupMask(cubeIds[i], -1, 0, 0); + } + + m_robotSim.loadURDF("plane.urdf"); + } + } + + { + SliderParams slider("Direct solver", &solverId); + slider.m_minVal = 0; + slider.m_maxVal = 1; + m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider); + } + { + SliderParams slider("numSolverIterations", &numSolverIterations); + slider.m_minVal = 50; + slider.m_maxVal = 1e4; + m_guiHelper->getParameterInterface()->registerSliderFloatParameter(slider); + } + + physicsArgs.m_defaultGlobalCFM = 1e-6; + m_robotSim.setPhysicsEngineParameter(physicsArgs); + + m_robotSim.setGravity(btVector3(0, 0, -10)); + m_robotSim.setNumSolverIterations((int)numSolverIterations); + } + + virtual void exitPhysics() + { + m_robotSim.disconnect(); + } + + void resetCubePosition() + { + for (int i = 0; i < numCubes; i++) + { + btVector3 pos(0, i * (btScalar)0.05, 1); + btQuaternion quar(0, 0, 0, 1); + m_robotSim.resetBasePositionAndOrientation(cubeIds[i], pos, quar); + } + } + virtual void stepSimulation(float deltaTime) + { + int newSolver = (int)(solverId + 0.5); + if (newSolver != solver) + { + printf("Switching solver, new %d, old %d\n", newSolver, solver); + solver = newSolver; + resetCubePosition(); + if (solver) + { + physicsArgs.m_constraintSolverType = eConstraintSolverLCP_DANTZIG; + } + else + { + physicsArgs.m_constraintSolverType = eConstraintSolverLCP_SI; + } + + m_robotSim.setPhysicsEngineParameter(physicsArgs); + } + m_robotSim.setNumSolverIterations((int)numSolverIterations); + m_robotSim.stepSimulation(); + } + virtual void renderScene() + { + m_robotSim.renderScene(); + } + + virtual bool mouseMoveCallback(float x, float y) + { + return m_robotSim.mouseMoveCallback(x, y); + } + virtual bool mouseButtonCallback(int button, int state, float x, float y) + { + return m_robotSim.mouseButtonCallback(button, state, x, y); + } + virtual bool keyboardCallback(int key, int state) + { + return false; + } + + virtual void resetCamera() + { + float dist = 1; + float pitch = -20; + float yaw = -30; + float targetPos[3] = {0, 0.2, 0.5}; + m_guiHelper->resetCamera(dist, yaw, pitch, targetPos[0], targetPos[1], targetPos[2]); + } +}; + +class CommonExampleInterface* FixJointBoxesCreateFunc(struct CommonExampleOptions& options) +{ + return new FixJointBoxes(options.m_guiHelper, options.m_option); +} diff --git a/pool/shard011/C++/0121767_cThread.cpp b/pool/shard011/C++/0121767_cThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af0d4f841ef5885598fc3aed6633c4126ae99b6a --- /dev/null +++ b/pool/shard011/C++/0121767_cThread.cpp @@ -0,0 +1,187 @@ + /* --COPYRIGHT--, +Permissive via Author: Emad Barsoum +15. September 2011 + * --/COPYRIGHT--*/ +#include "windows.h" +#include +#include "cThread.h" + + +cThread::cThread(int nPriority) +{ + m_hThread = NULL; + m_dwThreadID = 0; + m_bTerminate = true; + m_bSuspend = true; + m_bIsRunning = false; + m_nInitPriority = nPriority; + m_hEvent = ::CreateEvent(NULL,FALSE,FALSE,NULL); +} + +bool cThread::Start() +{ + if(m_bTerminate) + { + m_hThread = (HANDLE)_beginthreadex(NULL,0,_ThreadProc,(LPVOID)this,0/* CREATE_SUSPENDED*/,&m_dwThreadID); + + m_bTerminate = false; + m_bSuspend = false; + if(m_hThread != 0) + return true; + return false; + } + else if(m_bSuspend) + { + DWORD nRet = ::ResumeThread(m_hThread); + if(nRet == 0xFFFFFFFF) + return false; + m_bSuspend = false; + return true; + } + return true; +} + +bool cThread::StartAndWait() +{ + bool bRet = Start(); + if(bRet) + ::WaitForSingleObject(m_hEvent,INFINITE); + + return bRet; +} + +bool cThread::Pause() +{ + if(m_bTerminate) + return false; + if(m_bSuspend) + return true; + DWORD nRet = ::SuspendThread(m_hThread); + if(nRet == 0xFFFFFFFF) + return false; + m_bSuspend = true; + return true; +} + +bool cThread::IsRunning() +{ + return m_bIsRunning; +} + +bool cThread::IsTerminated() +{ + return m_bTerminate; +} + +bool cThread::IsSuspend() +{ + return m_bSuspend; +} + +void cThread::Terminate() +{ + DWORD dwExitCode; + ::GetExitCodeThread(m_hThread,&dwExitCode); + if (STILL_ACTIVE == dwExitCode) + { + ::TerminateThread(m_hThread,dwExitCode); + ::CloseHandle(m_hThread); + m_hThread = NULL; + } + m_bIsRunning = false; + m_bTerminate = true; +} + +void cThread::Exit() +{ + DWORD dwExitCode; + ::GetExitCodeThread(m_hThread,&dwExitCode); + if (STILL_ACTIVE == dwExitCode) + { + _endthreadex(dwExitCode); + ::ExitThread(dwExitCode); + ::CloseHandle(m_hThread); + m_hThread = NULL; + } + m_bIsRunning = false; + m_bTerminate = true; +} + +bool cThread::WaitUntilTerminate(DWORD dwMiliSec) +{ + if(WaitForSingleObject(m_hThread,dwMiliSec) == WAIT_TIMEOUT) + return false; + m_bIsRunning = false; + m_bTerminate = true; + return true; +} + +void cThread::SetPriority(int nLevel) +{ + ::SetThreadPriority(m_hThread,nLevel); +} + +int cThread::GetPriority() +{ + return ::GetThreadPriority(m_hThread); +} + +void cThread::SpeedUp() +{ + int nOldLevel=0; + int nNewLevel=0; + + nOldLevel = GetPriority(); + if (THREAD_PRIORITY_TIME_CRITICAL == nOldLevel) + return; + else if (THREAD_PRIORITY_HIGHEST == nOldLevel) + nNewLevel = THREAD_PRIORITY_TIME_CRITICAL; + else if (THREAD_PRIORITY_ABOVE_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_HIGHEST; + else if (THREAD_PRIORITY_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_ABOVE_NORMAL; + else if (THREAD_PRIORITY_BELOW_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_NORMAL; + else if (THREAD_PRIORITY_LOWEST == nOldLevel) + nNewLevel = THREAD_PRIORITY_BELOW_NORMAL; + else if (THREAD_PRIORITY_IDLE == nOldLevel) + nNewLevel = THREAD_PRIORITY_LOWEST; + + SetPriority(nNewLevel); +} + +void cThread::SlowDown() +{ + int nOldLevel=0; + int nNewLevel=0; + + nOldLevel = GetPriority(); + if (THREAD_PRIORITY_TIME_CRITICAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_HIGHEST; + else if (THREAD_PRIORITY_HIGHEST == nOldLevel) + nNewLevel = THREAD_PRIORITY_ABOVE_NORMAL; + else if (THREAD_PRIORITY_ABOVE_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_NORMAL; + else if (THREAD_PRIORITY_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_BELOW_NORMAL; + else if (THREAD_PRIORITY_BELOW_NORMAL == nOldLevel) + nNewLevel = THREAD_PRIORITY_LOWEST; + else if (THREAD_PRIORITY_LOWEST == nOldLevel) + nNewLevel = THREAD_PRIORITY_IDLE; + else if (THREAD_PRIORITY_IDLE == nOldLevel) + return; + + SetPriority(nNewLevel); +} + +unsigned __stdcall cThread::_ThreadProc(LPVOID lpParameter) +{ + cThread* pThread = reinterpret_cast(lpParameter); + + pThread->SetPriority(pThread->m_nInitPriority); + pThread->m_bIsRunning = true; + ::SetEvent(pThread->m_hEvent); + pThread->OnInitInstance(); + pThread->OnRunning(); + return pThread->OnExitInstance(); +} diff --git a/pool/shard011/C++/0121769_crash_reporter.cc b/pool/shard011/C++/0121769_crash_reporter.cc new file mode 100644 index 0000000000000000000000000000000000000000..fc07013a39ecf2f30fcf89f765fdb25b8b734672 --- /dev/null +++ b/pool/shard011/C++/0121769_crash_reporter.cc @@ -0,0 +1,136 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/updater/crash_reporter.h" + +#include +#include +#include +#include +#include +#include + +#include "base/command_line.h" +#include "base/files/file_path.h" +#include "base/logging.h" +#include "base/path_service.h" +#include "base/strings/strcat.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "build/build_config.h" +#include "chrome/updater/constants.h" +#include "chrome/updater/updater_branding.h" +#include "chrome/updater/updater_scope.h" +#include "chrome/updater/util.h" +#include "third_party/abseil-cpp/absl/types/optional.h" +#include "third_party/crashpad/crashpad/client/crashpad_client.h" +#include "third_party/crashpad/crashpad/handler/handler_main.h" + +namespace updater { +namespace { + +crashpad::CrashpadClient& GetCrashpadClient() { + static crashpad::CrashpadClient crashpad_client; + return crashpad_client; +} + +// Returns the command line arguments to start the crash handler process with. +std::vector MakeCrashHandlerArgs(UpdaterScope updater_scope) { + base::CommandLine command_line(base::CommandLine::NO_PROGRAM); + command_line.AppendSwitch(kCrashHandlerSwitch); + command_line.AppendSwitch(kEnableLoggingSwitch); + command_line.AppendSwitchASCII(kLoggingModuleSwitch, + kLoggingModuleSwitchValue); + if (updater_scope == UpdaterScope::kSystem) { + command_line.AppendSwitch(kSystemSwitch); + } + + // The first element in the command line arguments is the program name, + // which must be skipped. +#if defined(OS_WIN) + std::vector args; + std::transform(++command_line.argv().begin(), command_line.argv().end(), + std::back_inserter(args), + [](const auto& arg) { return base::WideToUTF8(arg); }); + + return args; +#else + return {++command_line.argv().begin(), command_line.argv().end()}; +#endif +} + +} // namespace + +void StartCrashReporter(UpdaterScope updater_scope, + const std::string& version) { + static bool started = false; + DCHECK(!started); + started = true; + + base::FilePath handler_path; + base::PathService::Get(base::FILE_EXE, &handler_path); + + const absl::optional database_path = + GetVersionedDirectory(updater_scope); + if (!database_path) { + LOG(DFATAL) << "Failed to get the database path."; + return; + } + + std::map annotations; + annotations["ver"] = version; + annotations["prod"] = PRODUCT_FULLNAME_STRING; + + // TODO(crbug.com/1163583): use the production front end instead of staging. + crashpad::CrashpadClient& client = GetCrashpadClient(); + if (!client.StartHandler(handler_path, *database_path, + /*metrics_dir=*/base::FilePath(), + CRASH_STAGING_UPLOAD_URL, annotations, + MakeCrashHandlerArgs(updater_scope), + /*restartable=*/true, + /*asynchronous_start=*/false)) { + LOG(DFATAL) << "Failed to start handler."; + return; + } + + VLOG(1) << "Crash handler launched and ready."; +} + +int CrashReporterMain() { + base::CommandLine command_line = *base::CommandLine::ForCurrentProcess(); + DCHECK(command_line.HasSwitch(kCrashHandlerSwitch)); + + // Disable rate-limiting until this is fixed: + // https://bugs.chromium.org/p/crashpad/issues/detail?id=23 + command_line.AppendSwitch(kNoRateLimitSwitch); + + // Because of https://bugs.chromium.org/p/crashpad/issues/detail?id=82, + // Crashpad fails on the presence of flags it doesn't handle. + command_line.RemoveSwitch(kCrashHandlerSwitch); + command_line.RemoveSwitch(kSystemSwitch); + command_line.RemoveSwitch(kEnableLoggingSwitch); + command_line.RemoveSwitch(kLoggingModuleSwitch); + + const std::vector argv = command_line.argv(); + + // |storage| must be declared before |argv_as_utf8|, to ensure it outlives + // |argv_as_utf8|, which will hold pointers into |storage|. + std::vector storage; + auto argv_as_utf8 = std::make_unique(argv.size() + 1); + storage.reserve(argv.size()); + for (size_t i = 0; i < argv.size(); ++i) { +#if defined(OS_WIN) + storage.push_back(base::WideToUTF8(argv[i])); +#else + storage.push_back(argv[i]); +#endif + argv_as_utf8[i] = &storage[i][0]; + } + argv_as_utf8[argv.size()] = nullptr; + + return crashpad::HandlerMain(argv.size(), argv_as_utf8.get(), + /*user_stream_sources=*/nullptr); +} + +} // namespace updater diff --git a/pool/shard011/C++/0121770_Main.cpp b/pool/shard011/C++/0121770_Main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65cbd0360d198f72966f490b5ac90de1fb5b71bf --- /dev/null +++ b/pool/shard011/C++/0121770_Main.cpp @@ -0,0 +1,234 @@ +// Copyright 2015 Dolphin Emulator Project +// Licensed under GPLv2+ +// Refer to the license.txt file included. + +#ifdef _WIN32 +#include +#include + +#include "Common/StringUtil.h" +#endif + +#include +#include +#include +#include +#include +#include + +#include "Common/MsgHandler.h" + +#include "Core/Analytics.h" +#include "Core/Boot/Boot.h" +#include "Core/ConfigManager.h" +#include "Core/Core.h" + +#include "DolphinQt/Host.h" +#include "DolphinQt/MainWindow.h" +#include "DolphinQt/QtUtils/ModalMessageBox.h" +#include "DolphinQt/QtUtils/RunOnObject.h" +#include "DolphinQt/Resources.h" +#include "DolphinQt/Settings.h" +#include "DolphinQt/Translation.h" +#include "DolphinQt/Updater.h" + +#include "UICommon/CommandLineParse.h" +#include "UICommon/UICommon.h" + +static bool QtMsgAlertHandler(const char* caption, const char* text, bool yes_no, + Common::MsgType style) +{ + std::optional r = RunOnObject(QApplication::instance(), [&] { + ModalMessageBox message_box(QApplication::activeWindow(), Qt::ApplicationModal); + message_box.setWindowTitle(QString::fromUtf8(caption)); + message_box.setText(QString::fromUtf8(text)); + + message_box.setStandardButtons(yes_no ? QMessageBox::Yes | QMessageBox::No : QMessageBox::Ok); + if (style == Common::MsgType::Warning) + message_box.addButton(QMessageBox::Ignore)->setText(QObject::tr("Ignore for this session")); + + message_box.setIcon([&] { + switch (style) + { + case Common::MsgType::Information: + return QMessageBox::Information; + case Common::MsgType::Question: + return QMessageBox::Question; + case Common::MsgType::Warning: + return QMessageBox::Warning; + case Common::MsgType::Critical: + return QMessageBox::Critical; + } + // appease MSVC + return QMessageBox::NoIcon; + }()); + + const int button = message_box.exec(); + if (button == QMessageBox::Yes) + return true; + + if (button == QMessageBox::Ignore) + { + Common::SetEnableAlert(false); + return true; + } + + return false; + }); + if (r.has_value()) + return *r; + return false; +} + +// N.B. On Windows, this should be called from WinMain. Link against qtmain and specify +// /SubSystem:Windows +int main(int argc, char* argv[]) +{ +#ifdef _WIN32 + const bool console_attached = AttachConsole(ATTACH_PARENT_PROCESS) != FALSE; + HANDLE stdout_handle = ::GetStdHandle(STD_OUTPUT_HANDLE); + if (console_attached && stdout_handle) + { + freopen("CONOUT$", "w", stdout); + freopen("CONOUT$", "w", stderr); + } +#endif + + QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); + QCoreApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QCoreApplication::setOrganizationName(QStringLiteral("Dolphin Emulator")); + QCoreApplication::setOrganizationDomain(QStringLiteral("dolphin-emu.org")); + QCoreApplication::setApplicationName(QStringLiteral("dolphin-emu")); + + QApplication app(argc, argv); + +#ifdef _WIN32 + // Get the default system font because Qt's way of obtaining it is outdated + NONCLIENTMETRICS metrics = {}; + LOGFONT& logfont = metrics.lfMenuFont; + metrics.cbSize = sizeof(NONCLIENTMETRICS); + + if (SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(metrics), &metrics, 0)) + { + // Sadly Qt 5 doesn't support turning a native font handle into a QFont so this is the next best + // thing + QFont font = QApplication::font(); + font.setFamily(QString::fromStdString(UTF16ToUTF8(logfont.lfFaceName))); + + font.setItalic(logfont.lfItalic); + font.setStrikeOut(logfont.lfStrikeOut); + font.setUnderline(logfont.lfUnderline); + + // The default font size is a bit too small + font.setPointSize(QFontInfo(font).pointSize() * 1.2); + + QApplication::setFont(font); + } +#endif + + auto parser = CommandLineParse::CreateParser(CommandLineParse::ParserOptions::IncludeGUIOptions); + const optparse::Values& options = CommandLineParse::ParseArguments(parser.get(), argc, argv); + const std::vector args = parser->args(); + +#ifdef _WIN32 + FreeConsole(); +#endif + + UICommon::SetUserDirectory(static_cast(options.get("user"))); + UICommon::CreateDirectories(); + UICommon::Init(); + Resources::Init(); + Settings::Instance().SetBatchModeEnabled(options.is_set("batch") && options.is_set("exec")); + + // Hook up alerts from core + Common::RegisterMsgAlertHandler(QtMsgAlertHandler); + + // Hook up translations + Translation::Initialize(); + + // Whenever the event loop is about to go to sleep, dispatch the jobs + // queued in the Core first. + QObject::connect(QAbstractEventDispatcher::instance(), &QAbstractEventDispatcher::aboutToBlock, + &app, &Core::HostDispatchJobs); + + std::unique_ptr boot; + if (options.is_set("exec")) + { + const std::list paths_list = options.all("exec"); + const std::vector paths{std::make_move_iterator(std::begin(paths_list)), + std::make_move_iterator(std::end(paths_list))}; + boot = BootParameters::GenerateFromFile(paths); + } + else if (options.is_set("nand_title")) + { + const std::string hex_string = static_cast(options.get("nand_title")); + if (hex_string.length() == 16) + { + const u64 title_id = std::stoull(hex_string, nullptr, 16); + boot = std::make_unique(BootParameters::NANDTitle{title_id}); + } + else + { + ModalMessageBox::critical(nullptr, QObject::tr("Error"), QObject::tr("Invalid title ID.")); + } + } + else if (!args.empty()) + { + boot = BootParameters::GenerateFromFile(args.front()); + } + + int retval; + + { + DolphinAnalytics::Instance().ReportDolphinStart("qt"); + + MainWindow win{std::move(boot), static_cast(options.get("movie"))}; + if (options.is_set("debugger")) + Settings::Instance().SetDebugModeEnabled(true); + win.Show(); + +#if defined(USE_ANALYTICS) && USE_ANALYTICS + if (!SConfig::GetInstance().m_analytics_permission_asked) + { + ModalMessageBox analytics_prompt(&win); + + analytics_prompt.setIcon(QMessageBox::Question); + analytics_prompt.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + analytics_prompt.setWindowTitle(QObject::tr("Allow Usage Statistics Reporting")); + analytics_prompt.setText( + QObject::tr("Do you authorize Dolphin to report information to Dolphin's developers?")); + analytics_prompt.setInformativeText( + QObject::tr("If authorized, Dolphin can collect data on its performance, " + "feature usage, and configuration, as well as data on your system's " + "hardware and operating system.\n\n" + "No private data is ever collected. This data helps us understand " + "how people and emulated games use Dolphin and prioritize our " + "efforts. It also helps us identify rare configurations that are " + "causing bugs, performance and stability issues.\n" + "This authorization can be revoked at any time through Dolphin's " + "settings.")); + + const int answer = analytics_prompt.exec(); + + SConfig::GetInstance().m_analytics_permission_asked = true; + Settings::Instance().SetAnalyticsEnabled(answer == QMessageBox::Yes); + + DolphinAnalytics::Instance().ReloadConfig(); + } +#endif + + if (!Settings::Instance().IsBatchModeEnabled()) + { + auto* updater = new Updater(&win); + updater->start(); + } + + retval = app.exec(); + } + + Core::Shutdown(); + UICommon::Shutdown(); + Host::GetInstance()->deleteLater(); + + return retval; +} diff --git a/pool/shard011/C++/0121771_ssffile.cpp b/pool/shard011/C++/0121771_ssffile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..93dd58ec5355edc130e157c767ea7a47bda015d3 --- /dev/null +++ b/pool/shard011/C++/0121771_ssffile.cpp @@ -0,0 +1,145 @@ +/* xoreos - A reimplementation of BioWare's Aurora engine + * + * xoreos is the legal property of its developers, whose names + * can be found in the AUTHORS file distributed with this source + * distribution. + * + * xoreos 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. + * + * xoreos 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 xoreos. If not, see . + */ + +/** @file + * Handling BioWare's SSFs (sound set file). + */ + +/* See BioWare's own specs released for Neverwinter Nights modding + * () + */ + +#include "src/common/readstream.h" +#include "src/common/util.h" +#include "src/common/strutil.h" +#include "src/common/error.h" +#include "src/common/encoding.h" + +#include "src/aurora/resman.h" +#include "src/aurora/ssffile.h" + +static const uint32 kSSFID = MKTAG('S', 'S', 'F', ' '); +static const uint32 kVersion1 = MKTAG('V', '1', '.', '0'); +static const uint32 kVersion11 = MKTAG('V', '1', '.', '1'); + +namespace Aurora { + +SSFFile::SSFFile(Common::SeekableReadStream &ssf) { + load(ssf); + + _emptySound.strRef = kStrRefInvalid; +} + +SSFFile::SSFFile(const Common::UString &ssf) { + Common::SeekableReadStream *res = ResMan.getResource(ssf, kFileTypeSSF); + if (!res) + throw Common::Exception("No such SSF \"%s\"", ssf.c_str()); + + try { + load(*res); + } catch (...) { + delete res; + throw; + } + + delete res; + + _emptySound.strRef = kStrRefInvalid; +} + +SSFFile::~SSFFile() { +} + +void SSFFile::load(Common::SeekableReadStream &ssf) { + readHeader(ssf); + + if (_id != kSSFID) + throw Common::Exception("Not a SSF file (%s)", Common::debugTag(_id).c_str()); + + if ((_version != kVersion1) && (_version != kVersion11)) + throw Common::Exception("Unsupported SSF file version %s", Common::debugTag(_version).c_str()); + + size_t entryCount = 0; + if (_version == kVersion1) + entryCount = ssf.readUint32LE(); + + uint32 offEntryTable = ssf.readUint32LE(); + + if (_version == kVersion11) + entryCount = (ssf.size() - offEntryTable) / 4; + + _sounds.resize(entryCount); + + try { + + readEntries(ssf, offEntryTable); + + } catch (Common::Exception &e) { + e.add("Failed reading SSF file"); + throw; + } + +} + +void SSFFile::readEntries(Common::SeekableReadStream &ssf, uint32 offset) { + ssf.seek(offset); + + if (_version == kVersion1) + readEntries1(ssf); + else if (_version == kVersion11) + readEntries11(ssf); +} + +void SSFFile::readEntries1(Common::SeekableReadStream &ssf) { + // V1.0 begins with a list of offsets to the data entries. + // Each data entry has a ResRef of a sound file and a StrRef of a text. + + size_t count = _sounds.size(); + + std::vector offsets; + + offsets.resize(count); + + for (size_t i = 0; i < count; i++) + offsets[i] = ssf.readUint32LE(); + + for (size_t i = 0; i < count; i++) { + ssf.seek(offsets[i]); + + _sounds[i].fileName = Common::readStringFixed(ssf, Common::kEncodingASCII, 16); + _sounds[i].strRef = ssf.readUint32LE(); + } +} + +void SSFFile::readEntries11(Common::SeekableReadStream &ssf) { + // V1.1 is just a list of StrRef + + for (SoundSet::iterator sound = _sounds.begin(); sound != _sounds.end(); ++sound) + sound->strRef = ssf.readUint32LE(); +} + +const SSFFile::Sound &SSFFile::getSound(uint32 index) const { + if (index >= _sounds.size()) + return _emptySound; + + return _sounds[index]; +} + +} // End of namespace Aurora diff --git a/pool/shard011/C++/0121772_UILabel.cpp b/pool/shard011/C++/0121772_UILabel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9615496b8eec9dfde99b3da76cc3bb5fb07a14d --- /dev/null +++ b/pool/shard011/C++/0121772_UILabel.cpp @@ -0,0 +1,243 @@ +#include "StdAfx.h" +#include "UILabel.h" +#include + +namespace DuiLib +{ + + CLabelUI::CLabelUI() + : m_uTextStyle(DT_VCENTER) + , m_dwTextColor(0) + , m_dwDisabledTextColor(0) + , m_iFont(-1) + , m_bShowHtml(false) + , m_bAutoCalcWidth(false) + { + ::ZeroMemory(&m_rcTextPadding, sizeof(m_rcTextPadding)); + } + + CLabelUI::~CLabelUI() + { + + } + + LPCTSTR CLabelUI::GetClass() const + { + return _T("LabelUI"); + } + + LPVOID CLabelUI::GetInterface(LPCTSTR pstrName) + { + if( _tcscmp(pstrName, _T("Label")) == 0 ) return static_cast(this); + return CControlUI::GetInterface(pstrName); + } + + void CLabelUI::SetTextStyle(UINT uStyle) + { + m_uTextStyle = uStyle; + Invalidate(); + } + + UINT CLabelUI::GetTextStyle() const + { + return m_uTextStyle; + } + + void CLabelUI::SetTextColor(DWORD dwTextColor) + { + m_dwTextColor = dwTextColor; + Invalidate(); + } + + DWORD CLabelUI::GetTextColor() const + { + return m_dwTextColor; + } + + void CLabelUI::SetDisabledTextColor(DWORD dwTextColor) + { + m_dwDisabledTextColor = dwTextColor; + Invalidate(); + } + + DWORD CLabelUI::GetDisabledTextColor() const + { + return m_dwDisabledTextColor; + } + + void CLabelUI::SetFont(int index) + { + m_iFont = index; + Invalidate(); + } + + int CLabelUI::GetFont() const + { + return m_iFont; + } + + RECT CLabelUI::GetTextPadding() const + { + return m_rcTextPadding; + } + + void CLabelUI::SetTextPadding(RECT rc) + { + m_rcTextPadding = rc; + Invalidate(); + } + + bool CLabelUI::IsShowHtml() + { + return m_bShowHtml; + } + + void CLabelUI::SetShowHtml(bool bShowHtml) + { + if( m_bShowHtml == bShowHtml ) return; + + m_bShowHtml = bShowHtml; + Invalidate(); + } + + SIZE CLabelUI::EstimateSize(SIZE szAvailable) + { + if (m_bAutoCalcWidth) + { + RECT rcText = {0}; + + CRenderEngine::DrawText(m_pManager->GetPaintDC(), m_pManager, rcText, m_sText, m_dwTextColor, m_iFont, DT_CALCRECT | m_uTextStyle); + m_cxyFixed.cx = rcText.right - rcText.left + m_rcTextPadding.left + m_rcTextPadding.right; + } + + if( m_cxyFixed.cy == 0 ) return CSize(m_cxyFixed.cx, m_pManager->GetFontInfo(GetFont())->tm.tmHeight + 4); + return CControlUI::EstimateSize(szAvailable); + } + + void CLabelUI::DoEvent(TEventUI& event) + { + if( event.Type == UIEVENT_SETFOCUS ) + { + m_bFocused = true; + return; + } + if( event.Type == UIEVENT_KILLFOCUS ) + { + m_bFocused = false; + return; + } + if( event.Type == UIEVENT_MOUSEENTER ) + { + // return; + } + if( event.Type == UIEVENT_MOUSELEAVE ) + { + // return; + } + CControlUI::DoEvent(event); + } + + void CLabelUI::SetAttribute(LPCTSTR pstrName, LPCTSTR pstrValue) + { + if( _tcscmp(pstrName, _T("align")) == 0 ) { + if( _tcsstr(pstrValue, _T("left")) != NULL ) { + m_uTextStyle &= ~(DT_CENTER | DT_RIGHT | DT_SINGLELINE); + m_uTextStyle |= DT_LEFT; + } + if( _tcsstr(pstrValue, _T("center")) != NULL ) { + m_uTextStyle &= ~(DT_LEFT | DT_RIGHT ); + m_uTextStyle |= DT_CENTER; + } + if( _tcsstr(pstrValue, _T("right")) != NULL ) { + m_uTextStyle &= ~(DT_LEFT | DT_CENTER | DT_SINGLELINE); + m_uTextStyle |= DT_RIGHT; + } + } + else if( _tcscmp(pstrName, _T("valign")) == 0 ) { + if( _tcsstr(pstrValue, _T("top")) != NULL ) { + m_uTextStyle &= ~(DT_BOTTOM | DT_VCENTER); + m_uTextStyle |= (DT_TOP | DT_SINGLELINE); + } + if( _tcsstr(pstrValue, _T("center")) != NULL ) { + m_uTextStyle &= ~(DT_TOP | DT_BOTTOM ); + m_uTextStyle |= (DT_VCENTER | DT_SINGLELINE); + } + if( _tcsstr(pstrValue, _T("bottom")) != NULL ) { + m_uTextStyle &= ~(DT_TOP | DT_VCENTER); + m_uTextStyle |= (DT_BOTTOM | DT_SINGLELINE); + } + } + else if( _tcscmp(pstrName, _T("endellipsis")) == 0 ) { + if( _tcscmp(pstrValue, _T("true")) == 0 ) m_uTextStyle |= DT_END_ELLIPSIS; + else m_uTextStyle &= ~DT_END_ELLIPSIS; + } + else if( _tcscmp(pstrName, _T("font")) == 0 ) SetFont(_ttoi(pstrValue)); + else if( _tcscmp(pstrName, _T("textcolor")) == 0 ) { + if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); + LPTSTR pstr = NULL; + DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); + SetTextColor(clrColor); + } + else if( _tcscmp(pstrName, _T("disabledtextcolor")) == 0 ) { + if( *pstrValue == _T('#')) pstrValue = ::CharNext(pstrValue); + LPTSTR pstr = NULL; + DWORD clrColor = _tcstoul(pstrValue, &pstr, 16); + SetDisabledTextColor(clrColor); + } + else if( _tcscmp(pstrName, _T("textpadding")) == 0 ) { + RECT rcTextPadding = { 0 }; + LPTSTR pstr = NULL; + rcTextPadding.left = _tcstol(pstrValue, &pstr, 10); ASSERT(pstr); + rcTextPadding.top = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); + rcTextPadding.right = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); + rcTextPadding.bottom = _tcstol(pstr + 1, &pstr, 10); ASSERT(pstr); + SetTextPadding(rcTextPadding); + } + else if( _tcscmp(pstrName, _T("showhtml")) == 0 ) SetShowHtml(_tcscmp(pstrValue, _T("true")) == 0); + else if( _tcscmp(pstrName, _T("autocalcwidth")) == 0 ) { + SetAutoCalcWidth(_tcscmp(pstrValue, _T("true")) == 0); + } + else CControlUI::SetAttribute(pstrName, pstrValue); + } + + void CLabelUI::PaintText(HDC hDC) + { + if( m_dwTextColor == 0 ) m_dwTextColor = m_pManager->GetDefaultFontColor(); + if( m_dwDisabledTextColor == 0 ) m_dwDisabledTextColor = m_pManager->GetDefaultDisabledColor(); + + RECT rc = m_rcItem; + rc.left += m_rcTextPadding.left; + rc.right -= m_rcTextPadding.right; + rc.top += m_rcTextPadding.top; + rc.bottom -= m_rcTextPadding.bottom; + + if( m_sText.IsEmpty() ) return; + int nLinks = 0; + if( IsEnabled() ) { + if( m_bShowHtml ) + CRenderEngine::DrawHtmlText(hDC, m_pManager, rc, m_sText, m_dwTextColor, \ + NULL, NULL, nLinks, DT_SINGLELINE | m_uTextStyle); + else + CRenderEngine::DrawText(hDC, m_pManager, rc, m_sText, m_dwTextColor, \ + m_iFont, DT_SINGLELINE | m_uTextStyle); + } + else { + if( m_bShowHtml ) + CRenderEngine::DrawHtmlText(hDC, m_pManager, rc, m_sText, m_dwDisabledTextColor, \ + NULL, NULL, nLinks, DT_SINGLELINE | m_uTextStyle); + else + CRenderEngine::DrawText(hDC, m_pManager, rc, m_sText, m_dwDisabledTextColor, \ + m_iFont, DT_SINGLELINE | m_uTextStyle); + } + } + + bool CLabelUI::GetAutoCalcWidth() const + { + return m_bAutoCalcWidth; + } + + void CLabelUI::SetAutoCalcWidth(bool bAutoCalcWidth) + { + m_bAutoCalcWidth = bAutoCalcWidth; + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0121775_common.cpp b/pool/shard011/C++/0121775_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..483694d57b7e6802616a98fffa53c64d5aec3e5c --- /dev/null +++ b/pool/shard011/C++/0121775_common.cpp @@ -0,0 +1,108 @@ +//===-- common.cpp ----------------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "gwp_asan/common.h" +#include "gwp_asan/stack_trace_compressor.h" + +#include + +using AllocationMetadata = gwp_asan::AllocationMetadata; +using Error = gwp_asan::Error; + +namespace gwp_asan { + +const char *ErrorToString(const Error &E) { + switch (E) { + case Error::UNKNOWN: + return "Unknown"; + case Error::USE_AFTER_FREE: + return "Use After Free"; + case Error::DOUBLE_FREE: + return "Double Free"; + case Error::INVALID_FREE: + return "Invalid (Wild) Free"; + case Error::BUFFER_OVERFLOW: + return "Buffer Overflow"; + case Error::BUFFER_UNDERFLOW: + return "Buffer Underflow"; + } + __builtin_trap(); +} + +constexpr size_t AllocationMetadata::kStackFrameStorageBytes; +constexpr size_t AllocationMetadata::kMaxTraceLengthToCollect; + +void AllocationMetadata::RecordAllocation(uintptr_t AllocAddr, + size_t AllocSize) { + Addr = AllocAddr; + Size = AllocSize; + IsDeallocated = false; + + AllocationTrace.ThreadID = getThreadID(); + DeallocationTrace.TraceSize = 0; + DeallocationTrace.ThreadID = kInvalidThreadID; +} + +void AllocationMetadata::RecordDeallocation() { + IsDeallocated = true; + DeallocationTrace.ThreadID = getThreadID(); +} + +void AllocationMetadata::CallSiteInfo::RecordBacktrace( + options::Backtrace_t Backtrace) { + TraceSize = 0; + if (!Backtrace) + return; + + uintptr_t UncompressedBuffer[kMaxTraceLengthToCollect]; + size_t BacktraceLength = + Backtrace(UncompressedBuffer, kMaxTraceLengthToCollect); + // Backtrace() returns the number of available frames, which may be greater + // than the number of frames in the buffer. In this case, we need to only pack + // the number of frames that are in the buffer. + if (BacktraceLength > kMaxTraceLengthToCollect) + BacktraceLength = kMaxTraceLengthToCollect; + TraceSize = + compression::pack(UncompressedBuffer, BacktraceLength, CompressedTrace, + AllocationMetadata::kStackFrameStorageBytes); +} + +size_t AllocatorState::maximumAllocationSize() const { return PageSize; } + +uintptr_t AllocatorState::slotToAddr(size_t N) const { + return GuardedPagePool + (PageSize * (1 + N)) + (maximumAllocationSize() * N); +} + +bool AllocatorState::isGuardPage(uintptr_t Ptr) const { + assert(pointerIsMine(reinterpret_cast(Ptr))); + size_t PageOffsetFromPoolStart = (Ptr - GuardedPagePool) / PageSize; + size_t PagesPerSlot = maximumAllocationSize() / PageSize; + return (PageOffsetFromPoolStart % (PagesPerSlot + 1)) == 0; +} + +static size_t addrToSlot(const AllocatorState *State, uintptr_t Ptr) { + size_t ByteOffsetFromPoolStart = Ptr - State->GuardedPagePool; + return ByteOffsetFromPoolStart / + (State->maximumAllocationSize() + State->PageSize); +} + +size_t AllocatorState::getNearestSlot(uintptr_t Ptr) const { + if (Ptr <= GuardedPagePool + PageSize) + return 0; + if (Ptr > GuardedPagePoolEnd - PageSize) + return MaxSimultaneousAllocations - 1; + + if (!isGuardPage(Ptr)) + return addrToSlot(this, Ptr); + + if (Ptr % PageSize <= PageSize / 2) + return addrToSlot(this, Ptr - PageSize); // Round down. + return addrToSlot(this, Ptr + PageSize); // Round up. +} + +} // namespace gwp_asan diff --git a/pool/shard011/C++/0121776_pet_load.cpp b/pool/shard011/C++/0121776_pet_load.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3d67cf6d71eb40982480f2a7e3f502b106e9cf0a --- /dev/null +++ b/pool/shard011/C++/0121776_pet_load.cpp @@ -0,0 +1,70 @@ +/* ScummVM - Graphic Adventure Engine + * + * ScummVM is the legal property of its developers, whose names + * are too numerous to list here. Please refer to the COPYRIGHT + * file distributed with this source distribution. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * + */ + +#include "titanic/pet_control/pet_load.h" +#include "titanic/pet_control/pet_control.h" +#include "titanic/core/project_item.h" +#include "titanic/game_manager.h" +#include "titanic/titanic.h" + +namespace Titanic { + +bool CPetLoad::reset() { + CPetLoadSave::reset(); + + CPetControl *pet = getPetControl(); + if (pet) { + setName("PetLoad", pet); + _btnLoadSave.reset("PetLoadOut", pet, MODE_UNSELECTED); + _btnLoadSave.reset("PetLoadIn", pet, MODE_SELECTED); + } + + return true; +} + +bool CPetLoad::MouseButtonUpMsg(const Point &pt) { + if (_btnLoadSave.MouseButtonUpMsg(pt)) { + execute(); + return true; + } else { + return false; + } +} + +void CPetLoad::getTooltip(CPetText *text) { + text->setText("Load the game."); +} + +void CPetLoad::execute() { + CPetControl *pet = getPetControl(); + + if (_savegameSlotNum >= 0 && _slotInUse[_savegameSlotNum]) { + CMainGameWindow *window = g_vm->_window; + + // WORKAROUND: Schedule the savegame to be loaded after frame rendering ends + window->loadGame(_savegameSlotNum); + } else if (pet) { + pet->displayMessage(SELECT_GAME_TO_LOAD); + } +} + +} // End of namespace Titanic diff --git a/pool/shard011/C++/0121777_dcodecomment.cpp b/pool/shard011/C++/0121777_dcodecomment.cpp new file mode 100644 index 0000000000000000000000000000000000000000..47575fc7a4427372d44a6996bfe6758a30534148 --- /dev/null +++ b/pool/shard011/C++/0121777_dcodecomment.cpp @@ -0,0 +1,77 @@ +/*************************************************************************** + * 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. * + * * + * copyright (C) 2007 Jari-Matti Mäkelä * + * copyright (C) 2008 * + * Umbrello UML Modeller Authors * + ***************************************************************************/ + +// own header +#include "dcodecomment.h" + +// qt/kde includes +#include + +DCodeComment::DCodeComment ( CodeDocument * doc, const QString & text ) + : CodeComment (doc, text) +{ +} + +DCodeComment::~DCodeComment ( ) +{ +} + +void DCodeComment::saveToXMI ( QDomDocument & doc, QDomElement & root ) +{ + QDomElement blockElement = doc.createElement( "dcodecomment" ); + + // as we added no additional fields to this class we may + // just use parent TextBlock method + setAttributesOnNode(doc, blockElement); + root.appendChild( blockElement ); +} + +QString DCodeComment::toString ( ) const +{ + QString output; + + // simple output method + if(getWriteOutText()) + { + QString indent = getIndentationString(); + QString endLine = getNewLineEndingChars(); + QString body = getText(); + + // check the need for multiline comments + if (body.indexOf(QRegExp(endLine)) >= 0) { + output += indent + "/**" + endLine; + output += formatMultiLineText (body, indent + " * ", endLine); + output += indent + " */" + endLine; + } else { + output += formatMultiLineText (body, indent + "// ", endLine); + } + } + + return output; +} + +// TODO: where is this used? +QString DCodeComment::getNewEditorLine ( int amount ) +{ + QString line = getIndentationString(amount) + "// "; + return line; +} + +// TODO: where is this used? +QString DCodeComment::unformatText ( const QString & text , const QString & indent) +{ + // remove leading or trailing comment stuff + QString mytext = TextBlock::unformatText(text, indent); + + // now leading slashes + mytext.remove(QRegExp("^\\/\\/\\s*")); + return mytext; +} diff --git a/pool/shard011/C++/0121778_ThreadPoolTest.cpp b/pool/shard011/C++/0121778_ThreadPoolTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c04967257a5ea9d282dc468089fa5623f21f3ad0 --- /dev/null +++ b/pool/shard011/C++/0121778_ThreadPoolTest.cpp @@ -0,0 +1,162 @@ +// +// ThreadPoolTest.cpp +// +// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. +// and Contributors. +// +// SPDX-License-Identifier: BSL-1.0 +// + + +#include "ThreadPoolTest.h" +#include "CppUnit/TestCaller.h" +#include "CppUnit/TestSuite.h" +#include "Poco/ThreadPool.h" +#include "Poco/RunnableAdapter.h" +#include "Poco/Exception.h" +#include "Poco/Thread.h" + + +using Poco::ThreadPool; +using Poco::RunnableAdapter; +using Poco::Thread; + + +ThreadPoolTest::ThreadPoolTest(const std::string& name): CppUnit::TestCase(name), _event(false) +{ +} + + +ThreadPoolTest::~ThreadPoolTest() +{ +} + + +void ThreadPoolTest::testThreadPool() +{ + ThreadPool pool(2, 3, 3); + pool.setStackSize(1); + + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 0); + assertTrue (pool.capacity() == 3); + assertTrue (pool.available() == 3); + pool.addCapacity(1); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 0); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 4); + + RunnableAdapter ra(*this, &ThreadPoolTest::count); + pool.start(ra); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 1); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 3); + + pool.start(ra); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 2); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 2); + + pool.start(ra); + assertTrue (pool.allocated() == 3); + assertTrue (pool.used() == 3); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 1); + + pool.start(ra); + assertTrue (pool.allocated() == 4); + assertTrue (pool.used() == 4); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 0); + + try + { + pool.start(ra); + failmsg("thread pool exhausted - must throw exception"); + } + catch (Poco::NoThreadAvailableException&) + { + } + catch (...) + { + failmsg("wrong exception thrown"); + } + + _event.set(); // go!!! + pool.joinAll(); + + assertTrue (_count == 40000); + + assertTrue (pool.allocated() == 4); + assertTrue (pool.used() == 0); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 4); + + Thread::sleep(4000); + + pool.collect(); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 0); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 4); + + _count = 0; + _event.reset(); + pool.start(ra); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 1); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 3); + + pool.start(ra); + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 2); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 2); + _event.set(); // go!!! + pool.joinAll(); + + assertTrue (_count == 20000); + + assertTrue (pool.allocated() == 2); + assertTrue (pool.used() == 0); + assertTrue (pool.capacity() == 4); + assertTrue (pool.available() == 4); +} + + +void ThreadPoolTest::setUp() +{ + _event.reset(); + _count = 0; +} + + +void ThreadPoolTest::tearDown() +{ +} + + +void ThreadPoolTest::count() +{ + _event.wait(); + for (int i = 0; i < 10000; ++i) + { + _mutex.lock(); + ++_count; + _mutex.unlock(); + } +} + + +CppUnit::Test* ThreadPoolTest::suite() +{ + CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("ThreadPoolTest"); + + CppUnit_addTest(pSuite, ThreadPoolTest, testThreadPool); + + return pSuite; +} diff --git a/pool/shard011/C++/0121779_pxodbccompat.cpp b/pool/shard011/C++/0121779_pxodbccompat.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d4a9db2a555987dd1357899290b198be93115877 --- /dev/null +++ b/pool/shard011/C++/0121779_pxodbccompat.cpp @@ -0,0 +1,31 @@ + +#include "pxodbc.h" + +bool Text_EqualsI(PyObject* lhs, const char* rhs) +{ +#if PY_MAJOR_VERSION < 3 + // In Python 2, allow ANSI strings. + if (lhs && PyString_Check(lhs)) + return _strcmpi(PyString_AS_STRING(lhs), rhs) == 0; +#endif + + if (lhs == 0 || !PyUnicode_Check(lhs)) + return false; + + Py_ssize_t cchLHS = PyUnicode_GET_SIZE(lhs); + Py_ssize_t cchRHS = (Py_ssize_t)strlen(rhs); + if (cchLHS != cchRHS) + return false; + + Py_UNICODE* p = PyUnicode_AS_UNICODE(lhs); + for (Py_ssize_t i = 0; i < cchLHS; i++) + { + int chL = (int)Py_UNICODE_TOUPPER(p[i]); + int chR = (int)toupper(rhs[i]); + if (chL != chR) + return false; + } + + return true; +} + diff --git a/pool/shard011/C++/0121781_UpdateProjectRequest.cpp b/pool/shard011/C++/0121781_UpdateProjectRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1c1c2336a4a7e824aac07f677c0eee4de9adbcd --- /dev/null +++ b/pool/shard011/C++/0121781_UpdateProjectRequest.cpp @@ -0,0 +1,204 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::CodeBuild::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +UpdateProjectRequest::UpdateProjectRequest() : + m_nameHasBeenSet(false), + m_descriptionHasBeenSet(false), + m_sourceHasBeenSet(false), + m_secondarySourcesHasBeenSet(false), + m_sourceVersionHasBeenSet(false), + m_secondarySourceVersionsHasBeenSet(false), + m_artifactsHasBeenSet(false), + m_secondaryArtifactsHasBeenSet(false), + m_cacheHasBeenSet(false), + m_environmentHasBeenSet(false), + m_serviceRoleHasBeenSet(false), + m_timeoutInMinutes(0), + m_timeoutInMinutesHasBeenSet(false), + m_queuedTimeoutInMinutes(0), + m_queuedTimeoutInMinutesHasBeenSet(false), + m_encryptionKeyHasBeenSet(false), + m_tagsHasBeenSet(false), + m_vpcConfigHasBeenSet(false), + m_badgeEnabled(false), + m_badgeEnabledHasBeenSet(false), + m_logsConfigHasBeenSet(false), + m_fileSystemLocationsHasBeenSet(false), + m_buildBatchConfigHasBeenSet(false) +{ +} + +Aws::String UpdateProjectRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_nameHasBeenSet) + { + payload.WithString("name", m_name); + + } + + if(m_descriptionHasBeenSet) + { + payload.WithString("description", m_description); + + } + + if(m_sourceHasBeenSet) + { + payload.WithObject("source", m_source.Jsonize()); + + } + + if(m_secondarySourcesHasBeenSet) + { + Array secondarySourcesJsonList(m_secondarySources.size()); + for(unsigned secondarySourcesIndex = 0; secondarySourcesIndex < secondarySourcesJsonList.GetLength(); ++secondarySourcesIndex) + { + secondarySourcesJsonList[secondarySourcesIndex].AsObject(m_secondarySources[secondarySourcesIndex].Jsonize()); + } + payload.WithArray("secondarySources", std::move(secondarySourcesJsonList)); + + } + + if(m_sourceVersionHasBeenSet) + { + payload.WithString("sourceVersion", m_sourceVersion); + + } + + if(m_secondarySourceVersionsHasBeenSet) + { + Array secondarySourceVersionsJsonList(m_secondarySourceVersions.size()); + for(unsigned secondarySourceVersionsIndex = 0; secondarySourceVersionsIndex < secondarySourceVersionsJsonList.GetLength(); ++secondarySourceVersionsIndex) + { + secondarySourceVersionsJsonList[secondarySourceVersionsIndex].AsObject(m_secondarySourceVersions[secondarySourceVersionsIndex].Jsonize()); + } + payload.WithArray("secondarySourceVersions", std::move(secondarySourceVersionsJsonList)); + + } + + if(m_artifactsHasBeenSet) + { + payload.WithObject("artifacts", m_artifacts.Jsonize()); + + } + + if(m_secondaryArtifactsHasBeenSet) + { + Array secondaryArtifactsJsonList(m_secondaryArtifacts.size()); + for(unsigned secondaryArtifactsIndex = 0; secondaryArtifactsIndex < secondaryArtifactsJsonList.GetLength(); ++secondaryArtifactsIndex) + { + secondaryArtifactsJsonList[secondaryArtifactsIndex].AsObject(m_secondaryArtifacts[secondaryArtifactsIndex].Jsonize()); + } + payload.WithArray("secondaryArtifacts", std::move(secondaryArtifactsJsonList)); + + } + + if(m_cacheHasBeenSet) + { + payload.WithObject("cache", m_cache.Jsonize()); + + } + + if(m_environmentHasBeenSet) + { + payload.WithObject("environment", m_environment.Jsonize()); + + } + + if(m_serviceRoleHasBeenSet) + { + payload.WithString("serviceRole", m_serviceRole); + + } + + if(m_timeoutInMinutesHasBeenSet) + { + payload.WithInteger("timeoutInMinutes", m_timeoutInMinutes); + + } + + if(m_queuedTimeoutInMinutesHasBeenSet) + { + payload.WithInteger("queuedTimeoutInMinutes", m_queuedTimeoutInMinutes); + + } + + if(m_encryptionKeyHasBeenSet) + { + payload.WithString("encryptionKey", m_encryptionKey); + + } + + if(m_tagsHasBeenSet) + { + Array tagsJsonList(m_tags.size()); + for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) + { + tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); + } + payload.WithArray("tags", std::move(tagsJsonList)); + + } + + if(m_vpcConfigHasBeenSet) + { + payload.WithObject("vpcConfig", m_vpcConfig.Jsonize()); + + } + + if(m_badgeEnabledHasBeenSet) + { + payload.WithBool("badgeEnabled", m_badgeEnabled); + + } + + if(m_logsConfigHasBeenSet) + { + payload.WithObject("logsConfig", m_logsConfig.Jsonize()); + + } + + if(m_fileSystemLocationsHasBeenSet) + { + Array fileSystemLocationsJsonList(m_fileSystemLocations.size()); + for(unsigned fileSystemLocationsIndex = 0; fileSystemLocationsIndex < fileSystemLocationsJsonList.GetLength(); ++fileSystemLocationsIndex) + { + fileSystemLocationsJsonList[fileSystemLocationsIndex].AsObject(m_fileSystemLocations[fileSystemLocationsIndex].Jsonize()); + } + payload.WithArray("fileSystemLocations", std::move(fileSystemLocationsJsonList)); + + } + + if(m_buildBatchConfigHasBeenSet) + { + payload.WithObject("buildBatchConfig", m_buildBatchConfig.Jsonize()); + + } + + return payload.View().WriteReadable(); +} + +Aws::Http::HeaderValueCollection UpdateProjectRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodeBuild_20161006.UpdateProject")); + return headers; + +} + + + + diff --git a/pool/shard011/C++/0121784_Marker.cpp b/pool/shard011/C++/0121784_Marker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18c7ca54aab21d52b6f668f9daa011baf15d2949 --- /dev/null +++ b/pool/shard011/C++/0121784_Marker.cpp @@ -0,0 +1,142 @@ +/*********************************************************************/ +/* Copyright (c) 2011 - 2012, The University of Texas at Austin. */ +/* All rights reserved. */ +/* */ +/* Redistribution and use in source and binary forms, with or */ +/* without modification, are permitted provided that the following */ +/* conditions are met: */ +/* */ +/* 1. Redistributions of source code must retain the above */ +/* copyright notice, this list of conditions and the following */ +/* disclaimer. */ +/* */ +/* 2. Redistributions in binary form must reproduce the above */ +/* copyright notice, this list of conditions and the following */ +/* disclaimer in the documentation and/or other materials */ +/* provided with the distribution. */ +/* */ +/* THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY OF TEXAS AT */ +/* AUSTIN ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, */ +/* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF */ +/* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE */ +/* DISCLAIMED. IN NO EVENT SHALL THE UNIVERSITY OF TEXAS AT */ +/* AUSTIN OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ +/* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES */ +/* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE */ +/* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR */ +/* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF */ +/* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT */ +/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT */ +/* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ +/* POSSIBILITY OF SUCH DAMAGE. */ +/* */ +/* The views and conclusions contained in the software and */ +/* documentation are those of the authors and should not be */ +/* interpreted as representing official policies, either expressed */ +/* or implied, of The University of Texas at Austin. */ +/*********************************************************************/ + +#include "Marker.h" +#include "log.h" +#include "main.h" +#include + +GLuint Marker::textureId_ = 0; + +Marker::Marker() +{ + x_ = y_ = 0.; + + if(g_mpiRank != 0 && textureId_ == 0 && g_mainWindow->getGLWindow() != NULL) + { + // load marker texture + std::string markerImageFilename = std::string(g_displayClusterDir) + std::string("/data/") + std::string(MARKER_IMAGE_FILENAME); + + QImage image(markerImageFilename.c_str()); + + if(image.isNull() == true) + { + put_flog(LOG_ERROR, "error loading marker texture %s", markerImageFilename.c_str()); + return; + } + + textureId_ = g_mainWindow->getGLWindow()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, QGLContext::DefaultBindOption); + } +} + +void Marker::setPosition(float x, float y) +{ + x_ = x; + y_ = y; + updatedTimestamp_ = *(g_displayGroupManager->getTimestamp()); + + emit(positionChanged()); +} + +void Marker::getPosition(float &x, float &y) +{ + x = x_; + y = y_; +} + +bool Marker::getActive() +{ + if((*(g_displayGroupManager->getTimestamp()) - updatedTimestamp_).total_seconds() > MARKER_TIMEOUT_SECONDS) + { + return false; + } + else + { + return true; + } +} + +void Marker::render() +{ + // only render recently active markers + if(getActive() == false) + { + return; + } + + float markerWidth = MARKER_WIDTH; + + // marker height needs to be scaled by the tiled display aspect ratio + float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight(); + float markerHeight = markerWidth * tiledDisplayAspect; + + // draw the texture + glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT); + + // disable depth testing and enable blending + glDisable(GL_DEPTH_TEST); + + glEnable(GL_BLEND); + glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); + + // enable texturing + glEnable(GL_TEXTURE_2D); + glBindTexture(GL_TEXTURE_2D, textureId_); + + glPushMatrix(); + glTranslated(x_, y_, 0.); + + glBegin(GL_QUADS); + + glTexCoord2f(0,0); + glVertex2f(-markerWidth,-markerHeight); + + glTexCoord2f(1,0); + glVertex2f(markerWidth,-markerHeight); + + glTexCoord2f(1,1); + glVertex2f(markerWidth,markerHeight); + + glTexCoord2f(0,1); + glVertex2f(-markerWidth,markerHeight); + + glEnd(); + + glPopMatrix(); + glPopAttrib(); +} diff --git a/pool/shard011/C++/0121785_PlayerHit.cpp b/pool/shard011/C++/0121785_PlayerHit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e4d4a68361af0528dcf83768eda5fd927b6cac1 --- /dev/null +++ b/pool/shard011/C++/0121785_PlayerHit.cpp @@ -0,0 +1,40 @@ +#include "PlayerHit.h" + + + +// Constructor +PlayerHit::PlayerHit() +{ + this->type_ = PacketType::PLAYERHIT; +} +PlayerHit::PlayerHit(byte *b, int i) : Packet(b, i) +{ + this->type_ = PacketType::PLAYERHIT; + read(); +} +PlayerHit::PlayerHit(Packet &p) : Packet(p) +{ + this->type_ = PacketType::PLAYERHIT; + read(); +} + +Packet *PlayerHit::write() +{ + // Clear the packet data just to be safe + this->clearData(); + // Write data + this->writeBytes(bulletId); + this->writeBytes(objectId); + // Send the packet + return this; +} + +void PlayerHit::read() +{ + // Make sure the index is set to 0 + this->setIndex(0); + // Read in the data + bulletId = this->readBytes(); + objectId = this->readBytes(); + // done! +} \ No newline at end of file diff --git a/pool/shard011/C++/0121786_sampling.cpp b/pool/shard011/C++/0121786_sampling.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e813905fa38ddcd78af451d9e83ee42cc42e8b76 --- /dev/null +++ b/pool/shard011/C++/0121786_sampling.cpp @@ -0,0 +1,120 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include "../include/helper.h" + + +int computeWeights( pcl::PointCloud::Ptr pc, int num_pts, float sigma_sq, int K,std::vector& imp_wt){ + + pcl::KdTreeFLANN kdtree; + kdtree.setInputCloud (pc); + printf("loaded point cloud into kdtree object for fast neighbor search \n"); + + float feature_length = 6; + float normalization_sum = 0.0; + float sum_p; + + for(int i = 0 ; i < num_pts ; i++){ + + std::vector pointIdxNKNSearch(K); + std::vector pointNKNSquaredDistance(K); + pcl::PointXYZRGB searchPoint = pc->points[i]; + float Aij_ew; + imp_wt[i] = 0.0; + std::vector sum_nbr(feature_length,0.0); + + if ( kdtree.nearestKSearch (searchPoint, K, pointIdxNKNSearch, pointNKNSquaredDistance) > 0 ) + { + std::vector x_j_feature(feature_length,0.0); + for (size_t j = 1; j < pointIdxNKNSearch.size(); ++j) + { + int x_j = pointIdxNKNSearch[j]; + + Aij_ew = exp(-1.0*(pointNKNSquaredDistance[j]/sigma_sq)); + + x_j_feature[0] = Aij_ew * pc->points[x_j].x; + x_j_feature[1] = Aij_ew * pc->points[x_j].y; + x_j_feature[2] = Aij_ew * pc->points[x_j].z; + x_j_feature[3] = Aij_ew * ((float(pc->points[x_j].r))/255.0); + x_j_feature[4] = Aij_ew * ((float(pc->points[x_j].g))/255.0); + x_j_feature[5] = Aij_ew * ((float(pc->points[x_j].b))/255.0); + + sum_nbr = operator+(sum_nbr,x_j_feature); + + } + + //compute norm: + float norm_sum = 0.0; + norm_sum += pow(sum_nbr[0]-searchPoint.x,2.0); + norm_sum += pow(sum_nbr[1] - searchPoint.y,2.0); + norm_sum += pow(sum_nbr[2] - searchPoint.z,2.0); + norm_sum += pow(sum_nbr[3] - ((float) searchPoint.r)/255.0,2.0); + norm_sum += pow(sum_nbr[4]- ((float) searchPoint.g)/255.0,2.0); + norm_sum += pow(sum_nbr[5] - ((float) searchPoint.b)/255.0,2.0); + imp_wt[i] = norm_sum; + } + else{ + printf("hello, found no neighbors\n"); + imp_wt[i] = 0.0; + } + normalization_sum += imp_wt[i]; +} + +for(int i = 0 ; i < num_pts ; i++){ + imp_wt[i] = imp_wt[i] / normalization_sum; +} + +return(1); +} + + +std::vector weightedRandomSample (std::vector weights, int num_pts, int total_samples){ + + srand (static_cast (time(0))); + std::vector samples(num_pts,0); + std::vector imp_wt_rs(num_pts,0.0); + + // calculate rolling sum of weights: + for (int i = 1 ; i< num_pts ; i++){ + imp_wt_rs[i] = imp_wt_rs[i-1] + weights[i-1]; + } + + for (int i = 0 ; i < total_samples ; i++){ + float r = static_cast (rand()) / static_cast (RAND_MAX); + // find bin: + for (int j = 0 ; j < num_pts-1; j++){ + if(r <= imp_wt_rs[j+1] && r >= imp_wt_rs[j]){ + samples[i] = j; + //printf("r: %f, low: %f, high: %f \n",r,imp_wt_rs[j],imp_wt_rs[j+1]); + //printf("sampleidx: %d, imp_wt: %0.9f \n ", j, imp_wt[j]); + break; + } + } + if(r>imp_wt_rs[num_pts-1]){ + samples[i] = num_pts-1; + } +} + +return(samples); +} + +void resamplePC(pcl::PointCloud::Ptr pc, pcl::PointCloud::Ptr pc_rs, + std::vector samples, int total_samples){ + pc_rs->width = total_samples; + pc_rs->height = 1; + pc_rs->points.resize(pc_rs->height * pc_rs->width); + + for (int i =0 ; i < total_samples ;i++){ + pc_rs->points[i].x = pc->points[samples[i]].x; + pc_rs->points[i].y = pc->points[samples[i]].y; + pc_rs->points[i].z = pc->points[samples[i]].z; + pc_rs->points[i].r = pc->points[samples[i]].r; + pc_rs->points[i].g = pc->points[samples[i]].g; + pc_rs->points[i].b = pc->points[samples[i]].b; + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0121787_variations_crash_keys_chromeos_unittest.cc b/pool/shard011/C++/0121787_variations_crash_keys_chromeos_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..ae0c6059e8deb1aaa6a1d2e5b46ad52982b7823f --- /dev/null +++ b/pool/shard011/C++/0121787_variations_crash_keys_chromeos_unittest.cc @@ -0,0 +1,89 @@ +// Copyright 2021 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/variations/variations_crash_keys_chromeos.h" + +#include "base/base_paths.h" +#include "base/files/file_util.h" +#include "base/files/scoped_temp_dir.h" +#include "base/metrics/field_trial.h" +#include "base/run_loop.h" +#include "base/test/scoped_path_override.h" +#include "base/test/task_environment.h" +#include "components/crash/core/common/crash_key.h" +#include "components/variations/synthetic_trials_active_group_id_provider.h" +#include "components/variations/variations_crash_keys.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace variations { +namespace { + +class VariationsCrashKeysChromeOsTest : public ::testing::Test { + public: + VariationsCrashKeysChromeOsTest() { + crash_reporter::ResetCrashKeysForTesting(); + crash_reporter::InitializeCrashKeysForTesting(); + } + + VariationsCrashKeysChromeOsTest(const VariationsCrashKeysChromeOsTest&) = + delete; + VariationsCrashKeysChromeOsTest& operator=( + const VariationsCrashKeysChromeOsTest&) = delete; + + ~VariationsCrashKeysChromeOsTest() override { + SyntheticTrialsActiveGroupIdProvider::GetInstance()->ResetForTesting(); + ClearCrashKeysInstanceForTesting(); + crash_reporter::ResetCrashKeysForTesting(); + } + + protected: + base::test::TaskEnvironment task_environment_; +}; + +TEST_F(VariationsCrashKeysChromeOsTest, WritesVariationsList) { + // Override the homedir so that the class writes to a known location we can + // check. + base::ScopedTempDir dir; + ASSERT_TRUE(dir.CreateUniqueTempDir()); + const base::FilePath& home_path = dir.GetPath(); + base::ScopedPathOverride home_override(base::DIR_HOME, home_path); + base::FilePath variations_list_path = + home_path.Append(".variations-list.txt"); + + // Start with 2 trials, one active and one not + base::FieldTrialList::CreateFieldTrial("Trial1", "Group1")->group(); + base::FieldTrialList::CreateFieldTrial("Trial2", "Group2"); + + InitCrashKeys(); + + base::RunLoop().RunUntilIdle(); + task_environment_.RunUntilIdle(); + + ExperimentListInfo info = GetExperimentListInfo(); + EXPECT_EQ(1, info.num_experiments); + EXPECT_EQ("8e7abfb0-c16397b7,", info.experiment_list); + + std::string contents; + ASSERT_TRUE(base::ReadFileToString(variations_list_path, &contents)); + EXPECT_EQ(contents, + "num-experiments=1\n" + "variations=8e7abfb0-c16397b7,\n"); + + // Now, activate Trial2. + EXPECT_EQ("Group2", base::FieldTrialList::FindFullName("Trial2")); + base::RunLoop().RunUntilIdle(); + task_environment_.RunUntilIdle(); + + info = GetExperimentListInfo(); + EXPECT_EQ(2, info.num_experiments); + EXPECT_EQ("8e7abfb0-c16397b7,277f2a3d-d77354d0,", info.experiment_list); + + ASSERT_TRUE(base::ReadFileToString(variations_list_path, &contents)); + EXPECT_EQ(contents, + "num-experiments=2\n" + "variations=8e7abfb0-c16397b7,277f2a3d-d77354d0,\n"); +} + +} // namespace +} // namespace variations diff --git a/pool/shard011/C++/0121788_stack.cpp b/pool/shard011/C++/0121788_stack.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c00ed1830c2fa1b79684cf2f1de4ec6ea0f9361 --- /dev/null +++ b/pool/shard011/C++/0121788_stack.cpp @@ -0,0 +1,88 @@ +/* +* (C) 2002 Jack Lloyd +* +* Distributed under the terms of the Botan license +*/ + +/* +An Botan example application showing how to use the pop and prepend +functions of Pipe. Based on the md5 example. It's output should always +be identical to such. +*/ + +#include +#include +#include + +int main(int argc, char* argv[]) + { + if(argc < 2) + { + std::cout << "Usage: " << argv[0] << " " << std::endl; + return 1; + } + + Botan::LibraryInitializer init; + + // this is a pretty vacuous example, but it's useful as a test + Botan::Pipe pipe; + + // CPS == Current Pipe Status, ie what Filters are set up + + pipe.prepend(new Botan::Hash_Filter("MD5")); + // CPS: MD5 + + pipe.prepend(new Botan::Hash_Filter("RIPEMD-160")); + // CPS: RIPEMD-160 | MD5 + + pipe.prepend(new Botan::Chain( + new Botan::Hash_Filter("RIPEMD-160"), + new Botan::Hash_Filter("RIPEMD-160"))); + // CPS: (RIPEMD-160 | RIPEMD-160) | RIPEMD-160 | MD5 + + pipe.pop(); // will pop everything inside the Chain as well as Chain itself + // CPS: RIPEMD-160 | MD5 + + pipe.pop(); // will get rid of the RIPEMD-160 Hash_Filter + // CPS: MD5 + + pipe.prepend(new Botan::Hash_Filter("SHA-1")); + // CPS: SHA-1 | MD5 + + pipe.append(new Botan::Hex_Encoder); + // CPS: SHA-1 | MD5 | Hex_Encoder + + pipe.prepend(new Botan::Hash_Filter("SHA-1")); + // CPS: SHA-1 | SHA-1 | MD5 | Hex_Encoder + + pipe.pop(); // Get rid of the Hash_Filter(SHA-1) + pipe.pop(); // Get rid of the other Hash_Filter(SHA-1) + // CPS: MD5 | Hex_Encoder + // The Hex_Encoder is safe because it is at the end of the Pipe, + // and pop() pulls off the Filter that is at the start. + + pipe.prepend(new Botan::Hash_Filter("RIPEMD-160")); + // CPS: RIPEMD-160 | MD5 | Hex_Encoder + + pipe.pop(); // Get rid of that last prepended Hash_Filter(RIPEMD-160) + // CPS: MD5 | Hex_Encoder + + int skipped = 0; + for(int j = 1; argv[j] != 0; j++) + { + std::ifstream file(argv[j], std::ios::binary); + if(!file) + { + std::cout << "ERROR: could not open " << argv[j] << std::endl; + skipped++; + continue; + } + pipe.start_msg(); + file >> pipe; + pipe.end_msg(); + file.close(); + pipe.set_default_msg(j-1-skipped); + std::cout << pipe << " " << argv[j] << std::endl; + } + return 0; + } diff --git a/pool/shard011/C++/0121789_resources.cpp b/pool/shard011/C++/0121789_resources.cpp new file mode 100644 index 0000000000000000000000000000000000000000..04b52be40fbde7c95f1e260298e1795039008756 --- /dev/null +++ b/pool/shard011/C++/0121789_resources.cpp @@ -0,0 +1,193 @@ +/*+**************************************************************************/ +/*** ***/ +/*** This file is distributed under a BSD license. ***/ +/*** See LICENSE.txt for details. ***/ +/*** ***/ +/**************************************************************************+*/ + +#include "resources.hpp" +#include "base/system.hpp" +#include "util/image.hpp" + +sResourceManager_ *sResourceManager; + +/****************************************************************************/ + +void sExitResourceManager() +{ + sDelete(sResourceManager); +} + +void sAddResourceManager() +{ + if(!sResourceManager) + { + sResourceManager = new sResourceManager_; + sAddSubsystem(L"sResourceManager",0x40,0,sExitResourceManager); + } +} + +/****************************************************************************/ + +sResourceManager_::sResourceManager_() +{ + for(sInt i=0;iRefCount==0) + delete r; + else + i++; + } + for(sInt i=0;iRefCount==0) + delete r; + else + i++; + } + for(sInt i=0;iRefCount==0) + delete r; + else + i++; + } +} + +void sResourceManager_::ClearTemp() +{ + sImageResource *ir; + sFontResource *fr; + sTextResource *tr; + + sFORALL(Images,ir) + ir->Temp = 0; + sFORALL(Fonts,fr) + fr->Temp = 0; + sFORALL(Texts,tr) + tr->Temp = 0; +} + +/****************************************************************************/ + +sFontResource *sResourceManager_::NewFont(const sChar *name,sInt size,sInt style) +{ + sFontResource *f; + sFORALL(Fonts,f) + { + if(sCmpStringI(f->Name,name)==0 && f->Size==size && f->Style==style) + { + f->AddRef(); + return f; + } + } + + f = new sFontResource; + f->Font = new sFont2D(name,size,style); + f->Name = name; + f->Size = size; + f->Height = f->Font->GetHeight(); + f->Style = style; + f->LogSize = sRFS_NORMAL; + + sDPrintF(L"flush resources %d img %d fonts %d text\n",Images.GetCount(),Fonts.GetCount(),Texts.GetCount()); + return f; +} + +sFontResource *sResourceManager_::NewLogFont(sInt family,sInt logsize,sInt style) +{ + const sChar *name = FontFamilies[family].Name; + sInt size = FontFamilies[family].Sizes[logsize]; + sFontResource *f = NewFont(name,size,style); + f->LogSize = logsize; + return f; +} + +void sResourceManager_::SetLogFont(sInt family,const sChar *name,sInt basesize) +{ + FontFamilies[family].Name = name; + FontFamilies[family].Sizes[0] = sInt(basesize*0.70f+0.5f); + FontFamilies[family].Sizes[1] = sInt(basesize*0.80f+0.5f); + FontFamilies[family].Sizes[2] = basesize; + FontFamilies[family].Sizes[3] = sInt(basesize*1.20f+0.5f); + FontFamilies[family].Sizes[4] = sInt(basesize*1.40f+0.5f); + FontFamilies[family].Sizes[5] = sInt(basesize*1.80f+0.5f); + FontFamilies[family].Sizes[6] = sInt(basesize*2.50f+0.5f); +} + +/****************************************************************************/ + +sImageResource *sResourceManager_::NewImage(const sChar *name) +{ + sImageResource *ir; + + sFORALL(Images,ir) + { + if(sCmpStringP(name,ir->Name)==0) + { + ir->AddRef(); + return ir; + } + } + + sImage *img = new sImage; + if(!img->Load(name)) + { + img->Init(16,16); + img->Fill(0x00ff0000); + } + ir = new sImageResource; + ir->Name = name; + ir->Image = new sImage2D(img->SizeX,img->SizeY,img->Data); + delete img; + + return ir; +} + +/****************************************************************************/ + +sTextResource *sResourceManager_::NewText(const sChar *name) +{ + sTextResource *tr; + + sFORALL(Texts,tr) + { + if(sCmpStringP(name,tr->Name)==0) + { + tr->AddRef(); + return tr; + } + } + + const sChar *text = sLoadText(name); + if(!text) + { + sChar *t = new sChar[1]; + *t = 0; + text = t; + } + tr = new sTextResource; + tr->Name = name; + tr->Text = text; + + return tr; +} + +/****************************************************************************/ diff --git a/pool/shard011/C++/0121791_SimDrawCreator.cpp b/pool/shard011/C++/0121791_SimDrawCreator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36ea59b40018fd0b5284467dff42757375c2f542 --- /dev/null +++ b/pool/shard011/C++/0121791_SimDrawCreator.cpp @@ -0,0 +1,168 @@ +/* + * $Revision: 3188 $ + * + * last checkin: + * $Author: gutwenger $ + * $Date: 2013-01-10 09:53:32 +0100 (Thu, 10 Jan 2013) $ + ***************************************************************/ + +/** \file + * \brief Offers variety of possible SimDraw creations. + * + * \author Michael Schulz and Daniel Lueckerath + * + * \par License: + * This file is part of the Open Graph Drawing Framework (OGDF). + * + * \par + * Copyright (C)
+ * See README.txt in the root directory of the OGDF installation for details. + * + * \par + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * Version 2 or 3 as published by the Free Software Foundation; + * see the file LICENSE.txt included in the packaging of this file + * for details. + * + * \par + * 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. + * + * \par + * 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. + * + * \see http://www.gnu.org/copyleft/gpl.html + ***************************************************************/ + +#include +#include + +namespace ogdf { + +//************************************************************* +//sets all edgeSubGraphs values to zero +// +void SimDrawCreator::clearESG() +{ + edge e; + forall_edges(e,*m_G) + m_GA->subGraphBits(e) = 0; + +}//end clearESG + + +//************************************************************* +//gives each edge in m_G a random edgeSubGraphs value +//works with two graphs +void SimDrawCreator::randomESG2(int doubleESGProbability) +{ + OGDF_ASSERT( doubleESGProbability <= 100 ); + OGDF_ASSERT( doubleESGProbability >= 0 ); + + clearESG(); + + edge e; + forall_edges(e,*m_G) + { + //all edges have a chance of doubleESGProbability (in percent) + //to belong to both input graphs + int doubleESGRandom = rand() % 100; + if(doubleESGRandom < doubleESGProbability) + { + m_GA->addSubGraph(e, 0); + m_GA->addSubGraph(e, 1); + } + else + { + // all edges, which do not belong to both input graphs + // have a 50/50 chance to belong to graph 0 or to graph 1 + int singleESGRandom = rand() % 2; + m_GA->addSubGraph(e, singleESGRandom); + } + } + +}//end randomESG2 + + +//************************************************************* +//gives each edge in m_G a random edgeSubGraphs value +//works with three graphs +void SimDrawCreator::randomESG3(int doubleESGProbability, int tripleESGProbability) +{ + OGDF_ASSERT( doubleESGProbability + tripleESGProbability <= 100 ); + OGDF_ASSERT( doubleESGProbability >= 0 ); + OGDF_ASSERT( tripleESGProbability >= 0 ); + + clearESG(); + + edge e; + forall_edges(e,*m_G) + { + /*All edges have a chance of tripleESGProbability (in percent) + to belong to all three graphs.*/ + int multipleESGRandom = rand() % 100; + if(multipleESGRandom < doubleESGProbability + tripleESGProbability) + { + m_GA->addSubGraph(e,0); + m_GA->addSubGraph(e,1); + m_GA->addSubGraph(e,2); + + /*Furthermore, all edges have a chance of doubleESGProbability + to belong to two of three graphs.*/ + if(multipleESGRandom >= tripleESGProbability) + { + int removeESGRandom = rand() % 3; + m_GA->removeSubGraph(e, removeESGRandom); + } + } + else + { + //all edges, which do not belong to two or three graphs + //have a 33 percent chance to belong to one of the three graphs. + int singleESGRandom = rand() % 3; + m_GA->addSubGraph(e, singleESGRandom); + } + } + +}//end randomESG3 + + +//************************************************************* +//gives each edge a random edgeSubgraph value +//works with graphNumber number of graphs +void SimDrawCreator::randomESG(int graphNumber) +{ + OGDF_ASSERT( 0 < graphNumber && graphNumber < 32 ); + + int max = (int)pow((double)2,graphNumber+1)-1; + edge e; + forall_edges(e,*m_G) + { + int randomESGValue = 1 + rand() % max; + m_GA->subGraphBits(e) = randomESGValue; + } + +}//end randomESG + + +//************************************************************* +// +// +void SimDrawCreator::createRandom(int numberOfNodes, + int numberOfEdges, + int numberOfBasicGraphs) +{ + OGDF_ASSERT( 0 < numberOfBasicGraphs && numberOfBasicGraphs < 32 ); + randomSimpleGraph(*m_G, numberOfNodes, numberOfEdges); + randomESG(numberOfBasicGraphs); + +}//end createRandom + + +} // end namespace ogdf diff --git a/pool/shard011/C++/0121794_move_event_handler.cc b/pool/shard011/C++/0121794_move_event_handler.cc new file mode 100644 index 0000000000000000000000000000000000000000..c7165bad7334178c995aed31e38e09de56e0ec15 --- /dev/null +++ b/pool/shard011/C++/0121794_move_event_handler.cc @@ -0,0 +1,129 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "mash/wm/frame/move_event_handler.h" + +#include "components/mus/public/cpp/window.h" +#include "components/mus/public/interfaces/cursor.mojom.h" +#include "mash/wm/frame/move_loop.h" +#include "mojo/converters/input_events/input_events_type_converters.h" +#include "ui/aura/window.h" +#include "ui/aura/window_delegate.h" +#include "ui/base/hit_test.h" +#include "ui/events/event.h" + +namespace mash { +namespace wm { +namespace { + +mus::mojom::Cursor CursorForWindowComponent(int window_component) { + switch (window_component) { + case HTBOTTOM: + return mus::mojom::Cursor::SOUTH_RESIZE; + case HTBOTTOMLEFT: + return mus::mojom::Cursor::SOUTH_WEST_RESIZE; + case HTBOTTOMRIGHT: + return mus::mojom::Cursor::SOUTH_EAST_RESIZE; + case HTLEFT: + return mus::mojom::Cursor::WEST_RESIZE; + case HTRIGHT: + return mus::mojom::Cursor::EAST_RESIZE; + case HTTOP: + return mus::mojom::Cursor::NORTH_RESIZE; + case HTTOPLEFT: + return mus::mojom::Cursor::NORTH_WEST_RESIZE; + case HTTOPRIGHT: + return mus::mojom::Cursor::NORTH_EAST_RESIZE; + default: + return mus::mojom::Cursor::CURSOR_NULL; + } +} + +} // namespace + +MoveEventHandler::MoveEventHandler(mus::Window* mus_window, + aura::Window* aura_window) + : mus_window_(mus_window), aura_window_(aura_window), + root_window_(aura_window->GetRootWindow()) { + root_window_->AddObserver(this); + root_window_->AddPreTargetHandler(this); +} + +MoveEventHandler::~MoveEventHandler() { + Detach(); +} + +void MoveEventHandler::ProcessLocatedEvent(ui::LocatedEvent* event) { + const bool had_move_loop = move_loop_.get() != nullptr; + DCHECK(event->IsMouseEvent() || event->IsTouchEvent()); + + // This event handler can receive mouse events like ET_MOUSE_CAPTURE_CHANGED + // that cannot be converted to PointerEvents. Ignore them because they aren't + // needed for move handling. + if (!ui::PointerEvent::CanConvertFrom(*event)) + return; + + // TODO(moshayedi): no need for this once MoveEventHandler directly receives + // pointer events. + std::unique_ptr pointer_event; + if (event->IsMouseEvent()) + pointer_event.reset(new ui::PointerEvent(*event->AsMouseEvent())); + else + pointer_event.reset(new ui::PointerEvent(*event->AsTouchEvent())); + + if (move_loop_) { + if (move_loop_->Move(*pointer_event.get()) == MoveLoop::DONE) + move_loop_.reset(); + } else if (pointer_event->type() == ui::ET_POINTER_DOWN) { + const int ht_location = GetNonClientComponentForEvent(pointer_event.get()); + if (ht_location != HTNOWHERE) { + move_loop_ = + MoveLoop::Create(mus_window_, ht_location, *pointer_event.get()); + } + } else if (pointer_event->type() == ui::ET_POINTER_MOVED) { + const int ht_location = GetNonClientComponentForEvent(pointer_event.get()); + mus_window_->SetPredefinedCursor(CursorForWindowComponent(ht_location)); + } + if (had_move_loop || move_loop_) + event->SetHandled(); +} + +int MoveEventHandler::GetNonClientComponentForEvent( + const ui::LocatedEvent* event) { + return aura_window_->delegate()->GetNonClientComponent(event->location()); +} + +void MoveEventHandler::Detach() { + if (!root_window_) + return; + + root_window_->RemoveObserver(this); + root_window_->RemovePreTargetHandler(this); + root_window_ = nullptr; +} + +void MoveEventHandler::OnMouseEvent(ui::MouseEvent* event) { + ProcessLocatedEvent(event); +} + +void MoveEventHandler::OnTouchEvent(ui::TouchEvent* event) { + ProcessLocatedEvent(event); +} + +void MoveEventHandler::OnCancelMode(ui::CancelModeEvent* event) { + if (!move_loop_) + return; + + move_loop_->Revert(); + move_loop_.reset(); + event->SetHandled(); +} + +void MoveEventHandler::OnWindowDestroying(aura::Window* window) { + DCHECK_EQ(root_window_, window); + Detach(); +} + +} // namespace wm +} // namespace mash diff --git a/pool/shard011/C++/0121795_database.cpp b/pool/shard011/C++/0121795_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c8da5010376e0c748b5834739ac787132ce39057 --- /dev/null +++ b/pool/shard011/C++/0121795_database.cpp @@ -0,0 +1,98 @@ +/** + * @file database.cpp + * @author Robin Dietrich + * + * @par License + * This file is part of deltadb. + * + * Foobar 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. + * + * Foobar 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 Foobar. If not, see . + */ + +#include +#include +#include +#include +#include + +#include +#include + +#include "../config.hpp" +#include "table.hpp" +#include "table_col.hpp" +#include "database.hpp" + +namespace deltadb { + bool database::open() { + // Set cwd to data directory + if (chdir(DELTADB_PATH_DATA) != 0) { + perror("Unable to set cwd"); + return false; + } + + // Aquire db lock + if (!m_lock.aquire()) { + perror("Unable to aquire database lock"); + return false; + } + + // Read a list of tables + DIR *dp; + struct dirent *file; + + if((dp = opendir("./")) == NULL) { + perror("Unable to list directory"); + return false; + } else { + while((file=readdir(dp)) != NULL) { + if (strcmp(file->d_name+(strlen(file->d_name)-3), "tbl") == 0) { + auto tbl_name = std::string(file->d_name, strlen(file->d_name)-4); + m_tables[tbl_name] = new table(tbl_name); + } + } + + closedir(dp); + } + + return true; + } + + void database::close() { + for (auto &tbl : m_tables) { + delete tbl.second; + } + + m_tables.clear(); + m_lock.release(); + } + + void database::create(const char* name, col** t, uint32_t len) { + std::string frm = std::string(name)+".tbl"; + if (file_exists(frm.c_str())) { + return; // @todo: error + } + + table* t2 = new table(std::string(name)); + t2->set_columns(t, len); + m_tables[std::string(name)] = t2; + } + + void database::write_row(const char* table, row* r) { + auto tbl = m_tables.find(table); + assert(tbl != m_tables.end()); + + class table* t = tbl->second; + t->write(r); + } +} diff --git a/pool/shard011/C++/0121796_SVGClipPathElement.cpp b/pool/shard011/C++/0121796_SVGClipPathElement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d95a61ef1ad3d7e74e31d6162f932858bd9227b2 --- /dev/null +++ b/pool/shard011/C++/0121796_SVGClipPathElement.cpp @@ -0,0 +1,128 @@ +/* + * Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann + * Copyright (C) 2004, 2005, 2006, 2007, 2008 Rob Buis + * Copyright (C) Research In Motion Limited 2009-2010. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" + +#if ENABLE(SVG) +#include "SVGClipPathElement.h" + +#include "Attribute.h" +#include "CSSStyleSelector.h" +#include "Document.h" +#include "RenderSVGResourceClipper.h" +#include "SVGElementInstance.h" +#include "SVGNames.h" +#include "SVGTransformList.h" + +namespace WebCore { + +// Animated property definitions +DEFINE_ANIMATED_ENUMERATION(SVGClipPathElement, SVGNames::clipPathUnitsAttr, ClipPathUnits, clipPathUnits, SVGUnitTypes::SVGUnitType) +DEFINE_ANIMATED_BOOLEAN(SVGClipPathElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired) + +BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGClipPathElement) + REGISTER_LOCAL_ANIMATED_PROPERTY(clipPathUnits) + REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired) + REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement) + REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests) +END_REGISTER_ANIMATED_PROPERTIES + +inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document* document) + : SVGStyledTransformableElement(tagName, document) + , m_clipPathUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE) +{ + ASSERT(hasTagName(SVGNames::clipPathTag)); + registerAnimatedPropertiesForSVGClipPathElement(); +} + +PassRefPtr SVGClipPathElement::create(const QualifiedName& tagName, Document* document) +{ + return adoptRef(new SVGClipPathElement(tagName, document)); +} + +bool SVGClipPathElement::isSupportedAttribute(const QualifiedName& attrName) +{ + DEFINE_STATIC_LOCAL(HashSet, supportedAttributes, ()); + if (supportedAttributes.isEmpty()) { + SVGTests::addSupportedAttributes(supportedAttributes); + SVGLangSpace::addSupportedAttributes(supportedAttributes); + SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes); + supportedAttributes.add(SVGNames::clipPathUnitsAttr); + } + return supportedAttributes.contains(attrName); +} + +void SVGClipPathElement::parseMappedAttribute(Attribute* attr) +{ + if (!isSupportedAttribute(attr->name())) { + SVGStyledTransformableElement::parseMappedAttribute(attr); + return; + } + + if (attr->name() == SVGNames::clipPathUnitsAttr) { + SVGUnitTypes::SVGUnitType propertyValue = SVGPropertyTraits::fromString(attr->value()); + if (propertyValue > 0) + setClipPathUnitsBaseValue(propertyValue); + return; + } + + if (SVGTests::parseMappedAttribute(attr)) + return; + if (SVGLangSpace::parseMappedAttribute(attr)) + return; + if (SVGExternalResourcesRequired::parseMappedAttribute(attr)) + return; + + ASSERT_NOT_REACHED(); +} + +void SVGClipPathElement::svgAttributeChanged(const QualifiedName& attrName) +{ + if (!isSupportedAttribute(attrName)) { + SVGStyledTransformableElement::svgAttributeChanged(attrName); + return; + } + + SVGElementInstance::InvalidationGuard invalidationGuard(this); + + if (RenderObject* object = renderer()) + object->setNeedsLayout(true); +} + +void SVGClipPathElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) +{ + SVGStyledTransformableElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta); + + if (changedByParser) + return; + + if (RenderObject* object = renderer()) + object->setNeedsLayout(true); +} + +RenderObject* SVGClipPathElement::createRenderer(RenderArena* arena, RenderStyle*) +{ + return new (arena) RenderSVGResourceClipper(this); +} + +} + +#endif // ENABLE(SVG) diff --git a/pool/shard011/C++/0121798_ozone_platform_gbm.cc b/pool/shard011/C++/0121798_ozone_platform_gbm.cc new file mode 100644 index 0000000000000000000000000000000000000000..370e5b44acae7a0546c463fd37e4b4209050b2b8 --- /dev/null +++ b/pool/shard011/C++/0121798_ozone_platform_gbm.cc @@ -0,0 +1,249 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/ozone/platform/drm/ozone_platform_gbm.h" + +#include +#include +#include + +#include "base/at_exit.h" +#include "base/bind.h" +#include "base/command_line.h" +#include "ui/base/cursor/ozone/bitmap_cursor_factory_ozone.h" +#include "ui/events/ozone/device/device_manager.h" +#include "ui/events/ozone/evdev/event_factory_evdev.h" +#include "ui/events/ozone/layout/keyboard_layout_engine_manager.h" +#include "ui/ozone/platform/drm/gbm_surface_factory.h" +#include "ui/ozone/platform/drm/gpu/drm_device_generator.h" +#include "ui/ozone/platform/drm/gpu/drm_device_manager.h" +#include "ui/ozone/platform/drm/gpu/drm_gpu_display_manager.h" +#include "ui/ozone/platform/drm/gpu/drm_gpu_platform_support.h" +#include "ui/ozone/platform/drm/gpu/drm_util.h" +#include "ui/ozone/platform/drm/gpu/drm_window_manager.h" +#include "ui/ozone/platform/drm/gpu/gbm_buffer.h" +#include "ui/ozone/platform/drm/gpu/gbm_device.h" +#include "ui/ozone/platform/drm/gpu/gbm_surface.h" +#include "ui/ozone/platform/drm/gpu/gpu_lock.h" +#include "ui/ozone/platform/drm/gpu/scanout_buffer.h" +#include "ui/ozone/platform/drm/gpu/screen_manager.h" +#include "ui/ozone/platform/drm/host/display_manager.h" +#include "ui/ozone/platform/drm/host/drm_cursor.h" +#include "ui/ozone/platform/drm/host/drm_gpu_platform_support_host.h" +#include "ui/ozone/platform/drm/host/drm_native_display_delegate.h" +#include "ui/ozone/platform/drm/host/drm_window_host.h" +#include "ui/ozone/platform/drm/host/drm_window_host_manager.h" +#include "ui/ozone/public/cursor_factory_ozone.h" +#include "ui/ozone/public/gpu_platform_support.h" +#include "ui/ozone/public/gpu_platform_support_host.h" +#include "ui/ozone/public/ozone_platform.h" +#include "ui/ozone/public/ozone_switches.h" + +#if defined(USE_XKBCOMMON) +#include "ui/events/ozone/layout/xkb/xkb_evdev_codes.h" +#include "ui/events/ozone/layout/xkb/xkb_keyboard_layout_engine.h" +#else +#include "ui/events/ozone/layout/stub/stub_keyboard_layout_engine.h" +#endif + +namespace ui { + +namespace { + +class GlApiLoader { + public: + GlApiLoader() + : glapi_lib_(dlopen("libglapi.so.0", RTLD_LAZY | RTLD_GLOBAL)) {} + + ~GlApiLoader() { + if (glapi_lib_) + dlclose(glapi_lib_); + } + + private: + // HACK: gbm drivers have broken linkage. The Mesa DRI driver references + // symbols in the libglapi library however it does not explicitly link against + // it. That caused linkage errors when running an application that does not + // explicitly link against libglapi. + void* glapi_lib_; + + DISALLOW_COPY_AND_ASSIGN(GlApiLoader); +}; + +class GbmBufferGenerator : public ScanoutBufferGenerator { + public: + GbmBufferGenerator() {} + ~GbmBufferGenerator() override {} + + // ScanoutBufferGenerator: + scoped_refptr Create(const scoped_refptr& drm, + const gfx::Size& size) override { + scoped_refptr gbm(static_cast(drm.get())); + return GbmBuffer::CreateBuffer(gbm, SurfaceFactoryOzone::RGBA_8888, size, + true); + } + + protected: + DISALLOW_COPY_AND_ASSIGN(GbmBufferGenerator); +}; + +class GbmDeviceGenerator : public DrmDeviceGenerator { + public: + GbmDeviceGenerator() {} + ~GbmDeviceGenerator() override {} + + // DrmDeviceGenerator: + scoped_refptr CreateDevice(const base::FilePath& path, + base::File file) override { + scoped_refptr drm = new GbmDevice(path, file.Pass()); + if (drm->Initialize()) + return drm; + + return nullptr; + } + + private: + DISALLOW_COPY_AND_ASSIGN(GbmDeviceGenerator); +}; + +class OzonePlatformGbm : public OzonePlatform { + public: + OzonePlatformGbm(bool use_surfaceless) : use_surfaceless_(use_surfaceless) {} + ~OzonePlatformGbm() override {} + + // OzonePlatform: + ui::SurfaceFactoryOzone* GetSurfaceFactoryOzone() override { + return surface_factory_ozone_.get(); + } + CursorFactoryOzone* GetCursorFactoryOzone() override { + return cursor_factory_ozone_.get(); + } + InputController* GetInputController() override { + return event_factory_ozone_->input_controller(); + } + GpuPlatformSupport* GetGpuPlatformSupport() override { + return gpu_platform_support_.get(); + } + GpuPlatformSupportHost* GetGpuPlatformSupportHost() override { + return gpu_platform_support_host_.get(); + } + scoped_ptr CreateSystemInputInjector() override { + return event_factory_ozone_->CreateSystemInputInjector(); + } + scoped_ptr CreatePlatformWindow( + PlatformWindowDelegate* delegate, + const gfx::Rect& bounds) override { + scoped_ptr platform_window( + new DrmWindowHost(delegate, bounds, gpu_platform_support_host_.get(), + event_factory_ozone_.get(), cursor_.get(), + window_manager_.get(), display_manager_.get())); + platform_window->Initialize(); + return platform_window.Pass(); + } + scoped_ptr CreateNativeDisplayDelegate() override { + return make_scoped_ptr(new DrmNativeDisplayDelegate( + gpu_platform_support_host_.get(), device_manager_.get(), + display_manager_.get(), primary_graphics_card_path_)); + } + void InitializeUI() override { + primary_graphics_card_path_ = GetPrimaryDisplayCardPath(); + display_manager_.reset(new DisplayManager()); + // Needed since the browser process creates the accelerated widgets and that + // happens through SFO. + if (!surface_factory_ozone_) + surface_factory_ozone_.reset(new GbmSurfaceFactory(use_surfaceless_)); + device_manager_ = CreateDeviceManager(); + gpu_platform_support_host_.reset(new DrmGpuPlatformSupportHost()); + window_manager_.reset(new DrmWindowHostManager()); + cursor_factory_ozone_.reset(new BitmapCursorFactoryOzone); + cursor_.reset( + new DrmCursor(window_manager_.get(), gpu_platform_support_host_.get())); + cursor_->Init(); +#if defined(USE_XKBCOMMON) + KeyboardLayoutEngineManager::SetKeyboardLayoutEngine(make_scoped_ptr( + new XkbKeyboardLayoutEngine(xkb_evdev_code_converter_))); +#else + KeyboardLayoutEngineManager::SetKeyboardLayoutEngine( + make_scoped_ptr(new StubKeyboardLayoutEngine())); +#endif + event_factory_ozone_.reset(new EventFactoryEvdev( + cursor_.get(), device_manager_.get(), + KeyboardLayoutEngineManager::GetKeyboardLayoutEngine())); + } + + void InitializeGPU() override { +#if defined(OS_CHROMEOS) + gpu_lock_.reset(new GpuLock()); +#endif + gl_api_loader_.reset(new GlApiLoader()); + // Async page flips are supported only on surfaceless mode. + gbm_ = new GbmDevice(GetPrimaryDisplayCardPath()); + if (!gbm_->Initialize()) + LOG(FATAL) << "Failed to initialize primary DRM device"; + + drm_device_manager_.reset(new DrmDeviceManager(gbm_)); + buffer_generator_.reset(new GbmBufferGenerator()); + screen_manager_.reset(new ScreenManager(buffer_generator_.get())); + // This makes sure that simple targets that do not handle display + // configuration can still use the primary display. + ForceInitializationOfPrimaryDisplay(gbm_, screen_manager_.get()); + + window_delegate_manager_.reset(new DrmWindowManager()); + if (!surface_factory_ozone_) + surface_factory_ozone_.reset(new GbmSurfaceFactory(use_surfaceless_)); + + surface_factory_ozone_->InitializeGpu(drm_device_manager_.get(), + window_delegate_manager_.get()); + scoped_ptr ndd(new DrmGpuDisplayManager( + screen_manager_.get(), gbm_, + scoped_ptr(new GbmDeviceGenerator()))); + gpu_platform_support_.reset(new DrmGpuPlatformSupport( + drm_device_manager_.get(), window_delegate_manager_.get(), + screen_manager_.get(), ndd.Pass())); + } + + private: + // Objects in both processes. + bool use_surfaceless_; + scoped_ptr surface_factory_ozone_; + + // Objects in the GPU process. + scoped_ptr gpu_lock_; + scoped_ptr gl_api_loader_; + scoped_refptr gbm_; + scoped_ptr drm_device_manager_; + scoped_ptr buffer_generator_; + scoped_ptr screen_manager_; + scoped_ptr gpu_platform_support_; + scoped_ptr window_delegate_manager_; + + // Obejcts in the Browser process. + base::FilePath primary_graphics_card_path_; + scoped_ptr device_manager_; + scoped_ptr cursor_factory_ozone_; + scoped_ptr event_factory_ozone_; + scoped_ptr gpu_platform_support_host_; + scoped_ptr cursor_; + scoped_ptr window_manager_; + scoped_ptr display_manager_; + +#if defined(USE_XKBCOMMON) + XkbEvdevCodes xkb_evdev_code_converter_; +#endif + + DISALLOW_COPY_AND_ASSIGN(OzonePlatformGbm); +}; + +} // namespace + +OzonePlatform* CreateOzonePlatformGbm() { + base::CommandLine* cmd = base::CommandLine::ForCurrentProcess(); +#if defined(USE_MESA_PLATFORM_NULL) + // Only works with surfaceless. + cmd->AppendSwitch(switches::kOzoneUseSurfaceless); +#endif + return new OzonePlatformGbm(cmd->HasSwitch(switches::kOzoneUseSurfaceless)); +} + +} // namespace ui diff --git a/pool/shard011/C++/0121799_ConnectionChecking_impl.cpp b/pool/shard011/C++/0121799_ConnectionChecking_impl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..55d28de79b18a32109d467c335d0a677d99b14e4 --- /dev/null +++ b/pool/shard011/C++/0121799_ConnectionChecking_impl.cpp @@ -0,0 +1,122 @@ +#include +#include "../../../shared/generated/cpp/ConnectionCheckingBase.h" +#include "HostTracker.h" +namespace rho { + +#define EXTN_NAME "ConnectionChecking"; + using namespace apiGenerator; + using namespace common; + + class CConnectionCheckingImpl: public CConnectionCheckingSingletonBase + { + + private: + CHostTracker* m_pHostTracker; + public: + CConnectionCheckingImpl(const rho::String& strID):CConnectionCheckingSingletonBase() + { + LOG(INFO) + "Initialising interface for ConnectingMessage "; + m_pHostTracker = HostTrackerFactory::createHostTracker(); + } + ~CConnectionCheckingImpl() + { + LOG(INFO) + "Shutting down connection checker "; + if (m_pHostTracker){ + m_pHostTracker->StopNetworkChecking(); + delete m_pHostTracker; + m_pHostTracker = NULL; + } + } + virtual void getHostURL(rho::apiGenerator::CMethodResult& oResult) + { + oResult.set(m_pHostTracker->getHostURL()); + } + virtual void getTrackConnection(rho::apiGenerator::CMethodResult& oResult) + { + oResult.set(m_pHostTracker->isFeatureEnabled()); + } + virtual void getTimeout(rho::apiGenerator::CMethodResult& oResult) + { + oResult.set(m_pHostTracker->getDailogTimeout()); + } + virtual void getPollInterval(rho::apiGenerator::CMethodResult& oResult) + { + oResult.set(m_pHostTracker->getPollInterval()); + } + virtual void getMessage(rho::apiGenerator::CMethodResult& oResult) + { + oResult.set(m_pHostTracker->getMessage()); + } + + void InitNetworkChecking() + { + m_pHostTracker->InitConfig(); + if(m_pHostTracker->isFeatureEnabled()) + { + m_pHostTracker->StartNetworkChecking(); + } + } + + + //overides IRhoExtention + virtual void onNavigateComplete(const wchar_t* szUrlBeingNavigatedTo, const CRhoExtData& oExtData) + { + if(m_pHostTracker->isFeatureEnabled()) + { + m_pHostTracker->SetNavigatedUrl(szUrlBeingNavigatedTo); + m_pHostTracker->fireEvent(eNavigateCompleteEventIndex); + } + } + virtual void OnLicenseScreen(bool bActivate, const CRhoExtData& oExtData) + { + if(m_pHostTracker->isFeatureEnabled()) + { + if(bActivate) + { + m_pHostTracker->fireEvent(eLicenseScreenPopupEventIndex); + + } + else + { + m_pHostTracker->fireEvent(eLicenseScreenHidesEventIndex); + + } + } + } + + }; + + class CConnectionCheckingSingleton: public CConnectionCheckingSingletonBase + { + ~CConnectionCheckingSingleton(){} + }; + + class CConnectionCheckingFactory: public CConnectionCheckingFactoryBase + { + ~CConnectionCheckingFactory(){} + virtual IConnectionChecking* createModuleByID(const rho::String& strID); + virtual IConnectionCheckingSingleton* createModuleSingleton(); + }; + + extern "C" void Init_ConnectionChecking_extension() + { + CConnectionCheckingFactory::setInstance( new CConnectionCheckingFactory() ); + Init_ConnectionChecking_API(); + CConnectionCheckingImpl* ptr = (CConnectionCheckingImpl*)CConnectionCheckingFactory::getConnectionCheckingSingletonS(); + ptr->InitNetworkChecking(); + } + + IConnectionChecking* CConnectionCheckingFactory::createModuleByID(const rho::String& strID) + { + //unused + return NULL; + } + IConnectionCheckingSingleton* CConnectionCheckingFactory::createModuleSingleton() + { + rho::String szExtnName = EXTN_NAME; + return new CConnectionCheckingImpl(szExtnName); + } + + + +} \ No newline at end of file diff --git a/pool/shard011/C++/0121800_JSWebGLByteArrayConstructor.cpp b/pool/shard011/C++/0121800_JSWebGLByteArrayConstructor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7db710fa88faf08a2e8907e3aa67e157b3777927 --- /dev/null +++ b/pool/shard011/C++/0121800_JSWebGLByteArrayConstructor.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2009 Apple Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" + +#if ENABLE(3D_CANVAS) + +#include "JSWebGLByteArrayConstructor.h" + +#include "Document.h" +#include "WebGLByteArray.h" +#include "JSWebGLArrayBuffer.h" +#include "JSWebGLArrayBufferConstructor.h" +#include "JSWebGLByteArray.h" +#include + +namespace WebCore { + +using namespace JSC; + +const ClassInfo JSWebGLByteArrayConstructor::s_info = { "WebGLByteArrayConstructor", &JSWebGLArray::s_info, 0, 0 }; + +JSWebGLByteArrayConstructor::JSWebGLByteArrayConstructor(ExecState* exec, JSDOMGlobalObject* globalObject) + : DOMConstructorObject(JSWebGLByteArrayConstructor::createStructure(globalObject->objectPrototype()), globalObject) +{ + putDirect(exec->propertyNames().prototype, JSWebGLByteArrayPrototype::self(exec, globalObject), None); + putDirect(exec->propertyNames().length, jsNumber(exec, 2), ReadOnly|DontDelete|DontEnum); +} + +static JSObject* constructCanvasByteArray(ExecState* exec, JSObject* constructor, const ArgList& args) +{ + JSWebGLByteArrayConstructor* jsConstructor = static_cast(constructor); + RefPtr array = static_cast(construct(exec, args).get()); + return asObject(toJS(exec, jsConstructor->globalObject(), array.get())); +} + +JSC::ConstructType JSWebGLByteArrayConstructor::getConstructData(JSC::ConstructData& constructData) +{ + constructData.native.function = constructCanvasByteArray; + return ConstructTypeHost; +} + +} // namespace WebCore + +#endif // ENABLE(3D_CANVAS) diff --git a/pool/shard011/C++/0121804_CWE124_Buffer_Underwrite__new_wchar_t_ncpy_51b.cpp b/pool/shard011/C++/0121804_CWE124_Buffer_Underwrite__new_wchar_t_ncpy_51b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90101f6d4a50a673f03ea999a30b69f95e5d4efd --- /dev/null +++ b/pool/shard011/C++/0121804_CWE124_Buffer_Underwrite__new_wchar_t_ncpy_51b.cpp @@ -0,0 +1,67 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE124_Buffer_Underwrite__new_wchar_t_ncpy_51b.cpp +Label Definition File: CWE124_Buffer_Underwrite__new.label.xml +Template File: sources-sink-51b.tmpl.cpp +*/ +/* + * @description + * CWE: 124 Buffer Underwrite + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sink: ncpy + * BadSink : Copy string to data using wcsncpy + * Flow Variant: 51 Data flow: data passed as an argument from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +namespace CWE124_Buffer_Underwrite__new_wchar_t_ncpy_51 +{ + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void badSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + wcsncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by new [] so can't safely call delete [] on it */ + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(wchar_t * data) +{ + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with 'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copying data to memory before the destination buffer */ + wcsncpy(data, source, 100-1); + /* Ensure the destination buffer is null terminated */ + data[100-1] = L'\0'; + printWLine(data); + /* INCIDENTAL CWE-401: Memory Leak - data may not point to location + * returned by new [] so can't safely call delete [] on it */ + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard011/C++/0121805_CBiRRTMotionValidator.cpp b/pool/shard011/C++/0121805_CBiRRTMotionValidator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..277c152bf1515902a8fb234f8e8e5ad4c43234d3 --- /dev/null +++ b/pool/shard011/C++/0121805_CBiRRTMotionValidator.cpp @@ -0,0 +1,111 @@ +#include +#include + +namespace openrave_ompl_bridge +{ + bool CBiRRTMotionValidator::checkMotion(const ompl::base::State *s1, const ompl::base::State *s2, std::pair &lastValid) const + { + /* assume motion starts in a valid configuration so s1 is valid */ + + bool result = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + if (nd > 1) + { + /* temporary storage for the checked state */ + ompl::base::State *test = si_->allocState(); + + for (int j = 1 ; j < nd ; ++j) + { + stateSpace_->interpolate(s1, s2, (double)j / (double)nd, test); + if (!si_->isValid(test) || !stateSpace_->as()->fulfillsPathConstraints(test)) + { + lastValid.second = (double)(j - 1) / (double)nd; + if (lastValid.first) + stateSpace_->interpolate(s1, s2, lastValid.second, lastValid.first); + result = false; + break; + } + } + si_->freeState(test); + } + + if (result) + if (!si_->isValid(s2) || !stateSpace_->as()->fulfillsPathConstraints(s2)) + { + lastValid.second = (double)(nd - 1) / (double)nd; + if (lastValid.first) + stateSpace_->interpolate(s1, s2, lastValid.second, lastValid.first); + result = false; + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + + bool CBiRRTMotionValidator::checkMotion(const ompl::base::State *s1, const ompl::base::State *s2) const + { + /* assume motion starts in a valid configuration so s1 is valid */ + if (!si_->isValid(s2) || !stateSpace_->as()->fulfillsPathConstraints(s2)) + { + invalid_++; + return false; + } + + bool result = true; + int nd = stateSpace_->validSegmentCount(s1, s2); + + /* initialize the queue of test positions */ + std::queue< std::pair > pos; + if (nd >= 2) + { + pos.push(std::make_pair(1, nd - 1)); + + /* temporary storage for the checked state */ + ompl::base::State *test = si_->allocState(); + + /* repeatedly subdivide the path segment in the middle (and check the middle) */ + while (!pos.empty()) + { + std::pair x = pos.front(); + + int mid = (x.first + x.second) / 2; + stateSpace_->interpolate(s1, s2, (double)mid / (double)nd, test); + + if (!si_->isValid(test) || !stateSpace_->as()->fulfillsPathConstraints(test)) + { + result = false; + break; + } + + pos.pop(); + + if (x.first < mid) + pos.push(std::make_pair(x.first, mid - 1)); + if (x.second > mid) + pos.push(std::make_pair(mid + 1, x.second)); + } + + si_->freeState(test); + } + + if (result) + valid_++; + else + invalid_++; + + return result; + } + + void CBiRRTMotionValidator::defaultSettings(void) + { + stateSpace_ = si_->getStateSpace().get(); + if (!stateSpace_) + throw ompl::Exception("No state space for motion validator"); + } + +} // namespace openrave_ompl_bridge diff --git a/pool/shard011/C++/0121806_channel.cpp b/pool/shard011/C++/0121806_channel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c2595b6684b1f320781acad6426aeee0e6df9c4 --- /dev/null +++ b/pool/shard011/C++/0121806_channel.cpp @@ -0,0 +1,108 @@ +#include "channel.h" +//#include +//#include +#include "../util/log.h" +#include "../util/list.h" +#include "server.h" +#include "subscriber.h" +#include "server_config.h" + +Channel::Channel(){ + serv = NULL; + idle = 0; + seq_next = 1; +} + +Channel::~Channel(){ +} + +void Channel::add_subscriber(Subscriber *sub){ + sub->channel = this; + subs.push_back(sub); +} + +void Channel::del_subscriber(Subscriber *sub){ + sub->channel = NULL; + subs.remove(sub); +} + +void Channel::create_token(){ + // TODO: rand() is not safe? + token.resize(33); + char *buf = (char *)token.data(); + int offset = 0; + while(1){ + int r = rand() + time(NULL); + int len = _snprintf(buf + offset, token.size() - offset, "%08x", r); + if(len == -1){ + break; + } + offset += len; + if(offset >= token.size() - 1){ + break; + } + } + token.resize(32); +} + +void Channel::clear(){ + msg_list.clear(); +} + +void Channel::close(){ + this->send("close", ""); + LinkedList::Iterator it = subs.iterator(); + while(Subscriber *sub = it.next()){ + sub->close(); + } +} + +static std::string json_encode(const char *str){ + std::string ret; + int len = strlen(str); + for(int i=0; i::Iterator it = subs.iterator(); + while(Subscriber *sub = it.next()){ + sub->send_chunk(this->seq_next, type, new_content.c_str()); + } + + msg_list.push_back(new_content); + seq_next ++; + if(msg_list.size() >= ServerConfig::channel_buffer_size * 1.5){ + std::vector::iterator it; + it = msg_list.end() - ServerConfig::channel_buffer_size; + msg_list.assign(it, msg_list.end()); + log_trace("resize msg_list to %d, seq_next: %d", msg_list.size(), seq_next); + } + }else{ + LinkedList::Iterator it = subs.iterator(); + while(Subscriber *sub = it.next()){ + sub->send_chunk(this->seq_next, type, content); + } + } +} diff --git a/pool/shard011/C++/0121807_dualshock4_controller.cc b/pool/shard011/C++/0121807_dualshock4_controller.cc new file mode 100644 index 0000000000000000000000000000000000000000..16c0a1aec6803b14d08ddd9db40d9110f0ee2dd1 --- /dev/null +++ b/pool/shard011/C++/0121807_dualshock4_controller.cc @@ -0,0 +1,283 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "device/gamepad/dualshock4_controller.h" + +#include + +#include "base/metrics/crc32.h" +#include "base/numerics/safe_conversions.h" +#include "device/gamepad/gamepad_data_fetcher.h" +#include "device/gamepad/gamepad_id_list.h" +#include "device/gamepad/hid_writer.h" + +namespace device { + +namespace { +// Expected values for |version_number| when connected over USB and Bluetooth. +const uint16_t kDualshock4VersionUsb = 0x0100; +const uint16_t kDualshock4VersionBluetooth = 0; + +// Report IDs. +const uint8_t kReportId05 = 0x05; +const uint8_t kReportId11 = 0x11; + +// Maximum in-range values for HID report fields. +const uint8_t kRumbleMagnitudeMax = 0xff; +const float kAxisMax = 255.0f; +const float kDpadMax = 7.0f; + +#pragma pack(push, 1) +struct ControllerData { + uint8_t axis_left_x; + uint8_t axis_left_y; + uint8_t axis_right_x; + uint8_t axis_right_y; + uint8_t axis_dpad : 4; + bool button_square : 1; + bool button_cross : 1; + bool button_circle : 1; + bool button_triangle : 1; + bool button_left_1 : 1; + bool button_right_1 : 1; + bool button_left_2 : 1; + bool button_right_2 : 1; + bool button_share : 1; + bool button_options : 1; + bool button_left_3 : 1; + bool button_right_3 : 1; + bool button_ps : 1; + bool button_touch : 1; + uint8_t sequence_number : 6; + uint8_t axis_left_2; + uint8_t axis_right_2; + uint16_t timestamp; + uint8_t sensor_temperature; + uint16_t axis_gyro_pitch; + uint16_t axis_gyro_yaw; + uint16_t axis_gyro_roll; + uint16_t axis_accelerometer_x; + uint16_t axis_accelerometer_y; + uint16_t axis_accelerometer_z; + uint8_t padding1[5]; + uint8_t battery_info : 5; + uint8_t padding2 : 2; + bool extension_detection : 1; +}; +#pragma pack(pop) +static_assert(sizeof(ControllerData) == 30, + "ControllerData has incorrect size"); + +#pragma pack(push, 1) +struct TouchPadData { + uint8_t touch_data_timestamp; + uint8_t touch0_id : 7; + bool touch0_is_invalid : 1; + uint8_t touch0_data[3]; + uint8_t touch1_id : 7; + bool touch1_is_invalid : 1; + uint8_t touch1_data[3]; +}; +#pragma pack(pop) +static_assert(sizeof(TouchPadData) == 9, "TouchPadData has incorrect size"); + +#pragma pack(push, 1) +struct Dualshock4InputReport11 { + uint8_t padding1[2]; + ControllerData controller_data; + uint8_t padding2[2]; + uint8_t touches_count; + TouchPadData touches[4]; + uint8_t padding3[2]; + uint32_t crc32; +}; +#pragma pack(pop) +static_assert(sizeof(Dualshock4InputReport11) == 77, + "Dualshock4InputReport11 has incorrect size"); + +// Returns the CRC32 checksum for a Dualshock4 Bluetooth output report. +// |report_data| is the report data excluding the bytes where the checksum will +// be written. +uint32_t ComputeDualshock4Checksum(base::span report_data) { + // The Bluetooth report checksum includes a constant header byte not contained + // in the report data. + constexpr uint8_t bt_header = 0xa2; + uint32_t crc = base::Crc32(0xffffffff, &bt_header, 1); + // Extend the checksum with the contents of the report. + return ~base::Crc32(crc, report_data.data(), report_data.size_bytes()); +} + +// Scales |value| with range [0,255] to a float within [-1.0,+1.0]. +static float NormalizeAxis(uint8_t value) { + return (2.0f * value / kAxisMax) - 1.0f; +} + +// Scales a D-pad value from a Dualshock4 report to an axis value. The D-pad +// report value has a logical range from 0 to 7, and uses an out-of-bounds value +// of 8 to indicate null input (no interaction). In-bounds values are scaled to +// the range [-1.0,+1.0]. The null input value returns +9/7 (about 1.29). +static float NormalizeDpad(uint8_t value) { + return (2.0f * value / kDpadMax) - 1.0f; +} + +} // namespace + +Dualshock4Controller::Dualshock4Controller(GamepadId gamepad_id, + GamepadBusType bus_type, + std::unique_ptr writer) + : gamepad_id_(gamepad_id), + bus_type_(bus_type), + writer_(std::move(writer)) {} + +Dualshock4Controller::~Dualshock4Controller() = default; + +// static +bool Dualshock4Controller::IsDualshock4(GamepadId gamepad_id) { + return gamepad_id == GamepadId::kSonyProduct05c4 || + gamepad_id == GamepadId::kSonyProduct09cc || + gamepad_id == GamepadId::kScufProduct7725; +} + +// static +GamepadBusType Dualshock4Controller::BusTypeFromVersionNumber( + uint32_t version_number) { + // RawInputDataFetcher on Windows does not distinguish devices by bus type. + // Detect the transport in use by inspecting the version number reported by + // the device. + if (version_number == kDualshock4VersionUsb) + return GAMEPAD_BUS_USB; + if (version_number == kDualshock4VersionBluetooth) + return GAMEPAD_BUS_BLUETOOTH; + return GAMEPAD_BUS_UNKNOWN; +} + +void Dualshock4Controller::DoShutdown() { + writer_.reset(); +} + +bool Dualshock4Controller::ProcessInputReport(uint8_t report_id, + base::span report, + Gamepad* pad) { + DCHECK(pad); + + // Input report 0x11 is the full-feature mode input report. It includes + // gamepad button and axis state, touch inputs, motion inputs, battery level + // and temperature. Dualshock4 starts sending this report after it has + // received an output report with ID 0x11. Prior to receiving the output + // report, input report 0x01 is sent which includes button and axis state. + // + // Here we only handle the full-feature report. Input report 0x01 is handled + // by the platform's HID data fetcher. + if (report_id != kReportId11 || + report.size_bytes() < sizeof(Dualshock4InputReport11)) { + return false; + } + + const auto* data = + reinterpret_cast(report.data()); + + // Button and axis indices must match the ordering expected by the Dualshock4 + // mapping function. + pad->axes[0] = NormalizeAxis(data->controller_data.axis_left_x); + pad->axes[1] = NormalizeAxis(data->controller_data.axis_left_y); + pad->axes[2] = NormalizeAxis(data->controller_data.axis_right_x); + pad->axes[3] = NormalizeAxis(data->controller_data.axis_left_2); + pad->axes[4] = NormalizeAxis(data->controller_data.axis_right_2); + pad->axes[5] = NormalizeAxis(data->controller_data.axis_right_y); + pad->axes[9] = NormalizeDpad(data->controller_data.axis_dpad); + const bool button_values[] = { + data->controller_data.button_square, + data->controller_data.button_cross, + data->controller_data.button_circle, + data->controller_data.button_triangle, + data->controller_data.button_left_1, + data->controller_data.button_right_1, + data->controller_data.button_left_2, + data->controller_data.button_right_2, + data->controller_data.button_share, + data->controller_data.button_options, + data->controller_data.button_left_3, + data->controller_data.button_right_3, + data->controller_data.button_ps, + data->controller_data.button_touch, + }; + for (size_t i = 0; i < base::size(button_values); ++i) { + pad->buttons[i].pressed = button_values[i]; + pad->buttons[i].touched = button_values[i]; + pad->buttons[i].value = button_values[i] ? 1.0 : 0.0; + } + pad->timestamp = GamepadDataFetcher::CurrentTimeInMicroseconds(); + return true; +} + +void Dualshock4Controller::SetVibration(double strong_magnitude, + double weak_magnitude) { + // Genuine DualShock 4 gamepads use an alternate output report when connected + // over Bluetooth. Always send USB-mode reports to SCUF Vantage gamepads. + if (bus_type_ == GAMEPAD_BUS_BLUETOOTH && + gamepad_id_ != GamepadId::kScufProduct7725) { + SetVibrationBluetooth(strong_magnitude, weak_magnitude); + return; + } + + SetVibrationUsb(strong_magnitude, weak_magnitude); +} + +void Dualshock4Controller::SetVibrationUsb(double strong_magnitude, + double weak_magnitude) { + DCHECK(writer_); + // Construct a USB output report with report ID 0x05. In USB mode, the 0x05 + // report is used to control vibration, LEDs, and audio volume. + // https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c#L2105 + std::array control_report; + control_report.fill(0); + control_report[0] = kReportId05; + control_report[1] = 0x01; // motor only, don't update LEDs + control_report[4] = + base::ClampRound(weak_magnitude * kRumbleMagnitudeMax); + control_report[5] = + base::ClampRound(strong_magnitude * kRumbleMagnitudeMax); + + writer_->WriteOutputReport(control_report); +} + +void Dualshock4Controller::SetVibrationBluetooth(double strong_magnitude, + double weak_magnitude) { + DCHECK(writer_); + // Construct a Bluetooth output report with report ID 0x11. In Bluetooth mode, + // the 0x11 report is used to control vibration, LEDs, and audio volume. + // https://www.psdevwiki.com/ps4/DS4-BT#0x11_2 + std::array control_report; + control_report.fill(0); + control_report[0] = kReportId11; + control_report[1] = 0xc0; // unknown + control_report[2] = 0x20; // unknown + control_report[3] = 0xf1; // motor only, don't update LEDs + control_report[4] = 0x04; // unknown + control_report[6] = + base::ClampRound(weak_magnitude * kRumbleMagnitudeMax); + control_report[7] = + base::ClampRound(strong_magnitude * kRumbleMagnitudeMax); + control_report[21] = 0x43; // volume left + control_report[22] = 0x43; // volume right + control_report[24] = 0x4d; // volume speaker + control_report[25] = 0x85; // unknown + + // The last four bytes of the report hold a CRC32 checksum. Compute the + // checksum and store it in little-endian byte order. + uint32_t crc = ComputeDualshock4Checksum( + base::make_span(control_report.data(), control_report.size() - 4)); + control_report[control_report.size() - 4] = crc & 0xff; + control_report[control_report.size() - 3] = (crc >> 8) & 0xff; + control_report[control_report.size() - 2] = (crc >> 16) & 0xff; + control_report[control_report.size() - 1] = (crc >> 24) & 0xff; + + writer_->WriteOutputReport(control_report); +} + +base::WeakPtr Dualshock4Controller::GetWeakPtr() { + return weak_factory_.GetWeakPtr(); +} + +} // namespace device diff --git a/pool/shard011/C++/0121810_chris-ostrouchov-problem-1.cpp b/pool/shard011/C++/0121810_chris-ostrouchov-problem-1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78f938d0532af3f9005f9a788772a96fb906fd14 --- /dev/null +++ b/pool/shard011/C++/0121810_chris-ostrouchov-problem-1.cpp @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +int main() { + std::string s; + + for (std::string line; std::getline(std::cin, line);) { + s.append(line); + } + + bool inside_quote = false; + + std::string token; + + int start = 0; + int end = 0; + + for (unsigned int i=0; i +#include +#include +#include "../include/PLYImage.h" + +using namespace std; + +PLYImage::PLYImage() : m_data(nullptr), m_x(0), m_y(0), m_z(0), m_maxRaw(0), m_path(string()) {} + +PLYImage::PLYImage(int x, int y, int z) { + assert((x >= 0) && (y >= 0) && (z >= 0)); + m_data = new double[x * y * z]; + memset(m_data, 0, sizeof(double) * x * y * z); + m_x = x; + m_y = y; + m_z = z; + m_maxRaw = 0; + m_path = string(); +} + +PLYImage::PLYImage(const PLYImage &other) { + m_data = new double[other.m_x * other.m_y * other.m_z]; + memcpy(m_data, other.m_data, sizeof(double) * other.m_x * other.m_y * other.m_z); + m_x = other.m_x; + m_y = other.m_y; + m_z = other.m_z; + m_maxRaw = other.m_maxRaw; + m_path = other.m_path; +} + +PLYImage::~PLYImage() { + delete [] m_data; + m_data = nullptr; +} + +PLYImage& PLYImage::operator=(const PLYImage &other) { + if (this == &other) + return *this; + + this->~PLYImage(); + m_data = new double[other.m_x * other.m_y * other.m_z]; + memcpy(m_data, other.m_data, sizeof(double) * other.m_x * other.m_y * other.m_z); + m_x = other.m_x; + m_y = other.m_y; + m_z = other.m_z; + m_maxRaw = other.m_maxRaw; + m_path = other.m_path; + return *this; +} + +void PLYImage::write() const { + FILE* fp = nullptr; + + if ((fp = fopen(m_path.c_str(), "w")) == nullptr) { + fprintf(stderr, "ERROR: write image %s \n", m_path.c_str()); + exit(EXIT_FAILURE); + } + + fprintf(fp, "ply\nformat ascii 1.0\n"); + fprintf(fp, "element vertex %d\n", m_x * m_y * m_z); + fprintf(fp, "property float x\nproperty float y\nproperty float z\n"); + fprintf(fp, "property uchar red\nproperty uchar green\nproperty uchar blue\n"); + fprintf(fp, "end_header\n"); + + for (int k = 0; k < m_z; k++) { + for (int j = 0; j < m_y; j++) { + for (int i = 0; i < m_x; i++) { + int intensity = (int) m_data[k*m_y*m_x + j*m_x + i]; + fprintf(fp, "%f %f %f %d %d %d\n", (float) i/m_x*300, (float) j/m_y*300, (float) k/m_z*300, intensity, intensity, intensity); + } + } + } + + fclose(fp); +} \ No newline at end of file diff --git a/pool/shard011/C++/0121817_mmse_interp_differentiator_cc.cc b/pool/shard011/C++/0121817_mmse_interp_differentiator_cc.cc new file mode 100644 index 0000000000000000000000000000000000000000..f88010850237ddd22306315c7b39a39cf879808d --- /dev/null +++ b/pool/shard011/C++/0121817_mmse_interp_differentiator_cc.cc @@ -0,0 +1,56 @@ +/* -*- c++ -*- */ +/* + * Copyright (C) 2002,2012,2017 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * SPDX-License-Identifier: GPL-3.0-or-later + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "gnuradio/filter/interp_differentiator_taps.h" +#include +#include + +namespace gr { +namespace filter { + +mmse_interp_differentiator_cc::mmse_interp_differentiator_cc() +{ + filters.resize(DNSTEPS + 1); + + for (int i = 0; i < DNSTEPS + 1; i++) { + std::vector t(&Dtaps[i][0], &Dtaps[i][DNTAPS]); + filters[i] = new kernel::fir_filter_ccf(1, t); + } +} + +mmse_interp_differentiator_cc::~mmse_interp_differentiator_cc() +{ + for (int i = 0; i < DNSTEPS + 1; i++) + delete filters[i]; +} + +unsigned mmse_interp_differentiator_cc::ntaps() const { return DNTAPS; } + +unsigned mmse_interp_differentiator_cc::nsteps() const { return DNSTEPS; } + +gr_complex mmse_interp_differentiator_cc::differentiate(const gr_complex input[], + float mu) const +{ + int imu = (int)rint(mu * DNSTEPS); + + if ((imu < 0) || (imu > DNSTEPS)) { + throw std::runtime_error("mmse_interp_differentiator_cc: imu out of bounds."); + } + + gr_complex r = filters[imu]->filter(input); + return r; +} + +} /* namespace filter */ +} /* namespace gr */ diff --git a/pool/shard011/C++/0121818_tlb.cpp b/pool/shard011/C++/0121818_tlb.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9c2d7119388afcd68f325a12aae1d4083fc5feb --- /dev/null +++ b/pool/shard011/C++/0121818_tlb.cpp @@ -0,0 +1,124 @@ +/* ********************************************************** + * Copyright (c) 2015 Google, Inc. All rights reserved. + * **********************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of Google, Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL VMWARE, INC. OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + */ + +#include "tlb.h" +#include "utils.h" +#include + +void +tlb_t::init_blocks() +{ + for (int i = 0; i < num_blocks; i++) { + blocks[i] = new tlb_entry_t; + } +} + +void +tlb_t::request(const memref_t &memref_in) +{ + // XXX: any better way to derive caching_device_t::request? + // Since pid is needed in a lot of places from the beginning to the end, + // it might also not be a good way to write a lot of helper functions + // to isolate them. + + // Unfortunately we need to make a copy for our loop so we can pass + // the right data struct to the parent and stats collectors. + memref_t memref; + // We support larger sizes to improve the IPC perf. + // This means that one memref could touch multiple blocks. + // We treat each block separately for statistics purposes. + addr_t final_addr = memref_in.addr + memref_in.size - 1/*avoid overflow*/; + addr_t final_tag = compute_tag(final_addr); + addr_t tag = compute_tag(memref_in.addr); + memref_pid_t pid = memref_in.pid; + + // Optimization: check last tag and pid if single-block + if (tag == final_tag && tag == last_tag && pid == last_pid) { + // Make sure last_tag and pid are properly in sync. + assert(tag != TAG_INVALID && + tag == get_caching_device_block(last_block_idx, last_way).tag && + pid == ((tlb_entry_t &)get_caching_device_block( + last_block_idx, last_way)).pid); + stats->access(memref_in, true/*hit*/); + if (parent != NULL) + parent->get_stats()->child_access(memref_in, true); + access_update(last_block_idx, last_way); + return; + } + + memref = memref_in; + for (; tag <= final_tag; ++tag) { + int way; + int block_idx = compute_block_idx(tag); + + if (tag + 1 <= final_tag) + memref.size = ((tag + 1) << block_size_bits) - memref.addr; + + for (way = 0; way < associativity; ++way) { + if (get_caching_device_block(block_idx, way).tag == tag && + ((tlb_entry_t &)get_caching_device_block(block_idx, way)).pid == pid) { + stats->access(memref, true/*hit*/); + if (parent != NULL) + parent->get_stats()->child_access(memref, true); + break; + } + } + + if (way == associativity) { + stats->access(memref, false/*miss*/); + // If no parent we assume we get the data from main memory + if (parent != NULL) { + parent->get_stats()->child_access(memref, false); + parent->request(memref); + } + + // XXX: do we need to handle TLB coherency? + + way = replace_which_way(block_idx); + get_caching_device_block(block_idx, way).tag = tag; + ((tlb_entry_t &)get_caching_device_block(block_idx, way)).pid = pid; + } + + access_update(block_idx, way); + + if (tag + 1 <= final_tag) { + addr_t next_addr = (tag + 1) << block_size_bits; + memref.addr = next_addr; + memref.size = final_addr - next_addr + 1/*undo the -1*/; + } + // Optimization: remember last tag and pid + last_tag = tag; + last_way = way; + last_block_idx = block_idx; + last_pid = pid; + } +} diff --git a/pool/shard011/C++/0121819_bookmark_api_helpers.cc b/pool/shard011/C++/0121819_bookmark_api_helpers.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b6a2522e9846919e74a4bec720a8b35ab2e908c --- /dev/null +++ b/pool/shard011/C++/0121819_bookmark_api_helpers.cc @@ -0,0 +1,191 @@ +// 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 "chrome/browser/extensions/api/bookmarks/bookmark_api_helpers.h" + +#include // For floor() +#include + +#include "base/strings/string_number_conversions.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/bookmarks/bookmark_model.h" +#include "chrome/browser/extensions/api/bookmarks/bookmark_api_constants.h" +#include "chrome/common/extensions/api/bookmarks.h" + +namespace extensions { + +namespace keys = bookmark_api_constants; +using api::bookmarks::BookmarkTreeNode; + +namespace bookmark_api_helpers { + +namespace { + +void AddNodeHelper(const BookmarkNode* node, + std::vector >* nodes, + bool recurse, + bool only_folders) { + if (node->IsVisible()) { + linked_ptr new_node(GetBookmarkTreeNode(node, + recurse, + only_folders)); + nodes->push_back(new_node); + } +} + +// TODO(mwrosen): Remove this function once chrome.bookmarkManagerPrivate is +// refactored to use the JSON schema compiler. +void AddNodeHelper(const BookmarkNode* node, + base::ListValue* list, + bool recurse, + bool only_folders) { + if (node->IsVisible()) { + base::DictionaryValue* dict = + GetNodeDictionary(node, recurse, only_folders); + list->Append(dict); + } +} + +} // namespace + +BookmarkTreeNode* GetBookmarkTreeNode(const BookmarkNode* node, + bool recurse, + bool only_folders) { + BookmarkTreeNode* bookmark_tree_node = new BookmarkTreeNode; + + bookmark_tree_node->id = base::Int64ToString(node->id()); + + const BookmarkNode* parent = node->parent(); + if (parent) { + bookmark_tree_node->parent_id.reset(new std::string( + base::Int64ToString(parent->id()))); + bookmark_tree_node->index.reset(new int(parent->GetIndexOf(node))); + } + + if (!node->is_folder()) { + bookmark_tree_node->url.reset(new std::string(node->url().spec())); + } else { + // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds. + base::Time t = node->date_folder_modified(); + if (!t.is_null()) { + bookmark_tree_node->date_group_modified.reset( + new double(floor(t.ToDoubleT() * 1000))); + } + } + + bookmark_tree_node->title = UTF16ToUTF8(node->GetTitle()); + if (!node->date_added().is_null()) { + // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds. + bookmark_tree_node->date_added.reset( + new double(floor(node->date_added().ToDoubleT() * 1000))); + } + + if (recurse && node->is_folder()) { + std::vector > children; + for (int i = 0; i < node->child_count(); ++i) { + const BookmarkNode* child = node->GetChild(i); + if (child->IsVisible() && (!only_folders || child->is_folder())) { + linked_ptr child_node( + GetBookmarkTreeNode(child, true, only_folders)); + children.push_back(child_node); + } + } + bookmark_tree_node->children.reset( + new std::vector >(children)); + } + return bookmark_tree_node; +} + +base::DictionaryValue* GetNodeDictionary(const BookmarkNode* node, + bool recurse, + bool only_folders) { + base::DictionaryValue* dict = new base::DictionaryValue; + dict->SetString(keys::kIdKey, base::Int64ToString(node->id())); + + const BookmarkNode* parent = node->parent(); + if (parent) { + dict->SetString(keys::kParentIdKey, base::Int64ToString(parent->id())); + dict->SetInteger(keys::kIndexKey, parent->GetIndexOf(node)); + } + + if (!node->is_folder()) { + dict->SetString(keys::kUrlKey, node->url().spec()); + } else { + // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds. + base::Time t = node->date_folder_modified(); + if (!t.is_null()) + dict->SetDouble(keys::kDateFolderModifiedKey, + floor(t.ToDoubleT() * 1000)); + } + + dict->SetString(keys::kTitleKey, node->GetTitle()); + if (!node->date_added().is_null()) { + // Javascript Date wants milliseconds since the epoch, ToDoubleT is seconds. + dict->SetDouble(keys::kDateAddedKey, + floor(node->date_added().ToDoubleT() * 1000)); + } + + if (recurse && node->is_folder()) { + base::ListValue* children = new base::ListValue; + for (int i = 0; i < node->child_count(); ++i) { + const BookmarkNode* child = node->GetChild(i); + if (child->IsVisible() && (!only_folders || child->is_folder())) { + base::DictionaryValue* dict = + GetNodeDictionary(child, true, only_folders); + children->Append(dict); + } + } + dict->Set(keys::kChildrenKey, children); + } + return dict; +} + +void AddNode(const BookmarkNode* node, + std::vector >* nodes, + bool recurse) { + return AddNodeHelper(node, nodes, recurse, false); +} + +void AddNodeFoldersOnly(const BookmarkNode* node, + std::vector >* nodes, + bool recurse) { + return AddNodeHelper(node, nodes, recurse, true); +} + +void AddNode(const BookmarkNode* node, base::ListValue* list, bool recurse) { + return AddNodeHelper(node, list, recurse, false); +} + +void AddNodeFoldersOnly(const BookmarkNode* node, + base::ListValue* list, + bool recurse) { + return AddNodeHelper(node, list, recurse, true); +} + +bool RemoveNode(BookmarkModel* model, + int64 id, + bool recursive, + std::string* error) { + const BookmarkNode* node = model->GetNodeByID(id); + if (!node) { + *error = keys::kNoNodeError; + return false; + } + if (model->is_permanent_node(node)) { + *error = keys::kModifySpecialError; + return false; + } + if (node->is_folder() && !node->empty() && !recursive) { + *error = keys::kFolderNotEmptyError; + return false; + } + + const BookmarkNode* parent = node->parent(); + model->Remove(parent, parent->GetIndexOf(node)); + return true; +} + +} // namespace bookmark_api_helpers +} // namespace extensions diff --git a/pool/shard011/C++/0121822_node.cpp b/pool/shard011/C++/0121822_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9126166dbd3cae2c73eb587f43c9d042ccdb43f2 --- /dev/null +++ b/pool/shard011/C++/0121822_node.cpp @@ -0,0 +1,258 @@ +#include "node.hh" + +#include +#include +#include +#include + +namespace cpprofiler +{ +namespace tree +{ + +Node::Tag Node::getTag() const +{ + // obtain the right-most bit + return static_cast(reinterpret_cast(m_childrenOrFirstChild) & 3); +} + +void Node::setTag(Tag tag) +{ + auto itag = static_cast(tag); + m_childrenOrFirstChild = reinterpret_cast( + (reinterpret_cast(m_childrenOrFirstChild) & ~(3)) | itag); +} + +NodeID *Node::getPtr() const +{ + return reinterpret_cast( + reinterpret_cast(m_childrenOrFirstChild) & ~(3)); +} + +void Node::setPtr(NodeID *ptr) +{ + m_childrenOrFirstChild = reinterpret_cast(ptr); +} + +int Node::childrenCount() const +{ + + auto tag = getTag(); + + switch (tag) + { + case Tag::LEAF: + return 0; + case Tag::ONE_CHILD: + return 1; + case Tag::TWO_CHILDREN: + return 2; + default: + return m_noOfChildren; + } +} + +void Node::setNumberOfChildren(int n) +{ + + const auto old_n = childrenCount(); + + /// Nothing to do + if (old_n == n) + return; + + /// This method works for "open" nodes only + if (old_n != 0) + throw std::exception(); + + if (n == 1) + { + setTag(Tag::ONE_CHILD); + } + else if (n == 2) + { + setTag(Tag::TWO_CHILDREN); + } + else if (n > 2) + { + m_noOfChildren = n; + setPtr(static_cast(malloc(sizeof(NodeID) * n))); + setTag(Tag::MORE_CHILDREN); + } +} + +Node::Node(NodeID parent_nid, int kids) : m_parent(parent_nid) +{ + // debug("node") << " Node()\n"; + setTag(Tag::LEAF); /// initialize to be a leaf first + setNumberOfChildren(kids); +} + +void Node::setChild(NodeID nid, int alt) +{ + + auto kids = childrenCount(); + + if (kids <= 0) + { + throw no_child(); + } + else if (kids <= 2) + { + if (alt == 0) + { + m_childrenOrFirstChild = + reinterpret_cast(static_cast(nid) << 2); + setNumberOfChildren(kids); + } + else + { + if (alt != 1) + { + throw std::exception(); + } + m_noOfChildren = -static_cast(nid); + } + } + else + { + getPtr()[alt] = nid; + } + + auto kids2 = childrenCount(); + + if (kids != kids2) + throw; +} + +NodeID Node::getChild(int alt) const +{ + const auto kids = childrenCount(); + + if (kids <= 0) + { + throw std::exception(); + } + else if (kids <= 2) + { + if (alt == 0) + { + return static_cast(static_cast(reinterpret_cast(m_childrenOrFirstChild) >> 2)); + } + else + { + return NodeID{-m_noOfChildren}; + } + } + else + { + return getPtr()[alt]; + } +} + +void Node::addChild() +{ + + auto kids = childrenCount(); + + switch (kids) + { + case 0: + { + setTag(Tag::ONE_CHILD); + } + break; + case 1: + { + setTag(Tag::TWO_CHILDREN); + } + break; + case 2: + { + /// copy existing children + // auto kids = new NodeID[3]; + auto kids = static_cast(malloc(sizeof(NodeID) * 3)); + kids[0] = getChild(0); + kids[1] = getChild(1); + setPtr(kids); + setTag(Tag::MORE_CHILDREN); + m_noOfChildren = 3; + } + break; + default: + { + m_noOfChildren++; + auto ptr = static_cast(realloc(getPtr(), sizeof(NodeID) * m_noOfChildren)); + setPtr(ptr); + setTag(Tag::MORE_CHILDREN); + } + break; + } +} + +NodeID Node::getParent() const +{ + return m_parent; +} + +void Node::removeChild(int alt) +{ + auto kids = childrenCount(); + + /// Note: only works for two kids for now + if (kids == 2) + { + /// move second child to first position + if (alt == 0) + { + const auto rkid = getChild(1); + setChild(rkid, 0); + } + + setTag(Tag::ONE_CHILD); + } +} + +Node::~Node() +{ + if (getTag() == Tag::MORE_CHILDREN) + { + free(getPtr()); + } +} + +QDebug &&operator<<(QDebug &&out, NodeStatus status) +{ + switch (status) + { + case NodeStatus::SOLVED: + { + out << "SOLVED"; + } + break; + case NodeStatus::FAILED: + { + out << "FAILED"; + } + break; + case NodeStatus::BRANCH: + { + out << "BRANCH"; + } + break; + case NodeStatus::SKIPPED: + { + out << "SKIPPED"; + } + break; + case NodeStatus::UNDETERMINED: + { + out << "UNDETERMINED"; + } + break; + } + return std::move(out); +} + +} // namespace tree +} // namespace cpprofiler \ No newline at end of file diff --git a/pool/shard011/C++/0121823_ResultUrlChecker.cpp b/pool/shard011/C++/0121823_ResultUrlChecker.cpp new file mode 100644 index 0000000000000000000000000000000000000000..08dca90a7f3f4375b9be3181d9054bcc262fb18d --- /dev/null +++ b/pool/shard011/C++/0121823_ResultUrlChecker.cpp @@ -0,0 +1,90 @@ +/* === This file is part of Tomahawk Player - === + * + * Copyright 2012, Leo Franchi + * Copyright 2013, Christian Muehlhaeuser + * + * Tomahawk 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. + * + * Tomahawk 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 Tomahawk. If not, see . + */ + +#include "ResultUrlChecker.h" + +#include +#include +#include + +#include "Query.h" +#include "Result.h" +#include "Source.h" +#include "utils/Logger.h" +#include "utils/NetworkAccessManager.h" + +using namespace Tomahawk; + + +ResultUrlChecker::ResultUrlChecker( const query_ptr& query, QObject* userData, + const QList< result_ptr >& results ) + : QObject( 0 ) + , m_query( query ) + , m_userData( userData ) + , m_results( results ) +{ + check(); +} + + +ResultUrlChecker::~ResultUrlChecker() +{ +} + + +void +ResultUrlChecker::check() +{ + foreach ( const result_ptr& result, m_results ) + { + tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Checking http url:" << result->url(); + QUrl url = QUrl::fromUserInput( result->url() ); + if ( url.isEmpty() || !url.toString().startsWith( "http" ) ) + continue; + + NetworkReply* reply = new NetworkReply( Tomahawk::Utils::nam()->head( QNetworkRequest( url ) ) ); + m_replies.insert( reply, result ); + connect( reply, SIGNAL( finished() ), SLOT( headFinished() ) ); + } +} + + +void +ResultUrlChecker::headFinished() +{ + NetworkReply* r = qobject_cast( sender() ); + r->deleteLater(); + + if ( !m_replies.contains( r ) ) + return; + + result_ptr result = m_replies.value( r ); + m_replies.remove( r ); + + if ( r->reply()->error() == QNetworkReply::NoError ) + { + tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Found valid http url:" << result->url(); + m_validResults << result; + } + else + tDebug( LOGVERBOSE ) << Q_FUNC_INFO << "Found invalid http url:" << result->url() << r->reply()->error(); + + if ( m_replies.isEmpty() ) + emit done(); +} diff --git a/pool/shard011/C++/0121824_TlfeCrossoverSettings.cpp b/pool/shard011/C++/0121824_TlfeCrossoverSettings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4f723dae46cf3ac27b83d0e775b66442b7e24d4 --- /dev/null +++ b/pool/shard011/C++/0121824_TlfeCrossoverSettings.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2004-2006 Milan Cutka + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "stdafx.h" +#include "TlfeCrossoverSettings.h" +#include "TaudioFilterLFEcrossover.h" +#include "TffdshowPageDec.h" +#include "ClfeCrossover.h" + +const TfilterIDFF TlfeCrossoverSettings::idffs = { + /*name*/ _l("LFE Crossover"), + /*id*/ IDFF_filterLFEcrossover, + /*is*/ IDFF_isLFEcrossover, + /*order*/ IDFF_orderLFEcrossover, + /*show*/ IDFF_showLFEcrossover, + /*full*/ 0, + /*half*/ 0, + /*dlgId*/ IDD_LFECROSSOVER, +}; + +TlfeCrossoverSettings::TlfeCrossoverSettings(TintStrColl *Icoll, TfilterIDFFs *filters): TfilterSettingsAudio(sizeof(*this), Icoll, filters, &idffs) +{ + static const TintOptionT iopts[] = { + IDFF_isLFEcrossover , &TlfeCrossoverSettings::is , 0, 0, _l(""), 1, + _l("isLFEcrossover"), 0, + IDFF_showLFEcrossover , &TlfeCrossoverSettings::show , 0, 0, _l(""), 1, + _l("showLFEcrossover"), 1, + IDFF_orderLFEcrossover , &TlfeCrossoverSettings::order , 1, 1, _l(""), 1, + _l("orderLFEcrossover"), 0, + IDFF_LFEcrossoverFreq , &TlfeCrossoverSettings::freq , 1, 300, _l(""), 1, + _l("LFEcrossoverFreq"), 180, + IDFF_LFEcrossoverGain , &TlfeCrossoverSettings::gain , -1000, 1000, _l(""), 1, + _l("LFEcrossoverGain"), -200, + IDFF_LFEcutLR , &TlfeCrossoverSettings::cutLR , 0, 0, _l(""), 1, + _l("IDFF_LFEcutLR"), 0, + 0 + }; + addOptions(iopts); +} + +void TlfeCrossoverSettings::createFilters(size_t filtersorder, Tfilters *filters, TfilterQueue &queue) const +{ + idffOnChange(idffs, filters, queue.temporary); + if (is && show) { + queueFilter(filtersorder, filters, queue); + } +} +void TlfeCrossoverSettings::createPages(TffdshowPageDec *parent) const +{ + parent->addFilterPage(&idffs); +} + +const int* TlfeCrossoverSettings::getResets(unsigned int pageId) +{ + static const int idResets[] = {IDFF_LFEcrossoverFreq, IDFF_LFEcrossoverGain, IDFF_LFEcutLR, 0}; + return idResets; +} + +bool TlfeCrossoverSettings::getTip(unsigned int pageId, char_t *tipS, size_t len) +{ + tsnprintf_s(tipS, len, _TRUNCATE, _l("lowpass frequency: %i\ngain: %.2f"), freq, gain / 100.0f); + return true; +} diff --git a/pool/shard011/C++/0121825_TextPreview.cpp b/pool/shard011/C++/0121825_TextPreview.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c46cd3e55ae18b6aa1cddc2204bd032e3f7bffe --- /dev/null +++ b/pool/shard011/C++/0121825_TextPreview.cpp @@ -0,0 +1,39 @@ +#include "TextPreview.h" + +#include +#include + +#include + +#include +#include + + +static unsigned int windowNumber = 0; + +TextPreviewWindow::TextPreviewWindow() +{ + setWindowTitle("Code Viewer"); + InitUI(); +} + +void TextPreviewWindow::InitUI() +{ + qtTextEdit = new QTextEdit(this); + qtTextEdit->setBaseSize(QSize(300, 200)); + qtTextEdit->setReadOnly(true); + + QFont font; + QFontMetrics metrics(font); + qtTextEdit->setTabStopWidth(8 * metrics.width(' ')); + + qtLayout->addWidget(qtTextEdit); + + GUI::Set(QT_INSTACE::TEXT_PREVIEW, (void*)this); +} + +void TextPreviewWindow::RenderText(const char* text) +{ + qtTextEdit->setPlainText(text); +} + diff --git a/pool/shard011/C++/0121827_commandsdlg.cpp b/pool/shard011/C++/0121827_commandsdlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cf709a2256d52b9f29e8134524ddd569ff5e89e0 --- /dev/null +++ b/pool/shard011/C++/0121827_commandsdlg.cpp @@ -0,0 +1,75 @@ +// CommandsDlg.cpp : implementation file +// + +#include "stdafx.h" +#include "Radiant.h" +#include "CommandsDlg.h" +#include "MainFrm.h" + +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CCommandsDlg dialog + + +CCommandsDlg::CCommandsDlg(CWnd* pParent /*=NULL*/) + : CDialog(CCommandsDlg::IDD, pParent) +{ + //{{AFX_DATA_INIT(CCommandsDlg) + // NOTE: the ClassWizard will add member initialization here + //}}AFX_DATA_INIT +} + + +void CCommandsDlg::DoDataExchange(CDataExchange* pDX) +{ + CDialog::DoDataExchange(pDX); + //{{AFX_DATA_MAP(CCommandsDlg) + DDX_Control(pDX, IDC_LIST_COMMANDS, m_lstCommands); + //}}AFX_DATA_MAP +} + + +BEGIN_MESSAGE_MAP(CCommandsDlg, CDialog) + //{{AFX_MSG_MAP(CCommandsDlg) + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CCommandsDlg message handlers + +BOOL CCommandsDlg::OnInitDialog() +{ + CDialog::OnInitDialog(); + m_lstCommands.SetTabStops(96); + int nCount = g_nCommandCount; + for (int n = 0; n < nCount; n++) + { + CString strLine; + char c = g_Commands[n].m_nKey; + CString strKeys = c; + for (int k = 0; k < g_nKeyCount; k++) + { + if (g_Keys[k].m_nVKKey == g_Commands[n].m_nKey) + { + strKeys = g_Keys[k].m_strName; + break; + } + } + if (g_Commands[n].m_nModifiers & RAD_SHIFT) + strKeys += "+Shift"; + if (g_Commands[n].m_nModifiers & RAD_ALT) + strKeys += "+Alt"; + if (g_Commands[n].m_nModifiers & RAD_CONTROL) + strKeys += "+Control"; + strLine.Format("%s \t%s", g_Commands[n].m_strCommand, strKeys); + m_lstCommands.AddString(strLine); + } + + return TRUE; // return TRUE unless you set the focus to a control + // EXCEPTION: OCX Property Pages should return FALSE +} diff --git a/pool/shard011/C++/0121828_drop_table_node.cpp b/pool/shard011/C++/0121828_drop_table_node.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4815de19922c2b7d86fb34c1f6d77dd7c3e1b88 --- /dev/null +++ b/pool/shard011/C++/0121828_drop_table_node.cpp @@ -0,0 +1,27 @@ +#include "drop_table_node.hpp" + +namespace opossum { + +DropTableNode::DropTableNode(const std::string& init_table_name, const bool init_if_exists) + : AbstractNonQueryNode(LQPNodeType::DropTable), table_name(init_table_name), if_exists(init_if_exists) {} + +std::string DropTableNode::description(const DescriptionMode mode) const { + return std::string("[DropTable] Name: '") + table_name + "'"; +} + +size_t DropTableNode::_on_shallow_hash() const { + auto hash = boost::hash_value(table_name); + boost::hash_combine(hash, if_exists); + return hash; +} + +std::shared_ptr DropTableNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const { + return DropTableNode::make(table_name, if_exists); +} + +bool DropTableNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const { + const auto& drop_table_node = static_cast(rhs); + return table_name == drop_table_node.table_name && if_exists == drop_table_node.if_exists; +} + +} // namespace opossum diff --git a/pool/shard011/C++/0121829_dublin_traceroute.cc b/pool/shard011/C++/0121829_dublin_traceroute.cc new file mode 100644 index 0000000000000000000000000000000000000000..f59172f8971e640ea5f3235281e4706548575509 --- /dev/null +++ b/pool/shard011/C++/0121829_dublin_traceroute.cc @@ -0,0 +1,297 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ + +/** + * \file dublin_traceroute.cc + * \author Andrea Barberio + * \copyright 2-clause BSD + * \date October 2015 + * \brief Main class for the NAT-aware multipath traceroute + * + * This module contains the implementation of the NAT-aware multipath + * traceroute known as dublin-traceroute. + * + * \sa dublin_traceroute.h + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +extern int errno; + +#include + +#include "dublintraceroute/dublin_traceroute.h" +#include "dublintraceroute/hops.h" +#include "dublintraceroute/udpv4probe.h" + +/* + * Dublin Traceroute + * NAT-aware extension of paris-traceroute based on libtins + * + * https://dublin-traceroute.net + * http://paris-traceroute.net + * https://libtins.github.io + */ + + +#define SNIFFER_TIMEOUT_MS 2000 + + +Tins::Timestamp extract_timestamp_from_msg(struct msghdr &msg) { + int level, type; + struct cmsghdr *cm; + struct timeval *tvp = NULL, + tv, + now; + // if there's no timestamp in the control message, fall back to + // gettimeofday, and get it early in this function + if (gettimeofday(&now, NULL) == -1) { + std::cerr << strerror(errno) << std::endl; + return Tins::Timestamp(); + } + for (cm = CMSG_FIRSTHDR(&msg); cm != NULL; cm = CMSG_NXTHDR(&msg, cm)) + { + level = cm->cmsg_level; + type = cm->cmsg_type; + if (SOL_SOCKET == level && SO_TIMESTAMP == type) { + tvp = (struct timeval *) CMSG_DATA(cm); + break; + } + } + if (tvp != NULL) { + tv.tv_sec = tvp->tv_sec; + tv.tv_usec = tvp->tv_usec; + return Tins::Timestamp(tv); + } + return Tins::Timestamp(now); +} + +/** \brief Method that validates the arguments passed at the construction + * + * This method checks that the arguments passed at the construction are valid + * and in the expected range. + * + * \sa DublinTraceroute + * + * \return none + */ +const void DublinTraceroute::validate_arguments() { + // it is not necessary to validate srcport, dstport, npaths and + // broken_nat, as they are already constrained by their types. + // Similarly for min_ttl and max_ttl, but the latter must be greater or + // equal than the former. + if (min_ttl_ > max_ttl_) { + throw std::invalid_argument( + "max-ttl must be greater or equal than min-ttl"); + } + if (delay_ > 1000) { + throw std::invalid_argument( + "delay must be between 0 and 1000 milliseconds"); + } + if (type_ <= probe_type::min || type_ >= probe_type::max) { + throw std::invalid_argument( + "invalid probe type"); + } +} + + +/** \brief run the multipath traceroute + * + * This method will execute a multipath traceroute. The way it operates is by + * crafting and sending packets suitable for a multipath traceroute, and + * sniffind the network traffic for the replies. + * + * \sa TracerouteResults + * \returns an instance of TracerouteResults + */ +std::shared_ptr DublinTraceroute::traceroute() { + // avoid running multiple traceroutes + if (mutex_tracerouting.try_lock() == false) + throw DublinTracerouteInProgressException("Traceroute already in progress"); + + validate_arguments(); + + // Resolve the target host + try { + target(Tins::Utils::resolve_domain(dst())); + } catch (std::runtime_error) { + target(Tins::IPv4Address(dst())); + } + + uint16_t num_packets = (max_ttl() - min_ttl() + 1) * npaths(); + std::chrono::steady_clock::time_point deadline = \ + std::chrono::steady_clock::now() + \ + std::chrono::milliseconds(SNIFFER_TIMEOUT_MS) + \ + std::chrono::milliseconds(delay() * num_packets); + // configure the sniffing handler + auto handler = std::bind( + &DublinTraceroute::sniffer_callback, + this, + std::placeholders::_1 + ); + + // start the ICMP listener + int sock = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); + if (sock == -1) { + throw std::runtime_error(strerror(errno)); + } + int ts_flag = 1; + int ret; + if ((ret = setsockopt(sock, SOL_SOCKET, SO_TIMESTAMP, (int *)&ts_flag, sizeof(ts_flag))) == -1) { + throw std::runtime_error(strerror(errno)); + } + std::thread listener_thread( + [&]() { + size_t received; + char buf[512]; + struct msghdr msg; + memset(&msg, 0, sizeof(msg)); + struct iovec iov[1]; + iov[0].iov_base = buf; + iov[0].iov_len = sizeof(buf); + msg.msg_iov = iov; + msg.msg_iovlen = sizeof(iov) / sizeof(struct iovec); + struct csmghdr *cmsg; + msg.msg_control = cmsg; + msg.msg_controllen = 0; + while (std::chrono::steady_clock::now() <= deadline) { + received = recvmsg(sock, &msg, MSG_DONTWAIT); + if (received == -1) { + if (errno != EAGAIN && errno != EWOULDBLOCK) { + std::cerr << strerror(errno) << std::endl; + } + } else if (msg.msg_flags & MSG_TRUNC) { + std::cerr << "Warning: received datagram too large for buffer" << std::endl; + } else if (received < 20) { + std::cerr << "Warning: short read, less than 20 bytes" << std::endl; + } else if (buf[0] >> 4 == 4) { + // is it IP version 4? Then enqueue it + // for processing + Tins::IP *ip; + try { + ip = new Tins::IP((const uint8_t *)buf, received); + } catch (Tins::malformed_packet&) { + std::cerr << "Warning: malformed packet" << std::endl; + continue; + } + // Tins::Timestamp is a timeval struct, + // so no monotonic clock anyway.. + auto timestamp = extract_timestamp_from_msg((struct msghdr &)msg); + Tins::Packet packet = Tins::Packet((Tins::PDU *)ip, timestamp); + handler(packet); + delete ip; + } + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + } + close(sock); + } + ); + + std::shared_ptr flows(new flow_map_t); + + uint16_t iterated_port = dstport(); + if(use_srcport_for_path_generation()) iterated_port = srcport(); + uint16_t end_port = iterated_port + npaths(); + + // forge the packets to send + for (iterated_port; iterated_port < end_port; iterated_port++) { + /* Forge the packets to send and append them to the packets + * vector. + * To force a packet through the same network flow, it has to + * maintain several constant fields that will be used for the + * ECMP hashing. These fields are, in the case of IP+UDP: + * + * IPv4.tos + * IPv4.proto + * IPv4.src + * IPv4.dst + * UDP.sport + * UDP.dport + */ + Hops hops; + for (uint8_t ttl = min_ttl_; ttl <= max_ttl_; ttl++) { + /* + * Adjust the payload for each flow to obtain the same UDP + * checksum. The UDP checksum is used to identify the flow. + */ + + UDPv4Probe *probe = NULL; + if(use_srcport_for_path_generation()){ + probe = new UDPv4Probe(target(), dstport(), iterated_port, ttl); + } + else{ + probe = new UDPv4Probe(target(), iterated_port, srcport(), ttl); + //UDPv4Probe probe(target(), dport, srcport(), ttl); + } + Tins::IP *packet; + try { + packet = &probe->send(); + } catch (std::runtime_error &e) { + std::stringstream ss; + ss << "Cannot send packet: " << e.what(); + throw DublinTracerouteException(ss.str()); + } + auto now = Tins::Timestamp::current_time(); + + try { + Hop hop; + hop.sent(*packet); + hop.sent_timestamp(now); + hops.push_back(hop); + } catch (std::runtime_error e) { + std::stringstream ss; + ss << "Cannot find flow: " << iterated_port << ": " << e.what(); + throw DublinTracerouteException(ss.str()); + } + std::this_thread::sleep_for(std::chrono::milliseconds(delay())); + } + flows->insert(std::make_pair(iterated_port, std::make_shared(hops))); + } + + listener_thread.join(); + + TracerouteResults *results = new TracerouteResults(flows, min_ttl_, broken_nat(), use_srcport_for_path_generation()); + + match_sniffed_packets(*results); + if (!no_dns()) { + match_hostnames(*results, flows); + } + + mutex_tracerouting.unlock(); + + return std::make_shared(*results); +} + + +bool DublinTraceroute::sniffer_callback(Tins::Packet &packet) { + std::lock_guard lock(mutex_sniffed_packets); + sniffed_packets.push_back(std::make_shared(packet)); + return true; +} + + +void DublinTraceroute::match_sniffed_packets(TracerouteResults &results) { + for (auto &packet: sniffed_packets) + results.match_packet(*packet); +} + + +void DublinTraceroute::match_hostnames(TracerouteResults &results, std::shared_ptr flows) { + // TODO make this asynchronous + // TODO move this to a proxy method ::resolve() in TracerouteResults + for (auto &iter: *flows) { + auto packets = iter.second; + for (auto &hop: *packets) { + hop.resolve(); + } + } +} + + diff --git a/pool/shard011/C++/0121830_regular-expression-matching.cc b/pool/shard011/C++/0121830_regular-expression-matching.cc new file mode 100644 index 0000000000000000000000000000000000000000..16329fc40e130c189ac4cdc0f0cccf73a3bbe923 --- /dev/null +++ b/pool/shard011/C++/0121830_regular-expression-matching.cc @@ -0,0 +1,69 @@ +#include +#include +#include + +using namespace std; + +class Solution { +public: + bool isMatch(const char *s, const char *p) { + //cout << "'" << s << "', '" << p << "'" << endl; + if(*s == '\0' && *p == '\0') return true; + if(*s != '\0' && *p == '\0') return false; + if(*s == '\0' && *p != '\0') { + while(*(p + 1) == '*') + p += 2; + if(*p == '\0') + return true; + return false; + } + if(*s == *p || *p == '.') { + if(*(p + 1) != '*') { + return isMatch(s + 1, p + 1); + } + return (isMatch(s + 1, p) || isMatch(s, p + 2)); + } + else { + if(*(p + 1) != '*') + return false; + return isMatch(s, p + 2); + } + } + + bool isMatch2(const char *s, const char *p) { + if (*p == '\0') return *s == '\0'; + + if (*(p+1) != '*') { + return ((*p == *s) || (*p == '.' && *s != '\0')) && isMatch(s+1, p+1); + } + while ((*p == *s) || (*p == '.' && *s != '\0')) { + if (isMatch(s, p+2)) return true; + s++; + } + return isMatch(s, p+2); + } +}; + +int main(int argc, char *argv[]) { + Solution s; + const char *i1 = argv[1]; + const char *i2 = argv[2]; + auto r = s.isMatch(i1, i2); + cout << r << endl; + + assert(s.isMatch("aaa", "a*a")); + assert(s.isMatch("aabc", "c*a*b..*")); + assert(s.isMatch("aaa", "a*")); + assert(!s.isMatch("aaa", "a")); + assert(!s.isMatch("daab", "c*a*b")); + assert(!s.isMatch("aa", "a")); + assert(!s.isMatch("aabcddddc", ".*dd")); + assert(s.isMatch("aaa", "a*.*")); + assert(s.isMatch("aab", "c*a*b")); + assert(s.isMatch("aa", ".*")); + assert(s.isMatch("aa", "aa")); + assert(s.isMatch("ab", ".*..c*")); + assert(s.isMatch("aabcddddc", ".*dc")); + assert(s.isMatch("aabcdddd", ".*d")); + return 0; +} diff --git a/pool/shard011/C++/0121831_TestLinkRoute.cpp b/pool/shard011/C++/0121831_TestLinkRoute.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1c0eaf5006365b6724a02e6df4e6ffdc7fbb8f2 --- /dev/null +++ b/pool/shard011/C++/0121831_TestLinkRoute.cpp @@ -0,0 +1,70 @@ +// +// Licensed to Green Energy Corp (www.greenenergycorp.com) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. Green Enery Corp licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// +#include + +#include +#include + +#include + +using namespace std; +using namespace apl; +using namespace apl::dnp; + +BOOST_AUTO_TEST_SUITE(LinkRouteSuite) + +BOOST_AUTO_TEST_CASE(ComparisonFunctor) +{ + LinkRoute lr1(1, 2); + LinkRoute lr2(1, 3); + LinkRoute lr3(2, 1); + + LinkRoute::LessThan lt; + + BOOST_REQUIRE(lt(lr1, lr3)); + BOOST_REQUIRE_FALSE(lt(lr3, lr1)); + + BOOST_REQUIRE(lt(lr1, lr2)); + BOOST_REQUIRE_FALSE(lt(lr2, lr1)); + + BOOST_REQUIRE_FALSE(lt(lr1, lr1)); +} + +BOOST_AUTO_TEST_CASE(UseWithStlMap) +{ + typedef map RouteMap; + + RouteMap rm; + rm[LinkRoute(4, 1)] = 13; + rm[LinkRoute(4, 1)] = 12; + BOOST_CHECK_EQUAL(12, rm[LinkRoute(4, 1)]); + + { + RouteMap::iterator i = rm.find(LinkRoute(1, 4)); + BOOST_CHECK(rm.end() == i); + } + { + RouteMap::iterator i = rm.find(LinkRoute(4, 1)); + BOOST_REQUIRE_EQUAL(4, i->first.remote); + BOOST_REQUIRE_EQUAL(1, i->first.local); + BOOST_REQUIRE_EQUAL(12, i->second); + } +} + +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard011/C++/0121832_RBNode.cpp b/pool/shard011/C++/0121832_RBNode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..57f337e8288fcf32d83a55b8aab4cce475a83ab1 --- /dev/null +++ b/pool/shard011/C++/0121832_RBNode.cpp @@ -0,0 +1,110 @@ +/******************************************************** + * File: RBNode.cpp + * + * This is the program file for a Red-Black Node + * + * @author Thomas McKeesick + * @version 0.1 8/01/2015 + * + ********************************************************/ + + #include + + #include + #include + + using std::cout; + using std::endl; + using std::string; + + /** + * @brief Constructor for a node that inserts the given data. The colour is red by default + * and the deleted status is false. + * @param data The data that will be contained by the node + */ + template RBNode::RBNode(T data) { + RBNode::data = data; + colour = 'R'; + deleted = false; + } + +template void RBNode::deleteNode() { + deleted = true; +} + +template void RBNode::display(int n) { + string indent = "- "; + + for(int i = 1; i <= n; i++) { + cout << indent; + } + cout << "ROOT: " << data << ", colour: " << colour << endl; + + for(int i = 1; i <= n; i++) { + cout << indent; + } + cout << "LEFT" << endl; + if( lChild == NULL) { + for(int i = 1; i <= n+1; i++) { + cout << indent; + } + cout << "null" << endl; + } else { + lChild->display(n+1); + } + + for(int i = 1; i <= n; i++) { + cout << indent; + } + + cout << "RIGHT" << endl; + + if( rChild == NULL) { + for(int i = 1; i <= n+1; i++) { + cout << indent; + } + cout << "null" << endl; + } else { + rChild->display(n+1); + } +} + +/**************************************************\ + * GETTER METHODS | + **************************************************/ + +template char RBNode::getColour() { + return colour; +} + +template T& RBNode::getData() { + return data; +} + +template bool RBNode::isDeleted() { + return deleted; +} + +/**************************************************\ + * SETTER METHODS | + **************************************************/ + +/** + * @brief Sets the colour of the node to the supplied colour. Must be a char matching + * either BLACK or RED as defined in the header. Must also not be the same colour + * as the current node colour. + * @param c The new colour of the node. + * @return true if the colour change was successful, false otherwise + */ +template bool RBNode::setColour(char c) { + + if( (c == 'R' || c == 'B' ) && c != colour ) { + colour = c; + return true; + } + return false; +} + +template void RBNode::setData(T data) { + RBNode::data = data; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121833_accelerator_util.cc b/pool/shard011/C++/0121833_accelerator_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..b71ba1310b350f07ec0702681044f9644dcddd10 --- /dev/null +++ b/pool/shard011/C++/0121833_accelerator_util.cc @@ -0,0 +1,101 @@ +// Copyright (c) 2013 GitHub, Inc. +// Use of this source code is governed by the MIT license that can be +// found in the LICENSE file. + +#include "atom/browser/ui/accelerator_util.h" + +#include + +#include +#include + +#include "atom/common/keyboard_util.h" +#include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" + +namespace accelerator_util { + +bool StringToAccelerator(const std::string& shortcut, + ui::Accelerator* accelerator) { + if (!base::IsStringASCII(shortcut)) { + LOG(ERROR) << "The accelerator string can only contain ASCII characters"; + return false; + } + + std::vector tokens = base::SplitString( + shortcut, "+", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + + // Now, parse it into an accelerator. + int modifiers = ui::EF_NONE; + ui::KeyboardCode key = ui::VKEY_UNKNOWN; + for (const auto& token : tokens) { + bool shifted = false; + ui::KeyboardCode code = atom::KeyboardCodeFromStr(token, &shifted); + if (shifted) + modifiers |= ui::EF_SHIFT_DOWN; + switch (code) { + // The token can be a modifier. + case ui::VKEY_SHIFT: + modifiers |= ui::EF_SHIFT_DOWN; + break; + case ui::VKEY_CONTROL: + modifiers |= ui::EF_CONTROL_DOWN; + break; + case ui::VKEY_MENU: + modifiers |= ui::EF_ALT_DOWN; + break; + case ui::VKEY_COMMAND: + modifiers |= ui::EF_COMMAND_DOWN; + break; + case ui::VKEY_ALTGR: + modifiers |= ui::EF_ALTGR_DOWN; + break; + // Or it is a normal key. + default: + key = code; + } + } + + if (key == ui::VKEY_UNKNOWN) { + LOG(WARNING) << shortcut << " doesn't contain a valid key"; + return false; + } + + *accelerator = ui::Accelerator(key, modifiers); + SetPlatformAccelerator(accelerator); + return true; +} + +void GenerateAcceleratorTable(AcceleratorTable* table, + atom::AtomMenuModel* model) { + int count = model->GetItemCount(); + for (int i = 0; i < count; ++i) { + atom::AtomMenuModel::ItemType type = model->GetTypeAt(i); + if (type == atom::AtomMenuModel::TYPE_SUBMENU) { + auto submodel = model->GetSubmenuModelAt(i); + GenerateAcceleratorTable(table, submodel); + } else { + ui::Accelerator accelerator; + if (model->GetAcceleratorAtWithParams(i, true, &accelerator)) { + MenuItem item = { i, model }; + (*table)[accelerator] = item; + } + } + } +} + +bool TriggerAcceleratorTableCommand(AcceleratorTable* table, + const ui::Accelerator& accelerator) { + if (ContainsKey(*table, accelerator)) { + const accelerator_util::MenuItem& item = (*table)[accelerator]; + if (item.model->IsEnabledAt(item.position)) { + item.model->ActivatedAt(item.position); + return true; + } + } + return false; +} + +} // namespace accelerator_util diff --git a/pool/shard011/C++/0121838_fileout.cpp b/pool/shard011/C++/0121838_fileout.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d603d15493ee1d2fa94c8739c036e37f8716babb --- /dev/null +++ b/pool/shard011/C++/0121838_fileout.cpp @@ -0,0 +1,238 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Script Generator project on Qt Labs. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "fileout.h" +#include "reporthandler.h" + +#include +#include + +bool FileOut::dummy = false; +bool FileOut::diff = false; +bool FileOut::license = false; + +#ifdef Q_OS_LINUX +const char* colorDelete = "\033[31m"; +const char* colorAdd = "\033[32m"; +const char* colorInfo = "\033[36m"; +const char* colorReset = "\033[0m"; +#else +const char* colorDelete = ""; +const char* colorAdd = ""; +const char* colorInfo = ""; +const char* colorReset = ""; +#endif + +FileOut::FileOut(QString n): + name(n), + stream(&tmp), + isDone(false) +{} + +static int* lcsLength(QList a, QList b) { + const int height = a.size() + 1; + const int width = b.size() + 1; + + int *res = new int[width * height]; + + for (int row=0; row a, QList b){ + { + if (type == Unchanged) { + if ((end - start) > 9) { + for (int i = start; i <= start+2; i++) + printf(" %s\n", a[i].data()); + printf("%s=\n= %d more lines\n=%s\n", colorInfo, end - start - 6, colorReset); + for (int i = end-2; i <= end; i++) + printf(" %s\n", a[i].data()); + } + else + for (int i = start; i <= end; i++) + printf(" %s\n", a[i].data()); + } + else if(type == Add) { + printf("%s", colorAdd); + for (int i = start; i <= end; i++){ + printf("+ %s\n", b[i].data()); + } + printf("%s", colorReset); + } + else if (type == Delete) { + printf("%s", colorDelete); + for (int i = start; i <= end; i++) { + printf("- %s\n", a[i].data()); + } + printf("%s", colorReset); + } + } + } +}; + +static QList *unitAppend(QList *res, Type type, int pos) +{ + if (res == 0) { + res = new QList; + res->append(new Unit(type, pos)); + return res; + } + + Unit *last = res->last(); + if (last->type == type) { + last->end = pos; + } else { + res->append(new Unit(type, pos)); + } + return res; +} + +static QList *diffHelper(int *lcs, QList a, QList b, int row, int col) { + if (row>0 && col>0 && (a[row-1] == b[col-1])) { + return unitAppend(diffHelper(lcs, a, b, row-1, col-1), Unchanged, row-1); + } + else { + int width = b.size()+1; + if ((col > 0) && ((row==0) || + lcs[width * row + col-1] >= lcs[width * (row-1) + col])) + { + return unitAppend(diffHelper(lcs, a, b, row, col-1), Add, col-1); + } + else if((row > 0) && ((col==0) || + lcs[width * row + col-1] < lcs[width * (row-1) + col])){ + return unitAppend(diffHelper(lcs, a, b, row-1, col), Delete, row-1);; + } + } + delete lcs; + return 0; +} + +static void diff(QList a, QList b) { + QList *res = diffHelper(lcsLength(a, b), a, b, a.size(), b.size()); + for (int i=0; i < res->size(); i++) { + Unit *unit = res->at(i); + unit->print(a, b); + delete(unit); + } + delete(res); +} + + +bool FileOut::done() { + Q_ASSERT( !isDone ); + isDone = true; + bool fileEqual = false; + QFile fileRead(name); + QFileInfo info(fileRead); + stream.flush(); + QByteArray original; + if (info.exists() && (diff || (info.size() == tmp.size()))) { + if ( !fileRead.open(QIODevice::ReadOnly) ) { + ReportHandler::warning(QString("failed to open file '%1' for reading") + .arg(fileRead.fileName())); + return false; + } + + original = fileRead.readAll(); + fileRead.close(); + fileEqual = (original == tmp); + } + + if( !fileEqual ) { + if( !FileOut::dummy ) { + QDir dir(info.absolutePath()); + if (!dir.mkpath(dir.absolutePath())) { + ReportHandler::warning(QString("unable to create directory '%1'") + .arg(dir.absolutePath())); + return false; + } + + QFile fileWrite(name); + if (!fileWrite.open(QIODevice::WriteOnly)) { + ReportHandler::warning(QString("failed to open file '%1' for writing") + .arg(fileWrite.fileName())); + return false; + } + stream.setDevice(&fileWrite); + stream << tmp; + } + if (diff) { + printf("%sFile: %s%s\n", colorInfo, qPrintable(name), colorReset); + + ::diff(original.split('\n'), tmp.split('\n')); + + printf("\n"); + } + return true; + } + return false; +} diff --git a/pool/shard011/C++/0121839_token_stream_test.cc b/pool/shard011/C++/0121839_token_stream_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e277da326761105ba17de5226d69548157318579 --- /dev/null +++ b/pool/shard011/C++/0121839_token_stream_test.cc @@ -0,0 +1,136 @@ +// Copyright 2016 The Bazel Authors. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include + +#include "src/tools/singlejar/test_util.h" +#include "src/tools/singlejar/token_stream.h" +#include "gtest/gtest.h" + +#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0])) + +// Indirect command file contents (each string is a separate line): +static const char *lines[] = { + "-cmd1 foo", "bar", "'abcd'", "\"efg\"", "hi'x'", + "'\\jkl'", "\"\\xyz\"", "\"\\\"0\"", "cont\\", "inue x", +}; + +// Tokens that the tokenizer is expected to return from the +// indirect file above: +static const char *expected_tokens[] = { + "-cmd1", "foo", "bar", "abcd", "efg", "hix", + "\\jkl", "\\xyz", "\"0", "continue", "x", +}; + +// Simple '-foo -bar' command line. +TEST(TokenStreamTest, SimpleArgs) { + const char *args[] = {"-foo", "-bar"}; + ArgTokenStream token_stream(ARRAY_SIZE(args), args); + EXPECT_EQ("-foo", token_stream.token()); + bool flag_foo = false; + EXPECT_FALSE(token_stream.MatchAndSet("-bar", &flag_foo)); + ASSERT_TRUE(token_stream.MatchAndSet("-foo", &flag_foo)); + EXPECT_TRUE(flag_foo); + bool flag_bar = false; + ASSERT_TRUE(token_stream.MatchAndSet("-bar", &flag_bar)); + EXPECT_TRUE(flag_bar); + EXPECT_TRUE(token_stream.AtEnd()); +} + +// '-foo @commandfile -bar' command line. +TEST(TokenStreamTest, CommandFile) { + const char *tempdir = getenv("TEST_TMPDIR"); + ASSERT_NE(nullptr, tempdir); + std::string command_file_path = singlejar_test_util::OutputFilePath("tokens"); + FILE *fp = fopen(command_file_path.c_str(), "w"); + ASSERT_NE(nullptr, fp); + for (size_t i = 0; i < ARRAY_SIZE(lines); ++i) { + fprintf(fp, "%s\n", lines[i]); + } + fclose(fp); + + std::string command_file_arg = std::string("@") + command_file_path; + const char *args[] = {"-before_file", "", "-after_file"}; + args[1] = command_file_arg.c_str(); + ArgTokenStream token_stream(ARRAY_SIZE(args), args); + bool flag = false; + ASSERT_TRUE(token_stream.MatchAndSet("-before_file", &flag)); + EXPECT_TRUE(flag); + for (size_t i = 0; i < ARRAY_SIZE(expected_tokens); ++i) { + flag = false; + ASSERT_TRUE(token_stream.MatchAndSet(expected_tokens[i], &flag)); + EXPECT_TRUE(flag); + } + ASSERT_TRUE(token_stream.MatchAndSet("-after_file", &flag)); + EXPECT_TRUE(flag); + EXPECT_TRUE(token_stream.AtEnd()); +} + +// '--arg1 optval1 --arg2' command line. +TEST(TokenStreamTest, OptargOne) { + const char *args[] = {"--arg1", "optval1", "--arg2", "--arg3", "optval3"}; + ArgTokenStream token_stream(ARRAY_SIZE(args), args); + std::string optval; + EXPECT_FALSE(token_stream.MatchAndSet("--foo", &optval)); + ASSERT_TRUE(token_stream.MatchAndSet("--arg1", &optval)); + EXPECT_EQ("optval1", optval); + bool flag = true; + ASSERT_TRUE(token_stream.MatchAndSet("--arg2", &flag)); + EXPECT_TRUE(flag); + ASSERT_TRUE(token_stream.MatchAndSet("--arg3", &optval)); + EXPECT_EQ("optval3", optval); + EXPECT_TRUE(token_stream.AtEnd()); +} + +// '--arg1 value1 value2 --arg2' command line. +TEST(TokenStreamTest, OptargMulti) { + const char *args[] = {"--arg1", "value11", "value12", + "--arg2", "value21", "value22"}; + ArgTokenStream token_stream(ARRAY_SIZE(args), args); + std::vector optvals1; + EXPECT_FALSE(token_stream.MatchAndSet("--arg2", &optvals1)); + ASSERT_TRUE(token_stream.MatchAndSet("--arg1", &optvals1)); + ASSERT_EQ(2, optvals1.size()); + EXPECT_EQ("value11", optvals1[0]); + EXPECT_EQ("value12", optvals1[1]); + + std::vector optvals2; + ASSERT_TRUE(token_stream.MatchAndSet("--arg2", &optvals2)); + ASSERT_EQ(2, optvals2.size()); + EXPECT_EQ("value21", optvals2[0]); + EXPECT_EQ("value22", optvals2[1]); + + EXPECT_TRUE(token_stream.AtEnd()); +} + +// '--arg1 optval1,optsuff1 optval2,optstuff2 --arg2' command line. +TEST(TokenStreamTest, OptargMultiSplit) { + const char *args[] = {"--arg1", "optval1,optsuff1", "optval2,optsuff2", + "optvalnosuff"}; + ArgTokenStream token_stream(ARRAY_SIZE(args), args); + std::vector > optvals1; + + EXPECT_FALSE(token_stream.MatchAndSet("--foo", &optvals1)); + ASSERT_TRUE(token_stream.MatchAndSet("--arg1", &optvals1)); + + ASSERT_EQ(3, optvals1.size()); + EXPECT_EQ("optval1", optvals1[0].first); + EXPECT_EQ("optsuff1", optvals1[0].second); + EXPECT_EQ("optval2", optvals1[1].first); + EXPECT_EQ("optsuff2", optvals1[1].second); + EXPECT_EQ("optvalnosuff", optvals1[2].first); + EXPECT_EQ("", optvals1[2].second); +} diff --git a/pool/shard011/C++/0121840_EppContactDisclose.cpp b/pool/shard011/C++/0121840_EppContactDisclose.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e03c84733fd43fb152cac9bd9a5f69e62bb91a6 --- /dev/null +++ b/pool/shard011/C++/0121840_EppContactDisclose.cpp @@ -0,0 +1,188 @@ +/******************************************************************************* + * The MIT License (MIT) + * + * Copyright (c)2015 Neustar Inc. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + *******************************************************************************/ +#include "EppContactDisclose.hpp" +#include "EppUtil.hpp" + +const int EppContactDisclose::TAG_NAME_INT = 1; +const int EppContactDisclose::TAG_NAME_LOC = 2; +const int EppContactDisclose::TAG_ORG_INT = 3; +const int EppContactDisclose::TAG_ORG_LOC = 4; +const int EppContactDisclose::TAG_ADDR_INT = 5; +const int EppContactDisclose::TAG_ADDR_LOC = 6; +const int EppContactDisclose::TAG_VOICE = 7; +const int EppContactDisclose::TAG_FAX = 8; +const int EppContactDisclose::TAG_EMAIL = 9; + +DOMElement* EppContactDisclose::toXML( DOMDocument& doc, const DOMString& tag ) +{ + DOMElement* body = doc.createElement(tag); + DOMElement* elm; + + body->setAttribute(XS("flag"), (disclose == true) ? XS("1") : XS("0")); + + if( name_int == true ) + { + elm = doc.createElement(XS("name")); + elm->setAttribute(XS("type"), XS("int")); + body->appendChild(elm); + } + if( name_loc == true ) + { + elm = doc.createElement(XS("name")); + elm->setAttribute(XS("type"), XS("loc")); + body->appendChild(elm); + } + if( org_int == true ) + { + elm = doc.createElement(XS("org")); + elm->setAttribute(XS("type"), XS("int")); + body->appendChild(elm); + } + if( org_loc == true ) + { + elm = doc.createElement(XS("org")); + elm->setAttribute(XS("type"), XS("loc")); + body->appendChild(elm); + } + if( addr_int == true ) + { + elm = doc.createElement(XS("addr")); + elm->setAttribute(XS("type"), XS("int")); + body->appendChild(elm); + } + if( addr_loc == true ) + { + elm = doc.createElement(XS("addr")); + elm->setAttribute(XS("type"), XS("loc")); + body->appendChild(elm); + } + if( voice == true ) + { + elm = doc.createElement(XS("voice")); + body->appendChild(elm); + } + if( fax == true ) + { + elm = doc.createElement(XS("fax")); + body->appendChild(elm); + } + if( email == true ) + { + elm = doc.createElement(XS("email")); + body->appendChild(elm); + } + + return body; +} + +EppContactDisclose * EppContactDisclose::fromXML( const DOMNode& root ) +{ + EppContactDisclose * disc = new EppContactDisclose(); + if( disc == null ) + { + return disc; + } + DOMString type = ((DOMElement *) &root)->getAttribute(XS("flag")); + + if( (type.isNotNull()) && + (type.equals("0") || type.equals("f") || type.equals("false") ) ) + { + disc->setDiscloseFlag(false); + } + else + { + disc->setDiscloseFlag(true); + } + + DOMNodeList* list = root.getChildNodes(); + for( unsigned int i = 0; i < list->getLength(); i++ ) + { + DOMNode* node = list->item(i); + DOMString name = node->getLocalName(); + + if( name.isNull() ) + { + name = node->getNodeName(); + } + if( name.isNull() ) + { + continue; + } +// if( name.equals("name") ) + if( name.equals("name") || name.equals("contact:name") ) + { + type = ((DOMElement *) node)->getAttribute(XS("type")); + if( (type.isNotNull()) && type.equals("int") ) + { + disc->set(TAG_NAME_INT, true); + } + else if( (type.isNotNull()) && type.equals("loc") ) + { + disc->set(TAG_NAME_LOC, true); + } + } +// else if( name.equals("org") ) + else if( name.equals("org") || name.equals("contact:org") ) + { + type = ((DOMElement *) node)->getAttribute(XS("type")); + if( (type.isNotNull()) && type.equals("int") ) + { + disc->set(TAG_ORG_INT, true); + } + else if( (type.isNotNull()) && type.equals("loc") ) + { + disc->set(TAG_ORG_LOC, true); + } + } +// else if( name.equals("addr") ) + else if( name.equals("addr") || name.equals("contact:addr") ) + { + type = ((DOMElement *) node)->getAttribute(XS("type")); + if( (type.isNotNull()) && type.equals("int") ) + { + disc->set(TAG_ADDR_INT, true); + } + else if( (type.isNotNull()) && type.equals("loc") ) + { + disc->set(TAG_ADDR_LOC, true); + } + } +// else if( name.equals("voice") ) + else if( name.equals("voice") || name.equals("contact:voice") ) + { + disc->set(TAG_VOICE, true); + } +// else if( name.equals("fax") ) + else if( name.equals("fax") || name.equals("contact:fax") ) + { + disc->set(TAG_FAX, true); + } +// else if( name.equals("email") ) + else if( name.equals("email") || name.equals("contact:email") ) + { + disc->set(TAG_EMAIL, true); + } + } + return disc; +} diff --git a/pool/shard011/C++/0121841_bitcoin.cpp b/pool/shard011/C++/0121841_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9b66afc1c4b90ea3da03849f2b57e0dea1c8c04 --- /dev/null +++ b/pool/shard011/C++/0121841_bitcoin.cpp @@ -0,0 +1,302 @@ +/* + * W.J. van der Laan 2011-2012 + */ + +#include + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "init.h" +#include "util.h" +#include "ui_interface.h" +#include "paymentserver.h" +#include "splashscreen.h" + +#include +#include +#include +#include +#include + +#if QT_VERSION < 0x050000 +#include +#endif + +#ifdef Q_OS_MAC +#include "macdockiconhandler.h" +#endif + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Declare meta types used for QMetaObject::invokeMethod +Q_DECLARE_METATYPE(bool*) + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static SplashScreen *splashref; + +static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + bool ret = false; + // In case of modal message, use blocking connection to wait for user to click a button + QMetaObject::invokeMethod(guiref, "message", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(unsigned int, style), + Q_ARG(bool*, &ret)); + return ret; + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + return false; + } +} + +static bool ThreadSafeAskFee(int64 nFeeRequired) +{ + if(!guiref) + return false; + if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) + return true; + + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); + qApp->processEvents(); + } + printf("init message: %s\n", message.c_str()); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("365coin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. 365Coin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Command-line options take precedence: + ParseParameters(argc, argv); + +#if QT_VERSION < 0x050000 + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); +#endif + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Register meta types used for QMetaObject::invokeMethod + qRegisterMetaType< bool* >(); + + // Do this early as we don't want to bother initializing if we are just calling IPC + // ... but do it after creating app, so QCoreApplication::arguments is initialized: + if (PaymentServer::ipcSendCommandLine()) + exit(0); + PaymentServer* paymentServer = new PaymentServer(&app); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then 365coin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in 365coin.conf in the data directory) + QMessageBox::critical(0, "365Coin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + QApplication::setOrganizationName("365Coin"); + QApplication::setOrganizationDomain("365Coin.org"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + QApplication::setApplicationName("365Coin-Qt-testnet"); + else + QApplication::setApplicationName("365Coin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + +#ifdef Q_OS_MAC + // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) + if(GetBoolArg("-testnet")) { + MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); + } +#endif + + SplashScreen splash(QPixmap(), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + app.setQuitOnLastWindowClosed(false); + + try + { + // Regenerate startup link, to fix links to old versions + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); + + boost::thread_group threadGroup; + + BitcoinGUI window; + guiref = &window; + + QTimer* pollShutdownTimer = new QTimer(guiref); + QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); + pollShutdownTimer->start(200); + + if(AppInit2(threadGroup)) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.addWallet("~Default", &walletModel); + window.setCurrentWallet("~Default"); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Now that initialization/startup is done, process any command-line + // 365coin: URIs + QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); + QTimer::singleShot(100, paymentServer, SLOT(uiReady())); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.removeAllWallets(); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit 365Coin-Qt here + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + } + else + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard011/C++/0121842_DutManager.cpp b/pool/shard011/C++/0121842_DutManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86a96c48d4a5af9b4f280bab2c2b303a9df932d9 --- /dev/null +++ b/pool/shard011/C++/0121842_DutManager.cpp @@ -0,0 +1,65 @@ +/* + * DUTManager.cpp + * + * Copyright (C) ST-Ericsson SA 2011 + * Authors: Srimanta Panda , + * Ola Borgelin , + * Karin Hedlund , + * Markus Andersson for ST-Ericsson. + * License terms: 3-clause BSD license + * + */ + +/* + * @addtogroup DUT Manager + * @{ + */ + +#include "DutManager.h" +#include "Utilities.h" +#include +using namespace std; + +vector DutManager::devices_; + +DUT* DutManager::createDut(Device_t device) +{ + string dutId = getDutId(device); + + DUT* dut = new DUT(device, dutId, SequenceFactory::getProfileSequence()); + devices_.push_back(dut); + + dut->startExecution(); + + return dut; +} + +const DUT* DutManager::getDut(Device_t device) +{ + for (vector::iterator i = devices_.begin(); i != devices_.end(); ++i) { + if ((*i)->getCommDevice() == device) { + return *i; + } + } + + return 0; +} + +void DutManager::destroyDut(Device_t device) +{ + for (vector::iterator i = devices_.begin(); i != devices_.end(); ++i) { + if ((*i)->getCommDevice() == device) { + delete *i; + devices_.erase(i); + break; + } + } +} + +string DutManager::getDutId(Device_t device) +{ + string physicalId = "Device@" + Utilities::convert(comm_get_physical_address(device)); + return physicalId; +} + +/* @} */ diff --git a/pool/shard011/C++/0121843_aggregateip.cc b/pool/shard011/C++/0121843_aggregateip.cc new file mode 100644 index 0000000000000000000000000000000000000000..f214ece74177d7e8fd942e5ba6a83aa0d32c5f92 --- /dev/null +++ b/pool/shard011/C++/0121843_aggregateip.cc @@ -0,0 +1,181 @@ +/* + * aggregateip.{cc,hh} -- set aggregate annotation based on IP field + * Eddie Kohler + * + * Copyright (c) 2001-2003 International Computer Science Institute + * Copyright (c) 2005-2006 Regents of the University of California + * + * 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 "aggregateip.hh" +#include +#include +#include +#include +#include +#include +#include +#include +CLICK_DECLS + +AggregateIP::AggregateIP() +{ +} + +AggregateIP::~AggregateIP() +{ +} + +int +AggregateIP::configure(Vector &conf, ErrorHandler *errh) +{ + String arg; + _incremental = _unshift_ip_addr = false; + if (Args(conf, this, errh) + .read_mp("FIELD", AnyArg(), arg) + .read("INCREMENTAL", _incremental) + .read("UNSHIFT_IP_ADDR", _unshift_ip_addr) + .complete() < 0) + return -1; + const char *end = IPField::parse(arg.begin(), arg.end(), -1, &_f, errh, this); + if (end == arg.begin()) + return -1; + else if (end != arg.end()) + return errh->error("garbage after field specification"); + int32_t right = _f.bit_offset() + _f.bit_length() - 1; + if ((_f.bit_offset() / 32) != (right / 32)) + return errh->error("field specification does not fit within a single word"); + if (_f.bit_length() > 32) + return errh->error("field length too large, max 32"); + else if (_f.bit_length() == 32 && _incremental) + return errh->error("'INCREMENTAL' is incompatible with field length 32"); + if (_f.bit_length() == 32) + _mask = 0xFFFFFFFFU; + else + _mask = (1 << _f.bit_length()) - 1; + _offset = (_f.bit_offset() / 32) * 4; + if (!_unshift_ip_addr || _f.proto() != 0 || _f.bit_offset() < 12*8 || _f.bit_offset() >= 20*8) + _shift = 31 - right % 32; + else { + _mask <<= 31 - right % 32; + _shift = 0; + } + return 0; +} + +Packet * +AggregateIP::bad_packet(Packet *p) +{ + if (noutputs() == 2) + output(1).push(p); + else + p->kill(); + return 0; +} + +Packet * +AggregateIP::handle_packet(Packet *p) +{ + if (!p->has_network_header()) + return bad_packet(p); + + const click_ip *iph = p->ip_header(); + int offset = p->length(); + switch (_f.proto()) { + case 0: + offset = p->network_header_offset(); + break; + case IP_PROTO_TCP_OR_UDP: + if (IP_FIRSTFRAG(iph) && (iph->ip_p == IP_PROTO_TCP || iph->ip_p == IP_PROTO_UDP)) + offset = p->transport_header_offset(); + break; + case IP_PROTO_TRANSP: + if (IP_FIRSTFRAG(iph)) + offset = p->transport_header_offset(); + break; + case IP_PROTO_PAYLOAD: + if (!IP_FIRSTFRAG(iph)) + /* bad; will be thrown away below */; + else if (iph->ip_p == IPPROTO_TCP && p->transport_header_offset() + sizeof(click_tcp) <= p->length()) { + const click_tcp *tcph = (const click_tcp *)p->transport_header(); + offset = p->transport_header_offset() + (tcph->th_off << 2); + } else if (iph->ip_p == IPPROTO_UDP) + offset = p->transport_header_offset() + sizeof(click_udp); + break; + default: + if (IP_FIRSTFRAG(iph) && iph->ip_p == _f.proto()) + offset = p->transport_header_offset(); + break; + } + offset += _offset; + + if (offset + 4 > (int)p->length()) + return bad_packet(p); + + uint32_t udata = *((const uint32_t *)(p->data() + offset)); + uint32_t agg = (ntohl(udata) >> _shift) & _mask; + + if (_incremental) + SET_AGGREGATE_ANNO(p, (AGGREGATE_ANNO(p) << _f.bit_length()) + agg); + else + SET_AGGREGATE_ANNO(p, agg); + + return p; +} + +void +AggregateIP::push(int, Packet *p) +{ + if (Packet *q = handle_packet(p)) + output(0).push(q); +} + +Packet * +AggregateIP::pull(int) +{ + Packet *p = input(0).pull(); + if (p) + p = handle_packet(p); + return p; +} + +String +AggregateIP::read_handler(Element *e, void *thunk) +{ + AggregateIP *aip = static_cast(e); + switch ((intptr_t)thunk) { + case 0: + return NameInfo::revquery_int(NameInfo::T_IP_PROTO, e, aip->_f.proto()); + case 1: + return String(aip->_f.bit_offset()); + case 2: + return String(aip->_f.bit_length()); + case 3: + return aip->_f.unparse(e, false); + default: + return ""; + } +} + +void +AggregateIP::add_handlers() +{ + add_read_handler("header", read_handler, (void *)0); + add_read_handler("bit_offset", read_handler, (void *)1); + add_read_handler("bit_length", read_handler, (void *)2); + add_read_handler("field", read_handler, (void *)3); +} + +CLICK_ENDDECLS +ELEMENT_REQUIRES(userlevel IPFieldInfo) +EXPORT_ELEMENT(AggregateIP) diff --git a/pool/shard011/C++/0121844_argmax_layer.cpp b/pool/shard011/C++/0121844_argmax_layer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b67f24cb9a5a4f1546c7df2807d1d56c2e33edb --- /dev/null +++ b/pool/shard011/C++/0121844_argmax_layer.cpp @@ -0,0 +1,57 @@ +#include +#include +#include +#include + +#include "caffe/layer.hpp" +#include "caffe/vision_layers.hpp" + +namespace caffe { + +template +void ArgMaxLayer::LayerSetUp(const vector*>& bottom, + vector*>* top) { + out_max_val_ = this->layer_param_.argmax_param().out_max_val(); + top_k_ = this->layer_param_.argmax_param().top_k(); + CHECK_GE(top_k_, 1) << " top k must not be less than 1."; + CHECK_LE(top_k_, bottom[0]->count() / bottom[0]->num()) + << "top_k must be less than or equal to the number of classes."; + if (out_max_val_) { + // Produces max_ind and max_val + (*top)[0]->Reshape(bottom[0]->num(), 2, top_k_, 1); + } else { + // Produces only max_ind + (*top)[0]->Reshape(bottom[0]->num(), 1, top_k_, 1); + } +} + +template +void ArgMaxLayer::Forward_cpu(const vector*>& bottom, + vector*>* top) { + const Dtype* bottom_data = bottom[0]->cpu_data(); + Dtype* top_data = (*top)[0]->mutable_cpu_data(); + int num = bottom[0]->num(); + int dim = bottom[0]->count() / bottom[0]->num(); + for (int i = 0; i < num; ++i) { + std::vector > bottom_data_vector; + for (int j = 0; j < dim; ++j) { + bottom_data_vector.push_back( + std::make_pair(bottom_data[i * dim + j], j)); + } + std::partial_sort( + bottom_data_vector.begin(), bottom_data_vector.begin() + top_k_, + bottom_data_vector.end(), std::greater >()); + for (int j = 0; j < top_k_; ++j) { + top_data[(*top)[0]->offset(i, 0, j)] = bottom_data_vector[j].second; + } + if (out_max_val_) { + for (int j = 0; j < top_k_; ++j) { + top_data[(*top)[0]->offset(i, 1, j)] = bottom_data_vector[j].first; + } + } + } +} + +INSTANTIATE_CLASS(ArgMaxLayer); + +} // namespace caffe diff --git a/pool/shard011/C++/0121845_spim.cc b/pool/shard011/C++/0121845_spim.cc new file mode 100644 index 0000000000000000000000000000000000000000..3286c65d1d0366891027e5d64c4eecc855710ebe --- /dev/null +++ b/pool/shard011/C++/0121845_spim.cc @@ -0,0 +1,181 @@ +/** + * Copyright (c) 2017 altroniq. + * + * This file is part of libaltroniq. + * + * libaltroniq 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. + * + * libaltroniq 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 libaltroniq. If not, see . + */ + +#include "spim.h" +#include "pin.h" +#include "hal/assert.h" +#include "hal/lock.h" + +namespace nrf52 { + +SPIM::SPIM(BaseAddr const a, nrf52::Prior const p, uint32_t const sclk, + uint32_t const mosi, uint32_t const miso) + : Peripheral(static_cast(a), + a == BaseAddr::SPI0 ? SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQn : + a == BaseAddr::SPI1 ? SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQn : + /*a == BaseAddr::SPI2*/ SPIM2_SPIS2_SPI2_IRQn, + p) + , handler_(nullptr) + , sclk_(sclk) + , mosi_(mosi) + , miso_(miso) + , bo_(BitOrder::MSB_FIRST) + , m_(Mode::CPOL0_CPHA0) + , bitrate_(250000) + , cs_pin_(Pin::DISCONNECTED) {} + +bool SPIM::open() { + if (!Peripheral::open()) { return false; } + + reg_.ENABLE = SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos; + reg_.PSEL.SCK = sclk_ & SPIM_PSEL_SCK_PIN_Msk; + reg_.PSEL.MOSI = mosi_ & SPIM_PSEL_MOSI_PIN_Msk; + reg_.PSEL.MISO = miso_ & SPIM_PSEL_MISO_PIN_Msk; + set_bitrate(bitrate_); + set_bit_order(bo_); + set_data_mode(m_); + reg_.ORC = DUMMY_BYTE; + reg_.ENABLE = SPIM_ENABLE_ENABLE_Enabled << SPIM_ENABLE_ENABLE_Pos; + state_ = Status::READY; + + return true; +} + +bool SPIM::close() { + if (state_ == Status::CLOSED) { return true; } + + disable_interrupt(); + reg_.TASKS_STOP = 1; + while (!reg_.EVENTS_STOPPED) { continue; } + reg_.EVENTS_STOPPED = 0; + reg_.EVENTS_STOPPED; + reg_.ENABLE = SPIM_ENABLE_ENABLE_Disabled << SPIM_ENABLE_ENABLE_Pos; + reg_.PSEL.SCK = 0xffffffffUL; + reg_.PSEL.MOSI = 0xffffffffUL; + reg_.PSEL.MISO = 0xffffffffUL; + reg_.FREQUENCY = 0x04000000UL; + reg_.CONFIG = 0UL; + reg_.ORC = 0UL; + + return Peripheral::close(); +} + +void SPIM::enable_interrupt() { + reg_.EVENTS_END = 0; + reg_.EVENTS_END; + reg_.INTENCLR = 0xffffffffUL; + reg_.INTENSET = 1UL << SPIM_INTENSET_END_Pos; + + Peripheral::enable_interrupt(); +} + +void SPIM::disable_interrupt() { + reg_.INTENCLR = 0xffffffffUL; + Peripheral::disable_interrupt(); +} + +using Status = altroniq::Status; + +Status SPIM::transaction(uint8_t const *tx_bytes, uint8_t *rx_bytes, + size_t const num_bytes, uint32_t const cs_pin, + EventHandler const h) { + debug_assert(tx_bytes != nullptr && rx_bytes != nullptr); + debug_assert(tx_bytes == nullptr || + (reinterpret_cast(tx_bytes) >= nrf52::SRAM_START && + reinterpret_cast(tx_bytes) <= nrf52::SRAM_END)); + debug_assert(rx_bytes == nullptr || + (reinterpret_cast(rx_bytes) >= nrf52::SRAM_START && + reinterpret_cast(rx_bytes) <= nrf52::SRAM_END)); + debug_assert(num_bytes != 0); + debug_assert(cs_pin <= Pin::MAX_PIN_NUMBER || cs_pin == Pin::DISCONNECTED); + + if (state_ != Status::READY) { return state_; } + + altroniq::lock(); + state_ = Status::BUSY; + altroniq::unlock(); + + cs_pin_ = cs_pin; + NRF_GPIO->OUTCLR = 1UL << cs_pin_; + + if (rx_bytes != nullptr) { + reg_.RXD.PTR = reinterpret_cast(rx_bytes); + reg_.RXD.MAXCNT = num_bytes; + } else { + reg_.RXD.MAXCNT = 0; + } + + if (tx_bytes != nullptr) { + reg_.TXD.PTR = reinterpret_cast(tx_bytes); + reg_.TXD.MAXCNT = num_bytes; + } else { + reg_.TXD.MAXCNT = 0; + } + + handler_ = h; + + enable_interrupt(); + reg_.TASKS_START = 1; + + return Status::SUCCESS; +} + +using BitOrder = altroniq::SPIM::BitOrder; + +BitOrder SPIM::set_bit_order(BitOrder const bo) { + if (state_ == Status::BUSY) { return bo_; } + + reg_.CONFIG &= ~SPIM_CONFIG_ORDER_Msk; + reg_.CONFIG |= static_cast(bo) << SPIM_CONFIG_ORDER_Pos; + bo_ = bo; + + return bo_; +} + +using Mode = altroniq::SPIM::Mode; + +Mode SPIM::set_data_mode(Mode const m) { + if (state_ == Status::BUSY) { return m_; } + + reg_.CONFIG &= ~(SPIM_CONFIG_CPHA_Msk | SPIM_CONFIG_CPOL_Msk); + reg_.CONFIG |= static_cast(m) << SPIM_CONFIG_CPHA_Pos; + m_ = m; + + return m_; +} + +uint32_t SPIM::set_bitrate(uint32_t const r) { + if (state_ == Status::BUSY) { return bitrate_; } + + auto br = BitRate::K250; + + if (r < 187500UL ) { br = BitRate::K125; bitrate_ = 125000; } + else if (r < 375000UL ) { br = BitRate::K250; bitrate_ = 250000; } + else if (r < 750000UL ) { br = BitRate::K500; bitrate_ = 500000; } + else if (r < 1500000UL) { br = BitRate::M1; bitrate_ = 1000000; } + else if (r < 3000000UL) { br = BitRate::M2; bitrate_ = 2000000; } + else if (r < 6000000UL) { br = BitRate::M4; bitrate_ = 4000000; } + else { br = BitRate::M8; bitrate_ = 8000000; } + + reg_.FREQUENCY = static_cast(br) << SPIM_FREQUENCY_FREQUENCY_Pos; + + return bitrate_; +} + +} /* namespace nrf52 */ diff --git a/pool/shard011/C++/0121846_X86InterleavedAccess.cpp b/pool/shard011/C++/0121846_X86InterleavedAccess.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d9edf4676faf8b02265983749fbda23db373032b --- /dev/null +++ b/pool/shard011/C++/0121846_X86InterleavedAccess.cpp @@ -0,0 +1,221 @@ +//===--------- X86InterleavedAccess.cpp ----------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===--------------------------------------------------------------------===// +/// +/// \file +/// This file contains the X86 implementation of the interleaved accesses +/// optimization generating X86-specific instructions/intrinsics for +/// interleaved access groups. +/// +//===--------------------------------------------------------------------===// + +#include "X86ISelLowering.h" +#include "X86TargetMachine.h" + +using namespace llvm; + +/// \brief This class holds necessary information to represent an interleaved +/// access group and supports utilities to lower the group into +/// X86-specific instructions/intrinsics. +/// E.g. A group of interleaving access loads (Factor = 2; accessing every +/// other element) +/// %wide.vec = load <8 x i32>, <8 x i32>* %ptr +/// %v0 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <0, 2, 4, 6> +/// %v1 = shuffle <8 x i32> %wide.vec, <8 x i32> undef, <1, 3, 5, 7> + +class X86InterleavedAccessGroup { + /// \brief Reference to the wide-load instruction of an interleaved access + /// group. + Instruction *const Inst; + + /// \brief Reference to the shuffle(s), consumer(s) of the (load) 'Inst'. + ArrayRef Shuffles; + + /// \brief Reference to the starting index of each user-shuffle. + ArrayRef Indices; + + /// \brief Reference to the interleaving stride in terms of elements. + const unsigned Factor; + + /// \brief Reference to the underlying target. + const X86Subtarget &Subtarget; + + const DataLayout &DL; + + IRBuilder<> &Builder; + + /// \brief Breaks down a vector \p 'Inst' of N elements into \p NumSubVectors + /// sub vectors of type \p T. Returns true and the sub-vectors in + /// \p DecomposedVectors if it decomposes the Inst, returns false otherwise. + bool decompose(Instruction *Inst, unsigned NumSubVectors, VectorType *T, + SmallVectorImpl &DecomposedVectors); + + /// \brief Performs matrix transposition on a 4x4 matrix \p InputVectors and + /// returns the transposed-vectors in \p TransposedVectors. + /// E.g. + /// InputVectors: + /// In-V0 = p1, p2, p3, p4 + /// In-V1 = q1, q2, q3, q4 + /// In-V2 = r1, r2, r3, r4 + /// In-V3 = s1, s2, s3, s4 + /// OutputVectors: + /// Out-V0 = p1, q1, r1, s1 + /// Out-V1 = p2, q2, r2, s2 + /// Out-V2 = p3, q3, r3, s3 + /// Out-V3 = P4, q4, r4, s4 + void transpose_4x4(ArrayRef InputVectors, + SmallVectorImpl &TrasposedVectors); + +public: + /// In order to form an interleaved access group X86InterleavedAccessGroup + /// requires a wide-load instruction \p 'I', a group of interleaved-vectors + /// \p Shuffs, reference to the first indices of each interleaved-vector + /// \p 'Ind' and the interleaving stride factor \p F. In order to generate + /// X86-specific instructions/intrinsics it also requires the underlying + /// target information \p STarget. + explicit X86InterleavedAccessGroup(Instruction *I, + ArrayRef Shuffs, + ArrayRef Ind, + const unsigned F, + const X86Subtarget &STarget, + IRBuilder<> &B) + : Inst(I), Shuffles(Shuffs), Indices(Ind), Factor(F), Subtarget(STarget), + DL(Inst->getModule()->getDataLayout()), Builder(B) {} + + /// \brief Returns true if this interleaved access group can be lowered into + /// x86-specific instructions/intrinsics, false otherwise. + bool isSupported() const; + + /// \brief Lowers this interleaved access group into X86-specific + /// instructions/intrinsics. + bool lowerIntoOptimizedSequence(); +}; + +bool X86InterleavedAccessGroup::isSupported() const { + VectorType *ShuffleVecTy = Shuffles[0]->getType(); + uint64_t ShuffleVecSize = DL.getTypeSizeInBits(ShuffleVecTy); + Type *ShuffleEltTy = ShuffleVecTy->getVectorElementType(); + + if (DL.getTypeSizeInBits(Inst->getType()) < Factor * ShuffleVecSize) + return false; + + // Currently, lowering is supported for 64 bits on AVX. + if (!Subtarget.hasAVX() || ShuffleVecSize != 256 || + DL.getTypeSizeInBits(ShuffleEltTy) != 64 || Factor != 4) + return false; + + return true; +} + +bool X86InterleavedAccessGroup::decompose( + Instruction *VecInst, unsigned NumSubVectors, VectorType *SubVecTy, + SmallVectorImpl &DecomposedVectors) { + Type *VecTy = VecInst->getType(); + (void)VecTy; + assert(VecTy->isVectorTy() && + DL.getTypeSizeInBits(VecTy) >= + DL.getTypeSizeInBits(SubVecTy) * NumSubVectors && + "Invalid Inst-size!!!"); + assert(VecTy->getVectorElementType() == SubVecTy->getVectorElementType() && + "Element type mismatched!!!"); + + if (!isa(VecInst)) + return false; + + LoadInst *LI = cast(VecInst); + Type *VecBasePtrTy = SubVecTy->getPointerTo(LI->getPointerAddressSpace()); + + Value *VecBasePtr = + Builder.CreateBitCast(LI->getPointerOperand(), VecBasePtrTy); + + // Generate N loads of T type + for (unsigned i = 0; i < NumSubVectors; i++) { + // TODO: Support inbounds GEP + Value *NewBasePtr = Builder.CreateGEP(VecBasePtr, Builder.getInt32(i)); + Instruction *NewLoad = + Builder.CreateAlignedLoad(NewBasePtr, LI->getAlignment()); + DecomposedVectors.push_back(NewLoad); + } + + return true; +} + +void X86InterleavedAccessGroup::transpose_4x4( + ArrayRef Matrix, + SmallVectorImpl &TransposedMatrix) { + assert(Matrix.size() == 4 && "Invalid matrix size"); + TransposedMatrix.resize(4); + + // dst = src1[0,1],src2[0,1] + uint32_t IntMask1[] = {0, 1, 4, 5}; + ArrayRef Mask = makeArrayRef(IntMask1, 4); + Value *IntrVec1 = Builder.CreateShuffleVector(Matrix[0], Matrix[2], Mask); + Value *IntrVec2 = Builder.CreateShuffleVector(Matrix[1], Matrix[3], Mask); + + // dst = src1[2,3],src2[2,3] + uint32_t IntMask2[] = {2, 3, 6, 7}; + Mask = makeArrayRef(IntMask2, 4); + Value *IntrVec3 = Builder.CreateShuffleVector(Matrix[0], Matrix[2], Mask); + Value *IntrVec4 = Builder.CreateShuffleVector(Matrix[1], Matrix[3], Mask); + + // dst = src1[0],src2[0],src1[2],src2[2] + uint32_t IntMask3[] = {0, 4, 2, 6}; + Mask = makeArrayRef(IntMask3, 4); + TransposedMatrix[0] = Builder.CreateShuffleVector(IntrVec1, IntrVec2, Mask); + TransposedMatrix[2] = Builder.CreateShuffleVector(IntrVec3, IntrVec4, Mask); + + // dst = src1[1],src2[1],src1[3],src2[3] + uint32_t IntMask4[] = {1, 5, 3, 7}; + Mask = makeArrayRef(IntMask4, 4); + TransposedMatrix[1] = Builder.CreateShuffleVector(IntrVec1, IntrVec2, Mask); + TransposedMatrix[3] = Builder.CreateShuffleVector(IntrVec3, IntrVec4, Mask); +} + +// Lowers this interleaved access group into X86-specific +// instructions/intrinsics. +bool X86InterleavedAccessGroup::lowerIntoOptimizedSequence() { + SmallVector DecomposedVectors; + VectorType *VecTy = Shuffles[0]->getType(); + // Try to generate target-sized register(/instruction). + if (!decompose(Inst, Factor, VecTy, DecomposedVectors)) + return false; + + SmallVector TransposedVectors; + // Perform matrix-transposition in order to compute interleaved + // results by generating some sort of (optimized) target-specific + // instructions. + transpose_4x4(DecomposedVectors, TransposedVectors); + + // Now replace the unoptimized-interleaved-vectors with the + // transposed-interleaved vectors. + for (unsigned i = 0; i < Shuffles.size(); i++) + Shuffles[i]->replaceAllUsesWith(TransposedVectors[Indices[i]]); + + return true; +} + +// Lower interleaved load(s) into target specific instructions/ +// intrinsics. Lowering sequence varies depending on the vector-types, factor, +// number of shuffles and ISA. +// Currently, lowering is supported for 4x64 bits with Factor = 4 on AVX. +bool X86TargetLowering::lowerInterleavedLoad( + LoadInst *LI, ArrayRef Shuffles, + ArrayRef Indices, unsigned Factor) const { + assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() && + "Invalid interleave factor"); + assert(!Shuffles.empty() && "Empty shufflevector input"); + assert(Shuffles.size() == Indices.size() && + "Unmatched number of shufflevectors and indices"); + + // Create an interleaved access group. + IRBuilder<> Builder(LI); + X86InterleavedAccessGroup Grp(LI, Shuffles, Indices, Factor, Subtarget, + Builder); + + return Grp.isSupported() && Grp.lowerIntoOptimizedSequence(); +} diff --git a/pool/shard011/C++/0121847_worker_info_handler_impl.cc b/pool/shard011/C++/0121847_worker_info_handler_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..6dd63d58f10bcc7ecbfcc7f2a1c40f518736ccd3 --- /dev/null +++ b/pool/shard011/C++/0121847_worker_info_handler_impl.cc @@ -0,0 +1,30 @@ +#include "worker_info_handler_impl.h" + +namespace ray { +namespace rpc { + +void DefaultWorkerInfoHandler::HandleReportWorkerFailure( + const ReportWorkerFailureRequest &request, ReportWorkerFailureReply *reply, + SendReplyCallback send_reply_callback) { + Address worker_address = request.worker_failure().worker_address(); + RAY_LOG(DEBUG) << "Reporting worker failure, " << worker_address.DebugString(); + auto worker_failure_data = std::make_shared(); + worker_failure_data->CopyFrom(request.worker_failure()); + auto on_done = [worker_address, send_reply_callback](Status status) { + if (!status.ok()) { + RAY_LOG(ERROR) << "Failed to report worker failure, " + << worker_address.DebugString(); + } + send_reply_callback(status, nullptr, nullptr); + }; + + Status status = + gcs_client_.Workers().AsyncReportWorkerFailure(worker_failure_data, on_done); + if (!status.ok()) { + on_done(status); + } + RAY_LOG(DEBUG) << "Finished reporting worker failure, " << worker_address.DebugString(); +} + +} // namespace rpc +} // namespace ray diff --git a/pool/shard011/C++/0121849_PlayerIcon.cpp b/pool/shard011/C++/0121849_PlayerIcon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1520d549c42b530d0ecc58d6b077e9f3dccfa7b9 --- /dev/null +++ b/pool/shard011/C++/0121849_PlayerIcon.cpp @@ -0,0 +1,158 @@ +// Copyright (C) 2004 Id Software, Inc. +// + +#include "../idlib/precompiled.h" +#pragma hdrstop + +#include "Game_local.h" +#include "PlayerIcon.h" + +static const char * iconKeys[ ICON_NONE ] = { + "mtr_icon_lag", + "mtr_icon_chat" +}; + +/* +=============== +idPlayerIcon::idPlayerIcon +=============== +*/ +idPlayerIcon::idPlayerIcon() { + iconHandle = -1; + iconType = ICON_NONE; +} + +/* +=============== +idPlayerIcon::~idPlayerIcon +=============== +*/ +idPlayerIcon::~idPlayerIcon() { + FreeIcon(); +} + +/* +=============== +idPlayerIcon::Draw +=============== +*/ +void idPlayerIcon::Draw( idPlayer *player, jointHandle_t joint ) { + idVec3 origin; + idMat3 axis; + + if ( joint == INVALID_JOINT ) { + FreeIcon(); + return; + } + + player->GetJointWorldTransform( joint, gameLocal.time, origin, axis ); + origin.z += 16.0f; + + Draw( player, origin ); +} + +/* +=============== +idPlayerIcon::Draw +=============== +*/ +void idPlayerIcon::Draw( idPlayer *player, const idVec3 &origin ) { + idPlayer *localPlayer = gameLocal.GetLocalPlayer(); + if ( !localPlayer || !localPlayer->GetRenderView() ) { + FreeIcon(); + return; + } + + idMat3 axis = localPlayer->GetRenderView()->viewaxis; + + if ( player->isLagged ) { + // create the icon if necessary, or update if already created + if ( !CreateIcon( player, ICON_LAG, origin, axis ) ) { + UpdateIcon( player, origin, axis ); + } + } else if ( player->isChatting ) { + if ( !CreateIcon( player, ICON_CHAT, origin, axis ) ) { + UpdateIcon( player, origin, axis ); + } + } else { + FreeIcon(); + } +} + +/* +=============== +idPlayerIcon::FreeIcon +=============== +*/ +void idPlayerIcon::FreeIcon( void ) { + if ( iconHandle != - 1 ) { + gameRenderWorld->FreeEntityDef( iconHandle ); + iconHandle = -1; + } + iconType = ICON_NONE; +} + +/* +=============== +idPlayerIcon::CreateIcon +=============== +*/ +bool idPlayerIcon::CreateIcon( idPlayer *player, playerIconType_t type, const idVec3 &origin, const idMat3 &axis ) { + assert( type != ICON_NONE ); + const char *mtr = player->spawnArgs.GetString( iconKeys[ type ], "_default" ); + return CreateIcon( player, type, mtr, origin, axis ); +} + +/* +=============== +idPlayerIcon::CreateIcon +=============== +*/ +bool idPlayerIcon::CreateIcon( idPlayer *player, playerIconType_t type, const char *mtr, const idVec3 &origin, const idMat3 &axis ) { + assert( type != ICON_NONE ); + + if ( type == iconType ) { + return false; + } + + FreeIcon(); + + memset( &renderEnt, 0, sizeof( renderEnt ) ); + renderEnt.origin = origin; + renderEnt.axis = axis; + renderEnt.shaderParms[ SHADERPARM_RED ] = 1.0f; + renderEnt.shaderParms[ SHADERPARM_GREEN ] = 1.0f; + renderEnt.shaderParms[ SHADERPARM_BLUE ] = 1.0f; + renderEnt.shaderParms[ SHADERPARM_ALPHA ] = 1.0f; + renderEnt.shaderParms[ SHADERPARM_SPRITE_WIDTH ] = 16.0f; + renderEnt.shaderParms[ SHADERPARM_SPRITE_HEIGHT ] = 16.0f; + renderEnt.hModel = renderModelManager->FindModel( "_sprite" ); + renderEnt.callback = NULL; + renderEnt.numJoints = 0; + renderEnt.joints = NULL; + renderEnt.customSkin = 0; + renderEnt.noShadow = true; + renderEnt.noSelfShadow = true; + renderEnt.customShader = declManager->FindMaterial( mtr ); + renderEnt.referenceShader = 0; + renderEnt.bounds = renderEnt.hModel->Bounds( &renderEnt ); + + iconHandle = gameRenderWorld->AddEntityDef( &renderEnt ); + iconType = type; + + return true; +} + +/* +=============== +idPlayerIcon::UpdateIcon +=============== +*/ +void idPlayerIcon::UpdateIcon( idPlayer *player, const idVec3 &origin, const idMat3 &axis ) { + assert( iconHandle >= 0 ); + + renderEnt.origin = origin; + renderEnt.axis = axis; + gameRenderWorld->UpdateEntityDef( iconHandle, &renderEnt ); +} + diff --git a/pool/shard011/C++/0121850_chapter.5.5.1.cpp b/pool/shard011/C++/0121850_chapter.5.5.1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdf9f597480506cc379acf31d4f9a17a83496fd8 --- /dev/null +++ b/pool/shard011/C++/0121850_chapter.5.5.1.cpp @@ -0,0 +1,74 @@ + +// +// This is example code from Chapter 5.5.1 "The caller deals with errors" of +// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup +// + +#include "std_lib_facilities.h" + +//------------------------------------------------------------------------------ + +int area(int length, int width) // calculate area of a rectangle +{ + return length*width; +} + +//------------------------------------------------------------------------------ + +const int frame_width = 2; +int framed_area(int x, int y) // calculate area within frame +{ + return area(x-frame_width,y-frame_width); +} + +//------------------------------------------------------------------------------ + +int main() +try +{ + int x = -1; + int y = 2; + int z = 4; + // ... + + { + if (x<=0) error("non-positive x"); + if (y<=0) error("non-positive y"); + int area1 = area(x,y); + } + + { + // If we didn't need separate error messages about each argument, we would simplify: + if (x<=0 || y<=0) error("non-positive argument for area()"); // || means "or" + int area1 = area(x,y); + + if (z<=2) + error("non-positive 2nd argument for area() called by framed_area()"); + + int area2 = framed_area(1,z); + if (y<=2 || z<=2) + error("non-positive argument for area() called by framed_area()"); + int area3 = framed_area(y,z); + double ratio = double(area1)/area3; // convert to double to get + // floating-point division + } + + { + if (1-frame_width<=0 || z-frame_width<=0) + error("non-positive 2nd argument for area() called by framed_area()"); + int area2 = framed_area(1,z); + if (y-frame_width<=0 || z-frame_width<=0) + error("non-positive argument for area() called by framed_area()"); + int area3 = framed_area(y,z); + } +} +catch (exception& e) { + cerr << "error: " << e.what() << '\n'; + return 1; +} +catch (...) { + cerr << "Oops: unknown exception!\n"; + return 2; +} + +//------------------------------------------------------------------------------ diff --git a/pool/shard011/C++/0121855_dest_evaluate.cpp b/pool/shard011/C++/0121855_dest_evaluate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1550ab95c05942ca1967254c8f6246fbfa43bac6 --- /dev/null +++ b/pool/shard011/C++/0121855_dest_evaluate.cpp @@ -0,0 +1,116 @@ +/** + This file is part of Deformable Shape Tracking (DEST). + + Copyright(C) 2015/2016 Christoph Heindl + All rights reserved. + + This software may be modified and distributed under the terms + of the BSD license.See the LICENSE file for details. +*/ + +#include +#include +#include +#include "dest_evaluate.h" + +/** + Evaluate a trained tracker based on some test data. + + This methods loads a database of test samples and evaluates the tracker. Deviations + from the true shape are normalized by the inter-ocular distance. + +*/ +int main(int argc, char **argv) +{ + struct { + std::string tracker; + std::string database; + std::string rectangles; + int loadMaxSize; + } opts; + + try { + TCLAP::CmdLine cmd("Evaluate regressor on test database.", ' ', "0.9"); + TCLAP::ValueArg trackerArg("t", "tracker", "Trained tracker to load", true, "dest.bin", "file", cmd); + TCLAP::ValueArg rectanglesArg("r", "rectangles", "Initial rectangles to provide to tracker", false, "rectangles.csv", "file", cmd); + TCLAP::ValueArg maxImageSizeArg("", "load-max-size", "Maximum size of images in the database", false, 2048, "int", cmd); + TCLAP::UnlabeledValueArg databaseArg("database", "Path to database directory to load", true, "./db", "string", cmd); + + + cmd.parse(argc, argv); + + opts.rectangles = rectanglesArg.isSet() ? rectanglesArg.getValue() : ""; + opts.database = databaseArg.getValue(); + opts.tracker = trackerArg.getValue(); + opts.loadMaxSize = maxImageSizeArg.getValue(); + } + catch (TCLAP::ArgException &e) { + std::cerr << "Error: " << e.error() << " for arg " << e.argId() << std::endl; + return -1; + } + + dest::core::Tracker t; + if (!t.load(opts.tracker)) { + std::cerr << "Failed to load tracker." << std::endl; + return -1; + } + + std::vector rects; + if (!opts.rectangles.empty() && !dest::io::importRectangles(opts.rectangles, rects)) { + std::cerr << "Failed to load rectangles." << std::endl; + return -1; + } + + dest::io::ShapeDatabase sd; + sd.setMaxImageLoadSize(opts.loadMaxSize); + sd.setRectangles(rects); + + dest::core::InputData inputs; + if (!sd.load(opts.database, inputs.images, inputs.shapes, inputs.rects)) { + std::cerr << "Failed to load database." << std::endl; + return -1; + } + + dest::core::InputData::normalizeShapes(inputs); + dest::core::SampleData td(inputs); + dest::core::SampleData::createTestingSamples(td); + + dest::core::LandmarkDistanceNormalizer ldn; + if (sd.lastLoaderType() == "imm") { + ldn = dest::core::LandmarkDistanceNormalizer::createInterocularNormalizerIMM(); + } + else if (sd.lastLoaderType() == "ibug") { + ldn = dest::core::LandmarkDistanceNormalizer::createInterocularNormalizerIBug(); + } + else if (sd.lastLoaderType() == "land") { + ldn = dest::core::LandmarkDistanceNormalizer::createInterocularNormalizerLAND(); + } + else { + std::cerr << "Unknown database type" << std::endl; + return -1; + } + + dest::core::TestResult tr = dest::core::testTracker(td, t, ldn); + + std::cout << std::setw(40) << std::left << "Average normalized error:" << tr.meanNormalizedDistance << std::endl; + std::cout << std::setw(40) << std::left << "Stddev normalized error:" << tr.stddevNormalizedDistance << std::endl; + std::cout << std::setw(40) << std::left << "Median normalized error:" << tr.medianNormalizedDistance << std::endl; + std::cout << std::setw(40) << std::left << "Worst normalized error:" << tr.worstNormalizedDistance << std::endl; + + const int bins = static_cast(tr.histNormalizedDistance.size() - 1); + const float binSize = 1.f / bins; + std::cout << "Error histogram (bin size " << std::setprecision(3) << binSize << "):" << std::endl; + for (size_t i = 0; i < tr.histNormalizedDistance.size(); ++i) { + std::stringstream str; + if (i < tr.histNormalizedDistance.size() - 1) { + str << std::fixed << std::setprecision(3) << i * binSize + binSize * 0.5f << "/" << std::setprecision(1) << tr.histNormalizedDistance[i] * 100.f << "%"; + } else { + str << std::fixed << std::setprecision(3) << " >1.0/" << std::setprecision(1) << tr.histNormalizedDistance[i] * 100.f << "%"; + } + + std::cout << std::setw(12) << str.str() << "|" << std::setw((int)(60 * tr.histNormalizedDistance[i])) << std::setfill('*') << "" << std::setfill(' ') << std::endl; + } + + + return 0; +} diff --git a/pool/shard011/C++/0121856_YaMangShader.cpp b/pool/shard011/C++/0121856_YaMangShader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..640de5b8937bfc89ae20c2e82a0908937fc95821 --- /dev/null +++ b/pool/shard011/C++/0121856_YaMangShader.cpp @@ -0,0 +1,181 @@ +#include "stdafx.h" +#include "yaMangDxDll.h" +#include "GlobalVar.h" +#include + +YAMANGDXDLL_API HRESULT ShaderCreate( int size ) +{ + if ( size <= 0 || g_EffectSize != 0 ) + { + return E_FAIL; + } + + g_Effects = new LPD3DXEFFECT[size]; + g_EffectSize = size; + + for ( int i = 0; i < g_EffectSize; ++i ) + { + g_Effects[i] = nullptr; + } + + return S_OK; +} + +YAMANGDXDLL_API HRESULT ShaderImport( LPCTSTR effectFile, int id ) +{ + DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE | D3DXSHADER_DEBUG | D3DXSHADER_NO_PRESHADER; + + HRESULT hr = S_OK; + hr = D3DXCreateEffectFromFile( g_D3dDevice, effectFile, NULL, NULL, dwShaderFlags, NULL, &g_Effects[id], NULL ); + + if ( FAILED( hr ) ) + { + MessageBox( NULL, L"Effect Load Failed", effectFile, MB_OK ); + return E_FAIL; + } + + return S_OK; +} + +enum UnitStatusFlagType +{ + UNIT_STATUS_FLAG_ENEMY = 0x1, + UNIT_STATUS_FLAG_ATTACK = 0x2, + UNIT_STATUS_FLAG_SELECT = 0x4 +}; + +YAMANGDXDLL_API void DrawBillboardByTexture( int id, char flag ) +{ + if ( id <= 0 || id >= g_MeshTextureSize ) + { + return; + } + + // ºôº¸µå Á¤Á¡ + BILLBOARDVERTEX vtx[4] = + { + { -1, 0, 0, 0, 1 }, + { -1, 4, 0, 0, 0 }, + { 1, 0, 0, 1, 1 }, + { 1, 4, 0, 1, 0 } + }; + + if ( g_Effects[1] ) + { + D3DVERTEXELEMENT9 ele[MAX_FVF_DECL_SIZE]; + + // FVF¸¦ »ç¿ëÇØ¼­ Á¤Á¡¼±¾ð°ªÀ» ÀÚµ¿À¸·Î ä¿ö³Ö´Â´Ù + D3DXDeclaratorFromFVF( BILLBOARDVERTEX::FVF, ele ); + LPDIRECT3DVERTEXDECLARATION9 decl; + + // Á¤Á¡¼±¾ð°ªÀ¸·Î declÀ» »ý¼ºÇÑ´Ù. + g_D3dDevice->CreateVertexDeclaration( ele, &decl ); + g_D3dDevice->SetVertexDeclaration( decl ); + + UINT nPass; + + float thisTime = D3DX_PI * ( timeGetTime() % 600 ) / 300; + g_Effects[1]->SetFloat( "time", thisTime ); + + float inputColor[3] = { 0.0f }; + + if ( flag & UNIT_STATUS_FLAG_ATTACK ) + { + g_Effects[1]->SetBool( "isAttack", true ); + } + else + { + g_Effects[1]->SetBool( "isAttack", false ); + } + + if ( flag & UNIT_STATUS_FLAG_ENEMY ) + { + inputColor[0] = 0.3f; + } + else + { + inputColor[2] = 0.3f; + } + + if ( flag & UNIT_STATUS_FLAG_SELECT ) + { + inputColor[0] += 0.3f; + inputColor[1] += 0.3f; + inputColor[2] += 0.3f; + } + + g_Effects[1]->SetFloatArray( "inputColor", inputColor, 3 ); + + // fxÃâ·Â¿¡ »ç¿ëÇÒ Å×Å©´Ð ¼±Á¤ + g_Effects[1]->SetTechnique( "MyShader" ); + + D3DXMATRIXA16 worldMatrix; + g_D3dDevice->GetTransform( D3DTS_WORLD, &worldMatrix ); + D3DXMATRIXA16 viewingMatrix; + g_D3dDevice->GetTransform( D3DTS_VIEW, &viewingMatrix ); + D3DXMATRIXA16 projectionMatrix; + g_D3dDevice->GetTransform( D3DTS_PROJECTION, &projectionMatrix ); + + D3DXMATRIXA16 thisMatrix = worldMatrix * viewingMatrix * projectionMatrix; + + g_Effects[1]->SetMatrix( "matWVP", &thisMatrix ); + + g_Effects[1]->SetTexture( "tex0", g_MeshTextures[id] ); + + // fx¸¦ »ç¿ëÇÑ Ãâ·Â°³½Ã + g_Effects[1]->Begin( &nPass, D3DXFX_DONOTSAVESHADERSTATE ); + + // PASS °³¼ö¸¸Å­ Ãâ·Â + for ( UINT i = 0; i < nPass; ++i ) + { + g_Effects[1]->BeginPass( i ); + + g_D3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, vtx, sizeof( BILLBOARDVERTEX ) ); + + g_Effects[1]->EndPass(); + } + + g_Effects[1]->End(); + } + else + { + g_D3dDevice->SetVertexShader( NULL ); + g_D3dDevice->SetPixelShader( NULL ); + + // 0¹ø ÅØ½ºÃ³¿¡ ºôº¸µå ÅØ½ºÃ³¸¦ ¿Ã¸°´Ù + g_D3dDevice->SetTexture( 0, g_MeshTextures[id] ); + g_D3dDevice->SetFVF( BILLBOARDVERTEX::FVF ); + g_D3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, vtx, sizeof( BILLBOARDVERTEX ) ); + } + + g_IsEffectReady = false; +} + +YAMANGDXDLL_API HRESULT MeshTextureCreateBySize( INT size ) +{ + if ( size <= 0 || g_MeshTextureSize != 0) + { + return E_FAIL; + } + + g_MeshTextures = new LPDIRECT3DTEXTURE9[size]; + g_MeshTextureSize = size; + + for ( int i = 0; i < g_MeshTextureSize; ++i ) + { + g_MeshTextures[i] = nullptr; + } + + return S_OK; +} + +YAMANGDXDLL_API HRESULT MeshTextureImport( LPCTSTR meshTexture, int id ) +{ + if ( FAILED( D3DXCreateTextureFromFile( g_D3dDevice, meshTexture, &g_MeshTextures[id] ) ) ) + { + MessageBox( NULL, L"Mesh Texture Load Failed", meshTexture, MB_OK ); + return E_FAIL; + } + + return S_OK; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121857_file.cpp b/pool/shard011/C++/0121857_file.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e0f28affbd074b2cdd5b589d69acf2514e1f34d --- /dev/null +++ b/pool/shard011/C++/0121857_file.cpp @@ -0,0 +1,273 @@ +/* + * This file is part of the UnTech Editor Suite. + * Copyright (c) 2016 - 2021, Marcus Rowe . + * Distributed under The MIT License: https://opensource.org/licenses/MIT + */ + +#include "file.h" +#include "string.h" +#include "models/common/stringbuilder.h" +#include +#include +#include +#include +#include +#include + +#if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__) +#define PLATFORM_WINDOWS +#endif + +#ifdef PLATFORM_WINDOWS +#include +#include +#include +#else +#include +#include +#include +#include +#endif + +namespace UnTech::File { + +std::vector readBinaryFile(const std::filesystem::path& filePath, size_t limit) +{ + std::ifstream in(filePath, std::ios::in | std::ios::binary); + if (!in) { + throw std::runtime_error(stringBuilder("Cannot open file: ", filePath.u8string())); + } + + in.seekg(0, std::ios::end); + auto pos = in.tellg(); + in.seekg(0); + + if (pos < 0) { + throw std::runtime_error(stringBuilder("Cannot open file: ", filePath.u8string(), " : Cannot read file size")); + } + const size_t size = pos; + + if (size > limit) { + throw std::runtime_error(stringBuilder("Cannot open file : ", filePath.u8string(), " : file too large")); + } + + std::vector ret(size); + in.read((char*)ret.data(), ret.size()); + in.close(); + + if (!in) { + throw std::runtime_error(stringBuilder("Error reading file: ", filePath.u8string())); + } + + return ret; +} + +std::string readUtf8TextFile(const std::filesystem::path& filePath) +{ + constexpr static unsigned N_BOM_CHARS = 3; + constexpr static std::array BOM{ 0xEF, 0xBB, 0xBF }; + static_assert(BOM.size() == sizeof(uint32_t)); + + std::ifstream in(filePath, std::ios::in | std::ios::binary); + if (!in) { + throw std::runtime_error(stringBuilder("Cannot open file: ", filePath.u8string())); + } + + std::array header{}; + static_assert(header.size() > N_BOM_CHARS); + + in.read((char*)header.data(), N_BOM_CHARS); + assert(header.back() == 0); + + in.seekg(0, std::ios::end); + auto size = in.tellg(); + + if (size < 0) { + throw std::runtime_error(stringBuilder("Cannot open file: ", filePath.u8string(), " : Cannot read file size")); + } + if (size > 25 * 1024 * 1024) { + throw std::runtime_error(stringBuilder("Cannot open file: ", filePath.u8string(), " : too large")); + } + + // check for BOM + if (size >= N_BOM_CHARS && header == BOM) { + in.seekg(3, std::ios::beg); + size -= 3; + } + else { + in.seekg(0, std::ios::beg); + } + + std::string ret; + if (size > 0) { + ret.resize(size_t(size)); + + in.read(ret.data(), size); + + const auto read = in.gcount(); + const bool atEof = in.get() == decltype(in)::traits_type::eof(); + + in.close(); + + if (read != size) { + throw std::runtime_error(stringBuilder("Error reading file: ", filePath.u8string(), " : Expected ", ptrdiff_t(size), " bytes got ", read, ".")); + } + if (atEof == false) { + throw std::runtime_error(stringBuilder("Error reading file: ", filePath.u8string(), " : Not at end of file")); + } + + if (!String::checkUtf8WellFormed(ret)) { + throw std::runtime_error(stringBuilder("Error reading file: ", filePath.u8string(), " : Not UTF-8 Well Formed")); + } + } + + return (ret); +} + +void atomicWrite(const std::filesystem::path& filePath, const std::vector& data) +{ + atomicWrite(filePath, data.data(), data.size()); +} + +void atomicWrite(const std::filesystem::path& filePath, const std::string& data) +{ + atomicWrite(filePath, data.data(), data.size()); +} + +// ::TODO replace with std::span when upgrading to c++20:: +#ifdef PLATFORM_WINDOWS +void atomicWrite(const std::filesystem::path& filePath, const void* data, size_t size) +{ + const size_t BLOCK_SIZE = 4096; + + // ::TODO properly test this function:: + + // I could not find a function to create and open a temporary file in a given directory in windows. + // Instead we create a `~` temp file and throw an error if tmpFilename already exists. + const std::filesystem::path tmpFilename = std::filesystem::path(filePath).concat(L"~"); + + // open a new file for writing. + // error if file exists. + HANDLE hFile = CreateFileW(tmpFilename.c_str(), GENERIC_WRITE, 0, nullptr, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, nullptr); + + if (hFile == INVALID_HANDLE_VALUE) { + if (GetLastError() == ERROR_FILE_EXISTS) { + throw std::runtime_error(stringBuilder("Temporary file already exists: ", tmpFilename.string())); + } + else { + throw std::runtime_error(stringBuilder("Cannot open temporary file ", tmpFilename.string())); + } + } + + const uint8_t* ptr = static_cast(data); + size_t todo = size; + + while (todo > 0) { + DWORD toWrite = std::min(BLOCK_SIZE, todo); + DWORD written = 0; + + auto ret = WriteFile(hFile, ptr, toWrite, &written, NULL); + + if (ret == FALSE || written != toWrite) { + CloseHandle(hFile); + throw std::runtime_error("Error writing file"); + } + + ptr += toWrite; + todo -= toWrite; + } + + CloseHandle(hFile); + + bool s = MoveFileExW(tmpFilename.c_str(), filePath.c_str(), + MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED); + if (!s) { + throw std::runtime_error("MoveFileEx failed"); + } +} +#else +void atomicWrite(const std::filesystem::path& filePath, const void* data, size_t size) +{ + using namespace std::string_literals; + + const std::string filename = filePath.u8string(); + + const size_t BLOCK_SIZE = 4096; + + std::string tmpFilename = filePath.native() + "-tmpXXXXXX"s; + + int fd; + struct stat statbuf; + + // Using lstat to detect if the filename is a symbolic link + if (lstat(filename.c_str(), &statbuf) == 0) { + if (S_ISLNK(statbuf.st_mode)) { + throw std::runtime_error("Cannot write to a symbolic link"); + } + + // check if we can write to file + bool canWrite = ((getuid() == statbuf.st_uid) && (statbuf.st_mode & S_IWUSR)) + || ((getgid() == statbuf.st_gid) && (statbuf.st_mode & S_IWGRP)) + || (statbuf.st_mode & S_IWOTH); + if (!canWrite) { + throw std::runtime_error(stringBuilder("User can not write to ", filename)); + } + + fd = mkstemp(tmpFilename.data()); + if (fd < 0) { + throw std::system_error(errno, std::system_category()); + } + + // mkstemp sets file permission to 0600 + // Set the permissions to match filename + int s = 0; + s |= chmod(tmpFilename.c_str(), statbuf.st_mode); + s |= chown(tmpFilename.c_str(), statbuf.st_uid, statbuf.st_gid); + if (s != 0) { + std::cerr << "Warning: unable to change the file permissions of " << tmpFilename << std::endl; + } + } + else { + fd = mkstemp(tmpFilename.data()); + if (fd < 0) { + throw std::system_error(errno, std::system_category()); + } + + // mkostemp sets file permission to 0600 + // Set the permissions what user would expect + mode_t mask = umask(0); + umask(mask); + chmod(tmpFilename.c_str(), 0666 & ~mask); + } + + const uint8_t* ptr = static_cast(data); + size_t todo = size; + ssize_t done; + + while (todo > 0) { + done = ::write(fd, ptr, std::min(BLOCK_SIZE, todo)); + if (done < 0) { + auto err = errno; + close(fd); + throw std::system_error(err, std::system_category()); + } + + ptr += done; + todo -= done; + } + + int r; + r = close(fd); + if (r != 0) { + throw std::system_error(errno, std::system_category()); + } + + r = rename(tmpFilename.c_str(), filename.c_str()); + if (r != 0) { + throw std::system_error(errno, std::system_category()); + } +} +#endif + +} diff --git a/pool/shard011/C++/0121859_Curve.cpp b/pool/shard011/C++/0121859_Curve.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b10775be8fe574220517b98b02bff651c5d1452 --- /dev/null +++ b/pool/shard011/C++/0121859_Curve.cpp @@ -0,0 +1,170 @@ +#include "Curve.h" +#include + +/* static matrices */ +glm::mat4 Curve::m_projection_matrix = glm::mat4(1.0f); +glm::mat4 Curve::m_view_matrix = glm::mat4(1.0f); + +/* +* \brief Constructor of the curve class. Sample and create a curve with the given parameters +* \param[in] max_power unsigned integer corresponding to the maximum power of the equation of the curve +* \param[in] precision unsigned integer corresponding to the number of points sampled for the rendering +* \param[in] length a float containing the length of the curve, i.e. the length between the first and the last sampled point +* \param[in] color a 3-vector containing the RGB values of the color of the curve +* \return A well initialized curve respecting the parameters +*/ +Curve::Curve(GLuint max_power, GLuint precision, GLfloat length, glm::vec3 color) +{ + m_color = color; + m_precision = precision; + m_length = length; + m_max_power = max_power; + m_local_rotation = glm::vec3(0,0,0); + m_local_scaling = 1.0f; + m_local_translation = glm::vec3(0,0,0); + + //Randomly generate the coefficients + GLfloat coefficient_1 = ((rand() % 101) - 50) / (m_length * 100.0f); + m_coefficients.push_back(coefficient_1); + + for (unsigned j = 0; j < m_max_power - 2; j++) + { + GLfloat coefficient = (rand() % 101) / 100.0f * m_length; + m_coefficients.push_back(coefficient); + } + + glGenBuffers(1, &m_points_id); + + sample(); +} + +/* \brief Destructor of the class Curve. Deallocates the ressources */ +Curve::~Curve(){ + glDeleteBuffers(1, &m_points_id); +} + +/* +* \brief Method that draws the curve to the currently bound buffer +* \param[in] shader the shader containing the uniforms to be bound in the method +*/ +void Curve::draw(Shader shader) +{ + computeModelMatrix(); + + glEnableVertexAttribArray(0); + glBindBuffer(GL_ARRAY_BUFFER, m_points_id); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); + + glUniformMatrix4fv(shader.getUniform("MVP"), 1, GL_FALSE, &(m_projection_matrix * m_view_matrix * m_model_matrix)[0][0]); + glUniform3fv(shader.getUniform("curve_color"), 1, &m_color[0]); + + glDrawArrays(GL_LINE_STRIP, 0, GLsizei(m_points.size())); + + glDisableVertexAttribArray(0); +} + +/* +* \brief Method that samples the points of the curve and push them in the points vector +*/ +void Curve::sample() +{ + //Find the interval between points on the curve for the given precision + GLfloat interval = -1.0f; + if (m_precision > 0) + { + interval = m_length / ((GLfloat) m_precision); + } + //Sample the equation at these intervals + for (unsigned i = 0; i <= m_precision; i++) + { + GLfloat x = i * interval; + GLfloat y = m_coefficients[0] * x * (x - m_length); + for (unsigned j = 1; j < m_max_power - 1; j++) + { + y *= (x - m_coefficients[j]); + } + + glm::vec2 point = glm::vec2(x, y); + m_points.push_back(point); + } + + //Prepare the data buffer + glBindBuffer(GL_ARRAY_BUFFER, m_points_id); + glBufferData(GL_ARRAY_BUFFER, m_points.size() * sizeof(glm::vec2), &m_points[0], GL_STATIC_DRAW); +} + +/* +* \brief Method that computes the model matrix of the curve from the translation, rotation and scaling data +*/ +void Curve::computeModelMatrix() +{ + glm::mat4 translation = glm::mat4( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + m_local_translation.x, m_local_translation.y, m_local_translation.z, 1.0f); + + glm::mat4 scaling = glm::mat4( + m_local_scaling, 0.0f, 0.0f, 0.0f, + 0.0f, m_local_scaling, 0.0f, 0.0f, + 0.0f, 0.0f, m_local_scaling, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + + glm::mat4 rotx = glm::mat4( + 1.0f, 0.0f, 0.0f, 0.0f, + 0.0f, cos(m_local_rotation.x), -sin(m_local_rotation.x), 0.0f, + 0.0f, sin(m_local_rotation.x), cos(m_local_rotation.x), 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + + glm::mat4 roty = glm::mat4( + cos(m_local_rotation.y), 0.0f, -sin(m_local_rotation.y), 0.0f, + 0.0f, 1.0f, 0.0f, 0.0f, + sin(m_local_rotation.y), 0.0f, cos(m_local_rotation.y), 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + + glm::mat4 rotz = glm::mat4( + cos(m_local_rotation.z), -sin(m_local_rotation.z), 0.0f, 0.0f, + sin(m_local_rotation.z), cos(m_local_rotation.z), 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f); + + m_model_matrix = translation * rotx * roty * rotz * scaling; +} + +/* +* \brief Getter of the local translation of the curve +* \return a reference to the 3-vector representing the translation of the curve +*/ +glm::vec3 & Curve::getLocalTranslation(){ + return m_local_translation; +} + +/* +* \brief Getter of the local rotation of the curve +* \return a reference to the 3-vector representing the rotation of the curve +*/ +glm::vec3 & Curve::getLocalRotation(){ + return m_local_rotation; +} + +/* +* \brief Getter of the local scaling of the curve +* \return a reference to a float representing the uniform scaling of the curve +*/ +GLfloat & Curve::getLocalScaling(){ + return m_local_scaling; +} + +/* +* \brief Setter of the view matrix of all the curves +*/ +void Curve::setViewMatrix(glm::mat4 matrix){ + m_view_matrix = matrix; +} + +/* +* \brief Setter of the projection matrix of all the curves +*/ +void Curve::setProjectionMatrix(glm::mat4 matrix){ + m_projection_matrix = matrix; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121860_qdeclarativegalleryfilter.cpp b/pool/shard011/C++/0121860_qdeclarativegalleryfilter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b873cdb4fa100f9f914daa5c2b987f2e9b48791 --- /dev/null +++ b/pool/shard011/C++/0121860_qdeclarativegalleryfilter.cpp @@ -0,0 +1,656 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the Qt Mobility Components. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qdeclarativegalleryfilter.h" + +#include + +QTM_BEGIN_NAMESPACE + +void QDeclarativeGalleryValueFilter::setValue(const QVariant &value) +{ + if (value != m_filter.value()) { + m_filter.setValue(value); + + emit valueChanged(); + emit filterChanged(); + } +} +void QDeclarativeGalleryValueFilter::setPropertyName(const QString &name) +{ + if (name != m_filter.propertyName()) { + m_filter.setPropertyName(name); + + emit propertyNameChanged(); + emit filterChanged(); + } +} + +void QDeclarativeGalleryValueFilter::setNegated(bool negated) +{ + if (negated != m_filter.isNegated()) { + m_filter.setNegated(negated); + + emit negatedChanged(); + emit filterChanged(); + } +} + +QGalleryFilter QDeclarativeGalleryValueFilter::filter() const +{ + return m_filter; +} + +void QDeclarativeGalleryStringFilter::setPropertyName(const QString &name) +{ + if (name != m_filter.propertyName()) { + m_filter.setPropertyName(name); + + emit propertyNameChanged(); + emit filterChanged(); + } +} + +void QDeclarativeGalleryStringFilter::setValue(const QString &value) +{ + if (value != m_filter.value()) { + m_filter.setValue(value); + + emit valueChanged(); + emit filterChanged(); + } +} + +void QDeclarativeGalleryStringFilter::setNegated(bool negated) +{ + if (negated != m_filter.isNegated()) { + m_filter.setNegated(negated); + + emit negatedChanged(); + emit filterChanged(); + } +} + +QGalleryFilter QDeclarativeGalleryStringFilter::filter() const +{ + return m_filter; +} + +/*! + \qmlclass GalleryEqualsFilter QDeclarativeGalleryEqualsFilter + + \brief The GalleryEqualsFilter element provides a filter which tests + if a meta-data property is equal to a value. + \since Mobility 1.1 + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryEqualsFilter { + property: "keywords" + value: "holiday" + } + \endqml +*/ + +/*! + \qmlproperty string GalleryEqualsFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryEqualsFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryEqualsFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +QGalleryFilter QDeclarativeGalleryEqualsFilter::filter() const +{ + if (m_filter.value().type() == QVariant::RegExp) { + QGalleryMetaDataFilter filter(m_filter); + + filter.setComparator(QGalleryFilter::RegExp); + + return filter; + } else { + return m_filter; + } +} + +/*! + \qmlclass GalleryLessThanFilter QDeclarativeGalleryLessThanFilter + \since Mobility 1.1 + + \brief The GalleryLessThanFilter element provides a filter which tests + if a meta-data property is less than a value. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryLessThanFilter { + property: "lastAccessed" + value: 2008-01-01T00:00:00 + } + \endqml +*/ + +/*! + \qmlproperty string GalleryLessThanFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryLessThanFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryLessThanFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + + +/*! + \qmlclass GalleryLessThanEqualsFilter QDeclarativeGalleryLessThanEqualsFilter + \since Mobility 1.1 + + \brief The GalleryLessThanEqualsFilter element provides a filter which tests + if a meta-data property is less than or equal to a value. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryLessThanEqualsFilter { + property: "rating" + value: 3.5 + } + \endqml +*/ + +/*! + \qmlproperty string GalleryLessThanEqualsFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryLessThanEqualsFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryLessThanEqualsFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + + +/*! + \qmlclass GalleryGreaterThanFilter QDeclarativeGalleryGreaterThanFilter + \since Mobility 1.1 + + \brief The GalleryGreaterThanFilter element provides a filter which tests + if a meta-data property is greater than a value. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryGreaterThanFilter { + property: "rating" + value: 3.5 + } + \endqml +*/ + +/*! + \qmlproperty string GalleryGreaterThanFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryGreaterThanFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryGreaterThanFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +/*! + \qmlclass GalleryGreaterThanEqualsFilter QDeclarativeGalleryGreaterThanEqualsFilter + \since Mobility 1.1 + + \brief The GalleryGreaterThanEqualsFilter element provides a filter which + tests if a meta-data property is greater than or equal to a value. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryGreaterThanEqualsFilter { + property: "lastAccessed" + value: 2008-01-01T00:00:00 + } + \endqml +*/ + +/*! + \qmlproperty string GalleryGreaterThanEqualsFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryGreaterThanEqualsFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryGreaterThanEqualsFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +/*! + \qmlclass GalleryContainsFilter QDeclarativeGalleryContainsFilter + \since Mobility 1.1 + + \brief The GalleryContainsFilter element provides a filter which tests if + a meta-data property contains a string. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryContainsFilter { + property: "title" + value: "excellent" + } + \endqml +*/ + +/*! + \qmlproperty string GalleryContainsFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryContainsFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryContainsFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +/*! + \qmlclass GalleryStartsWithFilter QDeclarativeGalleryStartsWithFilter + \since Mobility 1.1 + + \brief The GalleryStartsWithFilter element provides a filter which tests if + a meta-data property starts with a string. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryStartsWithFilter { + property: "title" + value: "the" + } + \endqml +*/ + +/*! + \qmlproperty string GalleryStartsWithFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryStartsWithFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryStartsWithFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +/*! + \qmlclass GalleryEndsWithFilter QDeclarativeGalleryEndsWithFilter + + \brief The GalleryEndsWithFilter element provides a filter which tests if a + meta-data property ends with a string. + \since Mobility 1.1 + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryEndsWithFilter { + property: "title" + value: ", the" + } + \endqml +*/ + +/*! + \qmlproperty string GalleryEndsWithFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryEndsWithFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryEndsWithFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + +/*! + \qmlclass GalleryWildcardFilter QDeclarativeGalleryWildcardFilter + \since Mobility 1.1 + + \brief The GalleryWildcardFilter element provides a filter which tests a + meta-data property against a value using wildcard matching. + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. + + \qml + GalleryWildcardFilter { + property: "fileName" + value: "*.png" + } + \endqml +*/ + +/*! + \qmlproperty string GalleryWildcardFilter::property + \since Mobility 1.1 + + This property holds the name of the property to filter against. +*/ + +/*! + \qmlproperty variant GalleryWildcardFilter::value + \since Mobility 1.1 + + This property holds the value to filter using. +*/ + +/*! + \qmlproperty bool GalleryWildcardFilter::negated + \since Mobility 1.1 + + This property holds whether the result of a filter should be negated. +*/ + + +void QDeclarativeGalleryFilterGroup::classBegin() +{ +} + +void QDeclarativeGalleryFilterGroup::componentComplete() +{ + m_complete = true; + + typedef QList::const_iterator iterator; + for (iterator it = m_filters.constBegin(), end = m_filters.constEnd(); it != end; ++it) + connect(*it, SIGNAL(filterChanged()), this, SIGNAL(filterChanged())); +} + +QDeclarativeListProperty QDeclarativeGalleryFilterGroup::filters() +{ + return QDeclarativeListProperty( + this, &m_filters, append, count, at, clear); +} + +void QDeclarativeGalleryFilterGroup::append( + QDeclarativeListProperty *filters, + QDeclarativeGalleryFilterBase *filter) +{ + QDeclarativeGalleryFilterGroup *filterGroup + = static_cast(filters->object); + + static_cast*>(filters->data)->append(filter); + + if (static_cast(filters->object)->m_complete) { + connect(filter, SIGNAL(filterChanged()), filterGroup, SIGNAL(filterChanged())); + + emit filterGroup->filterChanged(); + } +} + +int QDeclarativeGalleryFilterGroup::count( + QDeclarativeListProperty *filters) +{ + return static_cast*>(filters->data)->count(); +} + +QDeclarativeGalleryFilterBase *QDeclarativeGalleryFilterGroup::at( + QDeclarativeListProperty *filters, int index) +{ + return static_cast*>(filters->data)->at(index); +} + +void QDeclarativeGalleryFilterGroup::clear( + QDeclarativeListProperty *filters) +{ + QDeclarativeGalleryFilterGroup *filterGroup + = static_cast(filters->object); + + QList *list + = static_cast*>(filters->data); + + typedef QList::const_iterator iterator; + for (iterator it = list->constBegin(), end = list->constEnd(); it != end; ++it) + disconnect(*it, SIGNAL(filterChanged()), filterGroup, SIGNAL(filterChanged())); + + list->clear(); + + emit filterGroup->filterChanged(); +} + +/*! + \qmlclass GalleryFilterUnion GalleryFilterUnion + + \brief The GalleryFilterUnion elements provides a union of gallery filters. + \since Mobility 1.1 + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. +*/ + +/*! + \qmlproperty filterlist GalleryFilterUnion::filters + \since Mobility 1.1 + + This property holds the children of a union filter. +*/ + +QGalleryFilter QDeclarativeGalleryFilterUnion::filter() const +{ + QGalleryUnionFilter unionFilter; + + typedef QList::const_iterator iterator; + for (iterator it = m_filters.begin(), end = m_filters.end(); it != end; ++it) { + QGalleryFilter filter = (*it)->filter(); + switch (filter.type()) { + case QGalleryFilter::MetaData: + unionFilter.append(filter.toMetaDataFilter()); + break; + case QGalleryFilter::Union: + unionFilter.append(filter.toUnionFilter()); + break; + case QGalleryFilter::Intersection: + unionFilter.append(filter.toIntersectionFilter()); + break; + default: + break; + } + } + return unionFilter; +} + +/*! + \qmlclass GalleryFilterIntersection GalleryFilterIntersection + + \brief The GalleryFilterIntersection elements provides a intersection of + gallery filters. + \since Mobility 1.1 + + \ingroup qml-gallery + \ingroup qml-gallery-filters + + This element is part of the \bold {QtMobility.gallery 1.0} module. +*/ + +/*! + \qmlproperty filterlist GalleryFilterIntersection::filters + \since Mobility 1.1 + + This property holds the children of a intersection filter. +*/ + +QGalleryFilter QDeclarativeGalleryFilterIntersection::filter() const +{ + QGalleryIntersectionFilter intersectionFilter; + + typedef QList::const_iterator iterator; + for (iterator it = m_filters.begin(), end = m_filters.end(); it != end; ++it) { + QGalleryFilter filter = (*it)->filter(); + switch (filter.type()) { + case QGalleryFilter::MetaData: + intersectionFilter.append(filter.toMetaDataFilter()); + break; + case QGalleryFilter::Union: + intersectionFilter.append(filter.toUnionFilter()); + break; + case QGalleryFilter::Intersection: + intersectionFilter.append(filter.toIntersectionFilter()); + break; + default: + break; + } + } + return intersectionFilter; +} + +#include "moc_qdeclarativegalleryfilter.cpp" + +QTM_END_NAMESPACE diff --git a/pool/shard011/C++/0121863_template.cpp b/pool/shard011/C++/0121863_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a0e826408cb1f573bca33cc23a484366cff36b8b --- /dev/null +++ b/pool/shard011/C++/0121863_template.cpp @@ -0,0 +1,187 @@ +// Created by Kaidul Islam on 18/4/16. +// Copyright © 2016 Kaidul Islam. All rights reserved. +// +// +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +// #include + +using namespace std; + +#define rep(i, n) for(__typeof(n) i = 0; i < (n); i++) +#define rrep(i, n) for(__typeof(n) i = (n) - 1; i >= 0; --i) +#define rep1(i, n) for(__typeof(n) i = 1; i <= (n); i++) +#define FOR(i, a, b) for(__typeof(b) i = (a); i <= (b); i++) +#define forstl(i, s) for (__typeof ((s).end ()) i = (s).begin (); i != (s).end (); ++i) +#define SIZE(v) ((int)v.size()) +#define INF (1 << 30) +#define PI acos(-1.0) +#define bitcnt __builtin_popcount +#define pb push_back +#define ppb pop_back +#define all(x) x.begin(), x.end() +#define mem(x, y) memset(x, y, sizeof x) +#define eps 1e-9 +#define pii pair +#define couple make_pair +#define X first +#define Y second +#define vi vector +#define vpii vector< pii > +#define si set +#define SDi(x) sf("%d", &x) +#define SD2(x, y) sf("%d %d", &x, &y) +#define SD3(x, y, z) sf("%d %d %d", &x, &y, &z) +#define SDs(x) sf("%s", x) +#define pf printf +#define print(x) pf("%d ", x) +#define println(x) pf("%d\n", x) +#define output(x, y); pf("Case %d: %d", ++x, y) +#define newLine pf("\n") +#define sf scanf +#define READ(f) freopen(f, "r", stdin) +#define WRITE(f) freopen(f, "w", stdout) +#if ( _WIN32 or __WIN32__ ) +#define LLD "%I64d" +#else +#define LLD "%lld" +#endif +#define SDl(x) sf(LLD, &x) +#define MAX5 100000 +#define MAX7 10000000 +#define MAX9 1000000000 +#define MOD7 (MAX7 + 7) +#define MOD9 (MAX9 + 9) +typedef long long i64; +typedef unsigned long long ui64; +const i64 INF64 = (i64) 1E18; + +template string toStr(T n) { ostringstream oss; oss << n; oss.flush(); return oss.str(); } +template T toInt(string s) { T n = 0; istringstream sin(s); sin >> n; return n; } + +class TimeTracker { + clock_t start, end; +public: + TimeTracker() { + start = clock(); + } + ~TimeTracker() { + end = clock(); + fprintf(stderr, "%.3lf s\n", (double)(end - start) / CLOCKS_PER_SEC); + } +}; + +struct Point { + int x, y; + Point(): x(0), y(0) {} + Point(int a, int b): x(a), y(b) {} + bool operator < (const Point& other) const { + return x < other.x; + } +}; +// BitMask +int Set(int N, int pos) { + return N |= (1 << pos); +} +int Reset(int N, int pos) { + return N &= ~(1 << pos); +} +int Check(int N, int pos) { + return (N & (1 << pos)); +} +int toggle(int N, int pos) { + return N ^= (1 << pos); +} + +// direction array +//int dx[] = {0, -1, 0, 1}; +//int dy[] = {-1, 0, 1, 0}; +//int Dx[] = {0, -1, -1, -1, 0, 1, 1, 1}; +//int Dy[] = {-1, -1, 0, 1, 1, 1, 0, -1}; +//int _row, _col; +//inline bool isValid(int i, int j) { +// return i >= 0 and j >= 0 and i < _row and j < _col; +//} + +#define MOD (MAX9 + 7) + +inline void IncMod(int &x, int y) { + x += y; + if (x >= MOD) { + x -= MOD; + } +} + +#define keyType int +class Compare { +public: + bool operator() (keyType& lhs, keyType& rhs) const { + return lhs > rhs; + } +} compare; +// e.g. sort(all(arr), compare) + + +#define error(args...) { vector _v; split(#args, ',', _v); err(_v.begin(), args); } + +void split(const string& s, char c, vector& result) { + stringstream ss(s); + string x; + while (getline(ss, x, c)) + result.push_back(x); +} + +void err(vector::iterator it) {} +template +void err(vector::iterator it, T a, Args... args) { + cerr << it -> substr((*it)[0] == ' ', it -> length()) << " = " << a << '\n'; + err(++it, args...); +} + +/* + error(a, b, c) +output: + a = 4 + b = 8 + c = 9 +*/ + +/** Implementation **/ + +int main(int argc, const char * argv[]) { +#ifndef ONLINE_JUDGE + READ("input.txt"); +#endif + int tcase; + SDi(tcase); + while(tcase--) { + + } + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121864_test_rpim_1.cc b/pool/shard011/C++/0121864_test_rpim_1.cc new file mode 100644 index 0000000000000000000000000000000000000000..14f0c2688da7716864728160b720d22763387dfb --- /dev/null +++ b/pool/shard011/C++/0121864_test_rpim_1.cc @@ -0,0 +1,143 @@ +/* +GoGoRPIM - A RPIM implementation and 2-D Eletromagnetic simulator + Copyright (C) 2012 Péricles Lopes Machado (LANE-UFPA) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +/**Copyright 2012 Péricles Lopes Machado +@file test_rpim_1.cc + +UFPA - Universidade Federal do Pará +Laboratório de Análises Numéricas em Eletromagnetismo (LANE) + +Implementação do RPIM - Radial Point Interpolation Method + +Esta implementação faz parte do TCC de Engenharia da Computaçã de Péricles Lopes Machado (0608000101) +*/ + +#include + +#include "test_rpim_1.h" + +using namespace lane_maxwell::modules::matrix; +using namespace lane_maxwell::modules::point; +using namespace lane_maxwell::modules::rpim; +using namespace lane_maxwell::modules::domains; + +Point* point2D(double x, double y, double eps, double mu, int prop, int ID, char type) { + Point* po = new Point; + Vector* p = new Vector(2); + + p->set(0, x); + p->set(1, y); + + po->set(ID, eps, mu, prop, type, p); + return po; +} + +void genPoints(Points* const vp, int nx, int ny, char type) { + + double dx = 0.1; + double dy = 0.1; + + double eps = 8.841941e-12; + double mu = 1.256637e-6; + int prop = 0; + static int ID = 0; + //void set(int ID, double eps, double mu, int prop, char type, + //matrix::Vector* const p) + for (int ix = 0; ix < nx; ++ix) { + for (int iy = 0; iy < ny; ++iy) { + double x, y; + if (type == 'E') { + x = (2*ix)*dx; + y = (2*iy)*dy; + vp->push_back(point2D(x, y, eps, mu, prop, ID, type)); + ++ID; + + x = (2*ix+1)*dx; + y = (2*iy+1)*dy; + vp->push_back(point2D(x, y, eps, mu, prop, ID, type)); + ++ID; + + } else { + x = (2*ix+1)*dx; + y = (2*iy)*dy; + vp->push_back(point2D(x, y, eps, mu, prop, ID, type)); + ++ID; + + x = (2*ix)*dx; + y = (2*iy+1)*dy; + vp->push_back(point2D(x, y, eps, mu, prop, ID, type)); + ++ID; + } + } + } +} + +double dumb(const Points* p, int T, char A, char B) { + double acc = 0; + + for (int i = 0; i < p->size(); ++i) { + if(p->at(i)->getType() == A) { + std::vector d; + + for (int j = 0; j < p->size(); ++j) + if (i != j && p->at(j)->getType() == B) { + d.push_back(distE(p->at(i), p->at(j))); + } + + sort(d.begin(), d.end()); + for (int j = 0; j < T; ++j) { + acc+=d[j]; + } + } + if (i%100 == 0) std::printf("acc = %e\n", acc); + } + + return acc; +} + +int main() { + lane_maxwell::modules::matrix::matrixModuleInit(1e-7); + + Points* p = new Points; + int nx, ny, T; + std::printf("(nx,ny)="); + std::scanf("%d%d", &nx, &ny); + + std::printf("T="); + std::scanf("%d", &T); + + genPoints(p, nx, ny, 'E'); + genPoints(p, nx, ny, 'H'); + + //std::printf("Points...\n"); + //print(stdout, p); + + std::sort(p->begin(), p->end(),PointComp()); + + //printAll(stdout, p); + + buildSupportDomain(stdout, 'E', 'H', T, p, 0.01, distE, 1); + + //std::printf("r acc dumb = %e\n", dumb(p, T, 'E', 'H')); + std::printf("r acc line sweep = %e\n", accSD(p)); + + free(p); + return 0; +} + + diff --git a/pool/shard011/C++/0121865_InputFileCatalog.cc b/pool/shard011/C++/0121865_InputFileCatalog.cc new file mode 100644 index 0000000000000000000000000000000000000000..0966ed916f403f05238a96703c6f3bc5fde03864 --- /dev/null +++ b/pool/shard011/C++/0121865_InputFileCatalog.cc @@ -0,0 +1,229 @@ +////////////////////////////////////////////////////////////////////// +// +// InputFileCatalog +// +////////////////////////////////////////////////////////////////////// + +#include "art/Framework/IO/Catalog/InputFileCatalog.h" +#include "art/Framework/Services/FileServiceInterfaces/CatalogInterface.h" +#include "art/Framework/Services/FileServiceInterfaces/FileTransfer.h" +#include "canvas/Utilities/Exception.h" +#include "boost/algorithm/string.hpp" +#include "cetlib/exception.h" +#include "fhiclcpp/ParameterSet.h" + +#include + +namespace art { + + InputFileCatalog::InputFileCatalog(fhicl::TableFragment const& config) + : fileSources_{config().namesParameter()} + { + + if (fileSources_.empty()) { + throw art::Exception(art::errors::CatalogServiceError, "InputFileCatalog::InputFileCatalog()\n") + << "Empty '" << config().namesParameter.name() << "' parameter specified for input source.\n"; + } + + // Configure FileDelivery service + ci_->configure(fileSources_); + searchable_ = ci_->isSearchable(); + + if( searchable_ ) fileCatalogItems_.resize(fileSources_.size()); + } + + FileCatalogItem const & InputFileCatalog::currentFile() const { + if( fileIdx_==indexEnd ) { + throw art::Exception(art::errors::LogicError, + "Cannot access the current file while the file catalog is empty!"); + } + assert( fileIdx_ <= maxIdx_ ); + return fileCatalogItems_[fileIdx_]; + } + + size_t InputFileCatalog::currentIndex() const { + return fileIdx_; + } + + bool InputFileCatalog::getNextFile(int attempts) { + // get next file from FileDelivery service + // and give it to currentFile_ object + // returns false if theres no more file + // + // If hasNextFile() has been called prior to + // getNextFile(), it does not actually go fetch + // the next file from FileDelivery service, + // instead, it advances the iterator by one and + // make the "hidden" next file current. + + if( nextFileProbed_ && !hasNextFile_ ) + return false; + + if( (nextFileProbed_ && hasNextFile_) || retrieveNextFile(nextItem_, attempts) ) + { + nextFileProbed_ = false; + fileIdx_ = (fileIdx_ == indexEnd) ? 0 : (searchable_ ? (fileIdx_+1) : 0); + if( fileIdx_ > maxIdx_ ) maxIdx_ = fileIdx_; + fileCatalogItems_[fileIdx_] = nextItem_; + return true; + } + + return false; + } + + bool InputFileCatalog::hasNextFile(int attempts) { + // A probe. It tries(and actually does) retreive + // the next file from the FileDelivery service. But + // does not advance the current file pointer + if( nextFileProbed_ ) + return hasNextFile_; + + hasNextFile_ = retrieveNextFile(nextItem_, attempts); + nextFileProbed_ = true; + + return hasNextFile_; + } + + bool InputFileCatalog::retrieveNextFile(FileCatalogItem & item, int attempts, bool transferOnly) { + + // Tell the service the current opened file (if theres one) is consumed + if( fileIdx_!=indexEnd // there is a current file + && !currentFile().skipped() // not skipped + && !currentFile().consumed() ) // not consumed + { + ci_->updateStatus( currentFile().uri(), FileDisposition::CONSUMED ); + fileCatalogItems_[fileIdx_].consume(); + } + + // retrieve (deliver and transfer) next file from service + // or, do the transfer only + FileCatalogStatus status; + if( transferOnly ) { status = transferNextFile(item); } + else { status = retrieveNextFileFromCacheOrService(item); } + + if( status == FileCatalogStatus::SUCCESS ) { + // mark the file as transferred + ci_->updateStatus( item.uri(), FileDisposition::TRANSFERRED ); + return true; + } + + if( status == FileCatalogStatus::NO_MORE_FILES ) { + return false; + } + + if( status == FileCatalogStatus::DELIVERY_ERROR ) { + if( attempts <= 1 ) { + throw art::Exception(art::errors::Configuration, + "InputFileCatalog::retreiveNextFile()\n") + << "Delivery error encountered after reaching maximum number of attemtps!"; + } + else { + return retrieveNextFile(item, attempts-1, false); + } + } + + if( status == FileCatalogStatus::TRANSFER_ERROR ) { + if( attempts <= 1 ) { + // if we end up with a transfer error, the method returns + // with a true flag and empty filename. Weired enough, but + // the next file does exist we just cannot retrieve it. Therefore + // we notify the service that the file has been skipped + ci_->updateStatus( item.uri(), FileDisposition::SKIPPED ); + return true; + } + else { + return retrieveNextFile(item, attempts-1, true); + } + } + + // should never reach here + assert(0); + return false; + } + + FileCatalogStatus InputFileCatalog::retrieveNextFileFromCacheOrService(FileCatalogItem & item) { + // Try to get it from cached files + if( fileIdx_ < maxIdx_ ) { + item = fileCatalogItems_[fileIdx_+1]; + return FileCatalogStatus::SUCCESS; + } + + // Try to get it from the service + std::string uri; + double wait = 0.0; + + // get file delivered + int result = ci_->getNextFileURI( uri, wait ); + + if( result == FileDeliveryStatus::NO_MORE_FILES ) + return FileCatalogStatus::NO_MORE_FILES; + + if( result != FileDeliveryStatus::SUCCESS ) + return FileCatalogStatus::DELIVERY_ERROR; + + item = FileCatalogItem("", "", uri); + + // get file transfered + return transferNextFile(item); + } + + FileCatalogStatus InputFileCatalog::transferNextFile(FileCatalogItem & item) { + + std::string pfn; + + int result = ft_->translateToLocalFilename( item.uri(), pfn ); + + if( result != FileTransferStatus::SUCCESS ) + { + item.fileName(""); + item.logicalFileName(""); + item.skip(); + return FileCatalogStatus::TRANSFER_ERROR; + } + + // successfully retrieved the file + std::string lfn = pfn; + + boost::trim(pfn); + + if (pfn.empty()) { + throw art::Exception(art::errors::Configuration, + "InputFileCatalog::retrieveNextFileFromCacheService()\n") + << "An empty string specified in parameter for input source.\n"; + } + + if (isPhysical(pfn)) { + lfn.clear(); + } + + item.fileName(pfn); + item.logicalFileName(lfn); + return FileCatalogStatus::SUCCESS; + } + + void InputFileCatalog::rewind() { + if ( !searchable_ ) { + throw art::Exception(art::errors::LogicError, "InputFileCatalog::rewind()\n") + << "A non-searchable catalog is not allowed to rewind!"; + } + fileIdx_ = 0; + } + + void InputFileCatalog::rewindTo(size_t index) { + // rewind to a previous file location in the catalog + // service is not rewinded. only usable when FileDeliveryService:: + // areFilesPersistent() is true + if ( !searchable_ ) { + throw art::Exception(art::errors::LogicError, "InputFileCatalog::rewindTo()\n") + << "A non-searchable catalog is not allowed to rewind!"; + } + + if( index > maxIdx_ ) { + throw art::Exception(art::errors::InvalidNumber, "InputFileCatalog::rewindTo()\n") + << "Index " << index << " is out of range!"; + } + + fileIdx_ = index; + } + +} // art diff --git a/pool/shard011/C++/0121867_ex1.cpp b/pool/shard011/C++/0121867_ex1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c941c4953730d849870ca9108d8f01fe04e2d6d7 --- /dev/null +++ b/pool/shard011/C++/0121867_ex1.cpp @@ -0,0 +1,85 @@ +/** tutorial/Ex1 + * This example shows how to: + * initialize a femus application; + * define the multilevel-mesh object mlMsh; + * read from the file ./input/square.neu the coarse-level mesh and associate it to mlMsh; + * add in mlMsh uniform refined level-meshes; + * define the multilevel-solution object mlSol associated to mlMsh; + * add in mlSol different types of finite element solution variables; + * initialize the solution variables; + * define vtk and gmv writer objects associated to mlSol; + * print vtk and gmv binary-format files in ./output directory. + **/ + +#include "FemusInit.hpp" +#include "MultiLevelSolution.hpp" +#include "MultiLevelProblem.hpp" +#include "VTKWriter.hpp" +#include "GMVWriter.hpp" + +using namespace femus; + +double InitalValueU(const std::vector < double >& x) { + return x[0] + x[1]; +} + +double InitalValueP(const std::vector < double >& x) { + return x[0]; +} + +double InitalValueT(const std::vector < double >& x) { + return x[1]; +} + +int main(int argc, char** args) { + + // init Petsc-MPI communicator + FemusInit mpinit(argc, args, MPI_COMM_WORLD); + + // define multilevel mesh + MultiLevelMesh mlMsh; // Consider the "mlMsh" object of "MultiLevel" class. + double scalingFactor = 1.; + // read coarse level mesh and generate finers level meshes + mlMsh.ReadCoarseMesh("./input/square.neu", "seventh", scalingFactor); // Let mlMsh read the coarse mesh. + /* "seventh" is the order of accuracy that is used in the gauss integration scheme + probably in the furure it is not going to be an argument of this function */ + unsigned numberOfUniformLevels = 3; // We apply uniform refinement. + unsigned numberOfSelectiveLevels = 0; // we may want to see solutions on different level of meshes. + mlMsh.RefineMesh(numberOfUniformLevels , numberOfUniformLevels + numberOfSelectiveLevels, NULL); // Add those refined meshed in mlMsh object. + mlMsh.PrintInfo(); + + // define the multilevel solution and attach the mlMsh object to it + MultiLevelSolution mlSol(&mlMsh); // Define "mlSol" object with argument mlMsh of "MultiLevelSolution" class. + // add variables to mlSol + mlSol.AddSolution("U", LAGRANGE, FIRST); + mlSol.AddSolution("V", LAGRANGE, SERENDIPITY); + mlSol.AddSolution("W", LAGRANGE, SECOND); + mlSol.AddSolution("P", DISCONTINUOUS_POLYNOMIAL, ZERO); + mlSol.AddSolution("T", DISCONTINUOUS_POLYNOMIAL, FIRST); + + mlSol.Initialize("All"); // initialize all varaibles to zero + + mlSol.Initialize("U", InitalValueU); + mlSol.Initialize("P", InitalValueP); + mlSol.Initialize("T", InitalValueT); // note that this initialization is the same as piecewise constant element + + // print solutions + std::vector < std::string > variablesToBePrinted; + variablesToBePrinted.push_back("U"); + variablesToBePrinted.push_back("P"); + variablesToBePrinted.push_back("T"); + + VTKWriter vtkIO(&mlSol); + vtkIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted); + + GMVWriter gmvIO(&mlSol); + variablesToBePrinted.push_back("all"); + gmvIO.SetDebugOutput(false); + gmvIO.Write(DEFAULT_OUTPUTDIR, "biquadratic", variablesToBePrinted); + + return 0; +} + + + + diff --git a/pool/shard011/C++/0121870_testing_profile_manager.cc b/pool/shard011/C++/0121870_testing_profile_manager.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a5f6202af3cda43e60c9cac9afa4d175d89cd92 --- /dev/null +++ b/pool/shard011/C++/0121870_testing_profile_manager.cc @@ -0,0 +1,128 @@ +// 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 "chrome/test/base/testing_profile_manager.h" + +#include "base/files/file_path.h" +#include "base/memory/ref_counted.h" +#include "base/strings/utf_string_conversions.h" +#include "chrome/browser/extensions/extension_special_storage_policy.h" +#include "chrome/browser/prefs/pref_service_syncable.h" +#include "chrome/browser/profiles/profile_info_cache.h" +#include "chrome/browser/profiles/profile_manager.h" +#include "chrome/test/base/testing_browser_process.h" +#include "chrome/test/base/testing_profile.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace testing { + +class ProfileManager : public ::ProfileManager { + public: + explicit ProfileManager(const base::FilePath& user_data_dir) + : ::ProfileManager(user_data_dir) {} + + protected: + virtual Profile* CreateProfileHelper( + const base::FilePath& file_path) OVERRIDE { + return new TestingProfile(file_path); + } +}; + +} // namespace testing + +TestingProfileManager::TestingProfileManager(TestingBrowserProcess* process) + : called_set_up_(false), + browser_process_(process), + local_state_(process) { +} + +TestingProfileManager::~TestingProfileManager() { +} + +bool TestingProfileManager::SetUp() { + SetUpInternal(); + return called_set_up_; +} + +TestingProfile* TestingProfileManager::CreateTestingProfile( + const std::string& profile_name, + scoped_ptr prefs, + const string16& user_name, + int avatar_id) { + DCHECK(called_set_up_); + + // Create a path for the profile based on the name. + base::FilePath profile_path(profiles_dir_.path()); + profile_path = profile_path.AppendASCII(profile_name); + + // Create the profile and register it. + TestingProfile* profile = new TestingProfile( + profile_path, + NULL, + scoped_refptr(), + prefs.Pass()); + profile_manager_->AddProfile(profile); // Takes ownership. + + // Update the user metadata. + ProfileInfoCache& cache = profile_manager_->GetProfileInfoCache(); + size_t index = cache.GetIndexOfProfileWithPath(profile_path); + cache.SetNameOfProfileAtIndex(index, user_name); + cache.SetAvatarIconOfProfileAtIndex(index, avatar_id); + + testing_profiles_.insert(std::make_pair(profile_name, profile)); + + return profile; +} + +TestingProfile* TestingProfileManager::CreateTestingProfile( + const std::string& name) { + DCHECK(called_set_up_); + return CreateTestingProfile(name, scoped_ptr(), + UTF8ToUTF16(name), 0); +} + +void TestingProfileManager::DeleteTestingProfile(const std::string& name) { + DCHECK(called_set_up_); + + TestingProfilesMap::iterator it = testing_profiles_.find(name); + DCHECK(it != testing_profiles_.end()); + + TestingProfile* profile = it->second; + + ProfileInfoCache& cache = profile_manager_->GetProfileInfoCache(); + cache.DeleteProfileFromCache(profile->GetPath()); + + profile_manager_->profiles_info_.erase(profile->GetPath()); +} + +void TestingProfileManager::DeleteProfileInfoCache() { + profile_manager_->profile_info_cache_.reset(NULL); +} + +void TestingProfileManager::SetLoggedIn(bool logged_in) { + profile_manager_->logged_in_ = logged_in; +} + +ProfileManager* TestingProfileManager::profile_manager() { + DCHECK(called_set_up_); + return profile_manager_; +} + +ProfileInfoCache* TestingProfileManager::profile_info_cache() { + DCHECK(called_set_up_); + return &profile_manager_->GetProfileInfoCache(); +} + +void TestingProfileManager::SetUpInternal() { + ASSERT_FALSE(browser_process_->profile_manager()) + << "ProfileManager already exists"; + + // Set up the directory for profiles. + ASSERT_TRUE(profiles_dir_.CreateUniqueTempDir()); + + profile_manager_ = new testing::ProfileManager(profiles_dir_.path()); + browser_process_->SetProfileManager(profile_manager_); // Takes ownership. + + called_set_up_ = true; +} diff --git a/pool/shard011/C++/0121871_ThinClientHARegion.cpp b/pool/shard011/C++/0121871_ThinClientHARegion.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6881bdaf8fface4c061bd77c0d76c614a8ea9040 --- /dev/null +++ b/pool/shard011/C++/0121871_ThinClientHARegion.cpp @@ -0,0 +1,185 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ThinClientHARegion.hpp" +#include "TcrHADistributionManager.hpp" +#include "CacheImpl.hpp" +#include +#include "ReadWriteLock.hpp" +#include +#include "ThinClientPoolHADM.hpp" +namespace apache { +namespace geode { +namespace client { + +ThinClientHARegion::ThinClientHARegion( + const std::string& name, CacheImpl* cache, + const std::shared_ptr& rPtr, RegionAttributes attributes, + const std::shared_ptr& stats, bool shared, + bool enableNotification) + : ThinClientRegion(name, cache, rPtr, attributes, stats, shared), + m_attributes(attributes), + m_processedMarker(false), + m_poolDM(false) { + setClientNotificationEnabled(enableNotification); +} + +void ThinClientHARegion::initTCR() { + try { + const bool isPool = !m_attributes.getPoolName().empty(); + if (m_cacheImpl->getDistributedSystem() + .getSystemProperties() + .isGridClient()) { + LOGWARN( + "Region: HA region having notification channel created for grid " + "client; force starting required notification, cleanup and " + "failover threads"); + m_cacheImpl->tcrConnectionManager().startFailoverAndCleanupThreads( + isPool); + } + + if (isPool) { + m_tcrdm = dynamic_cast( + m_cacheImpl->getCache() + ->getPoolManager() + .find(m_attributes.getPoolName()) + .get()); + if (m_tcrdm) { + m_poolDM = true; + // Pool DM should only be inited once and it + // is already done in PoolFactory::create(); + // m_tcrdm->init(); + ThinClientPoolHADM* poolDM = dynamic_cast(m_tcrdm); + poolDM->addRegion(this); + poolDM->incRegionCount(); + + } else { + throw IllegalStateException("pool not found"); + } + } else { + m_poolDM = false; + m_tcrdm = new TcrHADistributionManager( + this, m_cacheImpl->tcrConnectionManager(), + m_cacheImpl->getAttributes()); + m_tcrdm->init(); + } + } catch (const Exception& ex) { + _GEODE_SAFE_DELETE(m_tcrdm); + LOGERROR( + "ThinClientHARegion: failed to create a DistributionManager " + "object due to: %s: %s", + ex.getName().c_str(), ex.what()); + throw; + } +} + +void ThinClientHARegion::acquireGlobals(bool isFailover) { + if (isFailover) { + ThinClientRegion::acquireGlobals(isFailover); + } else { + m_tcrdm->acquireRedundancyLock(); + } +} + +void ThinClientHARegion::releaseGlobals(bool isFailover) { + if (isFailover) { + ThinClientRegion::releaseGlobals(isFailover); + } else { + m_tcrdm->releaseRedundancyLock(); + } +} + +void ThinClientHARegion::handleMarker() { + TryReadGuard guard(m_rwLock, m_destroyPending); + if (m_destroyPending) { + return; + } + + if (m_listener != nullptr && !m_processedMarker) { + RegionEvent event(shared_from_this(), nullptr, false); + int64_t sampleStartNanos = startStatOpTime(); + try { + m_listener->afterRegionLive(event); + } catch (const Exception& ex) { + LOGERROR("Exception in CacheListener::afterRegionLive: %s: %s", + ex.getName().c_str(), ex.what()); + } catch (...) { + LOGERROR("Unknown exception in CacheListener::afterRegionLive"); + } + m_cacheImpl->getCachePerfStats().incListenerCalls(); + updateStatOpTime(m_regionStats->getStat(), + m_regionStats->getListenerCallTimeId(), sampleStartNanos); + m_regionStats->incListenerCallsCompleted(); + } + m_processedMarker = true; +} + +bool ThinClientHARegion::getProcessedMarker() { + return m_processedMarker || !isDurableClient(); +} + +void ThinClientHARegion::destroyDM(bool keepEndpoints) { + if (m_poolDM) { + LOGDEBUG( + "ThinClientHARegion::destroyDM( ): removing region from " + "ThinClientPoolHADM list."); + ThinClientPoolHADM* poolDM = dynamic_cast(m_tcrdm); + poolDM->removeRegion(this); + poolDM->decRegionCount(); + } else { + ThinClientRegion::destroyDM(keepEndpoints); + } +} +} // namespace client +} // namespace geode +} // namespace apache + +void ThinClientHARegion::addDisMessToQueue() { + if (m_poolDM) { + ThinClientPoolHADM* poolDM = dynamic_cast(m_tcrdm); + poolDM->addDisMessToQueue(this); + + if (poolDM->m_redundancyManager->m_globalProcessedMarker && + !m_processedMarker) { + TcrMessage* regionMsg = + new TcrMessageClientMarker(m_cacheImpl->createDataOutput(), true); + receiveNotification(regionMsg); + } + } +} + +GfErrType ThinClientHARegion::getNoThrow_FullObject( + std::shared_ptr eventId, std::shared_ptr& fullObject, + std::shared_ptr& versionTag) { + TcrMessageRequestEventValue fullObjectMsg(m_cacheImpl->createDataOutput(), + eventId); + TcrMessageReply reply(true, nullptr); + + ThinClientPoolHADM* poolHADM = dynamic_cast(m_tcrdm); + GfErrType err = GF_NOTCON; + if (poolHADM) { + err = poolHADM->sendRequestToPrimary(fullObjectMsg, reply); + } else { + err = static_cast(m_tcrdm)->sendRequestToPrimary( + fullObjectMsg, reply); + } + if (err == GF_NOERR) { + fullObject = reply.getValue(); + } + versionTag = reply.getVersionTag(); + return err; +} diff --git a/pool/shard011/C++/0121872_placement_pass_base.cc b/pool/shard011/C++/0121872_placement_pass_base.cc new file mode 100644 index 0000000000000000000000000000000000000000..35ba92006077999a541e700c6884db0d32f0bfab --- /dev/null +++ b/pool/shard011/C++/0121872_placement_pass_base.cc @@ -0,0 +1,92 @@ +/* Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. */ + +#include "paddle/fluid/framework/ir/placement_pass_base.h" +#include +#include "paddle/fluid/framework/operator.h" + +namespace paddle { +namespace framework { +namespace ir { + +void PlacementPassBase::ApplyImpl(ir::Graph* graph) const { + VLOG(3) << "Applies " << GetPlacementName() << " placement strategy."; + std::string attr_name = GetAttrName(); + const auto& op_types_list = GetOpTypesList(); + if (!graph->Has(attr_name)) { + graph->Set(attr_name, new bool(true)); + } + for (const Node* n : graph->Nodes()) { + if (n->IsOp()) { + auto* op = n->Op(); + if ((op->HasAttr(attr_name) || op->HasProtoAttr(attr_name)) && + IsSupport(op->Type())) { + if (op_types_list.empty() && IsDefaultOpTypes(op->Type())) { + op->SetAttr(attr_name, true); + } else if (std::find(op_types_list.begin(), op_types_list.end(), + n->Name()) != op_types_list.end()) { + op->SetAttr(attr_name, true); + } + } + } + } +} + +bool PlacementPassBase::IsSupport(const std::string& op_type) const { + if (GetAttrName() == "use_cudnn") { + auto& all_kernels = OperatorWithKernel::AllOpKernels(); + auto it = all_kernels.find(op_type); + if (it == all_kernels.end()) { + // All control operators don't have kernel. + return false; + } + for (auto& kernel_pair : it->second) { + if (platform::is_gpu_place(kernel_pair.first.place_) && + (kernel_pair.first.library_type_ == LibraryType::kCUDNN)) { + return true; + } + } + } else if (GetAttrName() == "use_mkldnn") { + // This ops have use_mkldnn attr, but not support for now. + const std::vector op_types = { + "trilinear_interp", "bicubic_interp", "linear_interp"}; + return std::find(op_types.begin(), op_types.end(), op_type) == + op_types.end(); + } + return false; +} + +bool PlacementPassBase::IsDefaultOpTypes(const std::string& op_type) const { + if (GetAttrName() == "use_cudnn") { + return true; + } else if (GetAttrName() == "use_mkldnn") { + // For interpolate ops, there's a little difference between Paddle and + // MKLDNN. + // If run MKLDNN interpolate ops, manual set AnalysisConfig and apply + // the corresponding pass. + const std::vector not_default_op_types = { + "bilinear_interp", "nearest_interp", "trilinear_interp", + "bicubic_interp", "linear_interp", "bilinear_interp_v2", + "linear_interp_v2"}; + bool is_interpolate_op = + std::find(not_default_op_types.begin(), not_default_op_types.end(), + op_type) != not_default_op_types.end(); + return !is_interpolate_op; + } + return false; +} + +} // namespace ir +} // namespace framework +} // namespace paddle diff --git a/pool/shard011/C++/0121873_MapReactors.cpp b/pool/shard011/C++/0121873_MapReactors.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7c905e7b59cb87312946cac641ea1cea7d746473 --- /dev/null +++ b/pool/shard011/C++/0121873_MapReactors.cpp @@ -0,0 +1,68 @@ +////////////////////////////////////////////////////////////////////////////// +// This file is part of the Journey MMORPG client // +// Copyright © 2015-2016 Daniel Allendorf // +// // +// This program is free software: you can redistribute it and/or modify // +// it under the terms of the GNU Affero General Public License as // +// published by the Free Software Foundation, either version 3 of the // +// License, or (at your option) any later version. // +// // +// This program is distributed in the hope that it will be useful, // +// but WITHOUT ANY WARRANTY; without even the implied warranty of // +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // +// GNU Affero General Public License for more details. // +// // +// You should have received a copy of the GNU Affero General Public License // +// along with this program. If not, see . // +////////////////////////////////////////////////////////////////////////////// +#include "MapReactors.h" + +#include "Reactor.h" + +namespace jrc +{ + void MapReactors::draw(Layer::Id layer, double viewx, double viewy, float alpha) const + { + reactors.draw(layer, viewx, viewy, alpha); + } + + void MapReactors::update(const Physics& physics) + { + for (; !spawns.empty(); spawns.pop()) + { + const ReactorSpawn& spawn = spawns.front(); + + int32_t oid = spawn.get_oid(); + if (auto reactor = reactors.get(oid)) + { + reactor->makeactive(); + } + else + { + reactors.add(spawn.instantiate(physics)); + } + } + + reactors.update(physics); + } + + void MapReactors::spawn(ReactorSpawn&& spawn) + { + spawns.emplace( + std::move(spawn) + ); + } + + void MapReactors::remove(int32_t oid, int8_t state, Point position) + { + if (Optional reactor = reactors.get(oid)) + { + reactor->destroy(state, position); + } + } + + void MapReactors::clear() + { + reactors.clear(); + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0121874_FileSED.cpp b/pool/shard011/C++/0121874_FileSED.cpp new file mode 100644 index 0000000000000000000000000000000000000000..22d77f5b7b11a9efbc4522bfbd8a3fe8e288d9b9 --- /dev/null +++ b/pool/shard011/C++/0121874_FileSED.cpp @@ -0,0 +1,64 @@ +/*////////////////////////////////////////////////////////////////// +//// SKIRT -- an advanced radiative transfer code //// +//// © Astronomical Observatory, Ghent University //// +///////////////////////////////////////////////////////////////// */ + +#include +#include "FilePaths.hpp" +#include "FatalError.hpp" +#include "FileSED.hpp" +#include "Log.hpp" +#include "WavelengthGrid.hpp" + +using namespace std; + +////////////////////////////////////////////////////////////////////// + +FileSED::FileSED() +{ +} + +//////////////////////////////////////////////////////////////////// + +void FileSED::setupSelfBefore() +{ + StellarSED::setupSelfBefore(); + + // read the data from the specified file into local vectors lambdav[k] and jv[k] + QString filename = find()->input(_filename); + ifstream file(filename.toLocal8Bit().constData()); + if (! file.is_open()) throw FATALERROR("Could not open the data file " + filename); + find()->info("Reading SED data from file " + filename + "..."); + + int Nlambda; + file >> Nlambda; + Array lambdav(Nlambda); + Array jv(Nlambda); + double lambda; + for (int k=0; k> lambda >> jv[k]; + lambdav[k] = lambda/1e6; // conversion from micron to m + } + file.close(); + find()->info("File " + filename + " closed."); + + // finish up + setemissivities(lambdav,jv); +} + +//////////////////////////////////////////////////////////////////// + +void FileSED::setFilename(QString value) +{ + _filename = value; +} + +//////////////////////////////////////////////////////////////////// + +QString FileSED::filename() const +{ + return _filename; +} + +////////////////////////////////////////////////////////////////////// diff --git a/pool/shard011/C++/0121876_c_lift_to_rudder_angle.cc b/pool/shard011/C++/0121876_c_lift_to_rudder_angle.cc new file mode 100644 index 0000000000000000000000000000000000000000..fdd8be93e694c4feaa7f342ea6c86b1aa0483c56 --- /dev/null +++ b/pool/shard011/C++/0121876_c_lift_to_rudder_angle.cc @@ -0,0 +1,66 @@ +// Copyright 2011 The Avalon Project Authors. All rights reserved. +// Use of this source code is governed by the Apache License 2.0 +// that can be found in the LICENSE file. +// Steffen Grundmann, June 2011 + + +#include "helmsman/c_lift_to_rudder_angle.h" +#include "helmsman/naca0010.h" +#include "common/sign.h" +#include "common/unknown.h" + +namespace naca0010 { + +namespace { + +double RudderLimit(double speed_m_s) { + // The least restrictive for exceptional situations. + // The only harm it can do is speed loss (which is of no concern because we + // don't know about it because we cannot measure it!). + if (speed_m_s == kUnknown || speed_m_s < 0) + return kAlphaLimit4Rad; + if (speed_m_s < kSpeed0_m_s) { + return kAlphaLimit0Rad; + } else if (speed_m_s < kSpeed1_m_s) { + return kAlphaLimit1Rad; + } else if (speed_m_s < kSpeed2_m_s) { + return kAlphaLimit2Rad; + } else if (speed_m_s < kSpeed3_m_s) { + return kAlphaLimit3Rad; + } else { + return kAlphaLimit4Rad; + } +} + +} // namespace + +} // namespace naca0010 + +// limited is +// -1 for limitation at the lower limit of c_lift +// 0 for the unlimited case +// +1 for a limitation at the positive limit of the c_lift. +void CLiftToRudderAngle(double c_lift, + double speed_m_s, + double* alpha_rad, + int* limited) { + double limit = naca0010::RudderLimit(speed_m_s); + double c_lift_per_rad; + if (speed_m_s != kUnknown && speed_m_s < 0) { + c_lift_per_rad = naca0010::kCLiftPerRadReverse; + } else { + c_lift_per_rad = naca0010::kCLiftPerRad; + } + + double alpha_unlimited = c_lift / c_lift_per_rad * Sign(speed_m_s); + if (alpha_unlimited < -limit) { + *alpha_rad = -limit; + *limited = -Sign(speed_m_s); + } else if (alpha_unlimited > limit) { + *alpha_rad = limit; + *limited = Sign(speed_m_s); + } else { + *alpha_rad = alpha_unlimited; + *limited = 0; + } +} diff --git a/pool/shard011/C++/0121878_cxx_version.cc b/pool/shard011/C++/0121878_cxx_version.cc new file mode 100644 index 0000000000000000000000000000000000000000..d130771f9756a3ad18c0f12bf18cd8d9b954b151 --- /dev/null +++ b/pool/shard011/C++/0121878_cxx_version.cc @@ -0,0 +1,30 @@ +#include +#include + +#include "examples/cgo/cc_dependency/version.h" + +// TODO(yugui) Support Darwin too once Bazel allows it. +// +// Bazel passes two or more -Wl,-rpath to $(CC) when it links a binary with +// shared libraries prebuilt outside of Bazel (i.e. when "srcs" attribute of +// the dependency cc_library contains ".so" files). +// Unfortunately tools/cpp/osx_cc_wrapper.sh, which is $(CC) on Darwin, expects +// only one -Wl,-rpath. So the binary fails to resolve the shared libraries +// at runtime. +#ifndef __APPLE_CC__ +# include "examples/cgo/cc_dependency/c_version.h" +#endif + +extern "C" void PrintCXXVersion() { +#ifndef __APPLE_CC__ + PrintCVersion(); +#endif + void* ptr = dlsym(RTLD_DEFAULT, "PrintCXXVersion"); + if (ptr) { + std::cout + << "function ptr: " << std::hex << ptr << std::dec << std::endl; + } else { + std::cout << dlerror() << std::endl; + } + std::cout << "C++ version: " << __cplusplus << std::endl; +} diff --git a/pool/shard011/C++/0121882_main.cpp b/pool/shard011/C++/0121882_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e2310c42a6855a0cf93dca1d8dce8a80795055d --- /dev/null +++ b/pool/shard011/C++/0121882_main.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +using namespace std; + +int main() +{ + setlocale(LC_ALL, "RUS"); + ifstream file("text.txt", ios::in); + if (!file.is_open()) + { + cout << "not found" << endl; + return 1; + } + + int emptyLines = 0; + while (!file.eof()) + { + string buffer; + getline(file, buffer); + bool isEmpty = true; + for (int i = 0; i < buffer.size(); ++i) + { + if ((buffer[i] == ' ' || buffer[i] == '\t' || buffer[i] == '\n') && isEmpty) + isEmpty = true; + else + isEmpty = false; + } + if (isEmpty) + emptyLines++; + } + file.close(); + cout << emptyLines << endl; + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121886_Show.cpp b/pool/shard011/C++/0121886_Show.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9789306843d96179d0db5c52b1c7db5ac98f5eec --- /dev/null +++ b/pool/shard011/C++/0121886_Show.cpp @@ -0,0 +1,204 @@ +#include +#include +#include +#include +#include +#include "Stage.h" +#include "Avc.h" +#include + +/* The class of the global object. */ +static JSClass global_class = { + "global", JSCLASS_GLOBAL_FLAGS, + JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, + JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, + JSCLASS_NO_OPTIONAL_MEMBERS +}; + +/* The error reporter callback. */ +void reportError(JSContext *cx, const char *message, JSErrorReport *report) { + fprintf(stderr, "%s:%u:%s\n", + report->filename ? report->filename : "", + (unsigned int) report->lineno, message); +} + +JSBool print(JSContext *cx, uintN argc, jsval *vp) { + char *str; + JSString *msg; + + if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "/S", &msg)) + return JS_FALSE; + + /* If called with no arguments, use the current time as the seed. */ + if (argc == 0) + str = ""; + else + str = JS_EncodeString(cx, msg); + + printf("%s", str); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + /* return undefined */ + return JS_TRUE; +} + +JSBool println(JSContext *cx, uintN argc, jsval *vp) { + char *str; + JSString *msg; + + if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "/S", &msg)) + return JS_FALSE; + + /* If called with no arguments, use the current time as the seed. */ + if (argc == 0) + str = ""; + else + str = JS_EncodeString(cx, msg); + + printf("%s\n", str); + + JS_SET_RVAL(cx, vp, JSVAL_VOID); + /* return undefined */ + return JS_TRUE; +} + +/** + * Reads a binary file and returns its content as a JS ArrayBuffer. + */ +JSObject *readFile(JSContext *cx, char *name) { + FILE *file = fopen(name, "rb"); + if (!file) { + fprintf(stderr, "Unable to open file %s\n", name); + return NULL; + } + + fseek(file, 0, SEEK_END); + unsigned long bufferSize = ftell(file) + 1; + fseek(file, 0, SEEK_SET); + + char *buffer = (char *) JS_malloc(cx, bufferSize + sizeof(uint64)); + if (!buffer) { + fprintf(stderr, "Memory error!\n"); + fclose(file); + return NULL; + } + + fread((char *)buffer + sizeof(uint64), bufferSize, 1, file); + ((uint64 *)buffer)[0] = bufferSize; + + fclose(file); + return JS_CreateArrayBuffer(cx, buffer, bufferSize); +} + +JSBool read(JSContext *cx, uintN argc, jsval *vp) { + char *str; + JSString *msg; + + if (!JS_ConvertArguments(cx, argc, JS_ARGV(cx, vp), "S", &msg)) + return JS_FALSE; + str = JS_EncodeString(cx, msg); + + JSObject *buffer = buffer = readFile(cx, str); + + if (buffer != NULL) { + JS_SET_RVAL(cx, vp, OBJECT_TO_JSVAL(buffer)); + } else { + JS_SET_RVAL(cx, vp, JSVAL_VOID); + return JS_FALSE; + } + return JS_TRUE; +} + +static JSFunctionSpec globalFunctions[] = { + JS_FS("print", print, 0, 0), + JS_FS("println", println, 0, 0), + JS_FS("read", read, 1, 0), + JS_FS_END +}; + + + +int SDL_main(int argc, char **argv) { + + bool referenceMode = false; + bool javaScriptMode = false; + char* scripts [32]; + int scriptCount = 0; + char* args; + + int o = 0; + while ((o = getopt (argc, argv, "rjs:a:")) != -1) { + switch (o) { + case 'r': + referenceMode = true; + break; + case 'j': + javaScriptMode = true; + break; + case 's': + scripts[scriptCount++] = optarg; + break; + case 'a': + args = optarg; + break; + case '?': + printf("[-r] [-s FILE] [-a ARGUMENTS]\n"); + break; + } + } + + if (referenceMode) { + Avc avc(args); + avc.Play(); + } else if (javaScriptMode) { + /* JS variables. */ + JSRuntime *rt; + JSContext *cx; + JSObject *global; + + /* Create a JS runtime. */ + rt = JS_NewRuntime(8L * 1024L * 1024L); + if (rt == NULL) + return 1; + + /* Create a context. */ + cx = JS_NewContext(rt, 8192); + if (cx == NULL) + return 1; + JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT); + JS_SetVersion(cx, JSVERSION_LATEST); + JS_SetErrorReporter(cx, reportError); + + /* Create the global object in a new compartment. */ + global = JS_NewCompartmentAndGlobalObject(cx, &global_class, NULL); + if (global == NULL) + return 1; + + /* Populate the global object with the standard globals, + like Object and Array. */ + if (!JS_InitStandardClasses(cx, global)) + return 1; + + if (!JS_DefineFunctions(cx, global, globalFunctions)) + return JS_FALSE; + + for (int i = 0; i < scriptCount; i++) { + JSScript *script = JS_CompileFile(cx, global, scripts[i]); + if (script == NULL) + return 1; + + jsval rval; + JSBool result = JS_ExecuteScript(cx, global, script, &rval); + if (!result) { + printf("Cannot execute script %s", scripts[i]); + } + } + + /* Cleanup. */ + JS_DestroyContext(cx); + JS_DestroyRuntime(rt); + JS_ShutDown(); + } + return 0; +} + diff --git a/pool/shard011/C++/0121887_TestCWIni.cpp b/pool/shard011/C++/0121887_TestCWIni.cpp new file mode 100644 index 0000000000000000000000000000000000000000..588c570ef9514792e057af52f30d575b218400a0 --- /dev/null +++ b/pool/shard011/C++/0121887_TestCWIni.cpp @@ -0,0 +1,76 @@ +#include "stdafx.h" +#include +#include +using namespace std; + +#include "CWTime.h" +#include "CWIni.h" + +#include "_GenerateTmh.h" +#include "TestCWIni.tmh" + +VOID TestIni() +{ + wprintf_s( L"\n========== TestIni() Enter ==========\n" ); + + WCHAR wzPath[MAX_PATH] = { 0 }; + wprintf_s( L"Input ini \"full\" path: " ); + wscanf_s( L"%ws", wzPath, _countof( wzPath ) ); + + list lsNames; + if ( FALSE == CWUtils::GetIniSectionNames( wzPath, lsNames ) ) + { + wprintf_s( L"GetIniSectionNames() failed. GetLastError()=%lu\n", GetLastError() ); + goto exit; + } + + for ( list::iterator itName = lsNames.begin(); itName != lsNames.end(); itName++ ) + { + wprintf_s( L"[%ws]\n", itName->c_str() ); + + map mapKeyVals; + if ( FALSE == CWUtils::GetIniSectionValues( wzPath, itName->c_str(), mapKeyVals ) ) + { + wprintf_s( L"GetIniSectionValues() failed. GetLastError()=%lu\n", GetLastError() ); + } + else + { + for ( map::iterator itKeyVal = mapKeyVals.begin(); itKeyVal != mapKeyVals.end(); + itKeyVal++ ) + { + wprintf_s( L"\t%ws=%ws\n", itKeyVal->first.c_str(), itKeyVal->second.c_str() ); + } + } + } + +exit: + wprintf_s( L"\n========== TestIni() Leave ==========\n" ); +} + + +INT wmain( INT aArgc, WCHAR * aArgv[] ) +{ + WPP_INIT_TRACING( L"TestCWIni" ); + DbgOut( INFO, DBG_TEST, "Enter" ); + for ( int i = 0; i < aArgc; i++ ) + { + wprintf_s( L"aArgv[%d]=%ws\n", i, aArgv[i] ); + } + wprintf_s( L"Start\n" ); + + CWUtils::CStopWatch stopWatch; + stopWatch.Start(); + + do + { + TestIni(); + } while ( 0 ); + + stopWatch.Stop(); + wprintf_s( L"%I64u micro-sec\n", stopWatch.GetTotalIntervalInMicro() ); + wprintf_s( L"End of the program\n" ); + DbgOut( INFO, DBG_TEST, "Leave" ); + WPP_CLEANUP(); + system( "pause" ); + return 0; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121889_gaussianSmoothing.cpp b/pool/shard011/C++/0121889_gaussianSmoothing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1311ded74df222240ce9cc7d1f6679011b54e90c --- /dev/null +++ b/pool/shard011/C++/0121889_gaussianSmoothing.cpp @@ -0,0 +1,28 @@ +/** + * @example gaussianSmoothing.cpp + */ +#include "FAST/Importers/ImageFileImporter.hpp" +#include "FAST/Algorithms/GaussianSmoothing/GaussianSmoothing.hpp" +#include "FAST/Visualization/ImageRenderer/ImageRenderer.hpp" +#include "FAST/Visualization/SimpleWindow.hpp" + + +using namespace fast; + +int main() { + // Import image from file using the ImageFileImporter + auto importer = ImageFileImporter::create(Config::getTestDataPath()+"/US/US-2D.jpg"); + + // Smooth image + auto filter = GaussianSmoothing::create(2.0, 7)->connect(importer); + + // Renderer image + auto renderer = ImageRenderer::create()->connect(filter); + + auto window = SimpleWindow2D::create()->connect(renderer); +#ifdef FAST_CONTINUOUS_INTEGRATION + // This will automatically close the window after 5 seconds, used for CI testing + window->setTimeout(5*1000); +#endif + window->run(); +} diff --git a/pool/shard011/C++/0121891_ChFilterVisualize.cpp b/pool/shard011/C++/0121891_ChFilterVisualize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e7cf60cabcca8209e2b0e0753d24d786da4aee8 --- /dev/null +++ b/pool/shard011/C++/0121891_ChFilterVisualize.cpp @@ -0,0 +1,243 @@ +// ============================================================================= +// PROJECT CHRONO - http://projectchrono.org +// +// Copyright (c) 2019 projectchrono.org +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be found +// in the LICENSE file at the top level of the distribution and at +// http://projectchrono.org/license-chrono.txt. +// +// ============================================================================= +// Authors: Eric Brandt, Asher Elmquist +// ============================================================================= +// +// ============================================================================= + +#include "chrono_sensor/filters/ChFilterVisualize.h" +#include "chrono_sensor/sensors/ChOptixSensor.h" +#include "chrono_sensor/utils/CudaMallocHelper.h" + +#include + +namespace chrono { +namespace sensor { + +int ChFilterVisualize::s_windowCount = 0; +std::mutex ChFilterVisualize::s_glfwMutex; + +CH_SENSOR_API ChFilterVisualize::ChFilterVisualize(int w, int h, std::string name, bool fullscreen) + : m_w(w), m_h(h), m_fullscreen(fullscreen), ChFilter(name) {} + +CH_SENSOR_API ChFilterVisualize::~ChFilterVisualize() { + ChFilterVisualize::OnCloseWindow(); +} + +CH_SENSOR_API void ChFilterVisualize::Apply() { + if (!m_window && !m_window_disabled) { + CreateGlfwWindow(Name()); + } + if (m_window) { + // std::chrono::high_resolution_clock::time_point t1 = std::chrono::high_resolution_clock::now(); + // do all memcpy + cudaStreamSynchronize(m_cuda_stream); + if (m_bufferR8) { + cudaMemcpyAsync(m_hostR8->Buffer.get(), m_bufferR8->Buffer.get(), + m_bufferR8->Width * m_bufferR8->Height * sizeof(char), cudaMemcpyDeviceToHost, + m_cuda_stream); + } else if (m_bufferRGBA8) { + cudaMemcpyAsync(m_hostRGBA8->Buffer.get(), m_bufferRGBA8->Buffer.get(), + m_hostRGBA8->Width * m_hostRGBA8->Height * sizeof(PixelRGBA8), cudaMemcpyDeviceToHost, + m_cuda_stream); + } else if (m_bufferSemantic) { + cudaMemcpyAsync(m_hostSemantic->Buffer.get(), m_bufferSemantic->Buffer.get(), + m_hostSemantic->Width * m_hostSemantic->Height * sizeof(PixelSemantic), + cudaMemcpyDeviceToHost, m_cuda_stream); + } else if (m_bufferDI) { + cudaMemcpyAsync(m_hostDI->Buffer.get(), m_bufferDI->Buffer.get(), + m_hostDI->Width * m_hostDI->Height * sizeof(PixelDI), cudaMemcpyDeviceToHost, + m_cuda_stream); + } else if (m_bufferRadar) { + cudaMemcpyAsync(m_hostRadar->Buffer.get(), m_bufferRadar->Buffer.get(), + m_hostRadar->Width * m_hostRadar->Height * sizeof(RadarReturn), cudaMemcpyDeviceToHost, + m_cuda_stream); + } else { + throw std::runtime_error("No buffer incoming for visualization"); + } + + // lock the glfw mutex because from here on out, we don't want to be interrupted + std::lock_guard lck(s_glfwMutex); + + // do window prep stuff + glfwMakeContextCurrent(m_window.get()); + if (!m_gl_tex_id) { + glGenTextures(1, &m_gl_tex_id); + glBindTexture(GL_TEXTURE_2D, m_gl_tex_id); + + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + + // GL_CLAMP_TO_EDGE for linear filtering, not relevant for nearest. + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + glBindTexture(GL_TEXTURE_2D, m_gl_tex_id); + + // Set Viewport to window dimensions + int window_w, window_h; + glfwGetWindowSize(m_window.get(), &window_w, &window_h); + glViewport(0, 0, window_w, window_h); + + // update the textures, making sure data has finished memcpy first + cudaStreamSynchronize(m_cuda_stream); + if (m_bufferR8) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, m_hostR8->Width, m_hostR8->Height, 0, GL_RED, GL_UNSIGNED_BYTE, + m_hostR8->Buffer.get()); + } else if (m_bufferRGBA8) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_hostRGBA8->Width, m_hostRGBA8->Height, 0, GL_RGBA, + GL_UNSIGNED_BYTE, m_hostRGBA8->Buffer.get()); + } else if (m_bufferSemantic) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RG16, m_hostSemantic->Width, m_hostSemantic->Height, 0, GL_RG, + GL_UNSIGNED_SHORT, m_hostSemantic->Buffer.get()); + } else if (m_bufferDI) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, m_hostDI->Width, m_hostDI->Height, 0, GL_RG, GL_FLOAT, + m_hostDI->Buffer.get()); + } else if (m_bufferRadar) { + glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, m_hostRadar->Width, m_hostRadar->Height, 0, GL_RG, GL_FLOAT, + m_hostRadar->Buffer.get()); + } else { + throw std::runtime_error("No buffer incoming for visualization"); + } + + // update the window + + // 1:1 texel to pixel mapping with glOrtho(0, 1, 0, 1, -1, 1) setup: + // The quad coordinates go from lower left corner of the lower left pixel + // to the upper right corner of the upper right pixel. + // Same for the texel coordinates. + + glEnable(GL_TEXTURE_2D); + glBegin(GL_QUADS); + glTexCoord2f(0.0f, 0.0f); + glVertex2f(0.0f, 0.0f); + glTexCoord2f(1.0f, 0.0f); + glVertex2f(1.0f, 0.0f); + glTexCoord2f(1.0f, 1.0f); + glVertex2f(1.0f, 1.0f); + glTexCoord2f(0.0f, 1.0f); + glVertex2f(0.0f, 1.0f); + glEnd(); + glDisable(GL_TEXTURE_2D); + + glfwSwapBuffers(m_window.get()); + glfwPollEvents(); + // std::chrono::high_resolution_clock::time_point t2 = std::chrono::high_resolution_clock::now(); + // std::chrono::duration wall_time = std::chrono::duration_cast>(t2 - t1); + // std::cout << "Render to window time: " << wall_time.count() << std::endl; + } +} +CH_SENSOR_API void ChFilterVisualize::Initialize(std::shared_ptr pSensor, + std::shared_ptr& bufferInOut) { + if (!bufferInOut) + InvalidFilterGraphNullBuffer(pSensor); + + auto pOptixSen = std::dynamic_pointer_cast(pSensor); + if (!pOptixSen) { + InvalidFilterGraphSensorTypeMismatch(pSensor); + } + m_cuda_stream = pOptixSen->GetCudaStream(); + m_bufferR8 = std::dynamic_pointer_cast(bufferInOut); + m_bufferRGBA8 = std::dynamic_pointer_cast(bufferInOut); + m_bufferSemantic = std::dynamic_pointer_cast(bufferInOut); + m_bufferDI = std::dynamic_pointer_cast(bufferInOut); + m_bufferRadar = std::dynamic_pointer_cast(bufferInOut); + + if (m_bufferR8) { + m_hostR8 = chrono_types::make_shared(); + std::shared_ptr b(cudaHostMallocHelper(m_bufferR8->Width * m_bufferR8->Height), + cudaHostFreeHelper); + m_hostR8->Buffer = std::move(b); + m_hostR8->Width = m_bufferR8->Width; + m_hostR8->Height = m_bufferR8->Height; + + } else if (m_bufferRGBA8) { + m_hostRGBA8 = chrono_types::make_shared(); + std::shared_ptr b(cudaHostMallocHelper(m_bufferRGBA8->Width * m_bufferRGBA8->Height), + cudaHostFreeHelper); + m_hostRGBA8->Buffer = std::move(b); + m_hostRGBA8->Width = m_bufferRGBA8->Width; + m_hostRGBA8->Height = m_bufferRGBA8->Height; + } else if (m_bufferSemantic) { + m_hostSemantic = chrono_types::make_shared(); + std::shared_ptr b( + cudaHostMallocHelper(m_bufferSemantic->Width * m_bufferSemantic->Height), + cudaHostFreeHelper); + m_hostSemantic->Buffer = std::move(b); + m_hostSemantic->Width = m_bufferSemantic->Width; + m_hostSemantic->Height = m_bufferSemantic->Height; + } else if (m_bufferDI) { + m_hostDI = chrono_types::make_shared(); + std::shared_ptr b(cudaHostMallocHelper(m_bufferDI->Width * m_bufferDI->Height), + cudaHostFreeHelper); + m_hostDI->Buffer = std::move(b); + m_hostDI->Width = m_bufferDI->Width; + m_hostDI->Height = m_bufferDI->Height; + } else if (m_bufferRadar) { + m_hostRadar = chrono_types::make_shared(); + std::shared_ptr b( + cudaHostMallocHelper(m_bufferRadar->Width * m_bufferRadar->Height), + cudaHostFreeHelper); + m_hostRadar->Buffer = std::move(b); + m_hostRadar->Width = m_bufferRadar->Width; + m_hostRadar->Height = m_bufferRadar->Height; + } else { + InvalidFilterGraphBufferTypeMismatch(pSensor); + } +} + +CH_SENSOR_API void ChFilterVisualize::CreateGlfwWindow(std::string window_name) { + // if we've already made the window, there's nothing to do. + if (m_window) + return; + + OnNewWindow(); // OnNewWindow will need to lock inside itself + + std::lock_guard lck(s_glfwMutex); + if (m_fullscreen) + m_window.reset(glfwCreateWindow(static_cast(m_w), static_cast(m_h), window_name.c_str(), + glfwGetPrimaryMonitor(), NULL)); + else + m_window.reset( + glfwCreateWindow(static_cast(m_w), static_cast(m_h), window_name.c_str(), NULL, NULL)); + if (m_window) { + glfwMakeContextCurrent(m_window.get()); + glfwSwapInterval(0); // disable vsync as we are "fast as possible" + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, 1, 0, 1, -1, 1); + + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glViewport(0, 0, m_w, m_h); + } else { + std::cerr << "WARNING: requested window could not be created by GLFW. Will proceed with no window.\n"; + m_window_disabled = true; + } +} + +CH_SENSOR_API void ChFilterVisualize::OnNewWindow() { + std::lock_guard l(s_glfwMutex); + if (s_windowCount++ == 0) { + glfwInit(); + } +} +CH_SENSOR_API void ChFilterVisualize::OnCloseWindow() { + std::lock_guard l(s_glfwMutex); + if (--s_windowCount == 0) { + glfwTerminate(); + } +} + +} // namespace sensor +} // namespace chrono diff --git a/pool/shard011/C++/0121892_Aimbot.cpp b/pool/shard011/C++/0121892_Aimbot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05e3beff633e479d8568a7a489762ecb84183c25 --- /dev/null +++ b/pool/shard011/C++/0121892_Aimbot.cpp @@ -0,0 +1,168 @@ +#include "Aimbot.h" +#include "TF2Entity.h" +#include "TraceHelper.h" +#include "AimAndMovementHelper.h" + +using namespace Skim; +using namespace AimAndMovementHelper; + +CAimbot *g_pAimbot; +int CAimbot::m_iIndexAimed; + +void AltKnifeAim(CUserCmd* pCmd, TF2Player* prey) +{ + //if we are behind, offset = 0 + //if we are in front, offset = 60 or something + AimAndMovementHelper::AimAt(prey, pCmd, HITBOX_SPINE_3, false); + + bool aimLeft = true; + float aimDiff = AimAndMovementHelper::AngleDifference(prey->angEyeAngles().y, pCmd->viewangles.y); + if (aimDiff < 0.0f){ + aimDiff *= -1.0f; + aimLeft = false; + } + + //Nice smooth aim + //static ConVar* multout = 0; + //if (!multout) multout = new ConVar( PREFIX "dev_aim_multout", "6" ); + //static ConVar* multin = 0; + //if (!multin) multin = new ConVar( PREFIX "dev_aim_multin", "6" ); + //static ConVar* multpow = 0; + //if (!multpow) multpow = new ConVar( PREFIX "dev_aim_multpow", "0.25" ); + + //large offset while in front and side, smaller only when in facing back + //**game goes crazy and freezes (but not crashes which makes it weird) if offset is messed up, probably + // because it is too small and becomes NAN when directly behind + //**could crash servers by sending messed up viewangles? + //found through testing that: + //the power is best at .5, + //the multiplier inside is best at .25, + //the multiplier outside is best at 13 + float offset = FastSqrt(aimDiff * 0.25f) * 13.0f; + + //static ConVar* maxDist = 0; + //if (!maxDist) + // maxDist = new ConVar( PREFIX "dev_aim_stabdist", "80"); + //static ConVar* maxAngle = 0; + //if (!maxAngle) + // maxAngle = new ConVar( PREFIX "dev_aim_stabangle", "40"); + + float dist = TF2Entity::DistanceFromMe(prey); + + if (offset < 40.0f && dist < 80.0f) + pCmd->buttons |= IN_ATTACK; + if (_isnan(offset)) { //the offset is very small and errored up, means I am definitely behind them... + if (dist < 80.0f) + pCmd->buttons |= IN_ATTACK; + return; + } + + float yAngle = atan2(offset,dist) * 180.0f / M_PI; + if (aimLeft) + pCmd->viewangles.y -= yAngle; + else + pCmd->viewangles.y += yAngle; + + ValveInterfaces::pEngine->SetViewAngles(pCmd->viewangles); +} + +void CAimbot::Run(CUserCmd* pcmd) +{ + m_iIndexAimed = -1; + //check if we're running + if (!(m_bRunning || m_pAutoshoot->GetBool() || ((m_pRunAttack->GetBool()) && (pcmd->buttons & IN_ATTACK)))) + return; + + float smallestdist = 8192.0f;//max trace distance, we cannot hit players if they're farther than this ;[ + TF2Player* closestplayer = 0; + int maxClients = Skim::ValveInterfaces::pEngine->GetMaxClients() + 1; + for(int i = 0; i < maxClients; i++) + { + // If we're in spy knife mode, then we want to make sure enemies are not above or below us + // TODO: add priorities to enemies + // e.g. medics are higher, people far away with melee weapons are lower, spies close to us are maximum + TF2Player *plyr = TF2Entity::GetPlayer(i); + float dist = TF2Entity::DistanceFromMe( plyr ); + //check for dormancy because we won't be able to see it + if ( plyr && !plyr->isDormant() && plyr->isValid() && ( ! m_pAltKnifeAim->GetBool() || abs(plyr->vecOrigin().z - TF2Entity::Me()->vecOrigin().z) < 100) ) + { + if ( plyr->iTeamNum() != TF2Entity::Me()->iTeamNum() && dist < smallestdist && TraceHelper::CanSee(TF2Entity::Me(), plyr)){ + smallestdist = dist; + closestplayer = plyr; + } + } + } + + if (closestplayer) + { + //int i = pcmd->weaponsubtype; + //bool knifeOut = (i == 2 && TF2Entity::Me()->playerClass() == Spy); + bool knifeMode = m_pAltKnifeAim->GetBool();//knifeOut && m_pAltKnifeAim->GetBool(); + + m_iIndexAimed = closestplayer->index(); + // to be not silent, cannot have silent aim but can if we have altknifeaim + // to be silent, must have silent on and altknifeaim off + bool silent = m_pSilentAim->GetBool() && !knifeMode; + + if(knifeMode) + { + AltKnifeAim(pcmd, closestplayer); + } + else //not in knife aim mode + { + int hitbox = 0; + switch (m_pAimBodypart->GetInt()) { + case 1: + hitbox = ::HITBOX_SPINE_2; + break; + case 2: + hitbox = ::HITBOX_PELVIS; + break; + case 3: + hitbox = HITBOX_ORIGIN; + default: + break; + } + AimAndMovementHelper::AimAt(closestplayer, pcmd, hitbox, silent); + } + + if(!silent) + pEngine->SetViewAngles(pcmd->viewangles); + if (m_pAttackAimed->GetBool() && !(knifeMode)) + pcmd->buttons |= IN_ATTACK; + } +} + +void StartAim() { + g_pAimbot->m_bRunning = true; +} +void EndAim() { + g_pAimbot->m_bRunning = false; +} + +CAimbot::CAimbot() +{ + m_pRunAttack = new ConVar(PREFIX "aim_runonattack", "0", 0, "Runs automatically when you fire"); + m_pRunAttack2 = new ConVar(PREFIX "aim_rononattack2", "0"); + m_pSilentAim = new ConVar(PREFIX "aim_silentaim", "0", 0); + m_pAltKnifeAim = new ConVar(PREFIX "aim_knifer", "0"); + m_pAutoshoot = new ConVar(PREFIX "aim_auto", "0"); + m_pEspAimed = new ConVar(PREFIX "esp_showaimbotted", "1"); + m_pAimBodypart = new ConVar(PREFIX "aim_bodypart", "0", 0, "0 = head; 1 = chest; 2 = pelvis; 3 = feet"); + m_pAttackAimed = new ConVar(PREFIX "aim_attackaimed", "1"); + m_pStartAim = new ConCommand("+" PREFIX "aim", StartAim, "Start autoaiming", 0); + m_pEndAim = new ConCommand("-" PREFIX "aim", EndAim, "Stop autoaiming", 0); + m_bRunning = false; + g_pAimbot = this; +} +CAimbot::~CAimbot(){ + FreeConCMD(m_pRunAttack); + FreeConCMD(m_pSilentAim); + FreeConCMD(m_pAltKnifeAim); + FreeConCMD(m_pAutoshoot); + FreeConCMD(m_pEspAimed); + FreeConCMD(m_pAimBodypart); + FreeConCMD(m_pAttackAimed); + FreeConCMD(m_pStartAim); + FreeConCMD(m_pEndAim); +} \ No newline at end of file diff --git a/pool/shard011/C++/0121894_WorldRunnable.cpp b/pool/shard011/C++/0121894_WorldRunnable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6ac80062abe5815725f294275a831e1347ca8a34 --- /dev/null +++ b/pool/shard011/C++/0121894_WorldRunnable.cpp @@ -0,0 +1,84 @@ +/* + * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/** \file + \ingroup mangosd +*/ + +#include "Common.h" +#include "World.h" +#include "WorldRunnable.h" +#include "Timer.h" +#include "ObjectAccessor.h" +#include "MapManager.h" + +#include "Database/DatabaseEnv.h" + +#define WORLD_SLEEP_CONST 50 + +#ifdef WIN32 +#include "ServiceWin32.h" +extern int m_ServiceStatus; +#endif + +/// Heartbeat for the World +void WorldRunnable::run() +{ + ///- Init new SQL thread for the world database + WorldDatabase.ThreadStart(); // let thread do safe mySQL requests (one connection call enough) + sWorld.InitResultQueue(); + + uint32 realCurrTime = 0; + uint32 realPrevTime = WorldTimer::tick(); + + uint32 prevSleepTime = 0; // used for balanced full tick time length near WORLD_SLEEP_CONST + + ///- While we have not World::m_stopEvent, update the world + while (!World::IsStopped()) + { + ++World::m_worldLoopCounter; + realCurrTime = WorldTimer::getMSTime(); + + uint32 diff = WorldTimer::tick(); + + sWorld.Update(diff); + realPrevTime = realCurrTime; + + // diff (D0) include time of previous sleep (d0) + tick time (t0) + // we want that next d1 + t1 == WORLD_SLEEP_CONST + // we can't know next t1 and then can use (t0 + d1) == WORLD_SLEEP_CONST requirement + // d1 = WORLD_SLEEP_CONST - t0 = WORLD_SLEEP_CONST - (D0 - d0) = WORLD_SLEEP_CONST + d0 - D0 + if (diff <= WORLD_SLEEP_CONST + prevSleepTime) + { + prevSleepTime = WORLD_SLEEP_CONST + prevSleepTime - diff; + MaNGOS::Thread::Sleep(prevSleepTime); + } + else + prevSleepTime = 0; + +#ifdef WIN32 + if (m_ServiceStatus == 0) World::StopNow(SHUTDOWN_EXIT_CODE); + while (m_ServiceStatus == 2) Sleep(1000); +#endif + } + + sWorld.CleanupsBeforeStop(); + + ///- End the database thread + WorldDatabase.ThreadEnd(); // free mySQL thread resources +} diff --git a/pool/shard011/C++/0121895_coordinates.cpp b/pool/shard011/C++/0121895_coordinates.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dd24f755f2cd256c797b78e9a152232f3e2db63 --- /dev/null +++ b/pool/shard011/C++/0121895_coordinates.cpp @@ -0,0 +1,88 @@ +# +/* + * Copyright (C) 2013, 2014, 2015, 2016, 2017 + * Jan van Katwijk (J.vanKatwijk@gmail.com) + * Lazy Chair Computing + * + * This file is part of the Qt-DAB (formerly SDR-J, JSDR). + * + * Qt-DAB 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. + * + * Qt-DAB 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 Qt-DAB; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#include "coordinates.h" +#include +#include +#include +#include +#include + + coordinates::coordinates (QSettings *dabSettings) { + this -> dabSettings = dabSettings; + latitudeText = new QLabel (this); + latitudeText -> setText ("latitude (decimal)"); + QDoubleValidator *la = new QDoubleValidator (-90.0, 9.0, 5); + latitude = new QLineEdit (this); + latitude -> setValidator (la); + longitudeText = new QLabel (this); + longitudeText -> setText ("longitude (decimal)"); + QDoubleValidator *lo = new QDoubleValidator (-180.0, 180.0, 5); + longitude = new QLineEdit (this); + longitude -> setValidator (lo); + QFormLayout *layout = new QFormLayout; + layout -> addWidget (latitudeText); + layout -> addWidget (latitude); + layout -> addWidget (longitudeText); + layout -> addWidget (longitude); + setWindowTitle ("select coordinates"); + acceptButton = new QPushButton ("accept"); + QVBoxLayout *total = new QVBoxLayout; + total -> addItem (layout); + total -> addWidget (acceptButton); + setLayout (total); + connect (latitude, SIGNAL (returnPressed ()), + this, SLOT (set_latitude ())); + connect (longitude, SIGNAL (returnPressed ()), + this, SLOT (set_longitude ())); + connect (acceptButton, SIGNAL (clicked ()), + this, SLOT (handle_acceptButton ())); + show (); + latitudeValue = false; + longitudeValue = false; +} + + coordinates::~coordinates () { + hide (); + delete acceptButton; + delete latitudeText; + delete longitudeText; + delete latitude; + delete longitude; +} + +void coordinates::set_latitude () { + latitudeValue = true; +} + +void coordinates::set_longitude () { + longitudeValue = true; +} + +void coordinates::handle_acceptButton () { + if (!latitude || !longitude) + return; + dabSettings -> setValue ("latitude", latitude -> text ()); + dabSettings -> setValue ("longitude", longitude -> text ()); + QDialog::done (0); +} + diff --git a/pool/shard011/C++/0121897_naive_greedy_hit_resolver.cpp b/pool/shard011/C++/0121897_naive_greedy_hit_resolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fba0d8b0f711540d65b8eb54d91e8a6d7dba57c6 --- /dev/null +++ b/pool/shard011/C++/0121897_naive_greedy_hit_resolver.cpp @@ -0,0 +1,55 @@ +/// \file +/// \brief The naive_greedy_hit_resolver class definitions + +/// \copyright +/// CATH Tools - Protein structure comparison tools such as SSAP and SNAP +/// Copyright (C) 2011, Orengo Group, University College London +/// +/// This program is free software: you can redistribute it and/or modify +/// it under the terms of the GNU General Public License as published by +/// the Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// This program is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/// GNU General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License +/// along with this program. If not, see . + +#include "naive_greedy_hit_resolver.hpp" + +#include "cath/common/algorithm/sort_uniq_build.hpp" +#include "cath/common/boost_addenda/range/indices.hpp" +#include "cath/common/exception/invalid_argument_exception.hpp" +#include "cath/resolve_hits/algo/scored_arch_proxy_fn.hpp" +#include "cath/resolve_hits/scored_hit_arch.hpp" + +using namespace ::cath::common; +using namespace ::cath::rslv; +using namespace ::cath::rslv::detail; + +/// \brief Naively, greedily resolve hits +scored_hit_arch cath::rslv::naive_greedy_resolve_hits(const calc_hit_list &prm_hits ///< The hits to resolve + ) { + scored_arch_proxy results; + + // Get a vector of the indices of the hits in descending order of score + const auto hit_indices_best_to_worst = sort_build( + indices( prm_hits.size() ), + [&] (const hitidx_t &x, const hitidx_t &y) { + return ( prm_hits[ y ].get_score() < prm_hits[ x ].get_score() ); + } + ); + + // Work through the hit indices and add any that don't clash with those already added + for (const hitidx_t &hit_index : hit_indices_best_to_worst) { + const calc_hit &the_hit = prm_hits[ hit_index ]; + const resscr_t &score = the_hit.get_score(); + add_hit_if_does_not_overlap( results, score, hit_index, prm_hits ); + } + + // Build a scored_hit_arch of the results + return make_scored_hit_arch( results, prm_hits ); +} diff --git a/pool/shard011/C++/0121898_2.cc b/pool/shard011/C++/0121898_2.cc new file mode 100644 index 0000000000000000000000000000000000000000..26f3e1408e12562e5309f4a75f5e8b08622f0223 --- /dev/null +++ b/pool/shard011/C++/0121898_2.cc @@ -0,0 +1,81 @@ +// Copyright (C) 2006-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +// 25.2.8 [lib.alg.unique] + +#include +#include +#include +#include + +using __gnu_test::test_container; +using __gnu_test::forward_iterator_wrapper; +using __gnu_test::output_iterator_wrapper; +using std::unique_copy; +using std::equal_to; + +typedef test_container Fcontainer; +typedef test_container Ocontainer; + +int array1[] = {0, 0, 0, 1, 1, 1}; +int array2[2]; + +void +test1() +{ + Fcontainer con1(array1, array1); + Ocontainer con2(array2, array2); + VERIFY( unique_copy(con1.begin(), con1.end(), con2.begin()).ptr == array2 ); +} + +void +test2() +{ + Fcontainer con1(array1, array1 + 6); + Ocontainer con2(array2, array2 + 2); + VERIFY( unique_copy(con1.begin(), con1.end(), con2.begin()).ptr + == array2 + 2 ); + VERIFY( array2[0] == 0 && array2[1] == 1 ); +} + +void +test3() +{ + Fcontainer con1(array1, array1); + Ocontainer con2(array2, array2); + VERIFY( unique_copy(con1.begin(), con1.end(), con2.begin(), + equal_to()).ptr == array2 ); +} + +void +test4() +{ + Fcontainer con1(array1, array1 + 6); + Ocontainer con2(array2, array2 + 2); + VERIFY( unique_copy(con1.begin(), con1.end(), con2.begin(), + equal_to()).ptr == array2 + 2 ); + VERIFY( array2[0] == 0 && array2[1] == 1 ); +} + +int +main() +{ + test1(); + test2(); + test3(); + test4(); +} diff --git a/pool/shard011/C++/0121900_test.cpp b/pool/shard011/C++/0121900_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed47da738982c5ec2c478468aab0ef5feb1ad4e4 --- /dev/null +++ b/pool/shard011/C++/0121900_test.cpp @@ -0,0 +1,201 @@ +/* +---------------------------------------------------------------------------+ + | The Mobile Robot Programming Toolkit (MRPT) | + | | + | http://www.mrpt.org/ | + | | + | Copyright (c) 2005-2013, Individual contributors, see AUTHORS file | + | Copyright (c) 2005-2013, MAPIR group, University of Malaga | + | Copyright (c) 2012-2013, University of Almeria | + | All rights reserved. | + | | + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the following conditions are | + | met: | + | * Redistributions of source code must retain the above copyright | + | notice, this list of conditions and the following disclaimer. | + | * Redistributions in binary form must reproduce the above copyright | + | notice, this list of conditions and the following disclaimer in the | + | documentation and/or other materials provided with the distribution. | + | * Neither the name of the copyright holders nor the | + | names of its contributors may be used to endorse or promote products | + | derived from this software without specific prior written permission.| + | | + | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | + | 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED | + | TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR| + | PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE | + | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL| + | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR| + | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) | + | HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, | + | STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN | + | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE | + | POSSIBILITY OF SUCH DAMAGE. | + +---------------------------------------------------------------------------+ */ + +#include +#include +#include +#include + +using namespace mrpt; +using namespace mrpt::hwdrivers; +using namespace mrpt::slam; +using namespace mrpt::gui; +using namespace mrpt::utils; +using namespace std; + + +string SERIAL_NAME; // Name of the serial port to open + +// ------------------------------------------------------ +// Test_HOKUYO +// ------------------------------------------------------ +void Test_HOKUYO() +{ + CHokuyoURG laser; + + string serName, type; + + string ip; + + unsigned int port; + + cout << "Specify the type of the Hokuyo connection, usb or ethernet: "; + getline(cin,type); + + while ( (lowerCase(type) != "usb" ) && ( lowerCase(type) != "ethernet" ) ) + { + cout << "Incorrect type" << endl; + cout << "Specify the type of the Hokuyo connection, usb or ethernet: "; + getline(cin,type); + } + + cout << endl << endl << "HOKUYO laser range finder test application." << endl << endl; + + if ( lowerCase(type) == "usb" ) + { + if (SERIAL_NAME.empty()) + { + cout << "Enter the serial port name (e.g. COM1, ttyS0, ttyUSB0, ttyACM0): "; + getline(cin,serName); + } + else + { + cout << "Using serial port: " << SERIAL_NAME << endl; + serName = SERIAL_NAME; + } + + // Set the laser serial port: + laser.setSerialPort( serName ); + + } + else + { + cout << "Enter the ip direction: "; + getline(cin,ip); + + cout << "Enter the port number: "; + cin >> port; + + // Set the laser serial port: + laser.setIPandPort( ip, port ); + + } + + // Config: Use defaults + selected port ( serial or ethernet ) + + printf("[TEST] Turning laser ON...\n"); + if (laser.turnOn()) + printf("[TEST] Initialization OK!\n"); + else + { + printf("[TEST] Initialization failed!\n"); + return; + } + +#if MRPT_HAS_WXWIDGETS + CDisplayWindowPlots win("Laser scans"); +#endif + + cout << "Press any key to stop capturing..." << endl; + + CTicTac tictac; + tictac.Tic(); + + while (!mrpt::system::os::kbhit()) + { + bool thereIsObservation,hardError; + CObservation2DRangeScan obs; + + laser.doProcessSimple( thereIsObservation, obs, hardError ); + + if (hardError) + printf("[TEST] Hardware error=true!!\n"); + + if (thereIsObservation) + { + double FPS = 1.0 / tictac.Tac(); + + + printf("Scan received: %u ranges, FOV: %.02fdeg, %.03fHz: mid rang=%fm\n", + (unsigned int)obs.scan.size(), + RAD2DEG(obs.aperture), + FPS, + obs.scan[obs.scan.size()/2]); + + obs.sensorPose = CPose3D(0,0,0); + + mrpt::slam::CSimplePointsMap theMap; + theMap.insertionOptions.minDistBetweenLaserPoints = 0; + theMap.insertObservation( &obs ); + //map.save2D_to_text_file("_out_scan.txt"); + + /* + COpenGLScene scene3D; + opengl::CPointCloudPtr points = opengl::CPointCloud::Create(); + points->loadFromPointsMap(&map); + scene3D.insert(points); + CFileStream("_out_point_cloud.3Dscene",fomWrite) << scene3D; + */ + +#if MRPT_HAS_WXWIDGETS + vector_float xs,ys,zs; + theMap.getAllPoints(xs,ys,zs); + win.plot(xs,ys,".b3"); + win.axis_equal(); +#endif + + tictac.Tic(); + } + + mrpt::system::sleep(15); + }; + + laser.turnOff(); +} + +int main(int argc, char **argv) +{ + try + { + if (argc>1) + { + SERIAL_NAME = string(argv[1]); + } + + Test_HOKUYO(); + return 0; + + } catch (std::exception &e) + { + std::cout << "EXCEPCION: " << e.what() << std::endl; + return -1; + } + catch (...) + { + printf("Another exception!!"); + return -1; + } + +} diff --git a/pool/shard011/C++/0121901_HelloTextures.cpp b/pool/shard011/C++/0121901_HelloTextures.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6aa511187da7bf49c6737b488d5a8b92c1861334 --- /dev/null +++ b/pool/shard011/C++/0121901_HelloTextures.cpp @@ -0,0 +1,204 @@ +// GLEW +#define GLEW_STATIC +#include + +// GLFW +#include + +// SOIL +#include + +#include "../include/Shader.hpp" + +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); + +const int WIDTH = 800; +const int HEIGHT = 600; +Shader *shaderProgram; +GLfloat mixture = 0.2; + + +int main(void) +{ + + glfwInit(); + glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); + glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); + glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); + glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); + + GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr); + glfwMakeContextCurrent(window); + + glewExperimental = GL_TRUE; + glewInit(); + + glViewport(0, 0, WIDTH, HEIGHT); + glfwSetKeyCallback(window, key_callback); + + shaderProgram = new Shader("shaders/HelloTextures.vs", "shaders/HelloTextures.frag"); + + GLfloat vertices[] = { + // Positions // Colors // Texture Coords + 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, // Top Right + 0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, // Bottom Right + -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left + -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f // Top Left + }; + + GLuint indices[] = { // Note that we start from 0! + 0, 1, 3, // First Triangle + 1, 2, 3 // Second Triangle + }; + + // referances to array object and buffer object + GLuint VAO; + GLuint VBO; + GLuint EBO; + + glGenVertexArrays(1, &VAO); + glGenBuffers(1, &VBO); + glGenBuffers(1, &EBO); + + // bind the array object + glBindVertexArray(VAO); + + // bind the buffer objects + glBindBuffer(GL_ARRAY_BUFFER, VBO); + glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); + + // st up the form of the data passed to the vertex shader + glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); + glEnableVertexAttribArray(0); + + glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3* sizeof(GLfloat))); + glEnableVertexAttribArray(1); + + glVertexAttribPointer(2, 2, GL_FLOAT,GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); + glEnableVertexAttribArray(2); + + // release buffer objects + glBindBuffer(GL_ARRAY_BUFFER, 0); + + // release the array object + glBindVertexArray(0); + + + GLuint texture1; + GLuint texture2; + + glGenTextures(1, &texture1); + glBindTexture(GL_TEXTURE_2D, texture1); + + // Set our texture parameters + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // Set texture wrapping to GL_REPEAT + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + + // Set texture filtering + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + int width, height; + unsigned char* image = SOIL_load_image("images/container.jpg", &width, &height, 0, SOIL_LOAD_RGB); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); + glGenerateMipmap(GL_TEXTURE_2D); + + SOIL_free_image_data(image); + + glBindTexture(GL_TEXTURE_2D, 0); + + + glGenTextures(1, &texture2); + glBindTexture(GL_TEXTURE_2D, texture2); + + // Set our texture parameters + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // Set texture wrapping to GL_REPEAT + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + + // Set texture filtering + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + + image = SOIL_load_image("images/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); + glGenerateMipmap(GL_TEXTURE_2D); + + SOIL_free_image_data(image); + + glBindTexture(GL_TEXTURE_2D, 0); + + + // Program loop + while(!glfwWindowShouldClose(window)) { + + // Check and call events + glfwPollEvents(); + + // Rclear screen + glClearColor(0.2f, 0.3f, 0.3f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + + // load shaderprogram + shaderProgram->use(); + + // uniforms + GLint mixtureLocation = glGetUniformLocation(shaderProgram->Program, "mixture"); + glUniform1f(mixtureLocation, mixture); + + // Bind Textures using texture units + glActiveTexture(GL_TEXTURE0); + glBindTexture(GL_TEXTURE_2D, texture1); + glUniform1i(glGetUniformLocation(shaderProgram->Program, "ourTexture1"), 0); + glActiveTexture(GL_TEXTURE1); + glBindTexture(GL_TEXTURE_2D, texture2); + glUniform1i(glGetUniformLocation(shaderProgram->Program, "ourTexture2"), 1); + + // Draw container + glBindVertexArray(VAO); + glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); + glBindVertexArray(0); + + // unbind the thing to draw + glBindVertexArray(0); + + // Swap the buffers + glfwSwapBuffers(window); + } + + glfwTerminate(); + return 0; +} + + +void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) +{ + // When a user presses the escape key, we set the WindowShouldClose property to true, + // closing the application + if(key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) + glfwSetWindowShouldClose(window, GL_TRUE); + + if(key == GLFW_KEY_R && action == GLFW_PRESS) { + delete(shaderProgram); + shaderProgram = new Shader("shaders/HelloTextures.vs", "shaders/HelloTextures.frag"); + } + + if(key == GLFW_KEY_UP && (action == GLFW_REPEAT || action == GLFW_PRESS) ) { + mixture = mixture + 0.01; + } + + if(key == GLFW_KEY_DOWN && (action == GLFW_REPEAT || action == GLFW_PRESS) ) { + mixture = mixture - 0.01; + } + + + if(mixture > 1.0f) + mixture = 1.0f; + else if(mixture < 0.0f) + mixture = 0.0f; + +} diff --git a/pool/shard011/C++/0121902_audit_tests.cpp b/pool/shard011/C++/0121902_audit_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..134c47adc1f97aa724f90f393beb6116b966de31 --- /dev/null +++ b/pool/shard011/C++/0121902_audit_tests.cpp @@ -0,0 +1,136 @@ +/** + * Copyright (c) 2014-present, The osquery authors + * + * This source code is licensed as defined by the LICENSE file found in the + * root directory of this source tree. + * + * SPDX-License-Identifier: (Apache-2.0 OR GPL-2.0-only) + */ + +#include + +#include + +#include +#include + +#include + +#include +#include + +#include "osquery/events/linux/auditdnetlink.h" +#include "osquery/tests/test_util.h" + +namespace osquery { + +DECLARE_bool(audit_allow_unix); + +/// Internal audit subscriber (socket events) testable methods. +extern void parseSockAddr(const std::string& saddr, Row& r, bool& unix_socket); + +using StringMap = std::map; + +/// Generates a fake audit id +std::string generateAuditId(std::uint32_t event_id) noexcept { + std::stringstream str_helper; + str_helper << std::time(nullptr) << ".000:" << event_id; + + return str_helper.str(); +} + +class AuditTests : public testing::Test { + protected: + void SetUp() override { + Row().swap(row_); + } + + protected: + Row row_; +}; + +TEST_F(AuditTests, test_handle_reply) { + // A 'fake' audit message. + std::string message = + "audit(1440542781.644:403030): argc=3 a0=\"H=1 \" a1=\"/bin/sh\" a2=c"; + + struct audit_reply reply; + reply.type = 1; + reply.len = message.size(); + reply.message = (char*)malloc(sizeof(char) * (message.size() + 1)); + memset((void*)reply.message, 0, message.size() + 1); + memcpy((void*)reply.message, message.c_str(), message.size()); + + // Perform the parsing. + AuditEventRecord audit_event_record = {}; + bool parser_status = + AuditdNetlinkParser::ParseAuditReply(reply, audit_event_record); + EXPECT_EQ(parser_status, true); + + free((char*)reply.message); + + EXPECT_EQ(reply.type, audit_event_record.type); + EXPECT_EQ("1440542781.644:403030", audit_event_record.audit_id); + EXPECT_EQ(audit_event_record.fields.size(), 4U); + EXPECT_EQ(audit_event_record.fields.count("argc"), 1U); + EXPECT_EQ(audit_event_record.fields["argc"], "3"); + EXPECT_EQ(audit_event_record.fields["a0"], "\"H=1 \""); + EXPECT_EQ(audit_event_record.fields["a1"], "\"/bin/sh\""); + EXPECT_EQ(audit_event_record.fields["a2"], "c"); +} + +TEST_F(AuditTests, test_audit_value_decode) { + // In the normal case the decoding only removes '"' characters from the ends. + auto decoded_normal = DecodeAuditPathValues("\"/bin/ls\""); + EXPECT_EQ(decoded_normal, "/bin/ls"); + + // If the first char is not '"', the value is expected to be hex-encoded. + auto decoded_hex = DecodeAuditPathValues("736C6565702031"); + EXPECT_EQ(decoded_hex, "sleep 1"); + + // When the hex fails to decode the input value is returned as the result. + auto decoded_fail = DecodeAuditPathValues("7"); + EXPECT_EQ(decoded_fail, "7"); +} + +size_t kAuditCounter{0}; + +bool SimpleUpdate(size_t t, const StringMap& f, StringMap& m) { + kAuditCounter++; + for (const auto& i : f) { + m[i.first] = i.second; + } + return true; +} + +TEST_F(AuditTests, test_parse_sock_addr) { + Row r; + std::string msg = "02001F907F0000010000000000000000"; + bool unix_socket; + parseSockAddr(msg, r, unix_socket); + ASSERT_FALSE(r["remote_address"].empty()); + EXPECT_EQ(r["remote_address"], "127.0.0.1"); + EXPECT_EQ(r["family"], "2"); + EXPECT_EQ(r["remote_port"], "8080"); + + Row r3; + std::string msg2 = "0A001F9100000000FE80000000000000022522FFFEB03684000000"; + parseSockAddr(msg2, r3, unix_socket); + ASSERT_FALSE(r3["remote_address"].empty()); + EXPECT_EQ(r3["remote_address"], "fe80:0000:0000:0000:0225:22ff:feb0:3684"); + EXPECT_EQ(r3["remote_port"], "8081"); + + auto socket_flag = FLAGS_audit_allow_unix; + FLAGS_audit_allow_unix = true; + Row r4; + std::string msg3 = "01002F746D702F6F7371756572792E656D0000"; + parseSockAddr(msg3, r4, unix_socket); + ASSERT_FALSE(r4["socket"].empty()); + EXPECT_EQ(r4["socket"], "/tmp/osquery.em"); + + msg3 = "0100002F746D702F6F7371756572792E656D"; + parseSockAddr(msg3, r4, unix_socket); + EXPECT_EQ(r4["socket"], "/tmp/osquery.em"); + FLAGS_audit_allow_unix = socket_flag; +} +} diff --git a/pool/shard011/C++/0121904_DecimalFormatRenderer.cpp b/pool/shard011/C++/0121904_DecimalFormatRenderer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af6f502a780d4c95a37e71bdc7a821fad42176eb --- /dev/null +++ b/pool/shard011/C++/0121904_DecimalFormatRenderer.cpp @@ -0,0 +1,119 @@ +/* + * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland + * All rights reserved. + * + * This library/application is free software; you can redistribute and/or modify it under the terms of + * the license that is included with this library/application in the file license.txt. + */ + +#include "DecimalFormatRenderer.h" +#include "AnythingUtils.h" +#include "SystemLog.h" +#include "Tracer.h" + +//---- DecimalFormatRenderer --------------------------------------------------------------- +RegisterRenderer(DecimalFormatRenderer); + +DecimalFormatRenderer::DecimalFormatRenderer(const char *name) : Renderer(name) { } + +DecimalFormatRenderer::~DecimalFormatRenderer() { } + +void DecimalFormatRenderer::RenderAll(std::ostream &reply, Context &ctx, const ROAnything &config) +{ + StartTrace(DecimalFormatRenderer.RenderAll); + + TraceAny(config, "config"); + String sString, sScale, sDecSeparator, sMaxLength; + + if (!ReadConfig( ctx, config, sString, sScale, sDecSeparator )) { + return; + } + + if (sString.Length()) { + if (!FormatNumber( sString, sScale, sDecSeparator )) { + return; + } + } + + Trace("string to return [" << sString << "]"); + reply << sString; +} + +bool DecimalFormatRenderer::ReadConfig( Context &ctx, const ROAnything &config, String &sString, String &sScale, String &sDecSeparator ) +{ + StartTrace(DecimalFormatRenderer.ReadConfig); + + ROAnything roaSlotConfig; + if (config.LookupPath(roaSlotConfig, "String")) { + RenderOnString(sString, ctx, roaSlotConfig); + } else { + SystemLog::Error("DecimalFormatRenderer::RenderAll: String not defined"); + return false; + } + Trace("String: [" << sString << "]"); + + if (config.LookupPath(roaSlotConfig, "Scale")) { + RenderOnString(sScale, ctx, roaSlotConfig); + } else { + SystemLog::Error("DecimalFormatRenderer::RenderAll: Scale not defined"); + return false; + } + Trace("Scale: [" << sScale << "]"); + + if (config.LookupPath(roaSlotConfig, "DecimalSeparator")) { + RenderOnString(sDecSeparator, ctx, roaSlotConfig); + } else { + sDecSeparator = ","; + } + Trace("DecimalSeparator: [" << sDecSeparator << "]"); + + return true; + +} + +bool DecimalFormatRenderer::FormatNumber( String &sString, String &sScale, String &sDecSeparator ) +{ + StartTrace(DecimalFormatRenderer.FormatNumber); + + String strTmp(sString); + String strToken, strNumber, strDecPlaces; + StringTokenizer tok(strTmp, sDecSeparator[0L]); + + if ( tok(strToken) ) { + + Trace("current token [" << strToken << "]"); + strNumber = strToken; + } else { + strNumber = "0"; + } + + if ( tok(strToken) ) { + Trace("current token [" << strToken << "]"); + strDecPlaces = strToken; + } else { + strDecPlaces = ""; + } + + if (sScale.AsLong(0L) > 0L) { + InsertFiller( sScale, strDecPlaces ); + Trace("decimal [" << strDecPlaces << "] scale [" << sScale.AsLong(0L) << "]"); + sString = strNumber << sDecSeparator << strDecPlaces.SubString(0L, sScale.AsLong(0L)); + } else { + sString = strNumber; + Trace("result scale = 0 [" << sString << "]"); + } + + return true; + +} + +void DecimalFormatRenderer::InsertFiller(String &sScale, String &strDecPlaces ) +{ + StartTrace(DecimalFormatRenderer.InsertFiller); + + for ( long lIdx = strDecPlaces.Length(); lIdx < sScale.AsLong(0L) ; lIdx++) { + strDecPlaces.Append("0"); + Trace("scale [ " << strDecPlaces << "] index [ " << lIdx << " ]"); + } +} + diff --git a/pool/shard011/C++/0121906_dgeqrf-v4.cpp b/pool/shard011/C++/0121906_dgeqrf-v4.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2365c4cf9495d0915be0da60dac8f79b90f4c03a --- /dev/null +++ b/pool/shard011/C++/0121906_dgeqrf-v4.cpp @@ -0,0 +1,183 @@ +/* + -- MAGMA (version 1.6.1) -- + Univ. of Tennessee, Knoxville + Univ. of California, Berkeley + Univ. of Colorado, Denver + @date January 2015 + + @generated from zgeqrf-v4.cpp normal z -> d, Fri Jan 30 19:00:15 2015 + +*/ +#include "common_magma.h" + +/** + Purpose + ------- + DGEQRF4 computes a QR factorization of a DOUBLE_PRECISION M-by-N matrix A: + A = Q * R using multiple GPUs. This version does not require work space on the GPU + passed as input. GPU memory is allocated in the routine. + + Arguments + --------- + @param[in] + ngpu INTEGER + Number of GPUs to use. ngpu > 0. + + @param[in] + m INTEGER + The number of rows of the matrix A. M >= 0. + + @param[in] + n INTEGER + The number of columns of the matrix A. N >= 0. + + @param[in,out] + A DOUBLE_PRECISION array, dimension (LDA,N) + On entry, the M-by-N matrix A. + On exit, the elements on and above the diagonal of the array + contain the min(M,N)-by-N upper trapezoidal matrix R (R is + upper triangular if m >= n); the elements below the diagonal, + with the array TAU, represent the orthogonal matrix Q as a + product of min(m,n) elementary reflectors (see Further + Details). + \n + Higher performance is achieved if A is in pinned memory, e.g. + allocated using magma_malloc_pinned. + + @param[in] + lda INTEGER + The leading dimension of the array A. LDA >= max(1,M). + + @param[out] + tau DOUBLE_PRECISION array, dimension (min(M,N)) + The scalar factors of the elementary reflectors (see Further + Details). + + @param[out] + work (workspace) DOUBLE_PRECISION array, dimension (MAX(1,LWORK)) + On exit, if INFO = 0, WORK[0] returns the optimal LWORK. + \n + Higher performance is achieved if WORK is in pinned memory, e.g. + allocated using magma_malloc_pinned. + + @param[in] + lwork INTEGER + The dimension of the array WORK. LWORK >= N*NB, + where NB can be obtained through magma_get_dgeqrf_nb(M). + \n + If LWORK = -1, then a workspace query is assumed; the routine + only calculates the optimal size of the WORK array, returns + this value as the first entry of the WORK array, and no error + message related to LWORK is issued. + + @param[out] + info INTEGER + - = 0: successful exit + - < 0: if INFO = -i, the i-th argument had an illegal value + or another error occured, such as memory allocation failed. + + Further Details + --------------- + The matrix Q is represented as a product of elementary reflectors + + Q = H(1) H(2) . . . H(k), where k = min(m,n). + + Each H(i) has the form + + H(i) = I - tau * v * v' + + where tau is a real scalar, and v is a real vector with + v(1:i-1) = 0 and v(i) = 1; v(i+1:m) is stored on exit in A(i+1:m,i), + and tau in TAU(i). + + @ingroup magma_dgeqrf_comp + ********************************************************************/ +extern "C" magma_int_t +magma_dgeqrf4( + magma_int_t ngpu, + magma_int_t m, magma_int_t n, + double *A, magma_int_t lda, double *tau, + double *work, magma_int_t lwork, + magma_int_t *info ) +{ + double *da[MagmaMaxGPUs]; + double c_one = MAGMA_D_ONE; + + int i, k, ldda; + + *info = 0; + int nb = magma_get_dgeqrf_nb(min(m, n)); + + int lwkopt = n * nb; + work[0] = MAGMA_D_MAKE( (double)lwkopt, 0 ); + int lquery = (lwork == -1); + if (ngpu < 0 || ngpu > MagmaMaxGPUs) { + *info = -1; + } else if (m < 0) { + *info = -2; + } else if (n < 0) { + *info = -3; + } else if (lda < max(1,m)) { + *info = -5; + } else if (lwork < max(1,n) && ! lquery) { + *info = -8; + } + if (*info != 0) { + magma_xerbla( __func__, -(*info) ); + return *info; + } + else if (lquery) + return *info; + + k = min(m,n); + if (k == 0) { + work[0] = c_one; + return *info; + } + + magma_device_t orig_dev; + magma_getdevice( &orig_dev ); + + ldda = ((m+31)/32)*32; + + magma_int_t n_local[MagmaMaxGPUs]; + for (i=0; i < ngpu; i++) { + n_local[i] = ((n/nb)/ngpu)*nb; + if (i < (n/nb)%ngpu) + n_local[i] += nb; + else if (i == (n/nb)%ngpu) + n_local[i] += n%nb; + + magma_setdevice(i); + + // TODO on failure, free previously allocated memory + if (MAGMA_SUCCESS != magma_dmalloc( &da[i], ldda*n_local[i] )) { + *info = MAGMA_ERR_DEVICE_ALLOC; + return *info; + } + } + + if (m > nb && n > nb) { + /* Copy the matrix to the GPUs in 1D block cyclic distribution */ + magma_dsetmatrix_1D_col_bcyclic(m, n, A, lda, da, ldda, ngpu, nb); + + /* Factor using the GPU interface */ + magma_dgeqrf2_mgpu( ngpu, m, n, da, ldda, tau, info); + + /* Copy the matrix back from the GPUs to the CPU */ + magma_dgetmatrix_1D_col_bcyclic(m, n, da, ldda, A, lda, ngpu, nb); + } + else { + lapackf77_dgeqrf(&m, &n, A, &lda, tau, work, &lwork, info); + } + + + /* Free the allocated GPU memory */ + for (i=0; i < ngpu; i++) { + magma_setdevice(i); + magma_free( da[i] ); + } + magma_setdevice( orig_dev ); + + return *info; +} /* magma_dgeqrf4 */ diff --git a/pool/shard011/C++/0121907_test_bitcoin.cpp b/pool/shard011/C++/0121907_test_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b46b2c6bba5b11cc56f8bda42ed313570bdafc9 --- /dev/null +++ b/pool/shard011/C++/0121907_test_bitcoin.cpp @@ -0,0 +1,66 @@ +#define BOOST_TEST_MODULE Bitcoin Test Suite +#include +#include + +#include "db.h" +#include "txdb.h" +#include "main.h" +#include "wallet.h" +#include "util.h" + +CWallet* pwalletMain; +CClientUIInterface uiInterface; + +extern bool fPrintToConsole; +extern void noui_connect(); + +struct TestingSetup { + CCoinsViewDB *pcoinsdbview; + boost::filesystem::path pathTemp; + boost::thread_group threadGroup; + + TestingSetup() { + fPrintToDebugger = true; // don't want to write to debug.log file + noui_connect(); + bitdb.MakeMock(); + pathTemp = GetTempPath() / strprintf("test_limecoinlite_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000))); + boost::filesystem::create_directories(pathTemp); + mapArgs["-datadir"] = pathTemp.string(); + pblocktree = new CBlockTreeDB(1 << 20, true); + pcoinsdbview = new CCoinsViewDB(1 << 23, true); + pcoinsTip = new CCoinsViewCache(*pcoinsdbview); + InitBlockIndex(); + bool fFirstRun; + pwalletMain = new CWallet("wallet.dat"); + pwalletMain->LoadWallet(fFirstRun); + RegisterWallet(pwalletMain); + nScriptCheckThreads = 3; + for (int i=0; i < nScriptCheckThreads-1; i++) + threadGroup.create_thread(&ThreadScriptCheck); + } + ~TestingSetup() + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + delete pwalletMain; + pwalletMain = NULL; + delete pcoinsTip; + delete pcoinsdbview; + delete pblocktree; + bitdb.Flush(true); + boost::filesystem::remove_all(pathTemp); + } +}; + +BOOST_GLOBAL_FIXTURE(TestingSetup); + +void Shutdown(void* parg) +{ + exit(0); +} + +void StartShutdown() +{ + exit(0); +} + diff --git a/pool/shard011/C++/0121910_LevelWindow.cpp b/pool/shard011/C++/0121910_LevelWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bbbb5f7ecd37854ae60dca44e76fd9266cc5b0a --- /dev/null +++ b/pool/shard011/C++/0121910_LevelWindow.cpp @@ -0,0 +1,79 @@ +/* + + LevelWindow.cpp + + Copyright 1995 Be Incorporated, All Rights Reserved. + +*/ + +#include +#include +#include + +#include "LevelView.h" + +#ifndef LEVELWINDOW_H +#include "LevelWindow.h" +#endif + +enum +{ + SAVE = 'save', + LOAD = 'load', + SAVE_AS = 'svas', + QUIT_REQUEST = 'qtrq' + +}; + +void set_palette_entry(long i,rgb_color c); + +LevelWindow::LevelWindow(BRect frame) + : BWindow(frame, "LevelWorld", B_TITLED_WINDOW, B_NOT_ZOOMABLE | B_NOT_RESIZABLE) +{ + BMenuBar* bar = new BMenuBar("menu"); + BView *aView = new LevelView("View"); + + BGroupLayout* layout = new BGroupLayout(B_VERTICAL); + SetLayout(layout); + layout->SetSpacing(0.f); + + AddChild(bar); + AddChild(aView); + + BMenu* fileMenu = new BMenu("Level"); + BMenuItem* loadMenu = new BMenuItem("Open" B_UTF8_ELLIPSIS, + new BMessage(LOAD), 'O'); + BMenuItem* saveMenu = new BMenuItem("Save" B_UTF8_ELLIPSIS, + new BMessage(SAVE), 'S'); + BMenuItem* saveAsMenu = new BMenuItem("Save As" B_UTF8_ELLIPSIS, + new BMessage(SAVE_AS), 'S', B_SHIFT_KEY); + + loadMenu->SetTarget(aView); + saveMenu->SetTarget(aView); + saveAsMenu->SetTarget(aView); + + bar->AddItem(fileMenu); + fileMenu->AddItem(loadMenu); + fileMenu->AddItem(saveMenu); + fileMenu->AddItem(saveAsMenu); +} + +void LevelWindow::MessageReceived(BMessage *message) +{ + switch(message->what) + { + case QUIT_REQUEST: + { + be_app->PostMessage(B_QUIT_REQUESTED); + Quit(); + break; + } + } +} + +bool LevelWindow::QuitRequested() +{ + be_app->DispatchMessage(new BMessage(QUIT_REQUEST), FindView("View")); + return(FALSE); +} + diff --git a/pool/shard011/C++/0121914_re_texture.cpp b/pool/shard011/C++/0121914_re_texture.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16f760f6d28e96ac5971e15931fcacd79edc8610 --- /dev/null +++ b/pool/shard011/C++/0121914_re_texture.cpp @@ -0,0 +1,157 @@ +#define _CRT_SECURE_NO_WARNINGS +#include +#include +#include +#include +#include +#include +#include +#include "../defs.h" + +bool FileExists(const char *path) { + FILE *file = fopen(path, "rb"); + if (file != NULL) { + fclose(file); + return true; + } + return false; +} + + +static GLuint RE_LoadTGA(const char *path) { + GLuint textureID; + glGenTextures(1, &textureID); + glBindTexture(GL_TEXTURE_2D, textureID); + if (glfwLoadTexture2D(path, 0) == GL_FALSE) { + CON_ERRS("error loading %s", path); + glDeleteTextures(1, &textureID); + textureID = 0; + } + #if 0 + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); + glGenerateMipmap(GL_TEXTURE_2D); + #endif + return textureID; +} + +#define FOURCC_DXT1 0x31545844 // Equivalent to "DXT1" in ASCII +#define FOURCC_DXT3 0x33545844 // Equivalent to "DXT3" in ASCII +#define FOURCC_DXT5 0x35545844 // Equivalent to "DXT5" in ASCII + +static GLuint RE_LoadDDS(const char *path) { + unsigned char header[124]; + FILE *fp; + + /* try to open the file */ + fp = fopen(path, "rb"); + if (fp == NULL) + return 0; + + /* verify the type of file */ + char filecode[4]; + int nn = fread(filecode, 1, 4, fp); + if (strncmp(filecode, "DDS ", 4) != 0) { + fclose(fp); + return 0; + } + + /* get the surface desc */ + nn = fread(&header, 124, 1, fp); + + unsigned int height = *(unsigned int*)&(header[8 ]); + unsigned int width = *(unsigned int*)&(header[12]); + unsigned int linearSize = *(unsigned int*)&(header[16]); + unsigned int mipMapCount = *(unsigned int*)&(header[24]); + unsigned int fourCC = *(unsigned int*)&(header[80]); + + + unsigned char * buffer; + unsigned int bufsize; + /* how big is it going to be including all mipmaps? */ + bufsize = mipMapCount > 1 ? linearSize * 2 : linearSize; + buffer = (unsigned char*)malloc(bufsize * sizeof(unsigned char)); + nn = fread(buffer, 1, bufsize, fp); + /* close the file pointer */ + fclose(fp); + + unsigned int components = (fourCC == FOURCC_DXT1) ? 3 : 4; + unsigned int format; + switch(fourCC) + { + case FOURCC_DXT1: + format = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT; + break; + case FOURCC_DXT3: + format = GL_COMPRESSED_RGBA_S3TC_DXT3_EXT; + break; + case FOURCC_DXT5: + format = GL_COMPRESSED_RGBA_S3TC_DXT5_EXT; + break; + default: + free(buffer); + return 0; + } + + // Create one OpenGL texture + GLuint textureID; + glGenTextures(1, &textureID); + + // "Bind" the newly created texture : all future texture functions will modify this texture + glBindTexture(GL_TEXTURE_2D, textureID); + glPixelStorei(GL_UNPACK_ALIGNMENT,1); + + unsigned int blockSize = (format == GL_COMPRESSED_RGBA_S3TC_DXT1_EXT) ? 8 : 16; + unsigned int offset = 0; + + /* load the mipmaps */ + for (unsigned int level = 0; level < mipMapCount && (width || height); ++level) + { + unsigned int size = ((width+3)/4)*((height+3)/4)*blockSize; + glCompressedTexImage2D(GL_TEXTURE_2D, level, format, width, height, + 0, size, buffer + offset); + + offset += size; + width /= 2; + height /= 2; + } + + free(buffer); + return textureID; +} + +glid_t RE_LoadTexture(const char *path, int flags) { + assert(path != NULL); + if (!FileExists(path)) { + path = ASS_GetPath(path); + } + GLuint tex; + tex = RE_LoadDDS(path); + if (tex == 0) { + tex = RE_LoadTGA(path); + if (tex == 0) { + return 0; + } + } + if (flags & TEX_REPEAT) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); + } else if (flags & TEX_CLAMP) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + } + if (flags & TEX_NN) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + } else if (flags & TEX_LM) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); + } else if (flags & TEX_MIP) { + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); + glGenerateMipmap(GL_TEXTURE_2D); + } + return tex; +} diff --git a/pool/shard011/C++/0121915_cp_view_tool.cpp b/pool/shard011/C++/0121915_cp_view_tool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7bc28b64920486f442c39c023be8af1c1d5a7975 --- /dev/null +++ b/pool/shard011/C++/0121915_cp_view_tool.cpp @@ -0,0 +1,196 @@ +#include "net_adapter.h" +#include "config_protocol.h" +#include "config_connector.h" +#include "config_addr_parser.h" +#include "config_types.h" +#include "config_ipinfo_parser.h" +#include "config_access.h" + +#include +#include +#include +#include + + +std::string IP; +__uint16_t PORT; + + +void GetNetData(wq::config::CheckUpdateReq &vReq, wq::config::UpdateItemReq &oResp) +{ + wq::config::NetAdapter *p_net = new wq::config::NetAdapter(inet_addr(IP.c_str()), PORT, 1000); + wq::config::Heartbeat oHeartbeat, oHeartbeatResp; + oHeartbeat.dwTimestamp = time(NULL); + oHeartbeat.sDesc = "cp test clinet"; + + + if (p_net->Invoke(wq::config::CMD_HEARTBEAT_REQ, oHeartbeat, oHeartbeatResp) < 0){ + + std::cout << p_net->GetErrMsg() << std::endl; + + return; + + } + + if (p_net->Invoke(wq::config::CMD_QUERY_NEW_ITEM_REQ, vReq, oResp) < 0){ + + std::cout << p_net->GetErrMsg() << std::endl; + + return; + } +} + +void GetTargetData(std::string &sKeyName, unsigned int uType) +{ + wq::config::KeyQueryItem oKeyQueryItem; + oKeyQueryItem.sKeyName = sKeyName; + oKeyQueryItem.uTimeStamp = 0; + oKeyQueryItem.uType = uType; + + wq::config::CheckUpdateReq vReq; + wq::config::UpdateItemReq oResp; + + vReq.push_back(oKeyQueryItem); + + GetNetData(vReq,oResp); + + if (oResp.vUpdated.size() > 0){ + std::vector *p_ver = &(oResp.vUpdated); + + if (oKeyQueryItem.uType == wq::config::TYPE_SVC_ROUTE || oKeyQueryItem.uType == wq::config::TYPE_SVC_L5SEQ || oKeyQueryItem.uType == wq::config::TYPE_CMD_ROUTE + || oKeyQueryItem.uType == wq::config::TYPE_CMD_L5SEQ) + { + + for (__uint32_t i = 0; i < p_ver->size(); i++){ + std::string & sAddr = (*p_ver)[i].sValue; + int iAddrCount = sAddr.size(); + wq::config::AddrParser oParser((const char*)(sAddr.data()), iAddrCount); + + std::cout << "===================[SET:" << (*p_ver)[i].iSetID << "] [COUNT:" << oParser.GetCount() << "]" << "===================" << std::endl; + for (int j = 0; juIP; + char *ip = inet_ntoa(oTestAddr); + + std::cout << "set" << i << " " << j << " " << ip << ":" << pstAddr->wPort << ":" << pstAddr->wWeight<size(); i++){ + std::string & sInfo = (*p_ver)[i].sValue; + int Count = sInfo.size(); + wq::config::IPInfoParser ipParser((const char*)(sInfo.data()), Count); + + ipParser.Dump(std::cout); + } + } + else{ + for (__uint32_t i = 0; i < p_ver->size(); i++){ + + std::cout << " " << i << "/" << p_ver->size() << " type:" << oKeyQueryItem.uType << ", keyname:" << oKeyQueryItem.sKeyName << std::endl; + std::cout << " value: " << (*p_ver)[i].sValue< vAddr; + std::string sSvcName("configcenter_cp"); + int iRet = (wq::config::CONFIG_ACCESS->GetAddrAll(sSvcName, 0, vAddr)); + if (iRet<0||vAddr.size() <= 0){ + std::cout << " ERROR ,plase check ca is run OR configcenter_cp set0 is empty" << std::endl; + exit(-1); + } + IP = wq::config::CONFIG_ACCESS->GetStrIP(vAddr[0].uIP); + PORT = vAddr[0].wPort; + +} + +const std::string SVC_OPTION = "svc"; +const std::string CMD_OPTION = "cmd"; +const std::string CONFIG_FILE_OPTION = "configfile"; +const std::string CONFIG_ITEM_OPTION = "configitem"; +const std::string DAL_OPTION = "dal"; +const std::string IPINFO_OPTION = "ipinfo"; + + + + + +int main(int argc, char** argv){ + + if (argc != 3 && argc != 5 ) + { + help(argc, argv); + } + if (argc == 5){ + IP = argv[3]; + sscanf(argv[4]," %hu",&PORT); + } + else{ + SetIpPort(); + } + + std::cout << " Connect cp is : IP[" << IP << "] PORT[" << PORT << "]" << std::endl; + + std::string sOption = argv[2]; + + std::string sKeyName(argv[1]); + int uType=-1; + + + if (sOption == SVC_OPTION){ + uType = wq::config::TYPE_SVC_ROUTE; + } + else if (sOption == CMD_OPTION){ + uType = wq::config::TYPE_CMD_ROUTE; + } + else if (sOption == CONFIG_FILE_OPTION){ + uType = wq::config::TYPE_CONFIG_FILE; + } + else if (sOption == CONFIG_ITEM_OPTION){ + uType = wq::config::TYPE_CONFIG_ITEM; + } + else if (sOption == DAL_OPTION){ + uType = wq::config::TYPE_DAL_ROUTE; + } + else if (sOption == IPINFO_OPTION){ + uType = wq::config::TYPE_IP_INFO; + } + else { + std::cout << " illegal operation " << std::endl; + help(argc, argv); + } + + + GetTargetData(sKeyName, uType); + +} + diff --git a/pool/shard011/C++/0121916_PostProcessComponent.cpp b/pool/shard011/C++/0121916_PostProcessComponent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b7f6e312b733601371cd77528dfa13ecc078ae28 --- /dev/null +++ b/pool/shard011/C++/0121916_PostProcessComponent.cpp @@ -0,0 +1,51 @@ +// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. + +#include "EnginePrivate.h" +#include "Components/PostProcessComponent.h" + +UPostProcessComponent::UPostProcessComponent(const FObjectInitializer& ObjectInitializer) + : Super(ObjectInitializer) +{ + bEnabled = true; + BlendRadius = 100.0f; + BlendWeight = 1.0f; + Priority = 0; + bUnbound = 1; +} + +bool UPostProcessComponent::EncompassesPoint(FVector Point, float SphereRadius/*=0.f*/, float* OutDistanceToPoint) +{ + UShapeComponent* ParentShape = Cast(AttachParent); + if (ParentShape != nullptr) + { +#if WITH_PHYSX + FVector ClosestPoint; + float Distance = ParentShape->GetDistanceToCollision(Point, ClosestPoint); +#else + FBoxSphereBounds Bounds = ParentShape->CalcBounds(ParentShape->ComponentToWorld); + float Distance = 0; + if (ParentShape->IsA()) + { + const FSphere& Sphere = Bounds.GetSphere(); + const FVector& Dist = Sphere.Center - Point; + Distance = FMath::Max(0.0f, Dist.Size() - Sphere.W); + } + else // UBox or UCapsule shape (approx). + { + Distance = FMath::Sqrt(Bounds.GetBox().ComputeSquaredDistanceToPoint(Point)); + } +#endif + + if (OutDistanceToPoint) + { + *OutDistanceToPoint = Distance; + } + + return Distance >= 0.f && Distance <= SphereRadius; + } + if (OutDistanceToPoint != nullptr) + { + *OutDistanceToPoint = 0; + } + return true; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121917_pastebindotcaprotocol.cpp b/pool/shard011/C++/0121917_pastebindotcaprotocol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1592cd2fd749323731b5b2e53a572ca854b37555 --- /dev/null +++ b/pool/shard011/C++/0121917_pastebindotcaprotocol.cpp @@ -0,0 +1,230 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "pastebindotcaprotocol.h" + +#include + +#include +#include +#include +#include + +static const char urlC[] = "http://pastebin.ca/"; + +namespace CodePaster { +PasteBinDotCaProtocol::PasteBinDotCaProtocol() : + m_fetchReply(0), + m_listReply(0), + m_pasteReply(0), + m_hostChecked(false) +{ +} + +unsigned PasteBinDotCaProtocol::capabilities() const +{ + return ListCapability | PostDescriptionCapability; +} + +void PasteBinDotCaProtocol::fetch(const QString &id) +{ + QTC_ASSERT(!m_fetchReply, return); + const QString url = QLatin1String(urlC); + const QString rawPostFix = QLatin1String("raw/"); + // Create link as ""http://pastebin.ca/raw/[id]" + // If we get a complete URL, just insert 'raw', else build URL. + QString link = id; + if (link.startsWith(url)) { + const int lastSlashPos = link.lastIndexOf(QLatin1Char('/')); + if (lastSlashPos != -1) + link.insert(lastSlashPos + 1, rawPostFix); + } else { + link.insert(0, rawPostFix); + link.insert(0, url); + } + m_fetchReply = httpGet(link); + connect(m_fetchReply, SIGNAL(finished()), this, SLOT(fetchFinished())); + m_fetchId = id; +} + +static QByteArray toTypeId(Protocol::ContentType ct) +{ + if (ct == Protocol::C) + return QByteArray(1, '3'); + if (ct == Protocol::Cpp) + return QByteArray(1, '4'); + if (ct == Protocol::JavaScript) + return QByteArray("27"); + if (ct == Protocol::Diff) + return QByteArray( "34"); + if (ct == Protocol::Xml) + return QByteArray("15"); + return QByteArray(1, '1'); +} + +void PasteBinDotCaProtocol::paste(const QString &text, + ContentType ct, int expiryDays, + const QString &username, + const QString & /* comment */, + const QString &description) +{ + QTC_ASSERT(!m_pasteReply, return); + QByteArray data = "api=+xKvWG+1UFXkr2Kn3Td4AnpYtCIjA4qt&"; + data += "content="; + data += QUrl::toPercentEncoding(fixNewLines(text)); + data += "&type="; + data += toTypeId(ct); + data += "&description="; + data += QUrl::toPercentEncoding(description); + data += "&expiry="; + data += QByteArray::number(expiryDays); + data += "%20day&name="; + data += QUrl::toPercentEncoding(username); + // fire request + const QString link = QLatin1String(urlC) + QLatin1String("quiet-paste.php"); + m_pasteReply = httpPost(link, data); + connect(m_pasteReply, SIGNAL(finished()), this, SLOT(pasteFinished())); +} + +void PasteBinDotCaProtocol::pasteFinished() +{ + if (m_pasteReply->error()) { + qWarning("Pastebin.ca protocol error: %s", qPrintable(m_pasteReply->errorString())); + } else { + /// returns ""SUCCESS:[id]"" + const QByteArray data = m_pasteReply->readAll(); + const QString link = QString::fromLatin1(urlC) + QString::fromLatin1(data).remove(QLatin1String("SUCCESS:")); + emit pasteDone(link); + } + m_pasteReply->deleteLater(); + m_pasteReply = 0; +} + +void PasteBinDotCaProtocol::fetchFinished() +{ + QString title; + QString content; + bool error = m_fetchReply->error(); + if (error) { + content = m_fetchReply->errorString(); + } else { + title = QString::fromLatin1("Pastebin.ca: %1").arg(m_fetchId); + const QByteArray data = m_fetchReply->readAll(); + content = QString::fromUtf8(data); + content.remove(QLatin1Char('\r')); + } + m_fetchReply->deleteLater(); + m_fetchReply = 0; + emit fetchDone(title, content, error); +} + +void PasteBinDotCaProtocol::list() +{ + QTC_ASSERT(!m_listReply, return); + m_listReply = httpGet(QLatin1String(urlC)); + connect(m_listReply, SIGNAL(finished()), this, SLOT(listFinished())); +} + +bool PasteBinDotCaProtocol::checkConfiguration(QString *errorMessage) +{ + if (m_hostChecked) // Check the host once. + return true; + const bool ok = httpStatus(QLatin1String(urlC), errorMessage); + if (ok) + m_hostChecked = true; + return ok; +} + +/* Quick & dirty: Parse the
-elements with the "Recent Posts" listing + * out of the page. +\code + +
+ + ...

Create a New Pastebin Post

+\endcode */ + +static inline QStringList parseLists(QIODevice *io) +{ + enum State { OutsideRecentLink, InsideRecentLink }; + + QStringList rc; + + const QString classAttribute = QLatin1String("class"); + const QString divElement = QLatin1String("div"); + const QString anchorElement = QLatin1String("a"); + + // Start parsing at the 'recent posts' entry as the HTML above is not well-formed + // as of 8.4.2010. This will then terminate with an error. + QByteArray data = io->readAll(); + const QByteArray recentPosts("

Recent Posts

"); + const int recentPostsPos = data.indexOf(recentPosts); + if (recentPostsPos == -1) + return rc; + data.remove(0, recentPostsPos + recentPosts.size()); + QXmlStreamReader reader(data); + State state = OutsideRecentLink; + while (!reader.atEnd()) { + switch (reader.readNext()) { + case QXmlStreamReader::StartElement: + // Inside a
of an entry: Anchor or description + if (state == InsideRecentLink && reader.name() == anchorElement) { // Anchor + // Strip host from link + QString link = reader.attributes().value(QLatin1String("href")).toString(); + if (link.startsWith(QLatin1Char('/'))) + link.remove(0, 1); + const QString nameTitle = reader.readElementText(); + rc.push_back(link + QLatin1Char(' ') + nameTitle); + } else if (state == OutsideRecentLink && reader.name() == divElement) { // "
" state switching + if (reader.attributes().value(classAttribute) == QLatin1String("recentlink")) + state = InsideRecentLink; + } // divElement + break; + default: + break; + } // switch reader + } // while reader.atEnd() + return rc; +} + +void PasteBinDotCaProtocol::listFinished() +{ + const bool error = m_listReply->error(); + if (error) + qWarning("pastebin.ca list failed: %s", qPrintable(m_listReply->errorString())); + else + emit listDone(name(), parseLists(m_listReply)); + m_listReply->deleteLater(); + m_listReply = 0; +} + +} // namespace CodePaster diff --git a/pool/shard011/C++/0121918_create-remove-bucket.cc b/pool/shard011/C++/0121918_create-remove-bucket.cc new file mode 100644 index 0000000000000000000000000000000000000000..480bb00937f7bfc57cefa857838035ce99762b99 --- /dev/null +++ b/pool/shard011/C++/0121918_create-remove-bucket.cc @@ -0,0 +1,65 @@ +#include +#include +#include +#include + +static void http_callback(lcb_t, int, const lcb_RESPHTTP *resp) +{ + printf("Operation completed with HTTP code: %d\n", resp->htstatus); + printf("Payload: %.*s\n", (int)resp->nbody, (char *)resp->body); +} + +int main(int, char **) +{ + lcb_create_st crst = {}; + lcb_t instance; + + crst.version = 3; + crst.v.v3.connstr = "couchbase://127.0.0.1/default"; + crst.v.v3.username = "testuser"; + crst.v.v3.passwd = "password"; + + lcb_create(&instance, &crst); + lcb_connect(instance); + lcb_wait(instance); + assert(lcb_get_bootstrap_status(instance) == LCB_SUCCESS); + lcb_install_callback3(instance, LCB_CALLBACK_HTTP, (lcb_RESPCALLBACK)http_callback); + + // Create the required parameters according to the Couchbase REST API + std::string path("/pools/default/buckets"); + + std::string params; + params += "name=newBucket&"; + params += "bucketType=couchbase&"; + + // authType should always be SASL. You can leave the saslPassword field + // empty if you don't want to protect this bucket. + params += "authType=sasl&saslPassword=&"; + params += "ramQuotaMB=100"; + printf("Using %s\n", params.c_str()); + + lcb_CMDHTTP htcmd = {}; + LCB_CMD_SET_KEY(&htcmd, path.c_str(), path.size()); + htcmd.body = params.c_str(); + htcmd.nbody = params.size(); + htcmd.content_type = "application/x-www-form-urlencoded"; + htcmd.method = LCB_HTTP_METHOD_POST; + htcmd.type = LCB_HTTP_TYPE_MANAGEMENT; + htcmd.username = "Administrator"; + htcmd.password = "password"; + lcb_http3(instance, NULL, &htcmd); + lcb_wait(instance); + + // now remove the bucket + memset(&htcmd, 0, sizeof htcmd); + path = "/pools/default/buckets/newBucket"; + LCB_CMD_SET_KEY(&htcmd, path.c_str(), path.size()); + htcmd.method = LCB_HTTP_METHOD_DELETE; + htcmd.type = LCB_HTTP_TYPE_MANAGEMENT; + htcmd.username = "Administrator"; + htcmd.password = "password"; + lcb_http3(instance, NULL, &htcmd); + lcb_wait(instance); + + lcb_destroy(instance); +} diff --git a/pool/shard011/C++/0121920_ForwardChainer.cc b/pool/shard011/C++/0121920_ForwardChainer.cc new file mode 100644 index 0000000000000000000000000000000000000000..bd05743ed5e586595be7aa8b68dbc909fd9cf4d4 --- /dev/null +++ b/pool/shard011/C++/0121920_ForwardChainer.cc @@ -0,0 +1,239 @@ +/* + * ForwardChainer.cc + * + * Copyright (C) 2014,2015 Misgana Bayetta + * + * Author: Misgana Bayetta + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License v3 as + * published by the Free Software Foundation and including the exceptions + * at http://opencog.org/wiki/Licenses + * + * 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 Affero General Public License + * along with this program; if not, write to: + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include +#include +#include +#include +#include +#include +#include "ForwardChainer.h" +#include "ForwardChainerCallBack.h" + +using namespace opencog; + +ForwardChainer::ForwardChainer(AtomSpace& as, Handle rbs) : + _as(as), _rec(_as), _rbs(rbs), _configReader(as, rbs), _fcmem(&as) +{ + init(); +} + +void ForwardChainer::init() +{ + _fcmem.set_search_in_af(_configReader.get_attention_allocation()); + _fcmem.set_rules(_configReader.get_rules()); + _fcmem.set_cur_rule(nullptr); + + // Provide a logger + _log = NULL; + setLogger(new opencog::Logger("forward_chainer.log", Logger::FINE, true)); +} + +void ForwardChainer::setLogger(Logger* log) +{ + if (_log) + delete _log; + _log = log; +} + +Logger* ForwardChainer::getLogger() +{ + return _log; +} + +/** + * Does one step forward chaining + * + * @param fcb a concrete implementation of of ForwardChainerCallBack class + */ +void ForwardChainer::do_step(ForwardChainerCallBack& fcb) +{ + + if (_fcmem.get_cur_source() == Handle::UNDEFINED) { + _log->info("[ForwardChainer] No current source, step " + "forward chaining aborted."); + return; + } + + _log->info("[ForwardChainer] Next source %s", + _fcmem.get_cur_source()->toString().c_str()); + + // Choose matching rules whose input matches with the source. + vector matched_rules = fcb.choose_rules(_fcmem); + _log->info("[ForwardChainer] Found matching rule"); + + //! If no rules matches the pattern of the source, + //! set all rules for candidacy to be selected by the proceeding step. + //! xxx this decision is maded based on recent discussion.I + //! it might still face some changes. + if (matched_rules.empty()) { + _log->info("[ForwardChainer] No matching rule found. " + "Setting all rules as candidates."); + matched_rules = _fcmem.get_rules(); + } + + // Select a rule amongst the matching rules by tournament selection + map rule_weight; + for (Rule* r : matched_rules) { + rule_weight[r] = r->get_weight(); + } + + _log->info("[ForwardChainer] Selecting a rule from the set of " + "candidate rules."); + Rule* r = _rec.tournament_select(rule_weight); + _fcmem.set_cur_rule(r); + _log->info("[ForwardChainer] Selected rule is %s", (r->get_handle())->toShortString().c_str()); + + //!TODO Find/add premises? + + //! Apply rule. + _log->info("[ForwardChainer] Applying chosen rule %s", + (r->get_handle())->toShortString().c_str()); + HandleSeq product = fcb.apply_rule(_fcmem); + + _log->info("PRODUCTS..."); + for(const auto& p:product) + { + _log->info("%s ", p->toShortString().c_str() ); + } + + _log->info("[ForwardChainer] updating premise list with the " + "inference made"); + _fcmem.update_potential_sources(product); + + _log->info("[ForwardChainer] adding inference to history"); + _fcmem.add_rules_product(_iteration, product); +} + +void ForwardChainer::do_chain(ForwardChainerCallBack& fcb, + Handle hsource/*=Handle::UNDEFINED*/) +{ + if (hsource == Handle::UNDEFINED) { + do_pm(); + return; + } + // Variable fulfillment query. + UnorderedHandleSet var_nodes = get_outgoing_nodes(hsource, + { VARIABLE_NODE }); + if (not var_nodes.empty()) + return do_pm(hsource, var_nodes, fcb); + + HandleSeq init_sources; + //Accept set of initial sources wrapped by a SET_LINK + if(LinkCast(hsource) and hsource->getType() == SET_LINK) + init_sources = _as.get_outgoing(hsource); + else + init_sources.push_back(hsource); + _fcmem.update_potential_sources(init_sources); + + _fcmem.set_source(fcb.choose_next_source(_fcmem)); //set initial source + auto max_iter = _configReader.get_maximum_iterations(); + + while (_iteration < max_iter /*OR other termination criteria*/) { + _log->info("Iteration %d", _iteration); + + do_step(fcb); + + //! Choose next source. + _log->info("[ForwardChainer] setting next source"); + _fcmem.set_source(fcb.choose_next_source(_fcmem)); + + _iteration++; + } + + _log->info("[ForwardChainer] finished do_chain."); +} + +/** + * Does pattern matching for a variable containing query. + * @param source a variable containing handle passed as an input to the pattern matcher + * @param var_nodes the VariableNodes in @param hsource + * @param fcb a forward chainer callback implementation used here only for choosing rules + * that contain @param hsource in their implicant + */ +void ForwardChainer::do_pm(const Handle& hsource, + const UnorderedHandleSet& var_nodes, + ForwardChainerCallBack& fcb) +{ + DefaultImplicator impl(&_as); + impl.implicand = hsource; + HandleSeq vars; + for (auto h : var_nodes) + vars.push_back(h); + _fcmem.set_source(hsource); + Handle hvar_list = _as.add_link(VARIABLE_LIST, vars); + Handle hclause = _as.add_link(AND_LINK, hsource); + + // Run the pattern matcher, find all patterns that satisfy the + // the clause, with the given variables in it. + PatternLinkPtr sl(createPatternLink(hvar_list, hclause)); + sl->satisfy(impl); + + // Update result + _fcmem.add_rules_product(0, impl.result_list); + + // Delete the AND_LINK and LIST_LINK + _as.remove_atom(hvar_list); + _as.remove_atom(hclause); + + //!Additionally, find applicable rules and apply. + vector rules = fcb.choose_rules(_fcmem); + for (Rule* rule : rules) { + BindLinkPtr bl(BindLinkCast(rule->get_handle())); + DefaultImplicator impl(&_as); + impl.implicand = bl->get_implicand(); + bl->imply(impl); + _fcmem.set_cur_rule(rule); + _fcmem.add_rules_product(0, impl.result_list); + } +} +/** + * Invokes pattern matcher using each rule declared in the configuration file. + */ +void ForwardChainer::do_pm() +{ + //! Do pattern matching using the rules declared in the declaration file + _log->info("Forward chaining on the rule-based system %s " + "declared in %s", _rbs->toString().c_str()); + vector rules = _fcmem.get_rules(); + for (Rule* rule : rules) { + _log->info("Applying rule %s on ", rule->get_name().c_str()); + BindLinkPtr bl(BindLinkCast(rule->get_handle())); + DefaultImplicator impl(&_as); + impl.implicand = bl->get_implicand(); + bl->imply(impl); + _fcmem.set_cur_rule(rule); + + _log->info("OUTPUTS"); + for (auto h : impl.result_list) + _log->info("%s", h->toString().c_str()); + + _fcmem.add_rules_product(0, impl.result_list); + } + +} + +HandleSeq ForwardChainer::get_chaining_result() +{ + return _fcmem.get_result(); +} diff --git a/pool/shard011/C++/0121921_CreateStandardMatrix.cc b/pool/shard011/C++/0121921_CreateStandardMatrix.cc new file mode 100644 index 0000000000000000000000000000000000000000..c7348e8c7501698eb8a4b8af57093f5b1bdfa9eb --- /dev/null +++ b/pool/shard011/C++/0121921_CreateStandardMatrix.cc @@ -0,0 +1,73 @@ +/* + For more information, please see: http://software.sci.utah.edu + + The MIT License + + Copyright (c) 2020 Scientific Computing and Imaging Institute, + University of Utah. + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ + + +#include +#include +#include +#include +#include + + +using namespace SCIRun::Modules::Math; +using namespace SCIRun::Dataflow::Networks; +using namespace SCIRun::Core::Algorithms::Math; +using namespace SCIRun::Core::Datatypes; +using namespace SCIRun::Core::Algorithms; + + +MODULE_INFO_DEF(CreateStandardMatrix,Math,SCIRun); + +CreateStandardMatrix::CreateStandardMatrix() : Module(staticInfo_) +{ + INITIALIZE_PORT(OutputMatrix); +} + +void CreateStandardMatrix::setStateDefaults() +{ + setStateStringFromAlgoOption(Parameters::MatrixType); + setStateIntFromAlgo(Parameters::Rows); + setStateIntFromAlgo(Parameters::Columns); + setStateDoubleFromAlgo(Parameters::Size); + setStateDoubleFromAlgo(Parameters::StartPointer); +} + +void CreateStandardMatrix::execute() +{ + if(needToExecute()) + { + setAlgoOptionFromState(Parameters::MatrixType); + setAlgoIntFromState(Parameters::Rows); + setAlgoIntFromState(Parameters::Columns); + setAlgoDoubleFromState(Parameters::Size); + setAlgoDoubleFromState(Parameters::StartPointer); + + AlgorithmInput input; + auto output=algo().run(input); + sendOutputFromAlgorithm(OutputMatrix,output); + } +} diff --git a/pool/shard011/C++/0121922_mrg3.cc b/pool/shard011/C++/0121922_mrg3.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a710bc73b678595cc8cab5205d0505cf843d4c8 --- /dev/null +++ b/pool/shard011/C++/0121922_mrg3.cc @@ -0,0 +1,122 @@ +// Copyright (c) 2000-2011, Heiko Bauke +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// +// * Neither the name of the copyright holder nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED +// OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +namespace trng { + + // Uniform random number generator concept + + // Parameter and status classes + + // EqualityComparable concept + bool operator==(const mrg3::parameter_type &P1, + const mrg3::parameter_type &P2) { + return P1.a1==P2.a1 and P1.a2==P2.a2 and P1.a3==P2.a3; + } + + bool operator!=(const mrg3::parameter_type &P1, + const mrg3::parameter_type &P2) { + return not (P1==P2); + } + + // Equality comparable concept + bool operator==(const mrg3::status_type &S1, + const mrg3::status_type &S2) { + return S1.r1==S2.r1 and S1.r2==S2.r2 and S1.r3==S2.r3; + } + + bool operator!=(const mrg3::status_type &S1, + const mrg3::status_type &S2) { + return not (S1==S2); + } + + const mrg3::parameter_type + mrg3::LEcuyer1=parameter_type(2021422057l, 1826992351l, 1977753457l); + const mrg3::parameter_type + mrg3::LEcuyer2=parameter_type(1476728729l, 0l, 1155643113l); + const mrg3::parameter_type + mrg3::LEcuyer3=parameter_type(65338l, 0l, 64636l); + + // Random number engine concept + mrg3::mrg3(mrg3::parameter_type P) : + P(P), S() { } + + mrg3::mrg3(unsigned long s, mrg3::parameter_type P) : + P(P), S() { + seed(s); + } + + void mrg3::seed() { + (*this)=mrg3(); + } + + void mrg3::seed(unsigned long s) { + long long t=s; + t%=modulus; + if (t<0) + t+=modulus; + S.r1=static_cast(t); + S.r2=1; + S.r3=1; + } + + void mrg3::seed(mrg3::result_type s1, mrg3::result_type s2, + mrg3::result_type s3) { + S.r1=s1%modulus; + if (S.r1<0) + S.r1+=modulus; + S.r2=s2%modulus; + if (S.r2<0) + S.r2+=modulus; + S.r3=s3%modulus; + if (S.r3<0) + S.r3+=modulus; + } + + // Equality comparable concept + bool operator==(const mrg3 &R1, const mrg3 &R2) { + return R1.P==R2.P and R1.S==R2.S; + } + + bool operator!=(const mrg3 &R1, const mrg3 &R2) { + return not (R1==R2); + } + + // other useful methods + const char * const mrg3::name_str="mrg3"; + + const char * mrg3::name() { + return name_str; + } + +} diff --git a/pool/shard011/C++/0121928_IInputPin.cpp b/pool/shard011/C++/0121928_IInputPin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bef25f16711ca9dc3049cd26571ce423a4019d81 --- /dev/null +++ b/pool/shard011/C++/0121928_IInputPin.cpp @@ -0,0 +1,133 @@ +#include "IInputPin.h" +#include "DataConsumer.h" + +using namespace plv; + +IInputPin::IInputPin( const QString& name, DataConsumer* consumer, + Required required, Synchronized sync ) : + Pin( name, consumer ), + m_consumer( consumer ), + m_required( required ), + m_synchronous( sync ) +{ + assert( m_consumer != 0 ); +} + +IInputPin::~IInputPin() +{ + m_consumer = 0; +} + +/** Connects this pin through the given connection. + * @require !this->isConnected() + * @ensure this->isConnected(); + */ +void IInputPin::setConnection(PinConnection* connection) +{ + assert(!this->isConnected()); + assert(connection != 0); + + m_connection = connection; + m_consumer->onInputConnectionSet(this,connection); +} + +void IInputPin::removeConnection() +{ + assert( m_connection.isNotNull() ); + PinConnection* con = m_connection; + m_connection.set( 0 ); + m_consumer->onInputConnectionRemoved(this, con); +} + +PinConnection* IInputPin::getConnection() const +{ + assert( m_connection.isNotNull() ); + return m_connection.getPtr(); +} + +bool IInputPin::isConnected() const +{ + return this->m_connection.isNotNull(); +} + +bool IInputPin::hasData() const +{ + if( m_connection.isNotNull() ) + { + return this->m_connection->hasData(); + } + return false; +} + +bool IInputPin::fastforward( unsigned int target ) +{ + return m_connection->fastforward( target ); +} + +void IInputPin::flushConnection() +{ + m_connection->flush(); +} + +void IInputPin::peekNext( unsigned int& serial, bool& isNull ) const +{ + assert( m_connection != 0 ); + m_connection->peek(serial, isNull); +} + +void IInputPin::pre() +{ + m_called = false; +} + +void IInputPin::post() +{ + // check if mandatory get() method has been called and + // data has been removed from this pin + if( this->isConnected() && this->isSynchronous() ) + { + if( !m_called ) + { + QString msg = tr("Processor %1 did not call mandatory get() on input Pin %2.") + .arg(getOwner()->getName()) + .arg(getName()); + throw RuntimeError(msg, __FILE__, __LINE__); + } + } +} + +void IInputPin::removeFirst() +{ + assert(m_connection.isNotNull()); + m_connection->get(); +} + +void IInputPin::acceptData(const Data& data) +{ + m_consumer->newData(this, data.getSerial()); +} + +void IInputPin::getVariant(QVariant& v) +{ + // check if get is not called twice during one process call + if( m_called ) + { + QString msg = tr("Illegal: method get() called twice during process() " + "on InputPin %1 of processor %2.") + .arg(m_name) + .arg(m_consumer->getName()); + throw RuntimeError(msg,__FILE__, __LINE__ ); + } + m_called = true; + if( !(this->m_connection.isNotNull() && + this->m_connection->hasData() )) + { + QString msg = tr("Illegal: method get() called on InputPin which " + "has no data available. Pin name is %1 of processor %2") + .arg(m_name) + .arg(m_consumer->getName()); + throw RuntimeError(msg, __FILE__, __LINE__); + } + Data d = m_connection->get(); + v.setValue(d.getPayload()); +} diff --git a/pool/shard011/C++/0121929_accessmanager.cpp b/pool/shard011/C++/0121929_accessmanager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f8730e98869c423ac18b22dfb2cb23f9bf7970cc --- /dev/null +++ b/pool/shard011/C++/0121929_accessmanager.cpp @@ -0,0 +1,80 @@ +/* + * Copyright (C) by Krzesimir Nowak + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "cookiejar.h" +#include "accessmanager.h" +#include "utility.h" + +namespace OCC +{ + +AccessManager::AccessManager(QObject* parent) + : QNetworkAccessManager (parent) +{ +#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) && defined(Q_OS_MAC) + // FIXME Workaround http://stackoverflow.com/a/15707366/2941 https://bugreports.qt-project.org/browse/QTBUG-30434 + QNetworkProxy proxy = this->proxy(); + proxy.setHostName(" "); + setProxy(proxy); +#endif + // Atempt to workaround for https://github.com/owncloud/client/issues/3969 + setConfiguration(QNetworkConfiguration()); + setCookieJar(new CookieJar); +} + +void AccessManager::setRawCookie(const QByteArray &rawCookie, const QUrl &url) +{ + QNetworkCookie cookie(rawCookie.left(rawCookie.indexOf('=')), + rawCookie.mid(rawCookie.indexOf('=')+1)); + qDebug() << Q_FUNC_INFO << cookie.name() << cookie.value(); + QList cookieList; + cookieList.append(cookie); + + QNetworkCookieJar *jar = cookieJar(); + jar->setCookiesFromUrl(cookieList, url); +} + +QNetworkReply* AccessManager::createRequest(QNetworkAccessManager::Operation op, const QNetworkRequest& request, QIODevice* outgoingData) +{ + QNetworkRequest newRequest(request); + + if (newRequest.hasRawHeader("cookie")) { + // This will set the cookie into the QNetworkCookieJar which will then override the cookie header + setRawCookie(request.rawHeader("cookie"), request.url()); + } + + newRequest.setRawHeader(QByteArray("User-Agent"), Utility::userAgentString()); + + // Some firewalls reject requests that have a "User-Agent" but no "Accept" header + newRequest.setRawHeader(QByteArray("Accept"), "*/*"); + + QByteArray verb = newRequest.attribute(QNetworkRequest::CustomVerbAttribute).toByteArray(); + // For PROPFIND (assumed to be a WebDAV op), set xml/utf8 as content type/encoding + // This needs extension + if (verb == "PROPFIND") { + newRequest.setHeader( QNetworkRequest::ContentTypeHeader, QLatin1String("text/xml; charset=utf-8")); + } + return QNetworkAccessManager::createRequest(op, newRequest, outgoingData); +} + +} // namespace OCC diff --git a/pool/shard011/C++/0121930_divecomputerextradatamodel.cpp b/pool/shard011/C++/0121930_divecomputerextradatamodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d2d43ce2e2ab2f30fbf433aad77ccb6811a9e2ef --- /dev/null +++ b/pool/shard011/C++/0121930_divecomputerextradatamodel.cpp @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0 +#include "qt-models/divecomputerextradatamodel.h" +#include "core/dive.h" +#include "core/metrics.h" + + +ExtraDataModel::ExtraDataModel(QObject *parent) : CleanerTableModel(parent), + rows(0) +{ + //enum Column {KEY, VALUE}; + setHeaderDataStrings(QStringList() << tr("Key") << tr("Value")); +} + +void ExtraDataModel::clear() +{ + if (rows > 0) { + beginRemoveRows(QModelIndex(), 0, rows - 1); + endRemoveRows(); + } +} + +QVariant ExtraDataModel::data(const QModelIndex &index, int role) const +{ + QVariant ret; + struct extra_data *ed = get_dive_dc(&displayed_dive, dc_number)->extra_data; + int i = -1; + while (ed && ++i < index.row()) + ed = ed->next; + if (!ed) + return ret; + + switch (role) { + case Qt::FontRole: + ret = defaultModelFont(); + break; + case Qt::TextAlignmentRole: + ret = int(Qt::AlignLeft | Qt::AlignVCenter); + break; + case Qt::DisplayRole: + switch (index.column()) { + case KEY: + ret = QString(ed->key); + break; + case VALUE: + ret = QString(ed->value); + break; + } + break; + } + return ret; +} + +int ExtraDataModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return rows; +} + +void ExtraDataModel::updateDive() +{ + clear(); + rows = 0; + struct extra_data *ed = get_dive_dc(&displayed_dive, dc_number)->extra_data; + while (ed) { + rows++; + ed = ed->next; + } + if (rows > 0) { + beginInsertRows(QModelIndex(), 0, rows - 1); + endInsertRows(); + } +} diff --git a/pool/shard011/C++/0121932_robotCommunicator.cpp b/pool/shard011/C++/0121932_robotCommunicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8254304df0839e9e23b164531fa96b97dd18323e --- /dev/null +++ b/pool/shard011/C++/0121932_robotCommunicator.cpp @@ -0,0 +1,92 @@ +/* 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 + +#include "utils/robotCommunication/robotCommunicator.h" + +#include +#include + +using namespace utils::robotCommunication; + +RobotCommunicator::RobotCommunicator(QObject *parent) + : QObject(parent) + , mRobotCommunicationThreadObject(nullptr) +{ +} + +RobotCommunicator::~RobotCommunicator() +{ + if (mRobotCommunicationThreadObject) { + mRobotCommunicationThreadObject->allowLongJobs(false); + } + + mRobotCommunicationThread.quit(); + mRobotCommunicationThread.wait(); + delete mRobotCommunicationThreadObject; +} + +void RobotCommunicator::send(QObject *addressee, const QByteArray &buffer, const unsigned responseSize) +{ + mRobotCommunicationThreadObject->send(addressee, buffer, responseSize); +} + +void RobotCommunicator::send(const QByteArray &buffer, const unsigned responseSize, QByteArray &outputBuffer) +{ + mRobotCommunicationThreadObject->send(buffer, responseSize, outputBuffer); +} + +void RobotCommunicator::connect() +{ + mRobotCommunicationThreadObject->connect(); +} + +void RobotCommunicator::disconnect() +{ + mRobotCommunicationThreadObject->disconnect(); +} + +void RobotCommunicator::checkConsistency() +{ + if (mRobotCommunicationThreadObject) { + mRobotCommunicationThreadObject->checkConsistency(); + } +} + +void RobotCommunicator::setRobotCommunicationThreadObject(RobotCommunicationThreadInterface *robotCommunication) +{ + if (mRobotCommunicationThreadObject) { + mRobotCommunicationThreadObject->allowLongJobs(false); + } + + mRobotCommunicationThread.quit(); + mRobotCommunicationThread.wait(); + delete mRobotCommunicationThreadObject; + mRobotCommunicationThreadObject = robotCommunication; + mRobotCommunicationThreadObject->moveToThread(&mRobotCommunicationThread); + mRobotCommunicationThreadObject->allowLongJobs(); + mRobotCommunicationThread.start(); + + QObject::connect(mRobotCommunicationThreadObject, &RobotCommunicationThreadInterface::connected + , this, &RobotCommunicator::connected); + QObject::connect(mRobotCommunicationThreadObject, &RobotCommunicationThreadInterface::disconnected + , this, &RobotCommunicator::disconnected); + QObject::connect(mRobotCommunicationThreadObject, &RobotCommunicationThreadInterface::response + , this, &RobotCommunicator::response); + QObject::connect(mRobotCommunicationThreadObject, &RobotCommunicationThreadInterface::errorOccured + , this, &RobotCommunicator::errorOccured); + + mRobotCommunicationThreadObject->checkConsistency(); +} diff --git a/pool/shard011/C++/0121933_packet.cpp b/pool/shard011/C++/0121933_packet.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dc1fddbe00dbc0aee2a218df009a82516b3f2f48 --- /dev/null +++ b/pool/shard011/C++/0121933_packet.cpp @@ -0,0 +1,77 @@ +/********************************************************************************* + * + * This file is part of ZelosOnline. + * + * ZelosOnline is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * ZelosOnline is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * Copyright 2013 Rafael Dominguez (npcdoom) + * + *********************************************************************************/ + +#include "packet.h" + +#include +#include +#include + +namespace srv_pkt +{ + void WriteNews (OPacket *pkt, const std::map &news) + { + pkt->WriteOpcode(SERVER_INFORMATION); + pkt->Write(0x00); + pkt->Write(news.size()); + + for (std::map::const_iterator i = news.begin(); i != news.end(); ++i) + { + pkt->Write(i->second.heading); + pkt->Write(i->second.message); + pkt->Write(0x07D8); + pkt->Write(i->second.month); //Month + pkt->Write(i->second.day); //Day + pkt->Write(0x0025000B); + pkt->Write(0xAFC00012); + pkt->Write(0x35D2); + } + } + + void WriteShards (OPacket *pkt, const std::string &name, const uint8_t locale, + const std::map &servers, const bool state) + { + pkt->WriteOpcode(SERVER_GAME_SERVER_LIST,ANSWER_ACCEPT); + pkt->Write(locale); + pkt->Write(name); + pkt->Write(0x00); + + for (std::map::const_iterator i = servers.begin(); i != servers.end(); ++i) + { + pkt->Write(i->second.is_new); + pkt->Write(i->second.id); + pkt->Write(i->second.name); + pkt->Write(i->second.usr_cnt); + pkt->Write(i->second.usr_max); + pkt->Write(state ? i->second.state : false); + } + + pkt->Write(0x00); + } + + void C5 (OPacket *pkt) + { + enum { LOGIN_ERROR_C5 = 4 }; + + pkt->WriteOpcode(SERVER_LOGIN,ANSWER_ERROR); + pkt->Write(LOGIN_ERROR_C5); + } +} diff --git a/pool/shard011/C++/0121934_remote_media_stream_impl.cc b/pool/shard011/C++/0121934_remote_media_stream_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..da684110f2e5dd34394c8118b055a298f3aa8634 --- /dev/null +++ b/pool/shard011/C++/0121934_remote_media_stream_impl.cc @@ -0,0 +1,220 @@ +// Copyright (c) 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "content/renderer/media/remote_media_stream_impl.h" + +#include + +#include "base/logging.h" +#include "base/strings/utf_string_conversions.h" +#include "content/renderer/media/media_stream_dependency_factory.h" +#include "content/renderer/media/media_stream_extra_data.h" +#include "third_party/WebKit/public/platform/WebString.h" + +namespace content { + +// RemoteMediaStreamTrackObserver is responsible for listening on change +// notification on a remote webrtc MediaStreamTrack and notify WebKit. +class RemoteMediaStreamTrackObserver + : NON_EXPORTED_BASE(public webrtc::ObserverInterface), + NON_EXPORTED_BASE(public base::NonThreadSafe) { + public: + RemoteMediaStreamTrackObserver( + webrtc::MediaStreamTrackInterface* webrtc_track, + const blink::WebMediaStreamTrack& webkit_track); + virtual ~RemoteMediaStreamTrackObserver(); + + webrtc::MediaStreamTrackInterface* observered_track() { + return webrtc_track_.get(); + } + const blink::WebMediaStreamTrack& webkit_track() { return webkit_track_; } + + private: + // webrtc::ObserverInterface implementation. + virtual void OnChanged() OVERRIDE; + + webrtc::MediaStreamTrackInterface::TrackState state_; + scoped_refptr webrtc_track_; + blink::WebMediaStreamTrack webkit_track_; + + DISALLOW_COPY_AND_ASSIGN(RemoteMediaStreamTrackObserver); +}; + +} // namespace content + +namespace { + +void InitializeWebkitTrack(webrtc::MediaStreamTrackInterface* track, + blink::WebMediaStreamTrack* webkit_track, + blink::WebMediaStreamSource::Type type) { + blink::WebMediaStreamSource webkit_source; + blink::WebString webkit_track_id(UTF8ToUTF16(track->id())); + + webkit_source.initialize(webkit_track_id, type, webkit_track_id); + webkit_track->initialize(webkit_track_id, webkit_source); + content::MediaStreamDependencyFactory::AddNativeTrackToBlinkTrack(track, + *webkit_track); +} + +content::RemoteMediaStreamTrackObserver* FindTrackObserver( + webrtc::MediaStreamTrackInterface* track, + const ScopedVector& observers) { + ScopedVector::const_iterator it = + observers.begin(); + for (; it != observers.end(); ++it) { + if ((*it)->observered_track() == track) + return *it; + } + return NULL; +} + +} // namespace anonymous + +namespace content { + +RemoteMediaStreamTrackObserver::RemoteMediaStreamTrackObserver( + webrtc::MediaStreamTrackInterface* webrtc_track, + const blink::WebMediaStreamTrack& webkit_track) + : state_(webrtc_track->state()), + webrtc_track_(webrtc_track), + webkit_track_(webkit_track) { + webrtc_track->RegisterObserver(this); +} + +RemoteMediaStreamTrackObserver::~RemoteMediaStreamTrackObserver() { + webrtc_track_->UnregisterObserver(this); +} + +void RemoteMediaStreamTrackObserver::OnChanged() { + DCHECK(CalledOnValidThread()); + + webrtc::MediaStreamTrackInterface::TrackState state = webrtc_track_->state(); + if (state == state_) + return; + + state_ = state; + switch (state) { + case webrtc::MediaStreamTrackInterface::kInitializing: + // Ignore the kInitializing state since there is no match in + // WebMediaStreamSource::ReadyState. + break; + case webrtc::MediaStreamTrackInterface::kLive: + webkit_track_.source().setReadyState( + blink::WebMediaStreamSource::ReadyStateLive); + break; + case webrtc::MediaStreamTrackInterface::kEnded: + webkit_track_.source().setReadyState( + blink::WebMediaStreamSource::ReadyStateEnded); + break; + default: + NOTREACHED(); + break; + } +} + +RemoteMediaStreamImpl::RemoteMediaStreamImpl( + webrtc::MediaStreamInterface* webrtc_stream) + : webrtc_stream_(webrtc_stream) { + webrtc_stream_->RegisterObserver(this); + + webrtc::AudioTrackVector webrtc_audio_tracks = + webrtc_stream_->GetAudioTracks(); + blink::WebVector webkit_audio_tracks( + webrtc_audio_tracks.size()); + + // Initialize WebKit audio tracks. + size_t i = 0; + for (; i < webrtc_audio_tracks.size(); ++i) { + webrtc::AudioTrackInterface* audio_track = webrtc_audio_tracks[i]; + DCHECK(audio_track); + InitializeWebkitTrack(audio_track, &webkit_audio_tracks[i], + blink::WebMediaStreamSource::TypeAudio); + audio_track_observers_.push_back( + new RemoteMediaStreamTrackObserver(audio_track, + webkit_audio_tracks[i])); + } + + // Initialize WebKit video tracks. + webrtc::VideoTrackVector webrtc_video_tracks = + webrtc_stream_->GetVideoTracks(); + blink::WebVector webkit_video_tracks( + webrtc_video_tracks.size()); + for (i = 0; i < webrtc_video_tracks.size(); ++i) { + webrtc::VideoTrackInterface* video_track = webrtc_video_tracks[i]; + DCHECK(video_track); + InitializeWebkitTrack(video_track, &webkit_video_tracks[i], + blink::WebMediaStreamSource::TypeVideo); + video_track_observers_.push_back( + new RemoteMediaStreamTrackObserver(video_track, + webkit_video_tracks[i])); + } + + webkit_stream_.initialize(UTF8ToUTF16(webrtc_stream->label()), + webkit_audio_tracks, webkit_video_tracks); + webkit_stream_.setExtraData(new MediaStreamExtraData(webrtc_stream, false)); +} + +RemoteMediaStreamImpl::~RemoteMediaStreamImpl() { + webrtc_stream_->UnregisterObserver(this); +} + +void RemoteMediaStreamImpl::OnChanged() { + // Find removed audio tracks. + ScopedVector::iterator audio_it = + audio_track_observers_.begin(); + while (audio_it != audio_track_observers_.end()) { + std::string track_id = (*audio_it)->observered_track()->id(); + if (webrtc_stream_->FindAudioTrack(track_id) == NULL) { + webkit_stream_.removeTrack((*audio_it)->webkit_track()); + audio_it = audio_track_observers_.erase(audio_it); + } else { + ++audio_it; + } + } + + // Find removed video tracks. + ScopedVector::iterator video_it = + video_track_observers_.begin(); + while (video_it != video_track_observers_.end()) { + std::string track_id = (*video_it)->observered_track()->id(); + if (webrtc_stream_->FindVideoTrack(track_id) == NULL) { + webkit_stream_.removeTrack((*video_it)->webkit_track()); + video_it = video_track_observers_.erase(video_it); + } else { + ++video_it; + } + } + + // Find added audio tracks. + webrtc::AudioTrackVector webrtc_audio_tracks = + webrtc_stream_->GetAudioTracks(); + for (webrtc::AudioTrackVector::iterator it = webrtc_audio_tracks.begin(); + it != webrtc_audio_tracks.end(); ++it) { + if (!FindTrackObserver(*it, audio_track_observers_)) { + blink::WebMediaStreamTrack new_track; + InitializeWebkitTrack(*it, &new_track, + blink::WebMediaStreamSource::TypeAudio); + audio_track_observers_.push_back( + new RemoteMediaStreamTrackObserver(*it, new_track)); + webkit_stream_.addTrack(new_track); + } + } + + // Find added video tracks. + webrtc::VideoTrackVector webrtc_video_tracks = + webrtc_stream_->GetVideoTracks(); + for (webrtc::VideoTrackVector::iterator it = webrtc_video_tracks.begin(); + it != webrtc_video_tracks.end(); ++it) { + if (!FindTrackObserver(*it, video_track_observers_)) { + blink::WebMediaStreamTrack new_track; + InitializeWebkitTrack(*it, &new_track, + blink::WebMediaStreamSource::TypeVideo); + video_track_observers_.push_back( + new RemoteMediaStreamTrackObserver(*it, new_track)); + webkit_stream_.addTrack(new_track); + } + } +} + +} // namespace content diff --git a/pool/shard011/C++/0121935_flavor.cpp b/pool/shard011/C++/0121935_flavor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2081f699841f0a300c1778eb4e49118fe04aa982 --- /dev/null +++ b/pool/shard011/C++/0121935_flavor.cpp @@ -0,0 +1,47 @@ +#include "flavor.h" + +#include + +Flavor::Flavor(FlavorProperties flavor) :m_properties(new FlavorProperties(flavor)) +{ + +} + +Flavor::~Flavor() +{ + delete m_properties; +} + +QString Flavor::GetFlavorName() const +{ + return m_properties->GetOptionName(); +} + +QString Flavor::GetFlavorImageUrl() const +{ + return m_properties->GetOptionImageUrl(); +} + +QList Flavor::GetFlavorOptions() const +{ + QList optionList; + + QList::const_iterator i; + + for (i = m_options.begin(); i != m_options.end(); i++) + { + optionList.append(&(*i)); + qDebug() << i->GetOptionImageUrl(); + + } + + + return optionList; +} + +void Flavor::AddFlavorOption(FlavorProperties option) +{ + m_options.append(option); +} + + diff --git a/pool/shard011/C++/0121936_smb_credentials_dialog.cc b/pool/shard011/C++/0121936_smb_credentials_dialog.cc new file mode 100644 index 0000000000000000000000000000000000000000..0e64776606ec919f050c9a217bbd085f0c089bc4 --- /dev/null +++ b/pool/shard011/C++/0121936_smb_credentials_dialog.cc @@ -0,0 +1,139 @@ +// Copyright (c) 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_credentials_dialog.h" + +#include + +#include "base/bind.h" +#include "base/json/json_writer.h" +#include "chrome/browser/ui/webui/chromeos/smb_shares/smb_handler.h" +#include "chrome/common/webui_url_constants.h" +#include "chrome/grit/browser_resources.h" +#include "chrome/grit/generated_resources.h" +#include "components/strings/grit/components_strings.h" +#include "content/public/browser/web_ui.h" +#include "content/public/browser/web_ui_data_source.h" + +namespace chromeos { +namespace smb_dialog { +namespace { + +constexpr int kSmbCredentialsDialogHeight = 250; + +void AddSmbCredentialsDialogStrings(content::WebUIDataSource* html_source) { + static const struct { + const char* name; + int id; + } localized_strings[] = { + {"smbCredentialsDialogTitle", IDS_SMB_SHARES_CREDENTIALS_DIALOG_TITLE}, + {"smbCredentialsUsername", IDS_SMB_SHARES_CREDENTIALS_USERNAME}, + {"smbCredentialsPassword", IDS_SMB_SHARES_CREDENTIALS_PASSWORD}, + {"save", IDS_SAVE}, + {"cancel", IDS_CANCEL}, + }; + for (const auto& entry : localized_strings) { + html_source->AddLocalizedString(entry.name, entry.id); + } +} + +std::string GetDialogId(const std::string& mount_id) { + return chrome::kChromeUISmbCredentialsURL + mount_id; +} + +SmbCredentialsDialog* GetDialog(const std::string& id) { + return static_cast( + SystemWebDialogDelegate::FindInstance(id)); +} + +} // namespace + +// static +void SmbCredentialsDialog::Show(const std::string& mount_id, + const std::string& share_path, + RequestCallback callback) { + // If an SmbCredentialsDialog is already opened for |mount_id|, focus that + // dialog rather than opening a second one. + SmbCredentialsDialog* dialog = GetDialog(GetDialogId(mount_id)); + if (dialog) { + // Replace the dialog's callback so that is responds to the most recent + // request. + dialog->callback_ = std::move(callback); + dialog->Focus(); + return; + } + + dialog = new SmbCredentialsDialog(mount_id, share_path, std::move(callback)); + dialog->ShowSystemDialog(); +} + +SmbCredentialsDialog::SmbCredentialsDialog(const std::string& mount_id, + const std::string& share_path, + RequestCallback callback) + : SystemWebDialogDelegate(GURL(GetDialogId(mount_id)), + base::string16() /* title */), + mount_id_(mount_id), + share_path_(share_path), + callback_(std::move(callback)) {} + +SmbCredentialsDialog::~SmbCredentialsDialog() { + if (callback_) { + std::move(callback_).Run(true /* canceled */, std::string() /* username */, + std::string() /* password */); + } +} + +void SmbCredentialsDialog::Respond(const std::string& username, + const std::string& password) { + DCHECK(callback_); + std::move(callback_).Run(false /* canceled */, username, password); +} + +void SmbCredentialsDialog::GetDialogSize(gfx::Size* size) const { + size->SetSize(SystemWebDialogDelegate::kDialogWidth, + kSmbCredentialsDialogHeight); +} + +std::string SmbCredentialsDialog::GetDialogArgs() const { + base::DictionaryValue args; + args.SetKey("mid", base::Value(mount_id_)); + args.SetKey("path", base::Value(share_path_)); + std::string json; + base::JSONWriter::Write(args, &json); + return json; +} + +SmbCredentialsDialogUI::SmbCredentialsDialogUI(content::WebUI* web_ui) + : ui::WebDialogUI(web_ui) { + content::WebUIDataSource* source = + content::WebUIDataSource::Create(chrome::kChromeUISmbCredentialsHost); + + AddSmbCredentialsDialogStrings(source); + + source->UseStringsJs(); + source->SetDefaultResource(IDR_SMB_CREDENTIALS_DIALOG_CONTAINER_HTML); + source->AddResourcePath("smb_credentials_dialog.js", + IDR_SMB_CREDENTIALS_DIALOG_JS); + + web_ui->AddMessageHandler(std::make_unique( + Profile::FromWebUI(web_ui), + base::BindOnce(&SmbCredentialsDialogUI::OnUpdateCredentials, + base::Unretained(this)))); + + content::WebUIDataSource::Add(Profile::FromWebUI(web_ui), source); +} + +SmbCredentialsDialogUI::~SmbCredentialsDialogUI() = default; + +void SmbCredentialsDialogUI::OnUpdateCredentials(const std::string& username, + const std::string& password) { + SmbCredentialsDialog* dialog = + GetDialog(web_ui()->GetWebContents()->GetLastCommittedURL().spec()); + if (dialog) { + dialog->Respond(username, password); + } +} + +} // namespace smb_dialog +} // namespace chromeos diff --git a/pool/shard011/C++/0121937_Rammus.cpp b/pool/shard011/C++/0121937_Rammus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..90f522208b1492d4dc0d99be69a61305deb50820 --- /dev/null +++ b/pool/shard011/C++/0121937_Rammus.cpp @@ -0,0 +1,206 @@ +#pragma once +#include "BaseOptions.h" +#include "SpellLib.h" +#include "IChampion.h" +#include "OnRender.cpp" + +class Rammus : public IChampion +{ +public: + void Menu() override + { + MainMenu = GPluginSDK->AddMenu("RyTaks_Rammus"); + + ComboMenu = MainMenu->AddMenu("Combo Settings"); + ComboQ = ComboMenu->CheckBox("Use Q", true); + ComboW = ComboMenu->CheckBox("Use W", true); + ComboE = ComboMenu->CheckBox("Use E", true); + ComboR = ComboMenu->CheckBox("Use R", true); + + HarassMenu = MainMenu->AddMenu("Harass Settings"); + HarassQ = HarassMenu->CheckBox("Use Q", true); + HarassW = HarassMenu->CheckBox("Use W", true); + HarassE = HarassMenu->CheckBox("Use E", true); + HarassMana = HarassMenu->AddFloat("Min. Mana", 0, 100, 60); + + LaneClearMenu = MainMenu->AddMenu("Farm Settings"); + LaneClearQ = LaneClearMenu->CheckBox("Use Q", true); + LaneClearW = LaneClearMenu->CheckBox("Use W", true); + LaneClearE = LaneClearMenu->CheckBox("Use E", true); + LaneClearMana = LaneClearMenu->AddFloat("Min. Mana", 0, 100, 40); + + KSMenu = MainMenu->AddMenu("Killsteal Settings"); + KSQ = KSMenu->CheckBox("Killsteal with Q", true); + KSW = KSMenu->CheckBox("Killsteal with W", true); + KSE = KSMenu->CheckBox("Killsteal with E", true); + KSR = KSMenu->CheckBox("Killsteal with R", true); + + DrawMenu = MainMenu->AddMenu("Drawing Settings"); + DrawReady = DrawMenu->CheckBox("Draw Only Ready Spells", true); + DrawOff = DrawMenu->CheckBox("Disable Drawings", false); + DrawQ = DrawMenu->CheckBox("Draw Q", true); + DrawW = DrawMenu->CheckBox("Draw W", true); + DrawE = DrawMenu->CheckBox("Draw E", true); + DrawR = DrawMenu->CheckBox("Draw R", true); + + } + + void Spells() override + { + SpellLib().Rammus(); + } + + void Combo(IUnit* Target) override + { + if (GOrbwalking->GetOrbwalkingMode() == kModeCombo) + { + Target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); + for (auto Target : GEntityList->GetAllHeros(false, true)) + { + if (ComboQ->Enabled() && Q->IsReady()) + { + Q->CastOnTarget(Target); + } + if (ComboW->Enabled() && W->IsReady()) + { + W->CastOnTarget(Target); + } + if (ComboE->Enabled() && E->IsReady()) + { + E->CastOnTarget(Target); + } + } + } + + } + + void Harass(IUnit* Target) override + { + if (GOrbwalking->GetOrbwalkingMode() == kModeMixed && GEntityList->Player()->ManaPercent() >= HarassMana->GetInteger()) + { + Target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); + for (auto Target : GEntityList->GetAllHeros(false, true)) + { + if (HarassQ->Enabled() && Q->IsReady() && GEntityList->Player()->ManaPercent() >= HarassMana->GetInteger()) + { + Q->CastOnTarget(Target); + } + if (HarassW->Enabled() && W->IsReady() && GEntityList->Player()->ManaPercent() >= HarassMana->GetInteger()) + { + W->CastOnTarget(Target); + } + if (HarassE->Enabled() && E->IsReady() && GEntityList->Player()->ManaPercent() >= HarassMana->GetInteger()) + { + E->CastOnTarget(Target); + } + } + } + } + + void LaneClear(IUnit* Target) override + { + if (GOrbwalking->GetOrbwalkingMode() == kModeLaneClear) + { + if (GEntityList->Player()->ManaPercent() >= LaneClearMana->GetFloat()) + { + minion = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); + for (auto minion : GEntityList->GetAllMinions(false, true, true)) + { + if (minion->IsTarget(GEntityList->Player()) && !minion->IsDead() && GEntityList->Player()->IsValidTarget(minion, Q->Range())) + { + if (LaneClearQ->Enabled() && Q->IsReady()) + { + Q->CastOnTarget(minion); + } + if (LaneClearW->Enabled() && W->IsReady()) + { + E->CastOnTarget(minion); + } + if (LaneClearE->Enabled() && E->IsReady()) + { + E->CastOnTarget(minion); + } + } + } + } + } + } + + void KS(IUnit* Target) override + { + Target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); + for (auto Target : GEntityList->GetAllHeros(false, true)) + { + if (Target != nullptr && !Target->IsDead()) + { + if (KSQ->Enabled() && Q->IsReady()) + { + auto dmg = GHealthPrediction->GetKSDamage(Target, kSlotQ, Q->GetDelay(), false); + if (Target->GetHealth() <= dmg) + { + Q->CastOnTarget(Target, kHitChanceHigh); + } + } + if (KSW->Enabled() && W->IsReady()) + { + auto dmg = GHealthPrediction->GetKSDamage(Target, kSlotW, W->GetDelay(), false); + if (Target->GetHealth() <= dmg) + { + W->CastOnTarget(Target, kHitChanceHigh); + } + } + if (KSE->Enabled() && E->IsReady()) + { + auto dmg = GHealthPrediction->GetKSDamage(Target, kSlotE, E->GetDelay(), false); + if (Target->GetHealth() <= dmg) + { + E->CastOnTarget(Target, kHitChanceHigh); + } + } + if (KSR->Enabled() && R->IsReady()) + { + auto dmg = GHealthPrediction->GetKSDamage(Target, kSlotR, R->GetDelay(), false); + if (Target->GetHealth() <= dmg) + { + R->CastOnPlayer(); + } + } + } + } + } + + void OnRender() override + { + OnRenderClass().Render(); + } + + void BeforeAttack(IUnit* Source, IUnit* Target) override + { + + } + + void AfterAttack(IUnit* Source, IUnit* Target) override + { + + } + + void OnGapCloser(GapCloserSpell const& Args) override + { + + } + + void OnProcessSpell(CastedSpell const& Args) override + { + + } + + void RRange() override + { + + } + + void RDamage() override + { + + } +}; \ No newline at end of file diff --git a/pool/shard011/C++/0121939_count_triplets.cpp b/pool/shard011/C++/0121939_count_triplets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c65382a13b902c120e4146eaf8fcf77a9e7e3d55 --- /dev/null +++ b/pool/shard011/C++/0121939_count_triplets.cpp @@ -0,0 +1,63 @@ +/********************************************************************* +Count the triplets +------------------ + +For the given array of distinct integers count all the triplets such +that the sum of two elements equals the third element. + +This file is covered by the LICENSE file in the root of this project. +**********************************************************************/ + +#include "base.hpp" +#include +#include +#include + +template +std::size_t count_sums(It first, It last, T sum) +{ + if (first == last) + return 0; + + std::size_t count = 0; + + --last; + while (first != last) + { + const auto s = *first + *last; + if (s == sum) + ++count; + + if (s < sum) + ++first; + else // s >= sum + --last; + } + + return count; +} + +class CP : public CP1 +{ +private: + virtual void read_input() override + { + read_size_vec(seq_); + } + + virtual void solve(unsigned int) override + { + std::sort(seq_.begin(), seq_.end()); + + std::size_t triplet_count = 0; + for (auto it = seq_.begin(); it != seq_.end(); ++it) + triplet_count += count_sums(seq_.begin(), seq_.end(), *it); + + write_ln(triplet_count); + } + +private: + std::vector seq_; +}; + +MAIN diff --git a/pool/shard011/C++/0121940_OPCommand.cc b/pool/shard011/C++/0121940_OPCommand.cc new file mode 100644 index 0000000000000000000000000000000000000000..e34a4fefbd2479d973b35a8a95dab155d5b17071 --- /dev/null +++ b/pool/shard011/C++/0121940_OPCommand.cc @@ -0,0 +1,121 @@ +/** + * OPCommand.cc + * Cause the bot to op users on a specific channel + * + * 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. + * + * $Id: OPCommand.cc,v 1.16 2006/09/26 17:36:00 kewlio Exp $ + */ + +#include +#include +#include +#include "ccontrol.h" +#include "CControlCommands.h" +#include "StringTokenizer.h" +#include "Network.h" +#include "Constants.h" +#include "ccBadChannel.h" +#include "gnuworld_config.h" + +namespace gnuworld +{ + +using std::string ; + +namespace uworld +{ + +bool OPCommand::Exec( iClient* theClient, const string& Message ) +{ +bool foundUser = false; + +StringTokenizer st( Message ) ; +if( st.size() < 3 ) + { + Usage( theClient ) ; + return true ; + } + +if(st[1].size() > channel::MaxName) + { + bot->Notice(theClient,"Channel name can't be more than %d characters", + channel::MaxName); + return false; + } + +Channel* theChan = Network->findChannel( st[ 1 ] ) ; +if( NULL == theChan ) + { + bot->Notice( theClient, "Unable to find channel %s\n", + st[ 1 ].c_str() ) ; + return true ; + } + +ccBadChannel* Chan = bot->isBadChannel(st[1]); +if(Chan) + { + bot->Notice(theClient,"Sorry, but you can't change modes in " + "this channel because: %s", + Chan->getReason().c_str()); + return false; + } + +iClient* Target = 0; + +// Use a std::set<> here to ensure that the same user is not +// included more than once. + +bot->MsgChanLog("OP %s\n",st.assemble(1).c_str()); +string modes = "+"; +string args=""; + +for( StringTokenizer::size_type i = 2 ; i < st.size() ; ++i ) + { + Target = Network->findNick( st[ i ] ) ; + if( 0 == Target ) + { + continue ; + } + + ChannelUser* tmpChanUser = theChan->findUser(Target) ; + if( 0 == tmpChanUser ) + { + continue ; + } + /* ok, the user is on the channel - flag it */ + foundUser = true; + modes +="o"; + args +=st[i]+ " "; + + } // for + +if (!foundUser) +{ + bot->Notice(theClient, "I'm sorry, I couldn't find anyone to op in %s!", + st[1].c_str()); + return false; +} +if( !args.empty() ) + { + bot->Mode(theChan,modes,args,true); + } +return true ; +} + +} +} // namespace gnuworld + diff --git a/pool/shard011/C++/0121941_interpolation.cpp b/pool/shard011/C++/0121941_interpolation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba34e0f6279d1007077ab3345db149356187a6ae --- /dev/null +++ b/pool/shard011/C++/0121941_interpolation.cpp @@ -0,0 +1,141 @@ +/* Copyright (c) 2010-2019, Delft University of Technology + * All rigths reserved + * + * This file is part of the Tudat. Redistribution and use in source and + * binary forms, with or without modification, are permitted exclusively + * under the terms of the Modified BSD license. You should have received + * a copy of the license with this file. If not, please or visit: + * http://tudat.tudelft.nl/LICENSE. + * + */ + +#include "Tudat/JsonInterface/Mathematics/interpolation.h" + +namespace tudat +{ + +namespace interpolators +{ + +// InterpolatorSettings + +//! Create a `json` object from a shared pointer to a `InterpolatorSettings` object. +void to_json( nlohmann::json& jsonObject, const std::shared_ptr< InterpolatorSettings >& interpolatorSettings ) +{ + if ( ! interpolatorSettings ) + { + return; + } + using namespace json_interface; + using K = Keys::Interpolation::Interpolator; + + const InterpolatorTypes interpolatorType = interpolatorSettings->getInterpolatorType( ); + jsonObject[ K::type ] = interpolatorType; + jsonObject[ K::lookupScheme ] = interpolatorSettings->getSelectedLookupScheme( ); + jsonObject[ K::useLongDoubleTimeStep ] = interpolatorSettings->getUseLongDoubleTimeStep( ); + jsonObject[ K::boundaryHandling ] = interpolatorSettings->getBoundaryHandling( ); + + switch ( interpolatorType ) + { + case linear_interpolator: + case cubic_spline_interpolator: + case hermite_spline_interpolator: + case piecewise_constant_interpolator: + return; + case lagrange_interpolator: + { + std::shared_ptr< LagrangeInterpolatorSettings > lagrangeInterpolatorSettings = + std::dynamic_pointer_cast< LagrangeInterpolatorSettings >( interpolatorSettings ); + assertNonnullptrPointer( lagrangeInterpolatorSettings ); + jsonObject[ K::order ] = lagrangeInterpolatorSettings->getInterpolatorOrder( ); + jsonObject[ K::lagrangeBoundaryHandling ] = lagrangeInterpolatorSettings->getLagrangeBoundaryHandling( ); + return; + } + default: + handleUnimplementedEnumValue( interpolatorType, oneDimensionalInterpolatorTypes, + unsupportedOneDimensionalInterpolatorTypes ); + } +} + +//! Create a shared pointer to a `InterpolatorSettings` object from a `json` object. +void from_json( const nlohmann::json& jsonObject, std::shared_ptr< InterpolatorSettings >& interpolatorSettings ) +{ + using namespace json_interface; + using K = Keys::Interpolation::Interpolator; + + // Get interpolator type + const InterpolatorTypes interpolatorType = + getValue< InterpolatorTypes >( jsonObject, K::type ); + + switch ( interpolatorType ) + { + case linear_interpolator: + case cubic_spline_interpolator: + case hermite_spline_interpolator: + case piecewise_constant_interpolator: + { + InterpolatorSettings defaults( linear_interpolator ); + interpolatorSettings = std::make_shared< InterpolatorSettings >( + interpolatorType, + getValue( jsonObject, K::lookupScheme, defaults.getSelectedLookupScheme( ) ), + getValue( jsonObject, K::useLongDoubleTimeStep, defaults.getUseLongDoubleTimeStep( ) ), + getValue( jsonObject, K::boundaryHandling, defaults.getBoundaryHandling( ) ) ); + return; + } + case lagrange_interpolator: + { + LagrangeInterpolatorSettings defaults( 0 ); + interpolatorSettings = std::make_shared< LagrangeInterpolatorSettings >( + getValue< double >( jsonObject, K::order ), + getValue( jsonObject, K::useLongDoubleTimeStep, defaults.getUseLongDoubleTimeStep( ) ), + getValue( jsonObject, K::lookupScheme, defaults.getSelectedLookupScheme( ) ), + getValue( jsonObject, K::lagrangeBoundaryHandling, defaults.getLagrangeBoundaryHandling( ) ) ); + return; + } + default: + handleUnimplementedEnumValue( interpolatorType, oneDimensionalInterpolatorTypes, + unsupportedOneDimensionalInterpolatorTypes ); + } +} + +} // namespace interpolators + + +namespace simulation_setup +{ + +// ModelInterpolationSettings + +//! Create a `json` object from a shared pointer to a `ModelInterpolationSettings` object. +void to_json( nlohmann::json& jsonObject, const std::shared_ptr< ModelInterpolationSettings >& modelInterpolationSettings ) +{ + if ( ! modelInterpolationSettings ) + { + return; + } + using namespace json_interface; + using K = Keys::Interpolation::ModelInterpolation; + + jsonObject[ K::initialTime ] = modelInterpolationSettings->initialTime_; + jsonObject[ K::finalTime ] = modelInterpolationSettings->finalTime_; + jsonObject[ K::timeStep ] = modelInterpolationSettings->timeStep_; + jsonObject[ K::interpolator ] = modelInterpolationSettings->interpolatorSettings_; +} + +//! Create a shared pointer to a `ModelInterpolationSettings` object from a `json` object. +void from_json( const nlohmann::json& jsonObject, std::shared_ptr< ModelInterpolationSettings >& modelInterpolationSettings ) +{ + using namespace json_interface; + using K = Keys::Interpolation::ModelInterpolation; + + ModelInterpolationSettings defaults; + modelInterpolationSettings = std::make_shared< ModelInterpolationSettings >( + getValue( jsonObject, K::initialTime, defaults.initialTime_ ), + getValue( jsonObject, K::finalTime, defaults.finalTime_ ), + getValue( jsonObject, K::timeStep, defaults.timeStep_ ), + getValue( jsonObject, K::interpolator, defaults.interpolatorSettings_ ) ); +} + +} // namespace simulation_setup + +} // namespace tudat diff --git a/pool/shard011/C++/0121942_qgeoareamonitor_simulator.cpp b/pool/shard011/C++/0121942_qgeoareamonitor_simulator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4218860e1b41b74fd1188a59443870e2e8b7a2fd --- /dev/null +++ b/pool/shard011/C++/0121942_qgeoareamonitor_simulator.cpp @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** 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 "qgeoareamonitor_simulator_p.h" + +QTM_BEGIN_NAMESPACE + +#define UPDATE_INTERVAL_5S 5000 + +QGeoAreaMonitorSimulator::QGeoAreaMonitorSimulator(QObject *parent) : QGeoAreaMonitor(parent) +{ + insideArea = false; + location = QGeoPositionInfoSource::createDefaultSource(this); + if(location) { + location->setUpdateInterval(UPDATE_INTERVAL_5S); + connect(location, SIGNAL(positionUpdated(QGeoPositionInfo)), + this, SLOT(positionUpdated(QGeoPositionInfo))); + location->startUpdates(); + } +} + +QGeoAreaMonitorSimulator::~QGeoAreaMonitorSimulator() +{ + if(location) + location->stopUpdates(); +} + +void QGeoAreaMonitorSimulator::setCenter(const QGeoCoordinate& coordinate) +{ + if (coordinate.isValid()) + QGeoAreaMonitor::setCenter(coordinate); +} + +void QGeoAreaMonitorSimulator::positionUpdated(const QGeoPositionInfo &info) +{ + qreal distance = info.coordinate().distanceTo(center()); + + if (distance <= QGeoAreaMonitor::radius()) { + if(!insideArea) + emit areaEntered(info); + insideArea = true; + } else if (insideArea) { + emit areaExited(info); + insideArea = false; + } +} + +#include "moc_qgeoareamonitor_simulator_p.cpp" +QTM_END_NAMESPACE diff --git a/pool/shard011/C++/0121943_BrewingRecipes.cpp b/pool/shard011/C++/0121943_BrewingRecipes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4c127649a839f8afe69d47cef58eeddc101fd883 --- /dev/null +++ b/pool/shard011/C++/0121943_BrewingRecipes.cpp @@ -0,0 +1,295 @@ + +#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules + +#include "BrewingRecipes.h" +#include "Item.h" + +#include + +#define BREWING_RECIPE_FILE "brewing.txt" + + + + + +typedef std::vector> RecipeList; + + + + + +struct cBrewingRecipes::sBrewingRecipeState +{ + RecipeList Recipes; +}; + + + + + +cBrewingRecipes::cBrewingRecipes() + : m_pState(new sBrewingRecipeState) +{ + ReloadRecipes(); +} + + + + + +cBrewingRecipes::~cBrewingRecipes() +{ + ClearRecipes(); +} + + + + + +void cBrewingRecipes::ReloadRecipes(void) +{ + ClearRecipes(); + LOGD("Loading brewing recipes..."); + + std::ifstream f(BREWING_RECIPE_FILE, std::ios::in); + if (!f.good()) + { + LOG("Could not open the brewing recipes file \"%s\". No brewing recipes are available.", BREWING_RECIPE_FILE); + return; + } + + unsigned int LineNum = 0; + AString ParsingLine; + + while (std::getline(f, ParsingLine)) + { + LineNum++; + // Remove comments from the line: + size_t FirstCommentSymbol = ParsingLine.find('#'); + if (FirstCommentSymbol != AString::npos) + { + ParsingLine.erase(ParsingLine.begin() += static_cast(FirstCommentSymbol), ParsingLine.end()); + } + + if (ParsingLine.empty()) + { + continue; + } + AddRecipeFromLine(ParsingLine, LineNum); + } // while (getline(ParsingLine)) + + LOG("Loaded " SIZE_T_FMT " brewing recipes", m_pState->Recipes.size()); +} + + + + + +void cBrewingRecipes::AddRecipeFromLine(const AString & a_Line, unsigned int a_LineNum) +{ + AString Line(a_Line); + Line.erase(std::remove_if(Line.begin(), Line.end(), isspace), Line.end()); + + short InputDamage; + short OutputDamage; + + std::unique_ptr InputItem = cpp14::make_unique(); + std::unique_ptr IngredientItem = cpp14::make_unique(); + std::unique_ptr OutputItem = cpp14::make_unique(); + + const AStringVector & InputAndIngredient = StringSplit(Line, "+"); + + if (InputAndIngredient.size() != 2) + { + LOGWARNING("brewing.txt: line %d: A line with '+' was expected", a_LineNum); + LOGINFO("Offending line: \"%s\"", a_Line.c_str()); + return; + } + + const AStringVector & IngredientAndOutput = StringSplit(InputAndIngredient[1].c_str(), "="); + if (IngredientAndOutput.size() != 2) + { + LOGWARNING("brewing.txt: line %d: A line with '=' was expected", a_LineNum); + LOGINFO("Offending line: \"%s\"", a_Line.c_str()); + return; + } + + if (!ParseItem(IngredientAndOutput[0], *IngredientItem)) + { + LOGWARNING("brewing.txt: Parsing of the item didn't worked."); + LOGINFO("Offending line: \"%s\"", a_Line.c_str()); + return; + } + + if (!StringToInteger(InputAndIngredient[0], InputDamage)) + { + LOGWARNING("brewing.txt: line %d: Cannot parse the damage value for the input item\"%s\".", a_LineNum, InputAndIngredient[0].c_str()); + LOGINFO("Offending line: \"%s\"", a_Line.c_str()); + return; + } + + if (!StringToInteger(IngredientAndOutput[1], OutputDamage)) + { + LOGWARNING("brewing.txt: line %d: Cannot parse the damage value for the output item\"%s\".", a_LineNum, IngredientAndOutput[1].c_str()); + LOGINFO("Offending line: \"%s\"", a_Line.c_str()); + return; + } + + // The items has always the same type + InputItem->m_ItemType = E_ITEM_POTION; + InputItem->m_ItemDamage = InputDamage; + + OutputItem->m_ItemType = E_ITEM_POTION; + OutputItem->m_ItemDamage = OutputDamage; + + std::unique_ptr Recipe = cpp14::make_unique(); + Recipe->Input = std::move(InputItem); + Recipe->Output = std::move(OutputItem); + Recipe->Ingredient = std::move(IngredientItem); + m_pState->Recipes.push_back(std::move(Recipe)); +} + + + + + +bool cBrewingRecipes::ParseItem(const AString & a_String, cItem & a_Item) +{ + return StringToItem(a_String, a_Item); +} + + + + + +void cBrewingRecipes::ClearRecipes(void) +{ + m_pState->Recipes.clear(); +} + + + + + +const cBrewingRecipes::cRecipe * cBrewingRecipes::GetRecipeFrom(const cItem & a_Input, const cItem & a_Ingredient) const +{ + for (auto & Recipe : m_pState->Recipes) + { + if ((Recipe->Input->IsEqual(a_Input)) && (Recipe->Ingredient->IsEqual(a_Ingredient))) + { + return Recipe.get(); + } + } + + // Check for gunpowder + if (a_Ingredient.m_ItemType == E_ITEM_GUNPOWDER) + { + if (a_Input.m_ItemDamage & 0x2000) + { + // Create new recipe and add it to list + std::unique_ptr InputItem = cpp14::make_unique(); + std::unique_ptr IngredientItem = cpp14::make_unique(); + std::unique_ptr OutputItem = cpp14::make_unique(); + + InputItem->m_ItemType = E_ITEM_POTION; + InputItem->m_ItemDamage = a_Input.m_ItemDamage; + OutputItem->m_ItemType = E_ITEM_POTION; + OutputItem->m_ItemDamage = a_Input.m_ItemDamage + 8192; + IngredientItem->m_ItemType = E_ITEM_GUNPOWDER; + + std::unique_ptr Recipe = cpp14::make_unique(); + Recipe->Input = std::move(InputItem); + Recipe->Output = std::move(OutputItem); + Recipe->Ingredient = std::move(IngredientItem); + m_pState->Recipes.push_back(std::move(Recipe)); + return Recipe.get(); + } + return nullptr; + } + + // Check for splash potion + if (a_Input.m_ItemDamage & 0x4000) + { + const std::unique_ptr * FoundRecipe = nullptr; + // Search for the drinkable potion, the ingredients are the same + short SplashItemDamage = a_Input.m_ItemDamage - 8192; + + for (auto & Recipe : m_pState->Recipes) + { + if ((Recipe->Input->m_ItemDamage == SplashItemDamage) && (Recipe->Ingredient->IsEqual(a_Ingredient))) + { + FoundRecipe = &Recipe; + break; + } + } + + if (FoundRecipe == nullptr) + { + return nullptr; + } + + // Create new recipe and add it to list + std::unique_ptr InputItem = cpp14::make_unique(); + std::unique_ptr IngredientItem = cpp14::make_unique(); + std::unique_ptr OutputItem = cpp14::make_unique(); + + InputItem->m_ItemType = E_ITEM_POTION; + InputItem->m_ItemDamage = a_Input.m_ItemDamage; + OutputItem->m_ItemType = E_ITEM_POTION; + OutputItem->m_ItemDamage = (*FoundRecipe)->Output->m_ItemDamage + 8192; + IngredientItem->m_ItemType = (*FoundRecipe)->Ingredient->m_ItemType; + + std::unique_ptr Recipe = cpp14::make_unique(); + Recipe->Input = std::move(InputItem); + Recipe->Output = std::move(OutputItem); + Recipe->Ingredient = std::move(IngredientItem); + m_pState->Recipes.push_back(std::move(Recipe)); + return Recipe.get(); + } + return nullptr; +} + + + + + + +bool cBrewingRecipes::IsIngredient(const cItem & a_Ingredient) const +{ + // Check for gunpowder + if (a_Ingredient.m_ItemType == E_ITEM_GUNPOWDER) + { + return true; + } + + for (auto & Recipe : m_pState->Recipes) + { + if (Recipe->Ingredient->IsEqual(a_Ingredient)) + { + return true; + } + } + return false; +} + + + + + +bool cBrewingRecipes::IsBottle(const cItem & a_Item) const +{ + return (a_Item.m_ItemType == E_ITEM_POTION); +} + + + + + +bool cBrewingRecipes::IsFuel(const cItem & a_Item) const +{ + return (a_Item.m_ItemType == E_ITEM_BLAZE_POWDER); +} + + + + diff --git a/pool/shard011/C++/0121944_Shape.cpp b/pool/shard011/C++/0121944_Shape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..888db22451529e6a0531fce7d25aa27f88558e2c --- /dev/null +++ b/pool/shard011/C++/0121944_Shape.cpp @@ -0,0 +1,87 @@ +/****************************************************************************** + + nomlib - C++11 cross-platform game engine + +Copyright (c) 2013, 2014 Jeffrey Carpenter +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +******************************************************************************/ +#include "nomlib/graphics/shapes/Shape.hpp" + +namespace nom { + +Shape::Shape ( void ) : + outline_color_ { Color4i::White }, + fill_color_ { Color4i::Black } +{ + NOM_LOG_TRACE_PRIO(NOM_LOG_CATEGORY_TRACE_RENDER, NOM_LOG_PRIORITY_VERBOSE); +} + +Shape::~Shape ( void ) +{ + NOM_LOG_TRACE_PRIO(NOM_LOG_CATEGORY_TRACE_RENDER, NOM_LOG_PRIORITY_VERBOSE); +} + +Shape::Shape ( const Shape& copy ) : + Transformable { copy.position(), copy.size() }, // Our base class + outline_color_ { copy.outline_color() }, + fill_color_ { copy.fill_color() } +{ + NOM_LOG_TRACE_PRIO(NOM_LOG_CATEGORY_TRACE_RENDER, NOM_LOG_PRIORITY_VERBOSE); +} + +/* +Shape& Shape::operator = ( const Shape& other ) +{ + this->color_ = other.color(); + + return *this; +} +*/ + +ObjectTypeInfo Shape::type( void ) const +{ + return NOM_OBJECT_TYPE_INFO( self_type ); +} + +const Color4i& Shape::outline_color ( void ) const +{ + return this->outline_color_; +} + +const Color4i& Shape::fill_color ( void ) const +{ + return this->fill_color_; +} + +void Shape::set_outline_color ( const Color4i& color ) +{ + this->outline_color_ = color; +} + +void Shape::set_fill_color ( const Color4i& color ) +{ + this->fill_color_ = color; +} + +} // namespace nom diff --git a/pool/shard011/C++/0121945_perfdata_reader_test.cc b/pool/shard011/C++/0121945_perfdata_reader_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8faecaa80e7c591148b6ddcd345365ecdf8c18e --- /dev/null +++ b/pool/shard011/C++/0121945_perfdata_reader_test.cc @@ -0,0 +1,136 @@ +#include "perfdata_reader.h" + +#include + +#include "gmock/gmock.h" +#include "gtest/gtest.h" +#include "third_party/abseil/absl/flags/flag.h" +#include "third_party/abseil/absl/strings/match.h" +#include "third_party/abseil/absl/strings/str_cat.h" + +#define FLAGS_test_tmpdir std::string(testing::UnitTest::GetInstance()->original_working_dir()) + +#define FLAGS_test_srcdir std::string(testing::UnitTest::GetInstance()->original_working_dir()) + +namespace { + +TEST(PerfdataReaderTest, SelectBinaryInfo_buildid) { + const std::string binary = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "llvm_function_samples.binary"); + auto reader = devtools_crosstool_autofdo::PerfDataReader(); + devtools_crosstool_autofdo::BinaryInfo binary_info; + reader.SelectBinaryInfo(binary, &binary_info); + EXPECT_STREQ(binary_info.build_id.c_str(), + "a56e4274b3adf7c87d165ca6deb66db002e72e1e"); +} + +// propeller_sample_with_two_same_binaries.perfdata contains buildid list: +// 04e6da50a63d4b859b0be7e235937cd5a7996ecf .../propeller_sample_1.bin +// 04e6da50a63d4b859b0be7e235937cd5a7996ecf .../propeller_sample_2.bin +TEST(PerfdataReaderTest, SelectBinaryInfo_duplicated_binaries) { + const std::string binary = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "propeller_sample.bin"); + const std::string perfdata = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "propeller_sample_with_two_same_binaries.perfdata"); + auto reader = devtools_crosstool_autofdo::PerfDataReader(); + devtools_crosstool_autofdo::BinaryPerfInfo bpi; + devtools_crosstool_autofdo::BinaryInfo &binary_info = bpi.binary_info; + reader.SelectBinaryInfo(binary, &binary_info); + EXPECT_STREQ(binary_info.build_id.c_str(), + "04e6da50a63d4b859b0be7e235937cd5a7996ecf"); + EXPECT_TRUE(reader.SelectPerfInfo(perfdata, "", &bpi)); + + EXPECT_EQ(bpi.binary_mmaps.size(), 2); + auto &mmap_set1 = bpi.binary_mmaps.begin()->second; + auto &mmap_set2 = bpi.binary_mmaps.rbegin()->second; + std::string fn1 = mmap_set1.begin()->file_name; + std::string fn2 = mmap_set2.begin()->file_name; + EXPECT_TRUE((absl::StrContains(fn1, "propeller_sample_1.bin") && + absl::StrContains(fn2, "propeller_sample_2.bin")) || + (absl::StrContains(fn1, "propeller_sample_2.bin") && + absl::StrContains(fn2, "propeller_sample_1.bin"))); +} + +TEST(PerfdataReaderTest, PieAndNoBuildId) { + const std::string binary = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "propeller_barebone_pie_nobuildid.bin"); + auto reader = devtools_crosstool_autofdo::PerfDataReader(); + devtools_crosstool_autofdo::BinaryInfo binary_info; + reader.SelectBinaryInfo(binary, &binary_info); + EXPECT_TRUE(binary_info.is_pie); + EXPECT_TRUE(binary_info.build_id.empty()); +} + +TEST(PerfdataReaderTest, TestSharedLibrary) { + const std::string binary = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "libro_sample.so"); + const std::string perfdata = + absl::StrCat(FLAGS_test_srcdir, + "/testdata/" + "ro_sample.perf"); + auto reader = devtools_crosstool_autofdo::PerfDataReader(); + devtools_crosstool_autofdo::BinaryPerfInfo binary_perf_info; + devtools_crosstool_autofdo::BinaryInfo &binary_info = + binary_perf_info.binary_info; + reader.SelectBinaryInfo(binary, &binary_info); + EXPECT_TRUE(binary_info.is_pie); + // Only 1 loadable & executable segment. + EXPECT_EQ(binary_info.segments.size(), 1); + + const devtools_crosstool_autofdo::BinaryInfo::Segment &seg = + binary_info.segments[0]; + EXPECT_EQ(seg.offset, 0x580); + EXPECT_EQ(seg.vaddr, 0x1580); + EXPECT_EQ(seg.memsz, 0x1a0); + + EXPECT_TRUE(reader.SelectPerfInfo(perfdata, "", &binary_perf_info)); + EXPECT_EQ(binary_perf_info.binary_mmaps.size(), 1); + + // Make sure mmap's offset does not equals to segment's offset before + // proceeding to the following test. (This is the sole purpose that we + // introduced BinaryPerfInfo data structure. + EXPECT_NE( + seg.offset, + (*(*binary_perf_info.binary_mmaps.begin()).second.begin()).page_offset); + + // We know by readelf -Ws "foo"'s symbol address = 0x1640 + uint64_t foo_sym_addr = 0x1640; + // We know one cycle event: + // 902132 7fedfd0306a0 foo+0x60 (libro_sample.so) + // We translate it: + uint64_t addr = reader.RuntimeAddressToBinaryAddress(902132, 0x7fedfd0306a0, + binary_perf_info); + EXPECT_EQ(addr, foo_sym_addr + 0x60); +} + +TEST(PerfdataReaderTest, FirstLoadableSegmentNoneExecutable) { + const std::string binary = + absl::StrCat(absl::GetFlag(FLAGS_test_srcdir), + "/google3/devtools/crosstool/autofdo/testdata/" + "binary_with_none_executable_first_loadable_segment.bin"); + llvm::Optional v = + devtools_crosstool_autofdo::CheckFirstLoadableSegmentIsExecutable(binary); + EXPECT_TRUE(v.hasValue() && !v.getValue()); +} + +TEST(PerfdataReaderTest, FirstLoadableSegmentExecutable) { + const std::string binary = + absl::StrCat(absl::GetFlag(FLAGS_test_srcdir), + "/google3/devtools/crosstool/autofdo/testdata/" + "binary_with_executable_first_loadable_segment.bin"); + llvm::Optional v = + devtools_crosstool_autofdo::CheckFirstLoadableSegmentIsExecutable(binary); + EXPECT_TRUE(v.hasValue() && v.getValue()); +} + +} // namespace diff --git a/pool/shard011/C++/0121946_ListAlarmModelVersionsResult.cpp b/pool/shard011/C++/0121946_ListAlarmModelVersionsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d9595da36f14bc22941b3719da87bb9ffb1f436 --- /dev/null +++ b/pool/shard011/C++/0121946_ListAlarmModelVersionsResult.cpp @@ -0,0 +1,49 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::IoTEvents::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListAlarmModelVersionsResult::ListAlarmModelVersionsResult() +{ +} + +ListAlarmModelVersionsResult::ListAlarmModelVersionsResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +ListAlarmModelVersionsResult& ListAlarmModelVersionsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("alarmModelVersionSummaries")) + { + Array alarmModelVersionSummariesJsonList = jsonValue.GetArray("alarmModelVersionSummaries"); + for(unsigned alarmModelVersionSummariesIndex = 0; alarmModelVersionSummariesIndex < alarmModelVersionSummariesJsonList.GetLength(); ++alarmModelVersionSummariesIndex) + { + m_alarmModelVersionSummaries.push_back(alarmModelVersionSummariesJsonList[alarmModelVersionSummariesIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("nextToken")) + { + m_nextToken = jsonValue.GetString("nextToken"); + + } + + + + return *this; +} diff --git a/pool/shard011/C++/0121947_opus_jni.cc b/pool/shard011/C++/0121947_opus_jni.cc new file mode 100644 index 0000000000000000000000000000000000000000..00443b988e9c4c8d3eee840ab2f3359242c98f8a --- /dev/null +++ b/pool/shard011/C++/0121947_opus_jni.cc @@ -0,0 +1,174 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include + +#include "opus.h" // NOLINT +#include "opus_multistream.h" // NOLINT + +#define LOG_TAG "opus_jni" +#define LOGE(...) \ + ((void)__android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)) + +#define DECODER_FUNC(RETURN_TYPE, NAME, ...) \ + extern "C" { \ + JNIEXPORT RETURN_TYPE Java_androidx_media3_decoder_opus_OpusDecoder_##NAME( \ + JNIEnv* env, jobject thiz, ##__VA_ARGS__); \ + } \ + JNIEXPORT RETURN_TYPE Java_androidx_media3_decoder_opus_OpusDecoder_##NAME( \ + JNIEnv* env, jobject thiz, ##__VA_ARGS__) + +#define LIBRARY_FUNC(RETURN_TYPE, NAME, ...) \ + extern "C" { \ + JNIEXPORT RETURN_TYPE Java_androidx_media3_decoder_opus_OpusLibrary_##NAME( \ + JNIEnv* env, jobject thiz, ##__VA_ARGS__); \ + } \ + JNIEXPORT RETURN_TYPE Java_androidx_media3_decoder_opus_OpusLibrary_##NAME( \ + JNIEnv* env, jobject thiz, ##__VA_ARGS__) + +// JNI references for SimpleOutputBuffer class. +static jmethodID outputBufferInit; + +jint JNI_OnLoad(JavaVM* vm, void* reserved) { + JNIEnv* env; + if (vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6) != JNI_OK) { + return -1; + } + return JNI_VERSION_1_6; +} + +static const int kBytesPerIntPcmSample = 2; +static const int kBytesPerFloatSample = 4; +static const int kMaxOpusOutputPacketSizeSamples = 960 * 6; +static int channelCount; +static int errorCode; +static bool outputFloat = false; + +DECODER_FUNC(jlong, opusInit, jint sampleRate, jint channelCount, + jint numStreams, jint numCoupled, jint gain, + jbyteArray jStreamMap) { + int status = OPUS_INVALID_STATE; + ::channelCount = channelCount; + errorCode = 0; + jbyte* streamMapBytes = env->GetByteArrayElements(jStreamMap, 0); + uint8_t* streamMap = reinterpret_cast(streamMapBytes); + OpusMSDecoder* decoder = opus_multistream_decoder_create( + sampleRate, channelCount, numStreams, numCoupled, streamMap, &status); + env->ReleaseByteArrayElements(jStreamMap, streamMapBytes, 0); + if (!decoder || status != OPUS_OK) { + LOGE("Failed to create Opus Decoder; status=%s", opus_strerror(status)); + return 0; + } + status = opus_multistream_decoder_ctl(decoder, OPUS_SET_GAIN(gain)); + if (status != OPUS_OK) { + LOGE("Failed to set Opus header gain; status=%s", opus_strerror(status)); + return 0; + } + + // Populate JNI References. + const jclass outputBufferClass = + env->FindClass("androidx/media3/decoder/SimpleDecoderOutputBuffer"); + outputBufferInit = + env->GetMethodID(outputBufferClass, "init", "(JI)Ljava/nio/ByteBuffer;"); + + return reinterpret_cast(decoder); +} + +DECODER_FUNC(jint, opusDecode, jlong jDecoder, jlong jTimeUs, + jobject jInputBuffer, jint inputSize, jobject jOutputBuffer) { + OpusMSDecoder* decoder = reinterpret_cast(jDecoder); + const uint8_t* inputBuffer = reinterpret_cast( + env->GetDirectBufferAddress(jInputBuffer)); + + const int byteSizePerSample = + outputFloat ? kBytesPerFloatSample : kBytesPerIntPcmSample; + const jint outputSize = + kMaxOpusOutputPacketSizeSamples * byteSizePerSample * channelCount; + + env->CallObjectMethod(jOutputBuffer, outputBufferInit, jTimeUs, outputSize); + if (env->ExceptionCheck()) { + // Exception is thrown in Java when returning from the native call. + return -1; + } + const jobject jOutputBufferData = env->CallObjectMethod( + jOutputBuffer, outputBufferInit, jTimeUs, outputSize); + if (env->ExceptionCheck()) { + // Exception is thrown in Java when returning from the native call. + return -1; + } + + int sampleCount; + if (outputFloat) { + float* outputBufferData = reinterpret_cast( + env->GetDirectBufferAddress(jOutputBufferData)); + sampleCount = opus_multistream_decode_float( + decoder, inputBuffer, inputSize, outputBufferData, + kMaxOpusOutputPacketSizeSamples, 0); + } else { + int16_t* outputBufferData = reinterpret_cast( + env->GetDirectBufferAddress(jOutputBufferData)); + sampleCount = opus_multistream_decode(decoder, inputBuffer, inputSize, + outputBufferData, + kMaxOpusOutputPacketSizeSamples, 0); + } + + // record error code + errorCode = (sampleCount < 0) ? sampleCount : 0; + return (sampleCount < 0) ? sampleCount + : sampleCount * byteSizePerSample * channelCount; +} + +DECODER_FUNC(jint, opusSecureDecode, jlong jDecoder, jlong jTimeUs, + jobject jInputBuffer, jint inputSize, jobject jOutputBuffer, + jint sampleRate, jobject mediaCrypto, jint inputMode, + jbyteArray key, jbyteArray javaIv, jint inputNumSubSamples, + jintArray numBytesOfClearData, jintArray numBytesOfEncryptedData) { + // Doesn't support + // Java client should have checked vpxSupportSecureDecode + // and avoid calling this + // return -2 (DRM Error) + return -2; +} + +DECODER_FUNC(void, opusClose, jlong jDecoder) { + OpusMSDecoder* decoder = reinterpret_cast(jDecoder); + opus_multistream_decoder_destroy(decoder); +} + +DECODER_FUNC(void, opusReset, jlong jDecoder) { + OpusMSDecoder* decoder = reinterpret_cast(jDecoder); + opus_multistream_decoder_ctl(decoder, OPUS_RESET_STATE); +} + +DECODER_FUNC(jstring, opusGetErrorMessage, jlong jContext) { + return env->NewStringUTF(opus_strerror(errorCode)); +} + +DECODER_FUNC(jint, opusGetErrorCode, jlong jContext) { return errorCode; } + +DECODER_FUNC(void, opusSetFloatOutput) { outputFloat = true; } + +LIBRARY_FUNC(jstring, opusIsSecureDecodeSupported) { + // Doesn't support + return 0; +} + +LIBRARY_FUNC(jstring, opusGetVersion) { + return env->NewStringUTF(opus_get_version_string()); +} diff --git a/pool/shard011/C++/0121949_1043.cpp b/pool/shard011/C++/0121949_1043.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0418a138ff38b17b3b1826e959547e90235fee0f --- /dev/null +++ b/pool/shard011/C++/0121949_1043.cpp @@ -0,0 +1,194 @@ +#include +#include +#include +#include +#include +using namespace std; + +struct TreeNode +{ + int data_; + TreeNode* left_; + TreeNode* right_; + + TreeNode(int value):data_(value), left_(NULL), right_(NULL){} +}; + +/******************************************************************** + * Insert an elem into BST + * + * Main idea: + * if root == NULL, create a new node, set root point to it + * else if value < root->data, insert into left subtree cursively + * else if value >= root->data, insert into right substree cursively + * + * Input: + * root - the root of the tree to be inserted + * caution: since we change the root value, so remember reference + * value - value to be inserted + * + * Output: + * the root parameter has pointed to the created tree + *******************************************************************/ +void InsertBST(TreeNode* &root, int value) +{ + // base case + if (root == NULL) + { + root = new TreeNode(value); + return; + } + + if (value < root->data_) + { + InsertBST(root->left_, value); + return; + } + else if (value >= root->data_) + { + InsertBST(root->right_, value); + return; + } +} + +/******************************************************************** + * preOrder a tree, easy job + * remember base case: root == null, return + *******************************************************************/ +void preOrder(TreeNode* root, vector& ans) +{ + // base case + if (root == NULL) + { + return; + } + + ans.push_back(root->data_); + preOrder(root->left_, ans); + preOrder(root->right_, ans); + return; +} + +/******************************************************************** + * preMirrorOrder a tree, easy job + * remember base case: root == null, return + *******************************************************************/ +void preMirrorOrder(TreeNode* root, vector& ans) +{ + if (root == NULL) + { + return; + } + + ans.push_back(root->data_); + preMirrorOrder(root->right_, ans); + preMirrorOrder(root->left_, ans); + return; +} + +void postOrder(TreeNode* root, vector& ans) +{ + if (root == NULL) + { + return; + } + + postOrder(root->left_, ans); + postOrder(root->right_, ans); + ans.push_back(root->data_); + return; +} + +void postMirrorOrder(TreeNode* root, vector& ans) +{ + if (root == NULL) + { + return; + } + + postMirrorOrder(root->right_, ans); + postMirrorOrder(root->left_, ans); + ans.push_back(root->data_); + return; +} + +/******************************************************************** + * whether the two vectors contain exactly the same elements + * ******************************************************************/ +bool allSame(const vector& v1, const vector& v2) +{ + assert(v1.size() == v2.size()); + + for (int i = 0; i < v1.size(); ++i) + { + if (v1[i] != v2[i]) + { + return false; + } + } + + return true; +} + +/******************************************************************** + * print all the elements in the vector + * *****************************************************************/ +void printVector(const vector& v) +{ + bool isFirst = true; + for (int i = 0; i < v.size(); ++i) + { + if (!isFirst) + { + cout << " "; + } + else + { + isFirst = false; + } + + cout << v[i]; + } + cout << endl; +} + +int main() +{ + int n = 0; + cin >> n; + + TreeNode* root; + vector v(n); + for (int i = 0; i < n; ++i) + { + cin >> v[i]; + InsertBST(root, v[i]); + } + + vector pre_order; + preOrder(root, pre_order); + + vector pre_mirror_order; + preMirrorOrder(root, pre_mirror_order); + + if (allSame(v, pre_order)) + { + cout << "YES" << endl; + vector post_order; + postOrder(root, post_order); + printVector(post_order); + } + else if (allSame(v, pre_mirror_order)) + { + cout << "YES" << endl; + vector post_mirror_order; + postMirrorOrder(root, post_mirror_order); + printVector(post_mirror_order); + } + else + { + cout << "NO" << endl; + } + + return 0; +} diff --git a/pool/shard011/C++/0121950_test_analysis.cc b/pool/shard011/C++/0121950_test_analysis.cc new file mode 100644 index 0000000000000000000000000000000000000000..03fa5df896f7f901264ece8350dbdb6b8b432cf2 --- /dev/null +++ b/pool/shard011/C++/0121950_test_analysis.cc @@ -0,0 +1,47 @@ +/* -*- c++ -*- */ +/* + * Copyright 2012 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * GNU Radio 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. + * + * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include +#include "qa_analysis.h" +#include + +int +main (int argc, char **argv) +{ + CppUnit::TextTestRunner runner; + std::ofstream xmlfile(get_unittest_path("analysis.xml").c_str()); + CppUnit::XmlOutputter *xmlout = new CppUnit::XmlOutputter(&runner.result(), xmlfile); + + runner.addTest(qa_analysis::suite()); + runner.setOutputter(xmlout); + + bool was_successful = runner.run("", false); + + return was_successful ? 0 : 1; +} diff --git a/pool/shard011/C++/0121952_ExchangeHalo.cpp b/pool/shard011/C++/0121952_ExchangeHalo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c0b6817206f731bc2af0da9e3abdbce9c964cfa5 --- /dev/null +++ b/pool/shard011/C++/0121952_ExchangeHalo.cpp @@ -0,0 +1,110 @@ + +//@HEADER +// *************************************************** +// +// HPCG: High Performance Conjugate Gradient Benchmark +// +// Contact: +// Michael A. Heroux ( maherou@sandia.gov) +// Jack Dongarra (dongarra@eecs.utk.edu) +// Piotr Luszczek (luszczek@eecs.utk.edu) +// +// *************************************************** +//@HEADER + +/*! + @file ExchangeHalo.cpp + + HPCG routine + */ + +#ifndef HPCG_NOMPI // Compile this routine only if running in parallel +#include +#include "Geometry.hpp" +#include "ExchangeHalo.hpp" +#include + +/*! + Communicates data that is at the border of the part of the domain assigned to this processor. + + @param[in] A The known system matrix + @param[inout] x On entry: the local vector entries followed by entries to be communicated; on exit: the vector with non-local entries updated by other processors + */ +void ExchangeHalo(const SparseMatrix & A, Vector & x) { + + // Extract Matrix pieces + + local_int_t localNumberOfRows = A.localNumberOfRows; + int num_neighbors = A.numberOfSendNeighbors; + local_int_t * receiveLength = A.receiveLength; + local_int_t * sendLength = A.sendLength; + int * neighbors = A.neighbors; + double * sendBuffer = A.sendBuffer; + local_int_t totalToBeSent = A.totalToBeSent; + local_int_t * elementsToSend = A.elementsToSend; + + double * const xv = x.values; + + int size, rank; // Number of MPI processes, My process ID + MPI_Comm_size(MPI_COMM_WORLD, &size); + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + // + // first post receives, these are immediate receives + // Do not wait for result to come, will do that at the + // wait call below. + // + + int MPI_MY_TAG = 99; + + MPI_Request * request = new MPI_Request[num_neighbors]; + + // + // Externals are at end of locals + // + double * x_external = (double *) xv + localNumberOfRows; + + // Post receives first + // TODO: Thread this loop + for (int i = 0; i < num_neighbors; i++) { + local_int_t n_recv = receiveLength[i]; + MPI_Irecv(x_external, n_recv, MPI_DOUBLE, neighbors[i], MPI_MY_TAG, MPI_COMM_WORLD, request+i); + x_external += n_recv; + } + + + // + // Fill up send buffer + // + + // TODO: Thread this loop + for (local_int_t i=0; ieventStructType == NS_TEXT_EVENT, "event type mismatch"); + + if (aEvent) { + mEventIsInternal = false; + } + else { + mEventIsInternal = true; + mEvent->time = PR_Now(); + } + + // + // extract the IME composition string + // + nsTextEvent *te = static_cast(mEvent); + mText = te->theText; + + // + // build the range list -- ranges need to be DOM-ified since the + // IME transaction will hold a ref, the widget representation + // isn't persistent + // + mTextRange = new nsPrivateTextRangeList(te->rangeCount); + if (mTextRange) { + uint16_t i; + + for(i = 0; i < te->rangeCount; i++) { + nsRefPtr tempPrivateTextRange = new + nsPrivateTextRange(te->rangeArray[i]); + + if (tempPrivateTextRange) { + mTextRange->AppendTextRange(tempPrivateTextRange); + } + } + } +} + +NS_IMPL_ADDREF_INHERITED(nsDOMTextEvent, nsDOMUIEvent) +NS_IMPL_RELEASE_INHERITED(nsDOMTextEvent, nsDOMUIEvent) + +NS_INTERFACE_MAP_BEGIN(nsDOMTextEvent) + NS_INTERFACE_MAP_ENTRY(nsIPrivateTextEvent) +NS_INTERFACE_MAP_END_INHERITING(nsDOMUIEvent) + +NS_METHOD nsDOMTextEvent::GetText(nsString& aText) +{ + aText = mText; + return NS_OK; +} + +NS_METHOD_(already_AddRefed) nsDOMTextEvent::GetInputRange() +{ + if (mEvent->message == NS_TEXT_TEXT) { + nsRefPtr textRange = mTextRange; + nsPrivateTextRangeList *textRangePtr = nullptr; + textRange.swap(textRangePtr); + return textRangePtr; + } + return nullptr; +} + +nsresult NS_NewDOMTextEvent(nsIDOMEvent** aInstancePtrResult, + nsPresContext* aPresContext, + nsTextEvent *aEvent) +{ + nsDOMTextEvent* it = new nsDOMTextEvent(aPresContext, aEvent); + if (nullptr == it) { + return NS_ERROR_OUT_OF_MEMORY; + } + + return CallQueryInterface(it, aInstancePtrResult); +} diff --git a/pool/shard011/C++/0121954_metadata_test.cc b/pool/shard011/C++/0121954_metadata_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..045c6a3d29a48b144fbab8a8768ce0d00aa0f62d --- /dev/null +++ b/pool/shard011/C++/0121954_metadata_test.cc @@ -0,0 +1,162 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// https://developers.google.com/protocol-buffers/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace google { +namespace protobuf { +namespace compiler { +namespace cpp { + +namespace atu = annotation_test_util; + +namespace { + +class CppMetadataTest : public ::testing::Test { + public: + // Tries to capture a FileDescriptorProto, GeneratedCodeInfo, and output + // code from the previously added file with name `filename`. Returns true on + // success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to + // pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info. + bool CaptureMetadata(const std::string& filename, FileDescriptorProto* file, + std::string* pb_h, GeneratedCodeInfo* pb_h_info, + std::string* proto_h, GeneratedCodeInfo* proto_h_info, + std::string* pb_cc) { + CommandLineInterface cli; + CppGenerator cpp_generator; + cli.RegisterGenerator("--cpp_out", &cpp_generator, ""); + std::string cpp_out = + "--cpp_out=annotate_headers=true," + "annotation_pragma_name=pragma_name," + "annotation_guard_name=guard_name:" + + TestTempDir(); + + const bool result = atu::RunProtoCompiler(filename, cpp_out, &cli, file); + + if (!result) { + return result; + } + + std::string output_base = TestTempDir() + "/" + StripProto(filename); + + if (pb_cc != NULL) { + GOOGLE_CHECK_OK( + File::GetContents(output_base + ".pb.cc", pb_cc, true)); + } + + if (pb_h != NULL && pb_h_info != NULL) { + GOOGLE_CHECK_OK( + File::GetContents(output_base + ".pb.h", pb_h, true)); + if (!atu::DecodeMetadata(output_base + ".pb.h.meta", pb_h_info)) { + return false; + } + } + + if (proto_h != NULL && proto_h_info != NULL) { + GOOGLE_CHECK_OK(File::GetContents(output_base + ".proto.h", proto_h, + true)); + if (!atu::DecodeMetadata(output_base + ".proto.h.meta", proto_h_info)) { + return false; + } + } + + return true; + } +}; + +const char kSmallTestFile[] = + "syntax = \"proto2\";\n" + "package foo;\n" + "enum Enum { VALUE = 0; }\n" + "message Message { }\n"; + +TEST_F(CppMetadataTest, CapturesEnumNames) { + FileDescriptorProto file; + GeneratedCodeInfo info; + std::string pb_h; + atu::AddFile("test.proto", kSmallTestFile); + EXPECT_TRUE( + CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); + EXPECT_EQ("Enum", file.enum_type(0).name()); + std::vector enum_path; + enum_path.push_back(FileDescriptorProto::kEnumTypeFieldNumber); + enum_path.push_back(0); + const GeneratedCodeInfo::Annotation* enum_annotation = + atu::FindAnnotationOnPath(info, "test.proto", enum_path); + EXPECT_TRUE(NULL != enum_annotation); + EXPECT_TRUE(atu::AnnotationMatchesSubstring(pb_h, enum_annotation, "Enum")); +} + +TEST_F(CppMetadataTest, AddsPragma) { + FileDescriptorProto file; + GeneratedCodeInfo info; + std::string pb_h; + atu::AddFile("test.proto", kSmallTestFile); + EXPECT_TRUE( + CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); + EXPECT_TRUE(pb_h.find("#ifdef guard_name") != string::npos); + EXPECT_TRUE(pb_h.find("#pragma pragma_name \"test.pb.h.meta\"") != + std::string::npos); +} + +TEST_F(CppMetadataTest, CapturesMessageNames) { + FileDescriptorProto file; + GeneratedCodeInfo info; + std::string pb_h; + atu::AddFile("test.proto", kSmallTestFile); + EXPECT_TRUE( + CaptureMetadata("test.proto", &file, &pb_h, &info, NULL, NULL, NULL)); + EXPECT_EQ("Message", file.message_type(0).name()); + std::vector message_path; + message_path.push_back(FileDescriptorProto::kMessageTypeFieldNumber); + message_path.push_back(0); + const GeneratedCodeInfo::Annotation* message_annotation = + atu::FindAnnotationOnPath(info, "test.proto", message_path); + EXPECT_TRUE(NULL != message_annotation); + EXPECT_TRUE( + atu::AnnotationMatchesSubstring(pb_h, message_annotation, "Message")); +} + +} // namespace +} // namespace cpp +} // namespace compiler +} // namespace protobuf +} // namespace google diff --git a/pool/shard011/C++/0121955_omnibox_metrics_provider.cc b/pool/shard011/C++/0121955_omnibox_metrics_provider.cc new file mode 100644 index 0000000000000000000000000000000000000000..499ce6f3606fe04e1002f934a6325fc8fc7cf930 --- /dev/null +++ b/pool/shard011/C++/0121955_omnibox_metrics_provider.cc @@ -0,0 +1,160 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/metrics/omnibox_metrics_provider.h" + +#include + +#include "base/bind.h" +#include "base/logging.h" +#include "base/strings/string16.h" +#include "base/strings/string_split.h" +#include "base/strings/string_util.h" +#include "components/metrics/metrics_log.h" +#include "components/metrics/proto/omnibox_event.pb.h" +#include "components/metrics/proto/omnibox_input_type.pb.h" +#include "components/omnibox/browser/autocomplete_match.h" +#include "components/omnibox/browser/autocomplete_provider.h" +#include "components/omnibox/browser/autocomplete_result.h" +#include "components/omnibox/browser/omnibox_log.h" + +using metrics::OmniboxEventProto; + +namespace { + +OmniboxEventProto::Suggestion::ResultType AsOmniboxEventResultType( + AutocompleteMatch::Type type) { + switch (type) { + case AutocompleteMatchType::URL_WHAT_YOU_TYPED: + return OmniboxEventProto::Suggestion::URL_WHAT_YOU_TYPED; + case AutocompleteMatchType::HISTORY_URL: + return OmniboxEventProto::Suggestion::HISTORY_URL; + case AutocompleteMatchType::HISTORY_TITLE: + return OmniboxEventProto::Suggestion::HISTORY_TITLE; + case AutocompleteMatchType::HISTORY_BODY: + return OmniboxEventProto::Suggestion::HISTORY_BODY; + case AutocompleteMatchType::HISTORY_KEYWORD: + return OmniboxEventProto::Suggestion::HISTORY_KEYWORD; + case AutocompleteMatchType::NAVSUGGEST: + return OmniboxEventProto::Suggestion::NAVSUGGEST; + case AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED: + return OmniboxEventProto::Suggestion::SEARCH_WHAT_YOU_TYPED; + case AutocompleteMatchType::SEARCH_HISTORY: + return OmniboxEventProto::Suggestion::SEARCH_HISTORY; + case AutocompleteMatchType::SEARCH_SUGGEST: + return OmniboxEventProto::Suggestion::SEARCH_SUGGEST; + case AutocompleteMatchType::SEARCH_SUGGEST_ENTITY: + return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_ENTITY; + case AutocompleteMatchType::SEARCH_SUGGEST_TAIL: + return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_TAIL; + case AutocompleteMatchType::SEARCH_SUGGEST_PERSONALIZED: + return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PERSONALIZED; + case AutocompleteMatchType::SEARCH_SUGGEST_PROFILE: + return OmniboxEventProto::Suggestion::SEARCH_SUGGEST_PROFILE; + case AutocompleteMatchType::CALCULATOR: + return OmniboxEventProto::Suggestion::CALCULATOR; + case AutocompleteMatchType::SEARCH_OTHER_ENGINE: + return OmniboxEventProto::Suggestion::SEARCH_OTHER_ENGINE; + case AutocompleteMatchType::EXTENSION_APP: + return OmniboxEventProto::Suggestion::EXTENSION_APP; + case AutocompleteMatchType::BOOKMARK_TITLE: + return OmniboxEventProto::Suggestion::BOOKMARK_TITLE; + case AutocompleteMatchType::NAVSUGGEST_PERSONALIZED: + return OmniboxEventProto::Suggestion::NAVSUGGEST_PERSONALIZED; + case AutocompleteMatchType::CONTACT_DEPRECATED: + case AutocompleteMatchType::NUM_TYPES: + break; + } + NOTREACHED(); + return OmniboxEventProto::Suggestion::UNKNOWN_RESULT_TYPE; +} + +} // namespace + +OmniboxMetricsProvider::OmniboxMetricsProvider( + const base::Callback& is_off_the_record_callback) + : is_off_the_record_callback_(is_off_the_record_callback) {} + +OmniboxMetricsProvider::~OmniboxMetricsProvider() { +} + +void OmniboxMetricsProvider::OnRecordingEnabled() { + subscription_ = OmniboxEventGlobalTracker::GetInstance()->RegisterCallback( + base::Bind(&OmniboxMetricsProvider::OnURLOpenedFromOmnibox, + base::Unretained(this))); +} + +void OmniboxMetricsProvider::OnRecordingDisabled() { + subscription_.reset(); +} + +void OmniboxMetricsProvider::ProvideGeneralMetrics( + metrics::ChromeUserMetricsExtension* uma_proto) { + uma_proto->mutable_omnibox_event()->Swap( + omnibox_events_cache.mutable_omnibox_event()); +} + +void OmniboxMetricsProvider::OnURLOpenedFromOmnibox(OmniboxLog* log) { + // Do not log events to UMA if the embedder reports that the user is in an + // off-the-record context. + if (!is_off_the_record_callback_.Run()) + RecordOmniboxOpenedURL(*log); +} + +void OmniboxMetricsProvider::RecordOmniboxOpenedURL(const OmniboxLog& log) { + std::vector terms = base::SplitStringPiece( + log.text, base::kWhitespaceUTF16, + base::KEEP_WHITESPACE, base::SPLIT_WANT_NONEMPTY); + + OmniboxEventProto* omnibox_event = omnibox_events_cache.add_omnibox_event(); + omnibox_event->set_time(metrics::MetricsLog::GetCurrentTime()); + if (log.tab_id != -1) { + // If we know what tab the autocomplete URL was opened in, log it. + omnibox_event->set_tab_id(log.tab_id); + } + omnibox_event->set_typed_length(log.text.length()); + omnibox_event->set_just_deleted_text(log.just_deleted_text); + omnibox_event->set_num_typed_terms(static_cast(terms.size())); + omnibox_event->set_selected_index(log.selected_index); + if (log.completed_length != base::string16::npos) + omnibox_event->set_completed_length(log.completed_length); + const base::TimeDelta default_time_delta = + base::TimeDelta::FromMilliseconds(-1); + if (log.elapsed_time_since_user_first_modified_omnibox != + default_time_delta) { + // Only upload the typing duration if it is set/valid. + omnibox_event->set_typing_duration_ms( + log.elapsed_time_since_user_first_modified_omnibox.InMilliseconds()); + } + if (log.elapsed_time_since_last_change_to_default_match != + default_time_delta) { + omnibox_event->set_duration_since_last_default_match_update_ms( + log.elapsed_time_since_last_change_to_default_match.InMilliseconds()); + } + omnibox_event->set_current_page_classification( + log.current_page_classification); + omnibox_event->set_input_type(log.input_type); + // We consider a paste-and-search/paste-and-go action to have a closed popup + // (as explained in omnibox_event.proto) even if it was not, because such + // actions ignore the contents of the popup so it doesn't matter that it was + // open. + omnibox_event->set_is_popup_open(log.is_popup_open && !log.is_paste_and_go); + omnibox_event->set_is_paste_and_go(log.is_paste_and_go); + + for (AutocompleteResult::const_iterator i(log.result.begin()); + i != log.result.end(); ++i) { + OmniboxEventProto::Suggestion* suggestion = omnibox_event->add_suggestion(); + suggestion->set_provider(i->provider->AsOmniboxEventProviderType()); + suggestion->set_result_type(AsOmniboxEventResultType(i->type)); + suggestion->set_relevance(i->relevance); + if (i->typed_count != -1) + suggestion->set_typed_count(i->typed_count); + } + for (ProvidersInfo::const_iterator i(log.providers_info.begin()); + i != log.providers_info.end(); ++i) { + OmniboxEventProto::ProviderInfo* provider_info = + omnibox_event->add_provider_info(); + provider_info->CopyFrom(*i); + } +} diff --git a/pool/shard011/C++/0121956_sdl2_resource.cpp b/pool/shard011/C++/0121956_sdl2_resource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..442cb7f6f879f95e82500e3a4dd58c6b226628a0 --- /dev/null +++ b/pool/shard011/C++/0121956_sdl2_resource.cpp @@ -0,0 +1,35 @@ +#include +#include + +#include "sdl2_resource.h" +#include "generated_resource.h" + +sdl2_resource::~sdl2_resource() +{ +} + +std::string sdl2_resource::get_text_resource(const std::string& name) const +{ + std::string filepath; + filepath.reserve(std::size(ABS_RES_PATH) + 1 + name.size()); + filepath.append(ABS_RES_PATH); + filepath.append("/"); + filepath.append(name); + + std::ifstream t(filepath); + std::string str((std::istreambuf_iterator(t)), std::istreambuf_iterator()); + return str; +} + +void sdl2_resource::save_text_data(const std::string& key, const std::string& val) +{ + std::ofstream stream(key); + stream << val; +} + +std::string sdl2_resource::load_text_data(const std::string& key) const +{ + std::ifstream t(key); + std::string str((std::istreambuf_iterator(t)), std::istreambuf_iterator()); + return str; +} diff --git a/pool/shard011/C++/0121960_atom.cpp b/pool/shard011/C++/0121960_atom.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7df690021f76b3ca60aa42e323c8934e91767da7 --- /dev/null +++ b/pool/shard011/C++/0121960_atom.cpp @@ -0,0 +1,361 @@ +/**************************************************************************** +** +** 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 tools applications of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "atom.h" +#include "location.h" +#include + +QT_BEGIN_NAMESPACE + +QString Atom::BOLD_ ("bold"); +QString Atom::INDEX_ ("index"); +QString Atom::ITALIC_ ("italic"); +QString Atom::LINK_ ("link"); +QString Atom::PARAMETER_ ("parameter"); +QString Atom::SUBSCRIPT_ ("subscript"); +QString Atom::SUPERSCRIPT_ ("superscript"); +QString Atom::TELETYPE_ ("teletype"); +QString Atom::UNDERLINE_ ("underline"); + +QString Atom::BULLET_ ("bullet"); +QString Atom::TAG_ ("tag"); +QString Atom::VALUE_ ("value"); +QString Atom::LOWERALPHA_ ("loweralpha"); +QString Atom::LOWERROMAN_ ("lowerroman"); +QString Atom::NUMERIC_ ("numeric"); +QString Atom::UPPERALPHA_ ("upperalpha"); +QString Atom::UPPERROMAN_ ("upperroman"); + +/*! \class Atom + \brief The Atom class is the fundamental unit for representing + documents internally. + + Atoms have a \i type and are completed by a \i string whose + meaning depends on the \i type. For example, the string + \quotation + \i italic text looks nicer than \bold bold text + \endquotation + is represented by the following atoms: + \quotation + (FormattingLeft, ATOM_FORMATTING_ITALIC) + (String, "italic") + (FormattingRight, ATOM_FORMATTING_ITALIC) + (String, " text is more attractive than ") + (FormattingLeft, ATOM_FORMATTING_BOLD) + (String, "bold") + (FormattingRight, ATOM_FORMATTING_BOLD) + (String, " text") + \endquotation + + \also Text +*/ + +/*! \enum Atom::Type + + \value AbstractLeft + \value AbstractRight + \value AnnotatedList + \value AutoLink + \value BaseName + \value BriefLeft + \value BriefRight + \value C + \value CaptionLeft + \value CaptionRight + \value Code + \value CodeBad + \value CodeNew + \value CodeOld + \value CodeQuoteArgument + \value CodeQuoteCommand + \value EndQmlText + \value FormatElse + \value FormatEndif + \value FormatIf + \value FootnoteLeft + \value FootnoteRight + \value FormattingLeft + \value FormattingRight + \value GeneratedList + \value Image + \value ImageText + \value InlineImage + \value LineBreak + \value Link + \value LinkNode + \value ListLeft + \value ListItemNumber + \value ListTagLeft + \value ListTagRight + \value ListItemLeft + \value ListItemRight + \value ListRight + \value Nop + \value ParaLeft + \value ParaRight + \value Qml + \value QmlText + \value QuotationLeft + \value QuotationRight + \value RawString + \value SectionLeft + \value SectionRight + \value SectionHeadingLeft + \value SectionHeadingRight + \value SidebarLeft + \value SidebarRight + \value SinceList + \value String + \value TableLeft + \value TableRight + \value TableHeaderLeft + \value TableHeaderRight + \value TableRowLeft + \value TableRowRight + \value TableItemLeft + \value TableItemRight + \value TableOfContents + \value Target + \value UnhandledFormat + \value UnknownCommand +*/ + +static const struct { + const char *english; + int no; +} atms[] = { + { "AbstractLeft", Atom::AbstractLeft }, + { "AbstractRight", Atom::AbstractRight }, + { "AnnotatedList", Atom::AnnotatedList }, + { "AutoLink", Atom::AutoLink }, + { "BaseName", Atom::BaseName }, + { "BriefLeft", Atom::BriefLeft }, + { "BriefRight", Atom::BriefRight }, + { "C", Atom::C }, + { "CaptionLeft", Atom::CaptionLeft }, + { "CaptionRight", Atom::CaptionRight }, + { "Code", Atom::Code }, + { "CodeBad", Atom::CodeBad }, + { "CodeNew", Atom::CodeNew }, + { "CodeOld", Atom::CodeOld }, + { "CodeQuoteArgument", Atom::CodeQuoteArgument }, + { "CodeQuoteCommand", Atom::CodeQuoteCommand }, +#ifdef QDOC_QML + { "EndQmlText", Atom::EndQmlText }, +#endif + { "FootnoteLeft", Atom::FootnoteLeft }, + { "FootnoteRight", Atom::FootnoteRight }, + { "FormatElse", Atom::FormatElse }, + { "FormatEndif", Atom::FormatEndif }, + { "FormatIf", Atom::FormatIf }, + { "FormattingLeft", Atom::FormattingLeft }, + { "FormattingRight", Atom::FormattingRight }, + { "GeneratedList", Atom::GeneratedList }, + { "Image", Atom::Image }, + { "ImageText", Atom::ImageText }, + { "InlineImage", Atom::InlineImage }, + { "LegaleseLeft", Atom::LegaleseLeft }, + { "LegaleseRight", Atom::LegaleseRight }, + { "LineBreak", Atom::LineBreak }, + { "Link", Atom::Link }, + { "LinkNode", Atom::LinkNode }, + { "ListLeft", Atom::ListLeft }, + { "ListItemNumber", Atom::ListItemNumber }, + { "ListTagLeft", Atom::ListTagLeft }, + { "ListTagRight", Atom::ListTagRight }, + { "ListItemLeft", Atom::ListItemLeft }, + { "ListItemRight", Atom::ListItemRight }, + { "ListRight", Atom::ListRight }, + { "Nop", Atom::Nop }, + { "ParaLeft", Atom::ParaLeft }, + { "ParaRight", Atom::ParaRight }, +#ifdef QDOC_QML + { "Qml", Atom::Qml}, + { "QmlText", Atom::QmlText }, +#endif + { "QuotationLeft", Atom::QuotationLeft }, + { "QuotationRight", Atom::QuotationRight }, + { "RawString", Atom::RawString }, + { "SectionLeft", Atom::SectionLeft }, + { "SectionRight", Atom::SectionRight }, + { "SectionHeadingLeft", Atom::SectionHeadingLeft }, + { "SectionHeadingRight", Atom::SectionHeadingRight }, + { "SidebarLeft", Atom::SidebarLeft }, + { "SidebarRight", Atom::SidebarRight }, + { "SinceList", Atom::SinceList }, + { "SnippetCommand", Atom::SnippetCommand }, + { "SnippetIdentifier", Atom::SnippetIdentifier }, + { "SnippetLocation", Atom::SnippetLocation }, + { "String", Atom::String }, + { "TableLeft", Atom::TableLeft }, + { "TableRight", Atom::TableRight }, + { "TableHeaderLeft", Atom::TableHeaderLeft }, + { "TableHeaderRight", Atom::TableHeaderRight }, + { "TableRowLeft", Atom::TableRowLeft }, + { "TableRowRight", Atom::TableRowRight }, + { "TableItemLeft", Atom::TableItemLeft }, + { "TableItemRight", Atom::TableItemRight }, + { "TableOfContents", Atom::TableOfContents }, + { "Target", Atom::Target }, + { "UnhandledFormat", Atom::UnhandledFormat }, + { "UnknownCommand", Atom::UnknownCommand }, + { 0, 0 } +}; + +/*! \fn Atom::Atom( Type type, const QString& string ) + + Constructs an atom (\a type, \a string) outside of any atom list. +*/ + +/*! \fn Atom( Atom *prev, Type type, const QString& string ) + + Constructs an atom (\a type, \a string) that follows \a prev in \a + prev's atom list. +*/ + +/*! \fn void Atom::appendChar( QChar ch ) + + Appends \a ch to the string parameter of this atom. + + \also string() +*/ + +/*! \fn void Atom::appendString( const QString& string ) + + Appends \a string to the string parameter of this atom. + + \also string() +*/ + +/*! \fn void Atom::chopString() + + \also string() +*/ + +/*! \fn Atom *Atom::next() + Return the next atom in the atom list. + \also type(), string() +*/ + +/*! + Return the next Atom in the list if it is of Type \a t. + Otherwise return 0. + */ +const Atom* Atom::next(Type t) const +{ + return (nxt && (nxt->type() == t)) ? nxt : 0; +} + +/*! + Return the next Atom in the list if it is of Type \a t + and its string part is \a s. Otherwise return 0. + */ +const Atom* Atom::next(Type t, const QString& s) const +{ + return (nxt && (nxt->type() == t) && (nxt->string() == s)) ? nxt : 0; +} + +/*! \fn const Atom *Atom::next() const + Return the next atom in the atom list. + \also type(), string() +*/ + +/*! \fn Type Atom::type() const + Return the type of this atom. + \also string(), next() +*/ + +/*! + Return the type of this atom as a string. Return "Invalid" if + type() returns an impossible value. + + This is only useful for debugging. + + \also type() +*/ +QString Atom::typeString() const +{ + static bool deja = false; + + if ( !deja ) { + int i = 0; + while ( atms[i].english != 0 ) { + if ( atms[i].no != i ) + Location::internalError( tr("atom %1 missing").arg(i) ); + i++; + } + deja = true; + } + + int i = (int) type(); + if ( i < 0 || i > (int) Last ) + return QLatin1String("Invalid"); + return QLatin1String(atms[i].english); +} + +/*! \fn const QString& Atom::string() const + + Returns the string parameter that together with the type + characterizes this atom. + + \also type(), next() +*/ + +/*! + Dumps this Atom to stderr in printer friendly form. + */ +void Atom::dump() const +{ + QString str = string(); + str.replace( "\\", "\\\\" ); + str.replace( "\"", "\\\"" ); + str.replace( "\n", "\\n" ); + str.replace( QRegExp("[^\x20-\x7e]"), "?" ); + if (!str.isEmpty()) + str = " \"" + str + "\""; + fprintf(stderr, + " %-15s%s\n", + typeString().toLatin1().data(), + str.toLatin1().data()); +} + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0121961_Buffer.cc b/pool/shard011/C++/0121961_Buffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b3090dc7324ab2644555e36ae49dbd4d5b5d480 --- /dev/null +++ b/pool/shard011/C++/0121961_Buffer.cc @@ -0,0 +1,113 @@ +#include "Buffer.hh" + +using namespace Animate::VK; + +uint64_t Buffer::id_counter = 1; + +Buffer::Buffer( + std::weak_ptr _context, + vk::DeviceSize size, + vk::BufferUsageFlags usage, + vk::MemoryPropertyFlags properties +) : context(_context), size(size), usage(usage) { + std::shared_ptr context = this->context.lock(); + + this->logical_device = context->logical_device; + + vk::BufferCreateInfo buffer_create_info = vk::BufferCreateInfo() + .setSize(size) + .setUsage(usage) + .setSharingMode(vk::SharingMode::eExclusive); + + if(context->logical_device.createBuffer(&buffer_create_info, nullptr, &this->ident) != vk::Result::eSuccess) { + throw std::runtime_error("Couldn't create buffer."); + } + + vk::MemoryRequirements memory_requirements; + context->logical_device.getBufferMemoryRequirements(this->ident, &memory_requirements); + + vk::MemoryAllocateInfo allocation_info = vk::MemoryAllocateInfo() + .setAllocationSize(memory_requirements.size) + .setMemoryTypeIndex( + context->find_memory_type( + memory_requirements.memoryTypeBits, + properties + ) + ); + + if(context->logical_device.allocateMemory(&allocation_info, nullptr, &this->memory) != vk::Result::eSuccess) { + throw std::runtime_error("Couldn't allocate buffer memory."); + } + + this->id = Buffer::id_counter++; + + this->context.lock()->logical_device.bindBufferMemory(this->ident, this->memory, 0); +} + +Buffer::~Buffer() +{ + this->logical_device.waitIdle(); + if (this->ident) { + this->logical_device.destroyBuffer(this->ident, nullptr); + } + + if (this->memory) { + this->logical_device.freeMemory(this->memory, nullptr); + } +} + +uint64_t Buffer::get_id() +{ + return this->id; +} + +void Buffer::copy_buffer_data(std::shared_ptr source) +{ + std::lock_guard guard(this->data_mutex); + + std::shared_ptr context = this->context.lock(); + + if (source->get_size() > this->size) { + throw std::runtime_error("Not enough space to copy buffer."); + } + + context->run_one_time_commands([&](vk::CommandBuffer command_buffer){ + vk::BufferCopy copy_details = vk::BufferCopy() + .setSrcOffset(0) + .setDstOffset(0) + .setSize(this->size); + + command_buffer.copyBuffer(source->get_ident(), ident, 1, ©_details); + }); +} + +void* Buffer::map() +{ + this->data_mutex.lock(); + + void* data; + this->context.lock()->logical_device.mapMemory(this->memory, 0, this->size, vk::MemoryMapFlags(), &data); + return data; +} + +void Buffer::unmap() +{ + this->context.lock()->logical_device.unmapMemory(this->memory); + + this->data_mutex.unlock(); +} + +vk::DeviceSize Buffer::get_size() +{ + return this->size; +} + +vk::BufferUsageFlags Buffer::get_usage() +{ + return this->usage; +} + +vk::Buffer Buffer::get_ident() +{ + return this->ident; +} \ No newline at end of file diff --git a/pool/shard011/C++/0121962_boss_gyth.cpp b/pool/shard011/C++/0121962_boss_gyth.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5b6ea8c14c9351e80a05095a235c150d806826d --- /dev/null +++ b/pool/shard011/C++/0121962_boss_gyth.cpp @@ -0,0 +1,167 @@ +/** + * ScriptDev2 is an extension for mangos providing enhanced features for + * area triggers, creatures, game objects, instances, items, and spells beyond + * the default database scripting in mangos. + * + * Copyright (C) 2006-2013 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, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * World of Warcraft, and all World of Warcraft or Warcraft art, images, + * and lore are copyrighted by Blizzard Entertainment, Inc. + */ + +/** + * ScriptData + * SDName: Boss_Gyth + * SD%Complete: 95 + * SDComment: Timers may need adjustments + * SDCategory: Blackrock Spire + * EndScriptData + */ + +#include "precompiled.h" +#include "blackrock_spire.h" + +enum +{ + SAY_NEFARIUS_BUFF_GYTH = -1229017, + EMOTE_KNOCKED_OFF = -1229019, + + SPELL_CHROMATIC_CHAOS = 16337, // casted by Nefarius at 50% + SPELL_REND_MOUNTS = 16167, + SPELL_SUMMON_REND = 16328, + SPELL_CORROSIVE_ACID = 16359, + SPELL_FREEZE = 16350, + SPELL_FLAME_BREATH = 16390, + SPELL_KNOCK_AWAY = 10101, +}; + +struct boss_gythAI : public ScriptedAI +{ + boss_gythAI(Creature* pCreature) : ScriptedAI(pCreature) + { + m_pInstance = (instance_blackrock_spire*) pCreature->GetInstanceData(); + Reset(); + } + + instance_blackrock_spire* m_pInstance; + + uint32 uiCorrosiveAcidTimer; + uint32 uiFreezeTimer; + uint32 uiFlamebreathTimer; + + bool m_bSummonedRend; + bool m_bHasChromaticChaos; + + void Reset() override + { + uiCorrosiveAcidTimer = 8000; + uiFreezeTimer = 11000; + uiFlamebreathTimer = 4000; + m_bSummonedRend = false; + m_bHasChromaticChaos = false; + + DoCastSpellIfCan(m_creature, SPELL_REND_MOUNTS); + } + + void JustSummoned(Creature* pSummoned) override + { + DoScriptText(EMOTE_KNOCKED_OFF, pSummoned); + } + + void UpdateAI(const uint32 uiDiff) override + { + // Return since we have no target + if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) + { + return; + } + + // Chromatic Chaos at 50% + if (!m_bHasChromaticChaos && m_creature->GetHealthPercent() < 50.0f) + { + if (m_pInstance) + { + if (Creature* pNefarius = m_pInstance->GetSingleCreatureFromStorage(NPC_LORD_VICTOR_NEFARIUS)) + { + pNefarius->CastSpell(m_creature, SPELL_CHROMATIC_CHAOS, true); + DoScriptText(SAY_NEFARIUS_BUFF_GYTH, pNefarius); + m_bHasChromaticChaos = true; + } + } + } + + // CorrosiveAcid_Timer + if (uiCorrosiveAcidTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_CORROSIVE_ACID) == CAST_OK) + { + uiCorrosiveAcidTimer = 7000; + } + } + else + { uiCorrosiveAcidTimer -= uiDiff; } + + // Freeze_Timer + if (uiFreezeTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_FREEZE) == CAST_OK) + { + uiFreezeTimer = 16000; + } + } + else + { uiFreezeTimer -= uiDiff; } + + // Flamebreath_Timer + if (uiFlamebreathTimer < uiDiff) + { + if (DoCastSpellIfCan(m_creature, SPELL_FLAME_BREATH) == CAST_OK) + { + uiFlamebreathTimer = 10500; + } + } + else + { uiFlamebreathTimer -= uiDiff; } + + // Summon Rend + if (!m_bSummonedRend && m_creature->GetHealthPercent() < 11.0f) + { + if (DoCastSpellIfCan(m_creature, SPELL_SUMMON_REND) == CAST_OK) + { + m_creature->RemoveAurasDueToSpell(SPELL_REND_MOUNTS); + m_bSummonedRend = true; + } + } + + DoMeleeAttackIfReady(); + } +}; + +CreatureAI* GetAI_boss_gyth(Creature* pCreature) +{ + return new boss_gythAI(pCreature); +} + +void AddSC_boss_gyth() +{ + Script* pNewScript; + + pNewScript = new Script; + pNewScript->Name = "boss_gyth"; + pNewScript->GetAI = &GetAI_boss_gyth; + pNewScript->RegisterSelf(); +} diff --git a/pool/shard011/C++/0121963_commandlocator.cpp b/pool/shard011/C++/0121963_commandlocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..092b013a46fa943817b1d798d5d6609664a2400b --- /dev/null +++ b/pool/shard011/C++/0121963_commandlocator.cpp @@ -0,0 +1,125 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of Qt Creator. +** +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +****************************************************************************/ + +#include "commandlocator.h" + +#include +#include + +#include + +#include + +namespace Locator { + +struct CommandLocatorPrivate { + CommandLocatorPrivate(const QString &prefix, + const QString &displayName) : + m_prefix(prefix), m_displayName(displayName) {} + + const QString m_prefix; + const QString m_displayName; + + QList commands; +}; + +CommandLocator::CommandLocator(const QString &prefix, + const QString &displayName, + const QString &shortCutString, + QObject *parent) : + Locator::ILocatorFilter(parent), + d(new CommandLocatorPrivate(prefix, displayName)) +{ + setShortcutString(shortCutString); +} + +CommandLocator::~CommandLocator() +{ + delete d; +} + +void CommandLocator::appendCommand(Core::Command *cmd) +{ + d->commands.push_back(cmd); +} + +QString CommandLocator::displayName() const +{ + return d->m_displayName; +} + +QString CommandLocator::id() const +{ + return d->m_prefix; +} + +ILocatorFilter::Priority CommandLocator::priority() const +{ + return Medium; +} + +QList CommandLocator::matchesFor(QFutureInterface &future, const QString &entry) +{ + QList filters; + // Get active, enabled actions matching text, store in list. + // Reference via index in extraInfo. + const QChar ampersand = QLatin1Char('&'); + const int count = d->commands.size(); + for (int i = 0; i < count; i++) { + if (future.isCanceled()) + break; + if (d->commands.at(i)->isActive()) { + if (QAction *action = d->commands.at(i)->action()) + if (action->isEnabled()) { + QString text = action->text(); + text.remove(ampersand); + if (text.contains(entry, Qt::CaseInsensitive)) { + filters.append(FilterEntry(this, text, QVariant(i))); + } + } + } + } + return filters; +} + +void CommandLocator::accept(Locator::FilterEntry entry) const +{ + // Retrieve action via index. + const int index = entry.internalData.toInt(); + QTC_ASSERT(index >= 0 && index < d->commands.size(), return); + QAction *action = d->commands.at(index)->action(); + QTC_ASSERT(action->isEnabled(), return); + action->trigger(); +} + +void CommandLocator::refresh(QFutureInterface &) +{ +} + +} // namespace Locator diff --git a/pool/shard011/C++/0121965_range_dataset_op.cc b/pool/shard011/C++/0121965_range_dataset_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..580702f741814b6bd86cab2d537b3ad49b4f6177 --- /dev/null +++ b/pool/shard011/C++/0121965_range_dataset_op.cc @@ -0,0 +1,158 @@ +/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ +#include "tensorflow/core/framework/dataset.h" +#include "tensorflow/core/framework/partial_tensor_shape.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { +namespace data { +namespace { + +// See documentation in ../../ops/dataset_ops.cc for a high-level +// description of the following op. + +class RangeDatasetOp : public DatasetOpKernel { + public: + explicit RangeDatasetOp(OpKernelConstruction* ctx) : DatasetOpKernel(ctx) {} + + void MakeDataset(OpKernelContext* ctx, DatasetBase** output) override { + int64 start; + OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, "start", &start)); + + int64 stop; + OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, "stop", &stop)); + + int64 step; + OP_REQUIRES_OK(ctx, ParseScalarArgument(ctx, "step", &step)); + OP_REQUIRES(ctx, step != 0, + errors::InvalidArgument("step must be a non-zero integer.")); + + *output = new Dataset(ctx, start, stop, step); + } + + private: + class Dataset : public DatasetBase { + public: + Dataset(OpKernelContext* ctx, int64 start, int64 stop, int64 step) + : DatasetBase(DatasetContext(ctx)), + start_(start), + stop_(stop), + step_(step) {} + + std::unique_ptr MakeIteratorInternal( + const string& prefix) const override { + return std::unique_ptr( + new Iterator({this, strings::StrCat(prefix, "::Range")})); + } + + const DataTypeVector& output_dtypes() const override { + static DataTypeVector* dtypes = new DataTypeVector({DT_INT64}); + return *dtypes; + } + + const std::vector& output_shapes() const override { + static std::vector* shapes = + new std::vector({{}}); + return *shapes; + } + + string DebugString() const override { + return strings::StrCat("RangeDatasetOp(", start_, ", ", stop_, ", ", + step_, ")::Dataset"); + } + + int64 Cardinality() const override { + if (step_ > 0) { + return std::max(0LL, (stop_ - start_ - 1) / step_ + 1); + } else { + return std::max(0LL, (start_ - stop_ - 1) / -step_ + 1); + } + } + + protected: + Status AsGraphDefInternal(SerializationContext* ctx, + DatasetGraphDefBuilder* b, + Node** output) const override { + Node* start = nullptr; + Node* stop = nullptr; + Node* step = nullptr; + TF_RETURN_IF_ERROR(b->AddScalar(start_, &start)); + TF_RETURN_IF_ERROR(b->AddScalar(stop_, &stop)); + TF_RETURN_IF_ERROR(b->AddScalar(step_, &step)); + TF_RETURN_IF_ERROR(b->AddDataset(this, {start, stop, step}, output)); + return Status::OK(); + } + + private: + class Iterator : public DatasetIterator { + public: + explicit Iterator(const Params& params) + : DatasetIterator(params) { + next_ = params.dataset->start_; + } + + Status GetNextInternal(IteratorContext* ctx, + std::vector* out_tensors, + bool* end_of_sequence) override { + mutex_lock l(mu_); + if ((dataset()->step_ > 0 && next_ >= dataset()->stop_) || + (dataset()->step_ < 0 && next_ <= dataset()->stop_)) { + *end_of_sequence = true; + return Status::OK(); + } + out_tensors->reserve(1); + out_tensors->emplace_back(next_); + *end_of_sequence = false; + next_ += dataset()->step_; + + return Status::OK(); + } + + protected: + std::shared_ptr CreateNode( + IteratorContext* ctx, model::Node::Args args) const override { + return model::MakeSourceNode(std::move(args)); + } + + Status SaveInternal(IteratorStateWriter* writer) override { + mutex_lock l(mu_); + TF_RETURN_IF_ERROR(writer->WriteScalar(full_name("next"), next_)); + return Status::OK(); + } + + Status RestoreInternal(IteratorContext* ctx, + IteratorStateReader* reader) override { + mutex_lock l(mu_); + TF_RETURN_IF_ERROR(reader->ReadScalar(full_name("next"), &next_)); + return Status::OK(); + } + + private: + mutex mu_; + int64 next_ GUARDED_BY(mu_); + }; + + const int64 start_; + const int64 stop_; + const int64 step_; + }; +}; + +REGISTER_KERNEL_BUILDER(Name("RangeDataset").Device(DEVICE_CPU), + RangeDatasetOp); + +} // namespace +} // namespace data +} // namespace tensorflow diff --git a/pool/shard011/C++/0121967_main.cpp b/pool/shard011/C++/0121967_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d583c5781c2818dbb5c846cff49ef1e5c32e1c0d --- /dev/null +++ b/pool/shard011/C++/0121967_main.cpp @@ -0,0 +1,274 @@ +/**************************************************************************** +** +** Copyright (C) 1992-2008 Trolltech ASA. All rights reserved. +** +** This file is part of an example program for Qt. This example +** program may be used, distributed and modified without limitation. +** +*****************************************************************************/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(QT_NO_THREAD) +# error Thread support not enabled. +#endif + +// Use pointers to create semaphores after QApplication object! +QSemaphore* yellowSem, *greenSem; + + +class YellowThread : public QThread +{ +public: + YellowThread(QWidget *o) + : receiver(o), stopped(FALSE) + { ; } + + void run(); + void stop(); + + +private: + QWidget *receiver; + QMutex mutex; + bool stopped; +}; + + +void YellowThread::run() +{ + for (int i = 0; i < 20; i++) { + (*yellowSem)++; + + QCustomEvent *event = new QCustomEvent(12345); + event->setData(new QString("Yellow!")); + QApplication::postEvent(receiver, event); + msleep(200); + + (*greenSem)--; + + mutex.lock(); + if (stopped) { + stopped = FALSE; + mutex.unlock(); + break; + } + mutex.unlock(); + } + + (*yellowSem)++; + + QCustomEvent *event = new QCustomEvent(12346); + event->setData(new QString("Yellow!")); + QApplication::postEvent(receiver, event); + + (*greenSem)--; +} + +void YellowThread::stop() +{ + mutex.lock(); + stopped = TRUE; + mutex.unlock(); +} + + +class GreenThread: public QThread +{ +public: + GreenThread(QWidget *o) + : receiver(o), stopped( FALSE ) + { ; } + + void run(); + void stop(); + + +private: + QWidget *receiver; + QMutex mutex; + bool stopped; +}; + + +void GreenThread::run() +{ + for (int i = 0; i < 20; i++) { + (*greenSem)++; + + QCustomEvent *event = new QCustomEvent(12345); + event->setData(new QString("Green!")); + QApplication::postEvent(receiver, event); + msleep(200); + + (*yellowSem)--; + + mutex.lock(); + if (stopped) { + stopped = FALSE; + mutex.unlock(); + break; + } + mutex.unlock(); + } + + (*greenSem)++; + + QCustomEvent *event = new QCustomEvent(12346); + event->setData(new QString("Green!")); + QApplication::postEvent(receiver, event); + msleep(10); + + (*yellowSem)--; +} + +void GreenThread::stop() +{ + mutex.lock(); + stopped = TRUE; + mutex.unlock(); +} + + + +class SemaphoreExample : public QWidget +{ + Q_OBJECT +public: + SemaphoreExample(); + ~SemaphoreExample(); + + void customEvent(QCustomEvent *); + + +public slots: + void startExample(); + + +protected: + + +private: + QMultiLineEdit *mlineedit; + QPushButton *button; + QLabel *label; + + YellowThread yellowThread; + GreenThread greenThread; +}; + + +SemaphoreExample::SemaphoreExample() + : QWidget(), yellowThread(this), greenThread(this) +{ + yellowSem = new QSemaphore(1); + greenSem = new QSemaphore(1); + + button = new QPushButton("&Ignition!", this); + connect(button, SIGNAL(clicked()), SLOT(startExample())); + + mlineedit = new QMultiLineEdit(this); + label = new QLabel(this); + + QVBoxLayout *vbox = new QVBoxLayout(this, 5); + vbox->addWidget(button); + vbox->addWidget(mlineedit); + vbox->addWidget(label); +} + + +SemaphoreExample::~SemaphoreExample() +{ + bool stopYellow = yellowThread.running(), + stopGreen = greenThread.running(); + if (stopYellow) + yellowThread.stop(); + if (greenThread.running()) + greenThread.stop(); + if (stopYellow) + yellowThread.wait(); + if (stopGreen) + greenThread.wait(); + delete yellowSem; + delete greenSem; +} + + +void SemaphoreExample::startExample() +{ + if (yellowThread.running() || greenThread.running()) { + QMessageBox::information(this, "Sorry", + "The threads have not completed yet, and must finish before " + "they can be started again."); + + return; + } + + mlineedit->clear(); + + while (yellowSem->available() < yellowSem->total()) (*yellowSem)--; + (*yellowSem)++; + + yellowThread.start(); + greenThread.start(); +} + + +void SemaphoreExample::customEvent(QCustomEvent *event) { + switch (event->type()) { + case 12345: + { + QString *s = (QString *) event->data(); + + mlineedit->append(*s); + + if (*s == "Green!") + label->setBackgroundColor(green); + else + label->setBackgroundColor(yellow); + label->setText(*s); + + delete s; + + break; + } + + case 12346: + { + QString *s = (QString *) event->data(); + + QMessageBox::information(this, (*s) + " - Finished", + "The thread creating the \"" + *s + + "\" events has finished."); + delete s; + + break; + } + + default: + { + qWarning("Unknown custom event type: %d", event->type()); + } + } +} + + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + SemaphoreExample se; + app.setMainWidget(&se); + se.show(); + return app.exec(); +} + + +#include "main.moc" diff --git a/pool/shard011/C++/0121972_Read.cpp b/pool/shard011/C++/0121972_Read.cpp new file mode 100644 index 0000000000000000000000000000000000000000..63d1fc6ef4e6d5dbe873736e828c2d4ba14b0931 --- /dev/null +++ b/pool/shard011/C++/0121972_Read.cpp @@ -0,0 +1,70 @@ +/* + * Read.cpp + * + * Created on: April 22, 2013 + * Author: Md. Bahlul Haider + */ + +#include "Read.h" + +#include "Common.h" + + + +/********************************************************************************************************************** + Default constructor +**********************************************************************************************************************/ +Read::Read(void) +{ + // Initialize the variables. + readNumber = 0; + superReadID = 0; + fileIndex=0; +} + +/********************************************************************************************************************** + Another constructor +**********************************************************************************************************************/ +Read::Read(UINT64 fIndx) +{ + readNumber = 0; + superReadID = 0; + fileIndex=fIndx; +} + +/********************************************************************************************************************** + Default destructor +**********************************************************************************************************************/ +Read::~Read(void) +{ + // delete all the pointers. +} +/********************************************************************************************************************** + This function assigns an ID to the read. +**********************************************************************************************************************/ +bool Read::setReadNumber(UINT64 id) +{ + if(id <= 0) MYEXIT("ID less than 1."); + readNumber = id; // Set the read number. + return true; +} +/********************************************************************************************************************** + This function assigns an ID to the read. +**********************************************************************************************************************/ +void Read::setFileIndex(UINT64 id) +{ + if(id <= 0) MYEXIT("ID less than 1."); + fileIndex = id; // Set the read number. +} +/********************************************************************************************************************** + Returns the reverse complement of a read. +**********************************************************************************************************************/ + +void Read::setReadHashOffset(UINT64 offset) +{ + readHashOffset=offset; +} + + + + diff --git a/pool/shard011/C++/0121974_CWE197_Numeric_Truncation_Error__short_rand_72b.cpp b/pool/shard011/C++/0121974_CWE197_Numeric_Truncation_Error__short_rand_72b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b0ebf841eac0605f50e67334fc0bcc2e4f0e0ddf --- /dev/null +++ b/pool/shard011/C++/0121974_CWE197_Numeric_Truncation_Error__short_rand_72b.cpp @@ -0,0 +1,55 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE197_Numeric_Truncation_Error__short_rand_72b.cpp +Label Definition File: CWE197_Numeric_Truncation_Error__short.label.xml +Template File: sources-sink-72b.tmpl.cpp +*/ +/* + * @description + * CWE: 197 Numeric Truncation Error + * BadSource: rand Set data to result of RAND32(), which could be negative + * GoodSource: Less than CHAR_MAX + * Sinks: + * BadSink : Convert data to a char + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +using namespace std; + +namespace CWE197_Numeric_Truncation_Error__short_rand_72 +{ + +#ifndef OMITBAD + +void badSink(vector dataVector) +{ + /* copy data out of dataVector */ + short data = dataVector[2]; + { + /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ + char charData = (char)data; + printHexCharLine(charData); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector dataVector) +{ + short data = dataVector[2]; + { + /* POTENTIAL FLAW: Convert data to a char, possibly causing a truncation error */ + char charData = (char)data; + printHexCharLine(charData); + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard011/C++/0121975_distancemaplib.cpp b/pool/shard011/C++/0121975_distancemaplib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..00631803ad65aa24c60b1188921cad8f5d2f9114 --- /dev/null +++ b/pool/shard011/C++/0121975_distancemaplib.cpp @@ -0,0 +1,70 @@ +#include "distancemaplib.h" + + + +void ComputeDistanceMap(const DistanceMapImage src, DistanceMapImage& dst, bool animation){ + Cell _c; + Cell _eight_cell; + ushort _value=0; + ushort _updated_value=0; + CellContainer _container; + Point _expanded_point; + + EightExpansionUtil _eightExpansion; + EightExpansion_init(_eightExpansion); + int _cols=src.cols; + int _rows=src.rows; + dst = Mat::ones(_rows,_cols,CV_16UC1); + dst.setTo(Scalar(65535)); + + int _eightExpansion_size = _eightExpansion.size(); + //first iteration to get all the obstacles + //they will be the seed of my next cycle + for(int i =0;i<_rows; i++){ + for(int j =0;j<_cols; j++){ + _value = (ushort)src.at(i,j); + if(_value==0){ + _c.point.x = j; + _c.point.y = i; + _c.parent.x= j; + _c.parent.y= i; + _c.value = 0; + _container.push(_c); + dst.at(_c.point) = 0; + } + } + } + + //second cycle, region growing like + int _cnt=0; + while(!_container.empty()){ + if(animation){ + if(_cnt%1000==0){ + cv::normalize(dst,dst,0,65535,cv::NORM_MINMAX); + imshow("animation",dst); + waitKey(1); + } + _cnt++; + } + Cell current; + Cell _cc = _container.top(); + _value = dst.at(_cc.point); + _container.pop(); + for(int i =0;i<_eightExpansion.size();i++){ + _expanded_point = _cc.point +_eightExpansion.at(i).point ; + //_updated_value = _value + _eightExpansion.at(i).value; + _updated_value = (pow((_cc.parent.x - _expanded_point.x),2)+pow((_cc.parent.y - _expanded_point.y),2)); + if( _expanded_point.x > 0 &&_expanded_point.x < _cols && _expanded_point.y > 0 && _expanded_point.y < _rows ){ + if( dst.at(_expanded_point) !=0 && dst.at(_expanded_point) > _updated_value){ + dst.at(_expanded_point) = _updated_value; + current.point= _expanded_point; + current.parent=_cc.parent; + current.value=_updated_value; + _container.push(current); + } + } + } + } + + +} diff --git a/pool/shard011/C++/0121976_03constParam.cpp b/pool/shard011/C++/0121976_03constParam.cpp new file mode 100644 index 0000000000000000000000000000000000000000..72ab07cbd9b4f46769960538f955429c43732d22 --- /dev/null +++ b/pool/shard011/C++/0121976_03constParam.cpp @@ -0,0 +1,43 @@ +// File: 03constParam.cpp for CS319-Week 12 +// Author: Niall Madden +// Date: March 2017 +// What: An example of a const parameter used in operator overloading. +// For more information see +// http://www.maths.nuigalway.ie/~niall/CS319 + +#include +#include + +class Number +{ +private: + double x; +public: + Number() {x=0.0;}; + Number(const Number ©) {x=copy.x;}; // notice const + void set_x(double X) {x=X;}; + double get_x(void) {return(x);}; + Number operator+(Number &b) + { + Number sum; + sum.x = x + b.x; + return(sum); + } +}; + + +int main(void) +{ + Number a; + a.set_x(121.234); + Number b(a+a); + std::cout << "a.x= \t" << a.get_x() << std::endl; + std::cout << "b.x= \t" << b.get_x() << std::endl; + return(0); +} + + + + + + diff --git a/pool/shard011/C++/0121977_GffreadSupportTask.cpp b/pool/shard011/C++/0121977_GffreadSupportTask.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8bf9a6528c3ce537d8fae0d8403f1e86092cad53 --- /dev/null +++ b/pool/shard011/C++/0121977_GffreadSupportTask.cpp @@ -0,0 +1,81 @@ +/** + * UGENE - Integrated Bioinformatics Tools. + * Copyright (C) 2008-2017 UniPro + * http://ugene.net + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#include "CufflinksSupport.h" + +#include +#include +#include +#include + +#include "GffreadSupportTask.h" + +namespace U2 { + +GffreadSupportTask::GffreadSupportTask(const GffreadSettings &_settings) +: ExternalToolSupportTask(tr("Running Gffread task"), TaskFlags_NR_FOSE_COSC), settings(_settings) +{ + +} + +void GffreadSupportTask::prepare() { + checkFormat(settings.genomeUrl, BaseDocumentFormats::FASTA); + CHECK_OP(stateInfo, ); + checkFormat(settings.transcriptsUrl, BaseDocumentFormats::GTF); + CHECK_OP(stateInfo, ); + + ExternalToolRunTask* runTask = new ExternalToolRunTask(ET_GFFREAD, settings.getArguments(), new ExternalToolLogParser()); + setListenerForTask(runTask); + addSubTask(runTask); +} + +QString GffreadSupportTask::result() const { + return settings.outputUrl; +} + +void GffreadSupportTask::checkFormat(const QString &url, const DocumentFormatId &target) { + FormatDetectionConfig cfg; + cfg.bestMatchesOnly = false; + QList result = DocumentUtils::detectFormat(url, cfg); + if (result.isEmpty()) { + setError(tr("Unknown file format: %1").arg(url)); + return; + } + foreach (const FormatDetectionResult &r, result) { + SAFE_POINT(NULL != r.format, "NULL doc format", ); + if (r.format->getFormatId() == target) { + return; + } + } + setError(tr("The file format is not [%1]: %2").arg(target).arg(url)); +} + +QStringList GffreadSettings::getArguments() const { + QStringList args; + args << "-w"; + args << outputUrl; + args << "-g"; + args << genomeUrl; + args << transcriptsUrl; + return args; +} + +} // U2 diff --git a/pool/shard011/C++/0121979_Date.cpp b/pool/shard011/C++/0121979_Date.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78a7dd4044f7c40caf4b8f009ea4ceb4b0e5113f --- /dev/null +++ b/pool/shard011/C++/0121979_Date.cpp @@ -0,0 +1,38 @@ +#include +#include + +TEST(DateTest, DateConstruct) { + adbase::Date date; + EXPECT_FALSE(date.valid()); + adbase::Date date1(1970, 1, 1); + EXPECT_EQ(date1.toIsoString(), "1970-01-01"); + adbase::Date date2(2457545); + EXPECT_EQ(date2.toIsoString(), "2016-06-05"); + + date1.swap(date2); + EXPECT_EQ(date1.toIsoString(), "2016-06-05"); + EXPECT_EQ(date2.toIsoString(), "1970-01-01"); + EXPECT_TRUE(date1.valid()); + EXPECT_TRUE(date2.valid()); + + EXPECT_EQ(adbase::Date::kJulianDayOf1970_01_01, 2440588); +} + +TEST(DateTest, DateJulianDayNumber) { + adbase::Date date(2016, 6, 5); + EXPECT_EQ(date.julianDayNumber(), 2457545); +} + +TEST(DateTest, DateDetail) { + adbase::Date date(2016, 6, 5); + EXPECT_EQ(date.weekDay(), 0); + EXPECT_EQ(date.day(), 5); + EXPECT_EQ(date.month(), 6); + EXPECT_EQ(date.year(), 2016); + + adbase::Date date1(2016, 6, 5); + adbase::Date date2(2016, 8, 4); + EXPECT_FALSE(date1 > date2); + EXPECT_TRUE(date1 < date2); + EXPECT_TRUE(date1 == date); +} diff --git a/pool/shard011/C++/0121980_HostStartup.cpp b/pool/shard011/C++/0121980_HostStartup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a857505c2c4eb5100bccf3e5447d3410bf984673 --- /dev/null +++ b/pool/shard011/C++/0121980_HostStartup.cpp @@ -0,0 +1,102 @@ +/* + ============================================================================== + + This file is part of the JUCE library. + Copyright (c) 2013 - Raw Material Software Ltd. + + Permission is granted to use this software under the terms of either: + a) the GPL v2 (or any later version) + b) the Affero GPL v3 + + Details of these licenses can be found at: www.gnu.org/licenses + + JUCE 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. + + ------------------------------------------------------------------------------ + + To release a closed-source product which uses JUCE, commercial licenses are + available: visit www.juce.com for more information. + + ============================================================================== +*/ + +#include "../JuceLibraryCode/JuceHeader.h" +#include "MainHostWindow.h" +#include "InternalFilters.h" + +#if ! (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_VST3 || JUCE_PLUGINHOST_AU) + #error "If you're building the audio plugin host, you probably want to enable VST and/or AU support" +#endif + + +//============================================================================== +class PluginHostApp : public JUCEApplication +{ +public: + PluginHostApp() {} + + void initialise (const String& commandLine) override + { + // initialise our settings file.. + + PropertiesFile::Options options; + options.applicationName = "Juce Audio Plugin Host"; + options.filenameSuffix = "settings"; + options.osxLibrarySubFolder = "Preferences"; + + appProperties = new ApplicationProperties(); + appProperties->setStorageParameters (options); + + LookAndFeel::setDefaultLookAndFeel (&lookAndFeel); + + mainWindow = new MainHostWindow(); + mainWindow->setUsingNativeTitleBar (true); + + commandManager.registerAllCommandsForTarget (this); + commandManager.registerAllCommandsForTarget (mainWindow); + + mainWindow->menuItemsChanged(); + + if (commandLine.isNotEmpty() + && ! commandLine.trimStart().startsWith ("-") + && mainWindow->getGraphEditor() != nullptr) + mainWindow->getGraphEditor()->graph.loadFrom (File::getCurrentWorkingDirectory() + .getChildFile (commandLine), true); + } + + void shutdown() override + { + mainWindow = nullptr; + appProperties = nullptr; + LookAndFeel::setDefaultLookAndFeel (nullptr); + } + + void systemRequestedQuit() override + { + if (mainWindow != nullptr) + mainWindow->tryToQuitApplication(); + else + JUCEApplicationBase::quit(); + } + + const String getApplicationName() override { return "Juce Plug-In Host"; } + const String getApplicationVersion() override { return ProjectInfo::versionString; } + bool moreThanOneInstanceAllowed() override { return true; } + + ApplicationCommandManager commandManager; + ScopedPointer appProperties; + LookAndFeel_V3 lookAndFeel; + +private: + ScopedPointer mainWindow; +}; + +static PluginHostApp& getApp() { return *dynamic_cast(JUCEApplication::getInstance()); } +ApplicationCommandManager& getCommandManager() { return getApp().commandManager; } +ApplicationProperties& getAppProperties() { return *getApp().appProperties; } + + +// This kicks the whole thing off.. +START_JUCE_APPLICATION (PluginHostApp) diff --git a/pool/shard011/C++/0121982_RequestOrResponse.cc b/pool/shard011/C++/0121982_RequestOrResponse.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5d6aafdc4d43f82926198c99f877827751e077f --- /dev/null +++ b/pool/shard011/C++/0121982_RequestOrResponse.cc @@ -0,0 +1,90 @@ +/////////////////////////////////////////////////////////////////////////// +// +// libkafka - C/C++ client for Apache Kafka v0.8+ +// +// David Tompkins -- 8/8/2013 +// tompkins@adobe_dot_com +// +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// +/////////////////////////////////////////////////////////////////////////// + +#include +#include + +#include "RequestOrResponse.h" + +using namespace std; + +namespace LibKafka { + +RequestOrResponse::RequestOrResponse(unsigned char *buffer, bool releaseBuffer) : WireFormatter() +{ + this->packet = new Packet(buffer, releaseBuffer); + + D(cout.flush() << "--------------RequestOrResponse(buffer)\n";) + + // Kafka Protocol: int32 size - managed within the Packet class +} + +RequestOrResponse::RequestOrResponse() : WireFormatter() +{ + this->packet = new Packet(); + + D(cout.flush() << "--------------RequestOrResponse(params)\n";) +} + +RequestOrResponse::~RequestOrResponse() +{ + delete this->packet; + + D(cout.flush() << "--------------~RequestOrResponse()\n";) +} + +unsigned char* RequestOrResponse::toWireFormat(bool updatePacketSize) +{ + D(cout.flush() << "--------------RequestOrResponse::toWireFormat()\n";) + + // Kafka Protocol: int32 size - managed within the Packet class + unsigned char *buffer = this->packet->toWireFormat(false); + if (updatePacketSize) this->packet->updatePacketSize(); + return buffer; +} + +int RequestOrResponse::getWireFormatSize(bool includePacketSize) +{ + D(cout.flush() << "--------------RequestOrResponse::getWireFormatSize()\n";) + + // Packet.size + + int size = 0; + if (includePacketSize) size += this->packet->getWireFormatSize(includePacketSize); + return size; +} + +int RequestOrResponse::size(bool includeProtocolSizeFieldLength) const +{ + return this->packet->getSize(includeProtocolSizeFieldLength); +} + +ostream& operator<< (ostream& os, const RequestOrResponse& r) +{ + os << "RequestOrResponse.size:" << r.size() << "\n"; + return os; +} + +}; // namespace LibKafka diff --git a/pool/shard011/C++/0121984_scroll_state_unittest.cc b/pool/shard011/C++/0121984_scroll_state_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a3a8965ad96d94b86880f70ddcf505b83ca1aef --- /dev/null +++ b/pool/shard011/C++/0121984_scroll_state_unittest.cc @@ -0,0 +1,90 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "cc/input/scroll_state.h" + +#include "cc/layers/layer_impl.h" +#include "cc/test/fake_impl_task_runner_provider.h" +#include "cc/test/fake_layer_tree_host_impl.h" +#include "cc/test/test_shared_bitmap_manager.h" +#include "cc/test/test_task_graph_runner.h" +#include "cc/trees/layer_tree_impl.h" +#include "cc/trees/scroll_node.h" +#include "testing/gmock/include/gmock/gmock.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace cc { + +class ScrollStateTest : public testing::Test {}; + +TEST_F(ScrollStateTest, ConsumeDeltaNative) { + const float delta_x = 12.3f; + const float delta_y = 3.9f; + + const float delta_x_to_consume = 1.2f; + const float delta_y_to_consume = 2.3f; + + ScrollStateData scroll_state_data; + scroll_state_data.delta_x = delta_x; + scroll_state_data.delta_y = delta_y; + ScrollState scroll_state(scroll_state_data); + + EXPECT_FLOAT_EQ(delta_x, scroll_state.delta_x()); + EXPECT_FLOAT_EQ(delta_y, scroll_state.delta_y()); + EXPECT_FALSE(scroll_state.delta_consumed_for_scroll_sequence()); + EXPECT_FALSE(scroll_state.FullyConsumed()); + + scroll_state.ConsumeDelta(0, 0); + EXPECT_FLOAT_EQ(delta_x, scroll_state.delta_x()); + EXPECT_FLOAT_EQ(delta_y, scroll_state.delta_y()); + EXPECT_FALSE(scroll_state.delta_consumed_for_scroll_sequence()); + EXPECT_FALSE(scroll_state.FullyConsumed()); + + scroll_state.ConsumeDelta(delta_x_to_consume, 0); + EXPECT_FLOAT_EQ(delta_x - delta_x_to_consume, scroll_state.delta_x()); + EXPECT_FLOAT_EQ(delta_y, scroll_state.delta_y()); + EXPECT_TRUE(scroll_state.delta_consumed_for_scroll_sequence()); + EXPECT_FALSE(scroll_state.FullyConsumed()); + + scroll_state.ConsumeDelta(0, delta_y_to_consume); + EXPECT_FLOAT_EQ(delta_x - delta_x_to_consume, scroll_state.delta_x()); + EXPECT_FLOAT_EQ(delta_y - delta_y_to_consume, scroll_state.delta_y()); + EXPECT_TRUE(scroll_state.delta_consumed_for_scroll_sequence()); + EXPECT_FALSE(scroll_state.FullyConsumed()); + + scroll_state.ConsumeDelta(scroll_state.delta_x(), scroll_state.delta_y()); + EXPECT_TRUE(scroll_state.delta_consumed_for_scroll_sequence()); + EXPECT_TRUE(scroll_state.FullyConsumed()); +} + +TEST_F(ScrollStateTest, CurrentNativeScrollingScrollable) { + ScrollStateData scroll_state_data; + ScrollState scroll_state(scroll_state_data); + + FakeImplTaskRunnerProvider task_runner_provider; + TestSharedBitmapManager shared_bitmap_manager; + TestTaskGraphRunner task_graph_runner; + FakeLayerTreeHostImpl host_impl(&task_runner_provider, &shared_bitmap_manager, + &task_graph_runner); + + std::unique_ptr layer_impl = + LayerImpl::Create(host_impl.active_tree(), 1); + ScrollNode* scroll_node = + host_impl.active_tree()->property_trees()->scroll_tree.Node( + layer_impl->scroll_tree_index()); + scroll_state.set_current_native_scrolling_node(scroll_node); + EXPECT_EQ(scroll_node, scroll_state.current_native_scrolling_node()); +} + +TEST_F(ScrollStateTest, FullyConsumed) { + ScrollStateData scroll_state_data; + scroll_state_data.delta_x = 1; + scroll_state_data.delta_y = 3; + ScrollState scroll_state(scroll_state_data); + + EXPECT_FALSE(scroll_state.FullyConsumed()); + scroll_state.ConsumeDelta(1, 3); + EXPECT_TRUE(scroll_state.FullyConsumed()); +} +} // namespace cc diff --git a/pool/shard011/C++/0121986_gr_wavfile_sink.cc b/pool/shard011/C++/0121986_gr_wavfile_sink.cc new file mode 100644 index 0000000000000000000000000000000000000000..b60a6e3abdd131e8297b53714351e94f5f7fd5e8 --- /dev/null +++ b/pool/shard011/C++/0121986_gr_wavfile_sink.cc @@ -0,0 +1,279 @@ +/* -*- c++ -*- */ +/* + * Copyright 2004,2006,2007,2008,2009,2010 Free Software Foundation, Inc. + * + * This file is part of GNU Radio + * + * GNU Radio 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. + * + * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// win32 (mingw/msvc) specific +#ifdef HAVE_IO_H +#include +#endif +#ifdef O_BINARY +#define OUR_O_BINARY O_BINARY +#else +#define OUR_O_BINARY 0 +#endif + +// should be handled via configure +#ifdef O_LARGEFILE +#define OUR_O_LARGEFILE O_LARGEFILE +#else +#define OUR_O_LARGEFILE 0 +#endif + + +gr_wavfile_sink_sptr +gr_make_wavfile_sink(const char *filename, + int n_channels, + unsigned int sample_rate, + int bits_per_sample) +{ + return gnuradio::get_initial_sptr(new gr_wavfile_sink (filename, + n_channels, + sample_rate, + bits_per_sample)); +} + +gr_wavfile_sink::gr_wavfile_sink(const char *filename, + int n_channels, + unsigned int sample_rate, + int bits_per_sample) + : gr_sync_block ("wavfile_sink", + gr_make_io_signature(1, n_channels, sizeof(float)), + gr_make_io_signature(0, 0, 0)), + d_sample_rate(sample_rate), d_nchans(n_channels), + d_fp(0), d_new_fp(0), d_updated(false) +{ + if (bits_per_sample != 8 && bits_per_sample != 16) { + throw std::runtime_error("Invalid bits per sample (supports 8 and 16)"); + } + d_bytes_per_sample = bits_per_sample / 8; + d_bytes_per_sample_new = d_bytes_per_sample; + + if (!open(filename)) { + throw std::runtime_error ("can't open file"); + } + + if (bits_per_sample == 8) { + d_max_sample_val = 0xFF; + d_min_sample_val = 0; + d_normalize_fac = d_max_sample_val/2; + d_normalize_shift = 1; + } else { + d_max_sample_val = 0x7FFF; + d_min_sample_val = -0x7FFF; + d_normalize_fac = d_max_sample_val; + d_normalize_shift = 0; + if (bits_per_sample != 16) { + fprintf(stderr, "Invalid bits per sample value requested, using 16"); + } + } +} + + +bool +gr_wavfile_sink::open(const char* filename) +{ + gruel::scoped_lock guard(d_mutex); + + // we use the open system call to get access to the O_LARGEFILE flag. + int fd; + if ((fd = ::open (filename, + O_WRONLY|O_CREAT|O_TRUNC|OUR_O_LARGEFILE|OUR_O_BINARY, + 0664)) < 0){ + perror (filename); + return false; + } + + if (d_new_fp) { // if we've already got a new one open, close it + fclose(d_new_fp); + d_new_fp = 0; + } + + if ((d_new_fp = fdopen (fd, "wb")) == NULL) { + perror (filename); + ::close(fd); // don't leak file descriptor if fdopen fails. + return false; + } + d_updated = true; + + if (!gri_wavheader_write(d_new_fp, + d_sample_rate, + d_nchans, + d_bytes_per_sample_new)) { + fprintf(stderr, "[%s] could not write to WAV file\n", __FILE__); + exit(-1); + } + + return true; +} + + +void +gr_wavfile_sink::close() +{ + gruel::scoped_lock guard(d_mutex); + + if (!d_fp) + return; + + close_wav(); +} + +void gr_wavfile_sink::close_wav() +{ + unsigned int byte_count = d_sample_count * d_bytes_per_sample; + + gri_wavheader_complete(d_fp, byte_count); + + fclose(d_fp); + d_fp = NULL; +} + + +gr_wavfile_sink::~gr_wavfile_sink () +{ + if (d_new_fp) { + fclose(d_new_fp); + } + + close(); +} + + +int +gr_wavfile_sink::work (int noutput_items, + gr_vector_const_void_star &input_items, + gr_vector_void_star &output_items) +{ + float **in = (float **) &input_items[0]; + int n_in_chans = input_items.size(); + + short int sample_buf_s; + + int nwritten; + + do_update(); // update: d_fp is reqd + if (!d_fp) // drop output on the floor + return noutput_items; + + for (nwritten = 0; nwritten < noutput_items; nwritten++) { + for (int chan = 0; chan < d_nchans; chan++) { + // Write zeros to channels which are in the WAV file + // but don't have any inputs here + if (chan < n_in_chans) { + sample_buf_s = + convert_to_short(in[chan][nwritten]); + } else { + sample_buf_s = 0; + } + + gri_wav_write_sample(d_fp, sample_buf_s, d_bytes_per_sample); + + if (feof(d_fp) || ferror(d_fp)) { + fprintf(stderr, "[%s] file i/o error\n", __FILE__); + close(); + exit(-1); + } + d_sample_count++; + } + } + + return nwritten; +} + + +short int +gr_wavfile_sink::convert_to_short(float sample) +{ + sample += d_normalize_shift; + sample *= d_normalize_fac; + if (sample > d_max_sample_val) { + sample = d_max_sample_val; + } else if (sample < d_min_sample_val) { + sample = d_min_sample_val; + } + + return (short int) roundf(sample); +} + + +void +gr_wavfile_sink::set_bits_per_sample(int bits_per_sample) +{ + gruel::scoped_lock guard(d_mutex); + if (bits_per_sample == 8 || bits_per_sample == 16) { + d_bytes_per_sample_new = bits_per_sample / 8; + } +} + + +void +gr_wavfile_sink::set_sample_rate(unsigned int sample_rate) +{ + gruel::scoped_lock guard(d_mutex); + d_sample_rate = sample_rate; +} + + +void +gr_wavfile_sink::do_update() +{ + if (!d_updated) { + return; + } + + gruel::scoped_lock guard(d_mutex); // hold mutex for duration of this block + if (d_fp) { + close_wav(); + } + + d_fp = d_new_fp; // install new file pointer + d_new_fp = 0; + d_sample_count = 0; + d_bytes_per_sample = d_bytes_per_sample_new; + + if (d_bytes_per_sample == 1) { + d_max_sample_val = UCHAR_MAX; + d_min_sample_val = 0; + d_normalize_fac = d_max_sample_val/2; + d_normalize_shift = 1; + } else if (d_bytes_per_sample == 2) { + d_max_sample_val = SHRT_MAX; + d_min_sample_val = SHRT_MIN; + d_normalize_fac = d_max_sample_val; + d_normalize_shift = 0; + } + + d_updated = false; +} diff --git a/pool/shard011/C++/0121990_removepreset.cpp b/pool/shard011/C++/0121990_removepreset.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6daf23db3111b29c009a6396ffb424036b209534 --- /dev/null +++ b/pool/shard011/C++/0121990_removepreset.cpp @@ -0,0 +1,24 @@ +#include "removepreset.h" +#include "message.h" + +using namespace ONVIF; + +RemovePreset::RemovePreset(QObject *parent):QObject(parent) +{ + +} + +RemovePreset::~RemovePreset() +{ + +} + +QDomElement RemovePreset::toxml() +{ + QDomElement removePreset = newElement("wsdl:RemovePreset"); + QDomElement profileToken = newElement("wsdl:ProfileToken",this->profileToken()); + QDomElement presetToken = newElement("wsdl:PresetToken",this->presetToken()); + removePreset.appendChild(profileToken); + removePreset.appendChild(presetToken); + return removePreset; +} diff --git a/pool/shard011/C++/0121993_source_c_impl.cc b/pool/shard011/C++/0121993_source_c_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..621c1d7767f46da13c21b7d357d35551f1580cbf --- /dev/null +++ b/pool/shard011/C++/0121993_source_c_impl.cc @@ -0,0 +1,252 @@ +/* -*- c++ -*- */ +/* + * Copyright 2011-2013 Free Software Foundation, Inc. + * + * GNU Radio 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. + * + * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "source_c_impl.h" +#include +#include // needed for extended API +#include +#include +#include + +//#include +//using namespace std; + +namespace gr { + namespace fcd { + + /* + * Create a new instance of gr::fcd::source_c_impl and return an + * upcasted boost shared_ptr. This is effectively the public + * constructor. + */ + source_c::sptr + source_c::make(const std::string device_name) + { + return gnuradio::get_initial_sptr + (new source_c_impl(device_name)); + } + + static const int MIN_IN = 0; /*!< Minimum number of input streams. */ + static const int MAX_IN = 0; /*!< Maximum number of input streams. */ + static const int MIN_OUT = 1; /*!< Minimum number of output streams. */ + static const int MAX_OUT = 1; /*!< Maximum number of output streams. */ + + source_c_impl::source_c_impl(const std::string device_name) + : gr::hier_block2("fcd_source_c", + gr::io_signature::make(MIN_IN, MAX_IN, sizeof(gr_complex)), + gr::io_signature::make(MIN_OUT, MAX_OUT, sizeof(gr_complex))), + d_freq_corr(-120), + d_freq_req(0) + { + gr::blocks::float_to_complex::sptr f2c; + + /* Audio source; sample rate fixed at 96kHz */ + fcd = gr::audio::source::make(96000, device_name, true); + + /* block to convert stereo audio to a complex stream */ + f2c = gr::blocks::float_to_complex::make(1); + + connect(fcd, 0, f2c, 0); + connect(fcd, 1, f2c, 1); + connect(f2c, 0, self(), 0); + } + + source_c_impl::~source_c_impl() + { + } + + // Set frequency with Hz resolution + void source_c_impl::set_freq(int freq) + { + FCD_MODE_ENUM __GR_ATTR_UNUSED fme; + double f = (double)freq; + + /* valid range 50 MHz - 2.0 GHz */ + if((freq < 50000000) || (freq > 2000000000)) { + return; + } + + d_freq_req = freq; + f *= 1.0 + d_freq_corr/1000000.0; + + fme = fcdAppSetFreq((int)f); + /* TODO: check fme */ + } + + // Set frequency with Hz resolution (type float) + void source_c_impl::set_freq(float freq) + { + FCD_MODE_ENUM __GR_ATTR_UNUSED fme; + double f = (double)freq; + + /* valid range 50 MHz - 2.0 GHz */ + if((freq < 50.0e6) || (freq > 2.0e9)) { + return; + } + + d_freq_req = (int)freq; + f *= 1.0 + d_freq_corr/1000000.0; + + fme = fcdAppSetFreq((int)f); + /* TODO: check fme */ + } + + + // Set frequency with kHz resolution. + void source_c_impl::set_freq_khz(int freq) + { + FCD_MODE_ENUM __GR_ATTR_UNUSED fme; + double f = freq*1000.0; + + /* valid range 50 MHz - 2.0 GHz */ + if((freq < 50000) || (freq > 2000000)) { + return; + } + + d_freq_req = freq*1000; + f *= 1.0 + d_freq_corr/1000000.0; + + fme = fcdAppSetFreqkHz((int)(f/1000.0)); + /* TODO: check fme */ + } + + + // Set LNA gain + void source_c_impl::set_lna_gain(float gain) + { + FCD_MODE_ENUM __GR_ATTR_UNUSED fme; + unsigned char g; + + /* convert to nearest discrete value */ + if(gain > 27.5) { + g = 14; // 30.0 dB + } + else if(gain > 22.5) { + g = 13; // 25.0 dB + } + else if(gain > 18.75) { + g = 12; // 20.0 dB + } + else if(gain > 16.25) { + g = 11; // 17.5 dB + } + else if(gain > 13.75) { + g = 10; // 15.0 dB + } + else if(gain > 11.25) { + g = 9; // 12.5 dB + } + else if(gain > 8.75) { + g = 8; // 10.0 dB + } + else if(gain > 6.25) { + g = 7; // 7.5 dB + } + else if(gain > 3.75) { + g = 6; // 5.0 dB + } + else if(gain > 1.25) { + g = 5; // 2.5 dB + } + else if(gain > -1.25) { + g = 4; // 0.0 dB + } + else if(gain > -3.75) { + g = 1; // -2.5 dB + } + else { + g = 0; // -5.0 dB + } + + fme = fcdAppSetParam(FCD_CMD_APP_SET_LNA_GAIN, &g, 1); + /* TODO: check fme */ + } + + // Set mixer gain + void source_c_impl::set_mixer_gain(float gain) + { + __GR_ATTR_UNUSED FCD_MODE_ENUM fme; + unsigned char g; + + if( gain > 4.0 ) { + g = TMGE_P12_0DB; + } + else { + g = TMGE_P4_0DB; + } + + fme = fcdAppSetParam(FCD_CMD_APP_SET_MIXER_GAIN, &g, 1); + /* TODO: check fme */ + } + + // Set new frequency correction + void source_c_impl::set_freq_corr(int ppm) + { + d_freq_corr = ppm; + // re-tune with new correction value + set_freq(d_freq_req); + } + + // Set DC offset correction. + void source_c_impl::set_dc_corr(double _dci, double _dcq) + { + union { + unsigned char auc[4]; + struct { + signed short dci; // equivalent of qint16 which should be 16 bit everywhere + signed short dcq; + }; + } dcinfo; + + if((_dci < -1.0) || (_dci > 1.0) || (_dcq < -1.0) || (_dcq > 1.0)) + return; + + dcinfo.dci = static_cast(_dci*32768.0); + dcinfo.dcq = static_cast(_dcq*32768.0); + + fcdAppSetParam(FCD_CMD_APP_SET_DC_CORR, dcinfo.auc, 4); + } + + // Set IQ phase and gain balance. + void source_c_impl::set_iq_corr(double _gain, double _phase) + { + union { + unsigned char auc[4]; + struct { + signed short phase; + signed short gain; + }; + } iqinfo; + + if ((_gain < -1.0) || (_gain > 1.0) || (_phase < -1.0) || (_phase > 1.0)) + return; + + iqinfo.phase = static_cast(_phase*32768.0); + iqinfo.gain = static_cast(_gain*32768.0); + + fcdAppSetParam(FCD_CMD_APP_SET_IQ_CORR, iqinfo.auc, 4); + } + + } /* namespace fcd */ +} /* namespace gr */ diff --git a/pool/shard011/C++/0121994_tree.cc b/pool/shard011/C++/0121994_tree.cc new file mode 100644 index 0000000000000000000000000000000000000000..67625dc21a3a22f1257063615d21f65e27f40696 --- /dev/null +++ b/pool/shard011/C++/0121994_tree.cc @@ -0,0 +1,36 @@ +#include +#include "tree.ph" + +Tree::Tree() { + myid = 0; + n = 0; + printf("Node\t%d\ton\t%s\n", myid, POPSystem::GetHost().c_str()); +} + +Tree::Tree(int id) { + myid = id; + n = 0; + printf("Node\t%d\ton\t%s\n", myid, POPSystem::GetHost().c_str()); +} + +Tree::~Tree() { + printf("Destroy node \t%d now!\n", myid); + for (int i = 0; i < n; i++) { + delete test[i]; + } +} + +void Tree::Create(int w, int d, int startid) { + n = 0; + if (d <= 0 || w <= 0) { + printf("Node\t%d: leaf\n", myid); + } else { + for (int i = 0; i < w; i++) { + test[i] = new Tree(startid + i); + n++; + test[i]->Create(w, d - 1, startid + w * (i + 1)); + } + } +} + +@pack(Tree); diff --git a/pool/shard011/C++/0121995_buffer_hole_manager.cpp b/pool/shard011/C++/0121995_buffer_hole_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19021fa4a08717b55dce66fb7de0eb42fc4df5b2 --- /dev/null +++ b/pool/shard011/C++/0121995_buffer_hole_manager.cpp @@ -0,0 +1,98 @@ +#include "./buffer_hole_manager.h" +#include +#include + +namespace Graphics +{ + +QLoggingCategory bhmChan("Graphics.BufferHoleManager"); + +BufferHoleManager::BufferHoleManager(int bufferSize) : bufferSize(bufferSize) +{ + holes[0] = bufferSize; +} + +bool BufferHoleManager::reserve(uint requestSize, uint &offset) +{ + qCInfo(bhmChan) << this << "request" << requestSize; + assert(requestSize > 0); + + if (requestSize > bufferSize) + return false; + + offset = -1; + + // FIXME: try to find optimal hole to avoid fragmentation + for (auto &hole : holes) + { + const uint holeStart = hole.first; + const uint holeSize = hole.second; + + if (holeSize >= requestSize) + { + reservedChunks[holeStart] = requestSize; + + if (holeSize > requestSize) + holes[holeStart + requestSize] = holeSize - requestSize; + + // remove old hole + holes.erase(holeStart); + + offset = holeStart; + + return true; + } + } + + qCCritical(bhmChan) << this << "No buffer hole found for size " + << requestSize << " in buffer of size " << bufferSize; + return false; +} + +bool BufferHoleManager::release(uint offset) +{ + auto reserved = reservedChunks.find(offset); + + if (reserved == reservedChunks.end()) + return false; + + const uint chunkSize = reserved->second; + reservedChunks.erase(offset); + holes[offset] = chunkSize; + + tryJoiningWithNextHole(offset, chunkSize); + tryJoiningWithPreviousHole(offset); + + return true; +} + +void BufferHoleManager::tryJoiningWithNextHole(uint offset, uint chunkSize) +{ + auto hole = holes.find(offset + chunkSize); + if (hole != holes.end()) + { + qCDebug(bhmChan) << this << "joining next hole at" << hole->first << "(" + << hole->second + << "). New size:" << hole->second + chunkSize; + + const uint nextHoleSize = hole->second; + holes.erase(hole->first); + holes[offset] = nextHoleSize + chunkSize; + } +} + +void BufferHoleManager::tryJoiningWithPreviousHole(uint offset) +{ + auto hole = --holes.find(offset); + + if ((hole->first + hole->second) == offset) + { + qCDebug(bhmChan) << this << "joining previous hole at" << hole->first << "(" + << hole->second + << "). New size:" << hole->second + holes[offset]; + + hole->second += holes[offset]; + holes.erase(offset); + } +} +} // namespace Graphics diff --git a/pool/shard011/C++/0121997_Text_Encadre.cpp b/pool/shard011/C++/0121997_Text_Encadre.cpp new file mode 100644 index 0000000000000000000000000000000000000000..181bdf220c9a809688deb3e2cdb2983e2fd8f78b --- /dev/null +++ b/pool/shard011/C++/0121997_Text_Encadre.cpp @@ -0,0 +1,114 @@ +#include "Text_Encadre.hpp" +#include + +using namespace sf; +using namespace std; + +TEXT_ENCADRE::TEXT_ENCADRE(const char* txt) +{ + text.SetText(txt); + init(); +}; + +void TEXT_ENCADRE::Draw(RenderTarget* App) +{ + if (string(text.GetText()) !="") + { + App->Draw(sprite); + App->Draw(text); + } +}; + +void TEXT_ENCADRE::SetSize(int size) +{ + text.SetSize(size); + MAJ(); +}; + +void TEXT_ENCADRE::SetText(const char * txt) +{ + text.SetText(txt); + MAJ(); +}; + +void TEXT_ENCADRE::SetPosition(float x,float y) +{ + SetPosition(Vector2f(x,y)); +}; + +void TEXT_ENCADRE::SetPosition(sf::Vector2f pos) +{ + text.SetPosition(pos); + sprite.SetPosition(pos); +}; + +void TEXT_ENCADRE::SetCentre(_POSITION POS) +{ + centre=POS; + const FloatRect Taille=text.GetRect(); + Vector2f TailleFond=sprite.GetSize(); + TailleFond.x/=Taille.GetWidth(); + TailleFond.y/=Taille.GetHeight(); + + Vector2f pos(0,0),pos2(0,0); + + switch (centre) + { + case HAUT_DROIT: + pos.y=2; + pos.x=Taille.GetWidth(); + pos2.x=TailleFond.x; + + break; + + case HAUT_GAUCHE: + pos.y=2; + break; + + case BAS_DROIT: + pos.y=Taille.GetHeight(); + pos.x=Taille.GetWidth(); + pos2.y=TailleFond.y; + pos2.x=TailleFond.x; + break; + + case BAS_GAUCHE: + pos.y=Taille.GetHeight(); + pos2.y=TailleFond.y; + + break; + default : + pos.y=Taille.GetHeight()/1.8; + pos.x=Taille.GetWidth()/2.05; + pos2.y=TailleFond.y/2; + pos2.x=TailleFond.x/2; + break; + } + + text.SetCenter(pos); + sprite.SetCenter(pos2); +}; + +void TEXT_ENCADRE::MAJ() +{ + const FloatRect Taille=text.GetRect(); + text.SetColor(couleur_Text); + sprite.Resize(Taille.GetWidth(),Taille.GetHeight()); + sprite.SetColor(couleur_Fond); + SetCentre(centre); +}; + +void TEXT_ENCADRE::init() +{ + couleur_Fond=Color(0, 0, 0, 255); + couleur_Text=Color(255, 255, 255, 255); + text.SetSize(20); + SetCentre(HAUT_GAUCHE); + sprite.SetColor(couleur_Fond); + MAJ(); +}; + +void TEXT_ENCADRE::operator+=(const char* a) +{ + SetText(string(string(text.GetText())+a).c_str()); +}; diff --git a/pool/shard011/C++/0121999_numerical_differentiation_incl_test.cpp b/pool/shard011/C++/0121999_numerical_differentiation_incl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56d2ea607dda8e075014491c65227da978d95262 --- /dev/null +++ b/pool/shard011/C++/0121999_numerical_differentiation_incl_test.cpp @@ -0,0 +1,24 @@ +// Copyright Nick Thompson 2017. +// Use, modification and distribution are subject to the +// Boost Software License, Version 1.0. (See accompanying file +// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) +// +// Basic sanity check that header +// #includes all the files that it needs to. +// +#include +// +// Note this header includes no other headers, this is +// important if this test is to be meaningful: +// +#include "test_compile_result.hpp" + +void compile_and_link_test() +{ + auto f = [](double x) { return x; }; + double x = 0; + check_result(boost::math::tools::finite_difference_derivative(f, x)); + + auto g = [](std::complex x){ return x;}; + check_result(boost::math::tools::complex_step_derivative(g, x)); +} diff --git a/pool/shard011/C++/0122000_mesh.cpp b/pool/shard011/C++/0122000_mesh.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f195786b04c4166216cbac9fccb43f9bb37b6f5f --- /dev/null +++ b/pool/shard011/C++/0122000_mesh.cpp @@ -0,0 +1,201 @@ +#include "mesh.h" + +#pragma warning(disable : 4996) + +const DWORD ObjectVertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1; + +MESH::MESH() +{ + m_pDevice = NULL; + m_pMesh = NULL; +} + +MESH::MESH(char fName[], IDirect3DDevice9* Dev) +{ + m_pDevice = Dev; + m_pMesh = NULL; + Load(fName, m_pDevice); +} + +MESH::~MESH() +{ + Release(); +} + +HRESULT MESH::Load(char fName[], IDirect3DDevice9* Dev) +{ + m_pDevice = Dev; + + //Set white material + white.Ambient = white.Specular = white.Diffuse = D3DXCOLOR(1.0f, 1.0f, 1.0f, 1.0f); + white.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f); + white.Power = 1.0f; + + Release(); + + //Load new mesh + ID3DXBuffer * adjacencyBfr = NULL; + ID3DXBuffer * materialBfr = NULL; + DWORD noMaterials = NULL; + + if(FAILED(D3DXLoadMeshFromX(fName, D3DXMESH_MANAGED, m_pDevice, &adjacencyBfr, &materialBfr, NULL, &noMaterials, &m_pMesh))) + return E_FAIL; + + D3DXMATERIAL *mtrls = (D3DXMATERIAL*)materialBfr->GetBufferPointer(); + + for(int i=0;i<(int)noMaterials;i++) + { + //mtrls[i].MatD3D.Ambient = mt[i].MatD3D.Diffuse; + materials.push_back(mtrls[i].MatD3D); + + if(mtrls[i].pTextureFilename != NULL) + { + char textureFileName[90]; + strcpy(textureFileName, "units/"); + strcat(textureFileName, mtrls[i].pTextureFilename); + IDirect3DTexture9 * newTexture = NULL; + D3DXCreateTextureFromFile(m_pDevice, textureFileName, &newTexture); + textures.push_back(newTexture); + } + else textures.push_back(NULL); + } + + m_pMesh->OptimizeInplace(D3DXMESHOPT_ATTRSORT | D3DXMESHOPT_COMPACT | D3DXMESHOPT_VERTEXCACHE, + (DWORD*)adjacencyBfr->GetBufferPointer(), NULL, NULL, NULL); + + adjacencyBfr->Release(); + materialBfr->Release(); + + return S_OK; +} + +void MESH::Render() +{ + for(int i=0;i<(int)materials.size();i++) + { + if(textures[i] != NULL)m_pDevice->SetMaterial(&white); + else m_pDevice->SetMaterial(&materials[i]); + m_pDevice->SetTexture(0,textures[i]); + m_pMesh->DrawSubset(i); + } +} + +void MESH::Release() +{ + //Clear old mesh... + if(m_pMesh != NULL) + { + m_pMesh->Release(); + m_pMesh = NULL; + } + + //Clear textures and materials + for(int i=0;i<(int)textures.size();i++) + if(textures[i] != NULL) + textures[i]->Release(); + + textures.clear(); + materials.clear(); +} + +MESHINSTANCE::MESHINSTANCE() +{ + m_pMesh = NULL; + m_pos = m_rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); + m_sca = D3DXVECTOR3(1.0f, 1.0f, 1.0f); +} + +MESHINSTANCE::MESHINSTANCE(MESH *meshPtr) +{ + m_pMesh = meshPtr; + m_pos = m_rot = D3DXVECTOR3(0.0f, 0.0f, 0.0f); + m_sca = D3DXVECTOR3(1.0f, 1.0f, 1.0f); +} + +D3DXMATRIX MESHINSTANCE::GetWorldMatrix() +{ + D3DXMATRIX p, r, s; + D3DXMatrixTranslation(&p, m_pos.x, m_pos.y, m_pos.z); + D3DXMatrixRotationYawPitchRoll(&r, m_rot.y, m_rot.x, m_rot.z); + D3DXMatrixScaling(&s, m_sca.x, m_sca.y, m_sca.z); + + D3DXMATRIX world = s * r * p; + return world; +} + +void MESHINSTANCE::Render() +{ + if(m_pMesh != NULL) + { + m_pMesh->m_pDevice->SetTransform(D3DTS_WORLD, &GetWorldMatrix()); + m_pMesh->Render(); + } +} + +BBOX MESHINSTANCE::GetBoundingBox() +{ + if(m_pMesh == NULL || m_pMesh->m_pMesh == NULL)return BBOX(); + + if(m_pMesh->m_pMesh->GetFVF() != ObjectVertex::FVF) // XYZ and NORMAL and UV + return BBOX(); + + BBOX bBox(D3DXVECTOR3(-10000.0f, -10000.0f, -10000.0f), + D3DXVECTOR3(10000.0f, 10000.0f, 10000.0f)); + D3DXMATRIX World = GetWorldMatrix(); + + //Lock vertex buffer of the object + ObjectVertex* vertexBuffer = NULL; + m_pMesh->m_pMesh->LockVertexBuffer(0,(void**)&vertexBuffer); + + //For each vertex in the mesh + for(int i=0;i<(int)m_pMesh->m_pMesh->GetNumVertices();i++) + { + //Transform vertex to world space using the MESHINSTANCE + //world matrix, i.e. the position, rotation and scale + D3DXVECTOR3 pos; + D3DXVec3TransformCoord(&pos, &vertexBuffer[i]._pos, &World); + + // Check if the vertex is outside the bounds + // if so, then update the bounding volume + if(pos.x < bBox.min.x)bBox.min.x = pos.x; + if(pos.x > bBox.max.x)bBox.max.x = pos.x; + if(pos.y < bBox.min.y)bBox.min.y = pos.y; + if(pos.y > bBox.max.y)bBox.max.y = pos.y; + if(pos.z < bBox.min.z)bBox.min.z = pos.z; + if(pos.z > bBox.max.z)bBox.max.z = pos.z; + } + + m_pMesh->m_pMesh->UnlockVertexBuffer(); + + return bBox; +} + +BSPHERE MESHINSTANCE::GetBoundingSphere() +{ + if(m_pMesh == NULL || m_pMesh->m_pMesh == NULL)return BSPHERE(); + if(m_pMesh->m_pMesh->GetFVF() != ObjectVertex::FVF) // XYZ and NORMAL and UV + return BSPHERE(); + + BBOX bBox = GetBoundingBox(); + BSPHERE bSphere; + D3DXMATRIX World = GetWorldMatrix(); + bSphere.center = (bBox.max + bBox.min) / 2.0f; + + ObjectVertex* vertexBuffer = NULL; + m_pMesh->m_pMesh->LockVertexBuffer(0,(void**)&vertexBuffer); + + //Get radius + for(int i=0;i<(int)m_pMesh->m_pMesh->GetNumVertices();i++) + { + D3DXVECTOR3 pos; + D3DXVec3TransformCoord(&pos, &vertexBuffer[i]._pos, &World); + + float l = D3DXVec3Length(&(pos - bSphere.center)); + if(l > bSphere.radius) + bSphere.radius = l; + } + + m_pMesh->m_pMesh->UnlockVertexBuffer(); + + return bSphere; +} \ No newline at end of file diff --git a/pool/shard011/C++/0122001_kis_set_global_selection_command.cpp b/pool/shard011/C++/0122001_kis_set_global_selection_command.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0d0869b5659b2adb501f592609412b8136ab4d61 --- /dev/null +++ b/pool/shard011/C++/0122001_kis_set_global_selection_command.cpp @@ -0,0 +1,56 @@ +/* + * Copyright (c) 2007 Sven Langkamp + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "kis_selection_commands.h" + +#include + +#include "kis_image.h" +#include "kis_selection.h" +#include "kis_undo_adapter.h" +#include "kis_selection_mask.h" +#include "kis_pixel_selection.h" + +KisSetGlobalSelectionCommand::KisSetGlobalSelectionCommand(KisImageWSP image, QUndoCommand * parent, KisSelectionSP selection) : + QUndoCommand(parent) + , m_image(image) +{ + m_oldSelection = m_image->globalSelection(); + + m_image->setGlobalSelection(selection); + m_newSelection = m_image->globalSelection(); +} + +KisSetGlobalSelectionCommand::~KisSetGlobalSelectionCommand() +{ +} + +void KisSetGlobalSelectionCommand::redo() +{ + m_image->setGlobalSelection(m_newSelection); +} + +void KisSetGlobalSelectionCommand::undo() +{ + if (m_oldSelection) + m_image->setGlobalSelection(m_oldSelection); + else + m_image->removeGlobalSelection(); + m_image->undoAdapter()->emitSelectionChanged(); +} + diff --git a/pool/shard011/C++/0122003_1047.cpp b/pool/shard011/C++/0122003_1047.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64d836750e02e0b45b3bae3318702f41b5a69cba --- /dev/null +++ b/pool/shard011/C++/0122003_1047.cpp @@ -0,0 +1,27 @@ +#include +#include + +int main() { + int16_t hi, mi, hf, mf, mr, hr; + + scanf("%d %d %d %d", &hi, &mi, &hf, &mf); + + hr = hf - hi; + if (hf - hi < 0) { + hr = 24 + hf - hi; + } + + mr = mf - mi; + if (mf - mi < 0) { + mr = 60 + mf - mi; + hr--; + } + + if (hf == hi && mf == mi) { + printf("O JOGO DUROU 24 HORA(S) E 0 MINUTO(S)\n"); + } else { + printf("O JOGO DUROU %d HORA(S) E %d MINUTO(S)\n", hr, mr); + } + + return 0; +} diff --git a/pool/shard011/C++/0122004_image.cpp b/pool/shard011/C++/0122004_image.cpp new file mode 100644 index 0000000000000000000000000000000000000000..11115ab28eafd653f0790e1ead0ec04230180675 --- /dev/null +++ b/pool/shard011/C++/0122004_image.cpp @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** 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 documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * Redistributions in binary form must reproduce the above copyright +** notice, this list of conditions and the following disclaimer in +** the documentation and/or other materials provided with the +** distribution. +** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor +** the names of its contributors may be used to endorse or promote +** products derived from this software without specific prior written +** permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +int main() +{ + int x, y; + { + // BIT ACCESS + QImage image; + // sets bit at (x, y) to 1 + if (image.format() == QImage::Format_MonoLSB) + image.scanLine(y)[x >> 3] |= 1 << (x & 7); + else + image.scanLine(y)[x >> 3] |= 1 << (7 - (x & 7)); + } + + { + // 8-BIT ACCESS + QImage image; + // set entry 19 in the color table to yellow + image.setColor(19, qRgb(255, 255, 0)); + + // set 8 bit pixel at (x,y) to value yellow (in color table) + image.scanLine(y)[x] = 19; + } + + { + // 32-BIT + QImage image; + // sets 32 bit pixel at (x,y) to yellow. + uint *ptr = reinterpret_cast(image.scanLine(y)) + x; + *ptr = qRgb(255, 255, 0); + } + + { + // SAVE +//! [0] + QImage image; + QByteArray ba; + QBuffer buffer(&ba); + buffer.open(QIODevice::WriteOnly); + image.save(&buffer, "PNG"); // writes image into ba in PNG format +//! [0] + } + + { + // PIX SAVE +//! [1] + QPixmap pixmap; + QByteArray bytes; + QBuffer buffer(&bytes); + buffer.open(QIODevice::WriteOnly); + pixmap.save(&buffer, "PNG"); // writes pixmap into bytes in PNG format +//! [1] + } + + { + // MASK +//! [2] + QPixmap alpha("image-with-alpha.png"); + QPixmap alphacopy = alpha; + alphacopy.setMask(alphacopy.mask()); +//! [2] + } +} diff --git a/pool/shard011/C++/0122005_filter_fusion.cc b/pool/shard011/C++/0122005_filter_fusion.cc new file mode 100644 index 0000000000000000000000000000000000000000..1837de79840d3ba5090fe9be0cb3f7bf18a0648a --- /dev/null +++ b/pool/shard011/C++/0122005_filter_fusion.cc @@ -0,0 +1,132 @@ +/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +#include "tensorflow/core/grappler/optimizers/data/filter_fusion.h" + +#include "absl/container/flat_hash_set.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/grappler/mutable_graph_view.h" +#include "tensorflow/core/grappler/op_types.h" +#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h" +#include "tensorflow/core/grappler/optimizers/data/fusion_utils.h" +#include "tensorflow/core/grappler/optimizers/data/graph_utils.h" +#include "tensorflow/core/grappler/utils.h" +#include "tensorflow/core/grappler/utils/topological_sort.h" +#include "tensorflow/core/platform/protobuf.h" + +namespace tensorflow { +namespace grappler { +namespace { + +NodeDef MakeFusedFilterNode(const NodeDef& first_filter_node, + const NodeDef& second_filter_node, + const FunctionDef& fused_function, + MutableGraphView* graph) { + NodeDef fused_node; + graph_utils::SetUniqueGraphNodeName("fused_filter", graph->graph(), + &fused_node); + + fused_node.set_op("FilterDataset"); + fused_node.add_input(first_filter_node.input(0)); + + auto attr = first_filter_node.attr().at("predicate"); + *attr.mutable_func()->mutable_name() = fused_function.signature().name(); + (*fused_node.mutable_attr())["predicate"] = std::move(attr); + + graph_utils::CopyAttribute("Targuments", first_filter_node, &fused_node); + + for (auto key : {"output_shapes", "output_types"}) + graph_utils::CopyAttribute(key, second_filter_node, &fused_node); + + return fused_node; +} + +} // namespace + +Status FilterFusion::OptimizeAndCollectStats(Cluster* cluster, + const GrapplerItem& item, + GraphDef* output, + OptimizationStats* stats) { + GraphDef sorted_old_graph = item.graph; + TF_RETURN_IF_ERROR(TopologicalSort(&sorted_old_graph)); + *output = sorted_old_graph; + + MutableGraphView graph(output); + absl::flat_hash_set nodes_to_delete; + FunctionLibraryDefinition function_library(OpRegistry::Global(), + output->library()); + + auto get_filter_node = [](const NodeDef& node) -> const NodeDef* { + // TODO(b/148614315): Support captured inputs. + if (node.op() == "FilterDataset" && node.input_size() == 1) return &node; + return nullptr; + }; + + auto make_fused_function = + [&](const NodeDef* first_filter_node, + const NodeDef* second_filter_node) -> FunctionDef* { + const auto& parent_fun = first_filter_node->attr().at("predicate"); + const FunctionDef* first_func = + function_library.Find(parent_fun.func().name()); + const auto& fun = second_filter_node->attr().at("predicate"); + const FunctionDef* second_func = function_library.Find(fun.func().name()); + + if (!fusion_utils::HasSameSignature(first_func->signature(), + second_func->signature())) { + VLOG(1) << "Can't fuse Filters because they have different signature\n"; + return nullptr; + } + + return fusion_utils::FuseFunctions( + *first_func, *second_func, "fused_predicate", + fusion_utils::SameSignature, fusion_utils::SameInput, + fusion_utils::LazyConjunctionOutput, fusion_utils::LazyConjunctionNodes, + output->mutable_library()); + }; + + for (const NodeDef& node : sorted_old_graph.node()) { + const NodeDef* second_filter_node = get_filter_node(node); + if (!second_filter_node) continue; + + const NodeDef* first_filter_node = + get_filter_node(*graph_utils::GetInputNode(*second_filter_node, graph)); + if (!first_filter_node) continue; + + const auto* fused_predicate = + make_fused_function(first_filter_node, second_filter_node); + if (!fused_predicate) continue; + const auto* fused_filter_node = graph.AddNode(MakeFusedFilterNode( + *first_filter_node, *second_filter_node, *fused_predicate, &graph)); + + TF_RETURN_IF_ERROR(graph.UpdateFanouts(second_filter_node->name(), + fused_filter_node->name())); + + TF_RETURN_IF_ERROR(function_library.AddFunctionDef(*fused_predicate)); + nodes_to_delete.insert(first_filter_node->name()); + nodes_to_delete.insert(second_filter_node->name()); + stats->num_changes++; + } + + TF_RETURN_IF_ERROR(graph.DeleteNodes(nodes_to_delete)); + return Status::OK(); +} + +REGISTER_GRAPH_OPTIMIZER_AS(FilterFusion, "filter_fusion"); + +} // namespace grappler +} // namespace tensorflow diff --git a/pool/shard011/C++/0122006_shape.cpp b/pool/shard011/C++/0122006_shape.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f5c18c6e3cfe0cd04afe40e900c07a692c0560b7 --- /dev/null +++ b/pool/shard011/C++/0122006_shape.cpp @@ -0,0 +1,51 @@ +#include "shape.hpp" + +Shape::Shape() : + name_("defaultshape"), + material_{Material{}}, + matrix_{glm::mat4x4{1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1}} { + // std::cout << "Default-Konstruktor-Aufruf fuer Shape: " << name() << "\n"; + } + +Shape::Shape(std::string const& n, Material const& m) : + name_(n), + material_{m}, + matrix_{glm::mat4x4{1,0,0,0, + 0,1,0,0, + 0,0,1,0, + 0,0,0,1}} { + // std::cout << "Konstruktor-Aufruf fuer Shape: " << name() << "\n"; + } + +Shape::~Shape() { + // std::cout << "Destruktor-Aufruf fuer Shape: " << name() << "\n"; +} + +std::string const& Shape::name() const { + return name_; +} + +Material const& Shape::material() const { + return material_; +} + +glm::mat4x4 const& Shape::matrix() const { + return matrix_; +} + +void Shape::setmatrix(glm::mat4x4 const& newmatrix) { + matrix_ = newmatrix; +} + +std::ostream& Shape::print(std::ostream& os) const { + os << "Name: " << name() << "\n"; + os << material(); + return os; +} + +std::ostream& operator<<(std::ostream& os, Shape const& s) { + return s.print(os); +} diff --git a/pool/shard011/C++/0122007_main.cpp b/pool/shard011/C++/0122007_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ecc0571f2bd382f3e7b2ee091580ce9738e1ade4 --- /dev/null +++ b/pool/shard011/C++/0122007_main.cpp @@ -0,0 +1,51 @@ +//===-- main.cpp ------------------------------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +// This test is intended to create a situation in which two threads are stopped +// at a breakpoint and the debugger issues a step-out command. + +#include "pseudo_barrier.h" +#include + +pseudo_barrier_t g_barrier; + +volatile int g_test = 0; + +void step_out_of_here() { + g_test += 5; // Set breakpoint here +} + +void * +thread_func () +{ + // Wait until both threads are running + pseudo_barrier_wait(g_barrier); + + // Do something + step_out_of_here(); // Expect to stop here after step-out (clang) + + // Return + return NULL; // Expect to stop here after step-out (icc and gcc) +} + +int main () +{ + // Don't let either thread do anything until they're both ready. + pseudo_barrier_init(g_barrier, 2); + + // Create two threads + std::thread thread_1(thread_func); + std::thread thread_2(thread_func); + + // Wait for the threads to finish + thread_1.join(); + thread_2.join(); + + return 0; +} diff --git a/pool/shard011/C++/0122008_check_bonds.cc b/pool/shard011/C++/0122008_check_bonds.cc new file mode 100644 index 0000000000000000000000000000000000000000..8fafc74f656bf3d54a616fbd2e8d260b5b19ba44 --- /dev/null +++ b/pool/shard011/C++/0122008_check_bonds.cc @@ -0,0 +1,16 @@ +#include +#include +#include +#include +#include + +int main(int, char *[]){ + std::ifstream input("check_bonds.pdb"); + dsrpdb::Protein helix(input); + //helix.dump(std::cout); + std::vector points; + std::vector bonds; + dsrpdb::backbone_coordinates_and_bonds(helix, std::back_inserter(points), std::back_inserter(bonds)); + assert(bonds.size() == points.size()-2); + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C++/0122009_acm_inst_req_7e0.cc b/pool/shard011/C++/0122009_acm_inst_req_7e0.cc new file mode 100644 index 0000000000000000000000000000000000000000..40c4e4c39a5a46cfbd460af2bc5b2919405cffce --- /dev/null +++ b/pool/shard011/C++/0122009_acm_inst_req_7e0.cc @@ -0,0 +1,128 @@ +/****************************************************************************** + * Copyright 2017 The Apollo Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +#include "modules/drivers/delphi_esr/protocol/acm_inst_req_7e0.h" + +#include "glog/logging.h" + +#include "modules/drivers/canbus/common/byte.h" +#include "modules/drivers/canbus/common/canbus_consts.h" + +namespace apollo { +namespace drivers { +namespace delphi_esr { + +using apollo::drivers::canbus::Byte; + +Acminstreq7e0::Acminstreq7e0() {} +const int32_t Acminstreq7e0::ID = 0x7E0; + +void Acminstreq7e0::Parse(const std::uint8_t* bytes, int32_t length, + DelphiESR* delphi_esr) const { + delphi_esr->mutable_acm_inst_req_7e0()->set_command_ctr( + command_ctr(bytes, length)); + delphi_esr->mutable_acm_inst_req_7e0()->set_command_code( + command_code(bytes, length)); + delphi_esr->mutable_acm_inst_req_7e0()->set_cc_word_2( + cc_word_2(bytes, length)); + delphi_esr->mutable_acm_inst_req_7e0()->set_cc_word_1( + cc_word_1(bytes, length)); + delphi_esr->mutable_acm_inst_req_7e0()->set_cc_byte_2( + cc_byte_2(bytes, length)); + delphi_esr->mutable_acm_inst_req_7e0()->set_cc_byte_1( + cc_byte_1(bytes, length)); +} + +// config detail: {'name': 'command_ctr', 'offset': 0.0, 'precision': 1.0, +// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 15, +// 'type': 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::command_ctr(const std::uint8_t* bytes, + int32_t length) const { + Byte t0(bytes + 1); + int32_t x = t0.get_byte(0, 8); + + int ret = x; + return ret; +} + +// config detail: {'name': 'command_code', 'offset': 0.0, 'precision': 1.0, +// 'len': 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 7, +// 'type': 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::command_code(const std::uint8_t* bytes, + int32_t length) const { + Byte t0(bytes + 0); + int32_t x = t0.get_byte(0, 8); + + int ret = x; + return ret; +} + +// config detail: {'name': 'cc_word_2', 'offset': 0.0, 'precision': 1.0, 'len': +// 16, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 55, 'type': +// 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::cc_word_2(const std::uint8_t* bytes, int32_t length) const { + Byte t0(bytes + 6); + int32_t x = t0.get_byte(0, 8); + + Byte t1(bytes + 7); + int32_t t = t1.get_byte(0, 8); + x <<= 8; + x |= t; + + int ret = x; + return ret; +} + +// config detail: {'name': 'cc_word_1', 'offset': 0.0, 'precision': 1.0, 'len': +// 16, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 39, 'type': +// 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::cc_word_1(const std::uint8_t* bytes, int32_t length) const { + Byte t0(bytes + 4); + int32_t x = t0.get_byte(0, 8); + + Byte t1(bytes + 5); + int32_t t = t1.get_byte(0, 8); + x <<= 8; + x |= t; + + int ret = x; + return ret; +} + +// config detail: {'name': 'cc_byte_2', 'offset': 0.0, 'precision': 1.0, 'len': +// 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 31, 'type': +// 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::cc_byte_2(const std::uint8_t* bytes, int32_t length) const { + Byte t0(bytes + 3); + int32_t x = t0.get_byte(0, 8); + + int ret = x; + return ret; +} + +// config detail: {'name': 'cc_byte_1', 'offset': 0.0, 'precision': 1.0, 'len': +// 8, 'is_signed_var': False, 'physical_range': '[0|0]', 'bit': 23, 'type': +// 'int', 'order': 'motorola', 'physical_unit': ''} +int Acminstreq7e0::cc_byte_1(const std::uint8_t* bytes, int32_t length) const { + Byte t0(bytes + 2); + int32_t x = t0.get_byte(0, 8); + + int ret = x; + return ret; +} +} // namespace delphi_esr +} // namespace drivers +} // namespace apollo diff --git a/pool/shard011/C++/0122010_arathi_highlands.cpp b/pool/shard011/C++/0122010_arathi_highlands.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d83cb9b32813b91efa1f94d9f11f856f096e12fb --- /dev/null +++ b/pool/shard011/C++/0122010_arathi_highlands.cpp @@ -0,0 +1,165 @@ +/* Copyright (C) 2006 - 2008 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, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +/* ScriptData +SDName: Arathi Highlands +SD%Complete: 100 +SDComment: Quest support: 665 +SDCategory: Arathi Highlands +EndScriptData */ + +/* ContentData +npc_professor_phizzlethorpe +EndContentData */ + +#include "precompiled.h" +#include "../../npc/npc_escortAI.h" + +/*###### +## npc_professor_phizzlethorpe +######*/ + +#define SAY_PROGRESS_1 -1000235 +#define SAY_PROGRESS_2 -1000236 +#define SAY_PROGRESS_3 -1000237 +#define EMOTE_PROGRESS_4 -1000238 +#define SAY_AGGRO -1000239 +#define SAY_PROGRESS_5 -1000240 +#define SAY_PROGRESS_6 -1000241 +#define SAY_PROGRESS_7 -1000242 +#define EMOTE_PROGRESS_8 -1000243 +#define SAY_PROGRESS_9 -1000244 + +#define QUEST_SUNKEN_TREASURE 665 +#define MOB_VENGEFUL_SURGE 2776 + +struct TRINITY_DLL_DECL npc_professor_phizzlethorpeAI : public npc_escortAI +{ + npc_professor_phizzlethorpeAI(Creature *c) : npc_escortAI(c) {} + + bool Completed; + + void WaypointReached(uint32 i) + { + Player* player = Unit::GetPlayer(PlayerGUID); + + switch(i) + { + case 4:DoScriptText(SAY_PROGRESS_2, m_creature, player);break; + case 5:DoScriptText(SAY_PROGRESS_3, m_creature, player);break; + case 8:DoScriptText(EMOTE_PROGRESS_4, m_creature);break; + case 9: + { + m_creature->SummonCreature(MOB_VENGEFUL_SURGE, -2052.96, -2142.49, 20.15, 1.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); + m_creature->SummonCreature(MOB_VENGEFUL_SURGE, -2052.96, -2142.49, 20.15, 1.0f, TEMPSUMMON_CORPSE_DESPAWN, 0); + break; + } + case 10:DoScriptText(SAY_PROGRESS_5, m_creature, player);break; + case 11:DoScriptText(SAY_PROGRESS_6, m_creature, player);break; + case 19:DoScriptText(SAY_PROGRESS_7, m_creature, player); break; + case 20: + DoScriptText(EMOTE_PROGRESS_8, m_creature); + DoScriptText(SAY_PROGRESS_9, m_creature, player); + Completed = true; + if(player) + ((Player*)player)->GroupEventHappens(QUEST_SUNKEN_TREASURE, m_creature); + break; + } + } + + void JustSummoned(Creature *summoned) + { + summoned->AI()->AttackStart(m_creature); + } + + void Reset() + { + Completed = true; + m_creature->setFaction(35); + } + + void Aggro(Unit* who) + { + DoScriptText(SAY_AGGRO, m_creature, NULL); + } + + void JustDied(Unit* killer) + { + if (PlayerGUID && !Completed ) + { + Player* player = Unit::GetPlayer(PlayerGUID); + if (player) + ((Player*)player)->FailQuest(QUEST_SUNKEN_TREASURE); + } + } + + void UpdateAI(const uint32 diff) + { + npc_escortAI::UpdateAI(diff); + } +}; + +bool QuestAccept_npc_professor_phizzlethorpe(Player* player, Creature* creature, Quest const* quest) +{ + if (quest->GetQuestId() == QUEST_SUNKEN_TREASURE) + { + DoScriptText(SAY_PROGRESS_1, creature, player); + ((npc_escortAI*)(creature->AI()))->Start(false, false, false, player->GetGUID()); + creature->setFaction(113); + } + return true; +} + +CreatureAI* GetAI_npc_professor_phizzlethorpeAI(Creature *_Creature) +{ + npc_professor_phizzlethorpeAI* professor_phizzlethorpeAI = new npc_professor_phizzlethorpeAI(_Creature); + + professor_phizzlethorpeAI->AddWaypoint(0, -2066.45, -2085.96, 9.08); + professor_phizzlethorpeAI->AddWaypoint(1, -2077.99, -2105.33, 13.24); + professor_phizzlethorpeAI->AddWaypoint(2, -2074.60, -2109.67, 14.24); + professor_phizzlethorpeAI->AddWaypoint(3, -2076.60, -2117.46, 16.67); + professor_phizzlethorpeAI->AddWaypoint(4, -2073.51, -2123.46, 18.42, 2000); + professor_phizzlethorpeAI->AddWaypoint(5, -2073.51, -2123.46, 18.42, 4000); + professor_phizzlethorpeAI->AddWaypoint(6, -2066.60, -2131.85, 21.56); + professor_phizzlethorpeAI->AddWaypoint(7, -2053.85, -2143.19, 20.31); + professor_phizzlethorpeAI->AddWaypoint(8, -2043.49, -2153.73, 20.20, 12000); + professor_phizzlethorpeAI->AddWaypoint(9, -2043.49, -2153.73, 20.20, 14000); + professor_phizzlethorpeAI->AddWaypoint(10, -2043.49, -2153.73, 20.20, 10000); + professor_phizzlethorpeAI->AddWaypoint(11, -2043.49, -2153.73, 20.20, 2000); + professor_phizzlethorpeAI->AddWaypoint(12, -2053.85, -2143.19, 20.31); + professor_phizzlethorpeAI->AddWaypoint(13, -2066.60, -2131.85, 21.56); + professor_phizzlethorpeAI->AddWaypoint(14, -2073.51, -2123.46, 18.42); + professor_phizzlethorpeAI->AddWaypoint(15, -2076.60, -2117.46, 16.67); + professor_phizzlethorpeAI->AddWaypoint(16, -2074.60, -2109.67, 14.24); + professor_phizzlethorpeAI->AddWaypoint(17, -2077.99, -2105.33, 13.24); + professor_phizzlethorpeAI->AddWaypoint(18, -2066.45, -2085.96, 9.08); + professor_phizzlethorpeAI->AddWaypoint(19, -2066.41, -2086.21, 8.97, 6000); + professor_phizzlethorpeAI->AddWaypoint(20, -2066.41, -2086.21, 8.97, 2000); + + return (CreatureAI*)professor_phizzlethorpeAI; +} + +void AddSC_arathi_highlands() +{ + Script * newscript; + + newscript = new Script; + newscript->Name = "npc_professor_phizzlethorpe"; + newscript->GetAI = &GetAI_npc_professor_phizzlethorpeAI; + newscript->pQuestAccept = &QuestAccept_npc_professor_phizzlethorpe; + newscript->RegisterSelf(); +} + diff --git a/pool/shard011/C++/0122011_gl_ozone_egl_cast.cc b/pool/shard011/C++/0122011_gl_ozone_egl_cast.cc new file mode 100644 index 0000000000000000000000000000000000000000..36ae5fac4d538331e440f5c9d9349c2c218861ac --- /dev/null +++ b/pool/shard011/C++/0122011_gl_ozone_egl_cast.cc @@ -0,0 +1,152 @@ +// Copyright 2017 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/ozone/platform/cast/gl_ozone_egl_cast.h" + +#include +#include +#include +#include + +#include "base/command_line.h" +#include "base/macros.h" +#include "base/strings/string_number_conversions.h" +#include "chromecast/base/chromecast_switches.h" +#include "chromecast/public/cast_egl_platform.h" +#include "chromecast/public/graphics_types.h" +#include "ui/gfx/vsync_provider.h" +#include "ui/ozone/platform/cast/gl_surface_cast.h" + +using chromecast::CastEglPlatform; + +namespace ui { + +namespace { + +typedef EGLDisplay (*EGLGetDisplayFn)(NativeDisplayType); +typedef EGLBoolean (*EGLTerminateFn)(EGLDisplay); + +chromecast::Size FromGfxSize(const gfx::Size& size) { + return chromecast::Size(size.width(), size.height()); +} + +// Display resolution, set in browser process and passed by switches. +gfx::Size GetDisplaySize() { + base::CommandLine* cmd_line = base::CommandLine::ForCurrentProcess(); + int width, height; + if (base::StringToInt( + cmd_line->GetSwitchValueASCII(switches::kCastInitialScreenWidth), + &width) && + base::StringToInt( + cmd_line->GetSwitchValueASCII(switches::kCastInitialScreenHeight), + &height)) { + return gfx::Size(width, height); + } + LOG(WARNING) << "Unable to get initial screen resolution from command line," + << "using default 720p"; + return gfx::Size(1280, 720); +} + +} // namespace + +GLOzoneEglCast::GLOzoneEglCast(std::unique_ptr egl_platform) + : display_size_(GetDisplaySize()), egl_platform_(std::move(egl_platform)) {} + +GLOzoneEglCast::~GLOzoneEglCast() { + // eglTerminate must be called first on display before releasing resources + // and shutting down hardware + TerminateDisplay(); +} + +void GLOzoneEglCast::InitializeHardwareIfNeeded() { + if (hardware_initialized_) + return; + + CHECK(egl_platform_->InitializeHardware()); + hardware_initialized_ = true; +} + +void GLOzoneEglCast::TerminateDisplay() { + void* egl_lib_handle = egl_platform_->GetEglLibrary(); + if (!egl_lib_handle) + return; + + EGLGetDisplayFn get_display = + reinterpret_cast(dlsym(egl_lib_handle, "eglGetDisplay")); + EGLTerminateFn terminate = + reinterpret_cast(dlsym(egl_lib_handle, "eglTerminate")); + DCHECK(get_display); + DCHECK(terminate); + + EGLDisplay display = get_display(GetNativeDisplay().GetDisplay()); + DCHECK_NE(display, EGL_NO_DISPLAY); + + EGLBoolean terminate_result = terminate(display); + DCHECK_EQ(terminate_result, static_cast(EGL_TRUE)); +} + +scoped_refptr GLOzoneEglCast::CreateViewGLSurface( + gfx::AcceleratedWidget widget) { + // Verify requested widget dimensions match our current display size. + DCHECK_EQ(widget >> 16, display_size_.width()); + DCHECK_EQ(widget & 0xffff, display_size_.height()); + + return gl::InitializeGLSurface(new GLSurfaceCast(widget, this)); +} + +scoped_refptr GLOzoneEglCast::CreateOffscreenGLSurface( + const gfx::Size& size) { + return gl::InitializeGLSurface(new gl::PbufferGLSurfaceEGL(size)); +} + +gl::EGLDisplayPlatform GLOzoneEglCast::GetNativeDisplay() { + CreateDisplayTypeAndWindowIfNeeded(); + return gl::EGLDisplayPlatform( + reinterpret_cast(display_type_)); +} + +void GLOzoneEglCast::CreateDisplayTypeAndWindowIfNeeded() { + InitializeHardwareIfNeeded(); + + if (!have_display_type_) { + chromecast::Size create_size = FromGfxSize(display_size_); + display_type_ = egl_platform_->CreateDisplayType(create_size); + have_display_type_ = true; + } + if (!window_) { + chromecast::Size create_size = FromGfxSize(display_size_); + window_ = egl_platform_->CreateWindow(display_type_, create_size); + CHECK(window_); + } +} + +intptr_t GLOzoneEglCast::GetNativeWindow() { + CreateDisplayTypeAndWindowIfNeeded(); + return reinterpret_cast(window_); +} + +bool GLOzoneEglCast::ResizeDisplay(gfx::Size size) { + DCHECK_EQ(size.width(), display_size_.width()); + DCHECK_EQ(size.height(), display_size_.height()); + return true; +} + +bool GLOzoneEglCast::LoadGLES2Bindings(gl::GLImplementation implementation) { + InitializeHardwareIfNeeded(); + + void* lib_egl = egl_platform_->GetEglLibrary(); + void* lib_gles2 = egl_platform_->GetGles2Library(); + gl::GLGetProcAddressProc gl_proc = reinterpret_cast( + egl_platform_->GetGLProcAddressProc()); + if (!lib_egl || !lib_gles2 || !gl_proc) { + return false; + } + + gl::SetGLGetProcAddressProc(gl_proc); + gl::AddGLNativeLibrary(lib_egl); + gl::AddGLNativeLibrary(lib_gles2); + return true; +} + +} // namespace ui diff --git a/pool/shard011/C++/0122012_libSuspendWithCurrentThread.cpp b/pool/shard011/C++/0122012_libSuspendWithCurrentThread.cpp new file mode 100644 index 0000000000000000000000000000000000000000..30316bd847037c04116939016304831882ed21fd --- /dev/null +++ b/pool/shard011/C++/0122012_libSuspendWithCurrentThread.cpp @@ -0,0 +1,209 @@ +/* + * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include +#include "jvmti.h" + +extern "C" { + +static jvmtiEnv* jvmti = NULL; +static jthread* threads = NULL; +static jsize threads_count = 0; +static jrawMonitorID agent_monitor = NULL; + +#define LOG(...) \ + do { \ + printf(__VA_ARGS__); \ + printf("\n"); \ + fflush(stdout); \ + } while (0) + +static void +check_jvmti_status(JNIEnv* jni, jvmtiError err, const char* msg) { + if (err != JVMTI_ERROR_NONE) { + LOG("check_jvmti_status: JVMTI function returned error: %d", err); + jni->FatalError(msg); + } +} + +static void +agent_lock(JNIEnv* jni) { + jvmtiError err = jvmti->RawMonitorEnter(agent_monitor); + check_jvmti_status(jni, err, "monitor_enter: error in JVMTI RawMonitorEnter"); +} + +static void +agent_unlock(JNIEnv* jni) { + jvmtiError err = jvmti->RawMonitorExit(agent_monitor); + check_jvmti_status(jni, err, "monitor_exit: error in JVMTI RawMonitorExit"); +} + +JNIEXPORT void JNICALL +Java_SuspendWithCurrentThread_registerTestedThreads(JNIEnv *jni, jclass cls, jobjectArray threadsArr) { + LOG("\nregisterTestedThreads: started"); + threads_count = jni->GetArrayLength(threadsArr); + + jvmtiError err = jvmti->Allocate((threads_count * sizeof(jthread)), + (unsigned char**)&threads); + check_jvmti_status(jni, err, "registerTestedThreads: error in JVMTI Allocate threads array"); + + for (int i = 0; i < threads_count; i++) { + jobject elem = jni->GetObjectArrayElement(threadsArr, i); + threads[i] = (jthread)jni->NewGlobalRef(elem); + } + LOG("registerTestedThreads: finished\n"); +} + +/* This function is executed on the suspender thread, not the Main thread */ +JNIEXPORT void JNICALL +Java_ThreadToSuspend_init(JNIEnv *jni, jclass cls) { + jvmtiError err = jvmti->CreateRawMonitor("Agent monitor", &agent_monitor); + check_jvmti_status(jni, err, "Java_ThreadToSuspend_init: error in JVMTI CreateRawMonitor"); + + // Main thread has to wait for the suspender thread to complete tested threads suspension + agent_lock(jni); +} + +/* This function is executed on the suspender thread which is not Main thread */ +JNIEXPORT void JNICALL +Java_ThreadToSuspend_suspendTestedThreads(JNIEnv *jni, jclass cls) { + jvmtiError* results = NULL; + jvmtiError err; + + LOG("\nsuspendTestedThreads: started"); + err = jvmti->Allocate((threads_count * sizeof(jvmtiError)), + (unsigned char**)&results); + check_jvmti_status(jni, err, "suspendTestedThreads: error in JVMTI Allocate results array"); + + LOG("suspendTestedThreads: before JVMTI SuspendThreadList"); + err = jvmti->SuspendThreadList(threads_count, threads, results); + check_jvmti_status(jni, err, "suspendTestedThreads: error in JVMTI SuspendThreadList"); + + LOG("suspendTestedThreads: check and print SuspendThreadList results:"); + for (int i = 0; i < threads_count; i++) { + LOG(" thread #%d: (%d)", i, (int)results[i]); + check_jvmti_status(jni, results[i], "suspendTestedThreads: error in SuspendThreadList results[i]"); + } + LOG("suspendTestedThreads: finished\n"); + + // Allow the Main thread to inspect the result of tested threads suspension + agent_unlock(jni); + + err = jvmti->Deallocate((unsigned char*)results); + check_jvmti_status(jni, err, "suspendTestedThreads: error in JVMTI Deallocate results"); +} + +JNIEXPORT jboolean JNICALL +Java_SuspendWithCurrentThread_checkTestedThreadsSuspended(JNIEnv *jni, jclass cls) { + LOG("checkTestedThreadsSuspended: started"); + + // Block until the suspender thread competes the tested threads suspension + agent_lock(jni); + agent_unlock(jni); + + for (int i = 0; i < threads_count; i++) { + jint state = 0; + jvmtiError err = jvmti->GetThreadState(threads[i], &state); + check_jvmti_status(jni, err, "checkTestedThreadsSuspended: error in GetThreadState"); + + if ((state & JVMTI_THREAD_STATE_SUSPENDED) == 0) { + LOG("thread #%d has not been suspended yet: " + "# state: (%#x)", i, (int)state); + jni->FatalError("checkTestedThreadsSuspended: error: expected all tested threads suspended"); + } + } + LOG("checkTestedThreadsSuspended: finished\n"); + return JNI_TRUE; +} + +JNIEXPORT void JNICALL +Java_SuspendWithCurrentThread_resumeTestedThreads(JNIEnv *jni, jclass cls) { + jvmtiError* results = NULL; + jvmtiError err; + + LOG("\nresumeTestedThreads: started"); + err = jvmti->Allocate((threads_count * sizeof(jvmtiError)), + (unsigned char**)&results); + check_jvmti_status(jni, err, "resumeTestedThreads: error in JVMTI Allocate results array"); + + LOG("resumeTestedThreads: before JVMTI ResumeThreadList"); + err = jvmti->ResumeThreadList(threads_count, threads, results); + check_jvmti_status(jni, err, "resumeTestedThreads: error in ResumeThreadList"); + + LOG("resumeTestedThreads: check and print ResumeThreadList results:"); + for (int i = 0; i < threads_count; i++) { + LOG(" thread #%d: (%d)", i, (int)results[i]); + check_jvmti_status(jni, results[i], "resumeTestedThreads: error in ResumeThreadList results[i]"); + } + + err = jvmti->Deallocate((unsigned char*)results); + check_jvmti_status(jni, err, "resumeTestedThreads: error in JVMTI Deallocate results"); + + LOG("resumeTestedThreads: finished\n"); +} + +JNIEXPORT void JNICALL +Java_SuspendWithCurrentThread_releaseTestedThreadsInfo(JNIEnv *jni, jclass cls) { + jvmtiError err; + + LOG("\nreleaseTestedThreadsInfo: started"); + err = jvmti->DestroyRawMonitor(agent_monitor); + check_jvmti_status(jni, err, "releaseTestedThreadsInfo: error in JVMTI DestroyRawMonitor"); + + for (int i = 0; i < threads_count; i++) { + if (threads[i] != NULL) { + jni->DeleteGlobalRef(threads[i]); + } + } + err = jvmti->Deallocate((unsigned char*)threads); + check_jvmti_status(jni, err, "releaseTestedThreadsInfo: error in JVMTI Deallocate threads"); + + LOG("releaseTestedThreadsInfo: finished\n"); +} + + +/** Agent library initialization. */ + +JNIEXPORT jint JNICALL +Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) { + LOG("\nAgent_OnLoad started"); + + // create JVMTI environment + if (jvm->GetEnv((void **) (&jvmti), JVMTI_VERSION) != JNI_OK) { + return JNI_ERR; + } + + // add specific capabilities for suspending thread + jvmtiCapabilities suspendCaps; + memset(&suspendCaps, 0, sizeof(suspendCaps)); + suspendCaps.can_suspend = 1; + + jvmtiError err = jvmti->AddCapabilities(&suspendCaps); + if (err != JVMTI_ERROR_NONE) { + return JNI_ERR; + } + LOG("Agent_OnLoad finished\n"); + return JNI_OK; +} + +} diff --git a/pool/shard011/C++/0122013_I2CBus.cpp b/pool/shard011/C++/0122013_I2CBus.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a3dafca971e101eb047137ed8569d77e16cf4c94 --- /dev/null +++ b/pool/shard011/C++/0122013_I2CBus.cpp @@ -0,0 +1,61 @@ +#include "I2CBus.h" +#include +#include +#include +#include + +I2CBus::I2CBus(const char * deviceName) +{ + fd = open(deviceName, O_RDWR); + if (fd == -1) + { + throw posix_error("Failed to open I2C device."); + } +} + +I2CBus::~I2CBus() +{ + close(fd); +} + +void I2CBus::addressSet(uint8_t address) +{ + int result = ioctl(fd, I2C_SLAVE, address); + if (result == -1) + { + throw posix_error("Failed to set address."); + } +} + +void I2CBus::writeByte(uint8_t command, uint8_t data) +{ + int result = i2c_smbus_write_byte_data(fd, command, data); + if (result == -1) + { + throw posix_error("Failed to write byte to I2C."); + } +} + +uint8_t I2CBus::readByte(uint8_t command) +{ + int result = i2c_smbus_read_byte_data(fd, command); + if (result == -1) + { + throw posix_error("Failed to read byte from I2C."); + } + return result; +} + +int I2CBus::tryReadByte(uint8_t command) +{ + return i2c_smbus_read_byte_data(fd, command); +} + +void I2CBus::readBlock(uint8_t command, uint8_t size, uint8_t * data) +{ + int result = i2c_smbus_read_i2c_block_data(fd, command, size, data); + if (result != size) + { + throw posix_error("Failed to read block from I2C."); + } +} diff --git a/pool/shard011/C++/0122014_ZoomWidget.cpp b/pool/shard011/C++/0122014_ZoomWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ccfc2a9bc76b74252647d788dcf2285b98467867 --- /dev/null +++ b/pool/shard011/C++/0122014_ZoomWidget.cpp @@ -0,0 +1,150 @@ +/************************************************************************** +* Otter Browser: Web browser controlled by the user, not vice-versa. +* Copyright (C) 2013 - 2019 Michal Dutkiewicz aka Emdek +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU General Public License for more details. +* +* You should have received a copy of the GNU General Public License +* along with this program. If not, see . +* +**************************************************************************/ + +#include "ZoomWidget.h" +#include "../../../core/SettingsManager.h" +#include "../../../ui/MainWindow.h" +#include "../../../ui/ToolBarWidget.h" +#include "../../../ui/Window.h" + +#include +#include +#include + +namespace Otter +{ + +ZoomWidget::ZoomWidget(Window *window, QWidget *parent) : QSlider(parent), + m_window(nullptr) +{ + const ToolBarWidget *toolBar(qobject_cast(parent)); + + setRange(0, 300); + setTracking(true); + setOrientation(Qt::Horizontal); + setFocusPolicy(Qt::TabFocus); + setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred); + setTickPosition(QSlider::TicksBelow); + setTickInterval(100); + setWindow(window); + + if (toolBar && toolBar->getDefinition().isGlobal()) + { + connect(toolBar, &ToolBarWidget::windowChanged, this, &ZoomWidget::setWindow); + } +} + +void ZoomWidget::changeEvent(QEvent *event) +{ + QSlider::changeEvent(event); + + if (event->type() == QEvent::LanguageChange) + { + setZoom(m_window ? m_window->getZoom() : SettingsManager::getOption(SettingsManager::Content_DefaultZoomOption).toInt()); + } +} + +void ZoomWidget::mousePressEvent(QMouseEvent *event) +{ + if (!isEnabled() || event->button() != Qt::LeftButton) + { + QSlider::mousePressEvent(event); + + return; + } + + QStyleOptionSlider option; + option.initFrom(this); + option.minimum = minimum(); + option.maximum = maximum(); + option.sliderPosition = value(); + option.sliderValue = value(); + + const QRect handle(style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderHandle, this)); + const QRect groove(style()->subControlRect(QStyle::CC_Slider, &option, QStyle::SC_SliderGroove, this)); + int value(0); + + if (orientation() == Qt::Horizontal) + { + value = QStyle::sliderValueFromPosition(minimum(), maximum(), (event->x() - (handle.width() / 2) - groove.x()), (groove.right() - handle.width())); + } + else + { + value = QStyle::sliderValueFromPosition(minimum(), maximum(), (event->y() - (handle.height() / 2) - groove.y()), (groove.bottom() - handle.height()), true); + } + + setZoom(value); + + if (handle.contains(event->pos())) + { + QSlider::mousePressEvent(event); + } +} + +void ZoomWidget::setWindow(Window *window) +{ + if (m_window) + { + disconnect(m_window, &Window::canZoomChanged, this, &ZoomWidget::setEnabled); + disconnect(m_window, &Window::zoomChanged, this, &ZoomWidget::setZoom); + disconnect(this, &ZoomWidget::valueChanged, m_window, &Window::setZoom); + } + + m_window = window; + + setEnabled(m_window && m_window->canZoom()); + + if (window) + { + setZoom(window->getZoom()); + + connect(window, &Window::canZoomChanged, this, &ZoomWidget::setEnabled); + connect(window, &Window::zoomChanged, this, &ZoomWidget::setZoom); + connect(this, &ZoomWidget::valueChanged, window, &Window::setZoom); + } + else + { + setZoom(SettingsManager::getOption(SettingsManager::Content_DefaultZoomOption).toInt()); + } +} + +void ZoomWidget::setZoom(int zoom) +{ + zoom = qMax(zoom, 10); + + setValue(zoom); + setToolTip(tr("Zoom %1%").arg(zoom)); + setStatusTip(tr("Zoom %1%").arg(zoom)); + + MainWindow *mainWindow(MainWindow::findMainWindow(this)); + + if (mainWindow && (underMouse() || isSliderDown())) + { + QStatusTipEvent event(statusTip()); + + QApplication::sendEvent(mainWindow, &event); + } +} + +QSize ZoomWidget::sizeHint() const +{ + return {150, QSlider::sizeHint().height()}; +} + +} diff --git a/pool/shard011/C++/0122015_excel-sheet-column-number.cc b/pool/shard011/C++/0122015_excel-sheet-column-number.cc new file mode 100644 index 0000000000000000000000000000000000000000..37c65d35dac251be6c3becf20c0388124f71706d --- /dev/null +++ b/pool/shard011/C++/0122015_excel-sheet-column-number.cc @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +class Solution { +public: + int titleToNumber(string s) { + int d = 0; + int r = 1; + for (int i = 0, j = s.size()-1; j >= 0; i++, j--) { + d += (s[j] - 'A' + 1) * r; + r *= 26; + } + + return d; + } +}; + +int main(int argc, char *argv[]) +{ + cout << Solution().titleToNumber("A") << endl; + cout << Solution().titleToNumber("E") << endl; + cout << Solution().titleToNumber("Z") << endl; + cout << Solution().titleToNumber("AA") << endl; + cout << Solution().titleToNumber("AZ") << endl; + cout << Solution().titleToNumber("BA") << endl; + cout << Solution().titleToNumber("AAZ") << endl; + return 0; +} + diff --git a/pool/shard011/C++/0122019_web_frame_content_dumper.cc b/pool/shard011/C++/0122019_web_frame_content_dumper.cc new file mode 100644 index 0000000000000000000000000000000000000000..892c7b3e21323254050938832d7fd40572a50467 --- /dev/null +++ b/pool/shard011/C++/0122019_web_frame_content_dumper.cc @@ -0,0 +1,149 @@ +// Copyright 2016 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/public/web/web_frame_content_dumper.h" + +#include "base/stl_util.h" +#include "third_party/blink/public/web/web_document.h" +#include "third_party/blink/public/web/web_frame_widget.h" +#include "third_party/blink/public/web/web_local_frame.h" +#include "third_party/blink/public/web/web_view.h" +#include "third_party/blink/renderer/core/editing/ephemeral_range.h" +#include "third_party/blink/renderer/core/editing/iterators/text_iterator.h" +#include "third_party/blink/renderer/core/editing/serializers/serialization.h" +#include "third_party/blink/renderer/core/exported/web_view_impl.h" +#include "third_party/blink/renderer/core/frame/local_frame.h" +#include "third_party/blink/renderer/core/frame/local_frame_view.h" +#include "third_party/blink/renderer/core/frame/web_frame_widget_base.h" +#include "third_party/blink/renderer/core/frame/web_local_frame_impl.h" +#include "third_party/blink/renderer/core/html_element_type_helpers.h" +#include "third_party/blink/renderer/core/layout/layout_embedded_content.h" +#include "third_party/blink/renderer/core/layout/layout_tree_as_text.h" +#include "third_party/blink/renderer/core/layout/layout_view.h" +#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" + +namespace blink { + +namespace { + +void FrameContentAsPlainText(size_t max_chars, + LocalFrame* frame, + StringBuilder& output) { + Document* document = frame->GetDocument(); + if (!document) + return; + + if (!frame->View() || frame->View()->ShouldThrottleRendering()) + return; + + DCHECK(!frame->View()->NeedsLayout()); + DCHECK(!document->NeedsLayoutTreeUpdate()); + + if (document->documentElement()) { + output.Append(document->documentElement()->innerText()); + if (output.length() >= max_chars) + output.Resize(max_chars); + } + + // The separator between frames when the frames are converted to plain text. + const LChar kFrameSeparator[] = {'\n', '\n'}; + const size_t frame_separator_length = base::size(kFrameSeparator); + + // Recursively walk the children. + const FrameTree& frame_tree = frame->Tree(); + for (Frame* cur_child = frame_tree.FirstChild(); cur_child; + cur_child = cur_child->Tree().NextSibling()) { + auto* cur_local_child = DynamicTo(cur_child); + if (!cur_local_child) + continue; + // Ignore the text of non-visible frames. + LayoutView* layout_view = cur_local_child->ContentLayoutObject(); + LayoutObject* owner_layout_object = cur_local_child->OwnerLayoutObject(); + if (!layout_view || !layout_view->Size().Width() || + !layout_view->Size().Height() || + (layout_view->Location().X() + layout_view->Size().Width() <= 0) || + (layout_view->Location().Y() + layout_view->Size().Height() <= 0) || + (owner_layout_object && owner_layout_object->Style() && + owner_layout_object->Style()->Visibility() != EVisibility::kVisible)) { + continue; + } + + // Make sure the frame separator won't fill up the buffer, and give up if + // it will. The danger is if the separator will make the buffer longer than + // maxChars. This will cause the computation above: + // maxChars - output->size() + // to be a negative number which will crash when the subframe is added. + if (output.length() >= max_chars - frame_separator_length) + return; + + output.Append(kFrameSeparator, frame_separator_length); + FrameContentAsPlainText(max_chars, cur_local_child, output); + if (output.length() >= max_chars) + return; // Filled up the buffer. + } +} + +} // namespace + +WebString WebFrameContentDumper::DeprecatedDumpFrameTreeAsText( + WebLocalFrame* frame, + size_t max_chars) { + if (!frame) + return WebString(); + StringBuilder text; + FrameContentAsPlainText(max_chars, To(frame)->GetFrame(), + text); + return text.ToString(); +} + +WebString WebFrameContentDumper::DumpWebViewAsText(WebView* web_view, + size_t max_chars) { + DCHECK(web_view); + WebLocalFrame* frame = web_view->MainFrame()->ToWebLocalFrame(); + if (!frame) + return WebString(); + + WebViewImpl* web_view_impl = static_cast(web_view); + DCHECK(web_view_impl->MainFrameWidgetBase()); + // Updating the document lifecycle isn't enough, the BeginFrame() step + // should come first which runs events such as notifying of media query + // changes or raf-based events. + web_view_impl->MainFrameWidgetBase()->BeginMainFrame(base::TimeTicks::Now()); + web_view_impl->MainFrameWidgetBase()->UpdateAllLifecyclePhases( + DocumentUpdateReason::kTest); + + StringBuilder text; + FrameContentAsPlainText(max_chars, To(frame)->GetFrame(), + text); + return text.ToString(); +} + +WebString WebFrameContentDumper::DumpAsMarkup(WebLocalFrame* frame) { + if (!frame) + return WebString(); + return CreateMarkup(To(frame)->GetFrame()->GetDocument()); +} + +WebString WebFrameContentDumper::DumpLayoutTreeAsText( + WebLocalFrame* frame, + LayoutAsTextControls to_show) { + if (!frame) + return WebString(); + LayoutAsTextBehavior behavior = kLayoutAsTextShowAllLayers; + + if (to_show & kLayoutAsTextWithLineTrees) + behavior |= kLayoutAsTextShowLineTrees; + + if (to_show & kLayoutAsTextDebug) { + behavior |= kLayoutAsTextShowCompositedLayers | kLayoutAsTextShowAddresses | + kLayoutAsTextShowIDAndClass | kLayoutAsTextShowLayerNesting; + } + + if (to_show & kLayoutAsTextPrinting) + behavior |= kLayoutAsTextPrintingMode; + + return ExternalRepresentation(To(frame)->GetFrame(), + behavior); +} +} diff --git a/pool/shard011/C++/0122020_viator_tests.cpp b/pool/shard011/C++/0122020_viator_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3afa682b2c4232b39e23d167c7d96844d4b7ca5 --- /dev/null +++ b/pool/shard011/C++/0122020_viator_tests.cpp @@ -0,0 +1,125 @@ +#include "testing/testing.hpp" + +#include "partners_api/viator_api.hpp" + +#include +#include +#include +#include + +#include "3party/jansson/myjansson.hpp" + +namespace +{ +UNIT_TEST(Viator_GetTopProducts) +{ + string result; + viator::RawApi::GetTopProducts("684", "USD", 5, result); + + TEST(!result.empty(), ()); + + my::Json root(result.c_str()); + bool success; + FromJSONObjectOptionalField(root.get(), "success", success); + TEST(success, ()); +} + +UNIT_TEST(Viator_GetTop5Products) +{ + viator::Api api; + std::string const kSofia = "5630"; + std::string resultId; + std::vector resultProducts; + + api.GetTop5Products(kSofia, "", + [&resultId, &resultProducts](std::string const & destId, + std::vector const & products) { + resultId = destId; + resultProducts = products; + + testing::StopEventLoop(); + }); + + testing::RunEventLoop(); + + TEST_EQUAL(resultId, kSofia, ()); + TEST(!resultProducts.empty(), ()); + + for (auto const & p : resultProducts) + TEST_EQUAL(p.m_currency, "USD", ()); + + resultId.clear(); + resultProducts.clear(); + + api.GetTop5Products(kSofia, "RUB", + [&resultId, &resultProducts](std::string const & destId, + std::vector const & products) { + resultId = destId; + resultProducts = products; + + testing::StopEventLoop(); + }); + + testing::RunEventLoop(); + + TEST_EQUAL(resultId, kSofia, ()); + TEST(!resultProducts.empty(), ()); + + for (auto const & p : resultProducts) + TEST_EQUAL(p.m_currency, "USD", ()); + + resultId.clear(); + resultProducts.clear(); + + api.GetTop5Products(kSofia, "GBP", + [&resultId, &resultProducts](std::string const & destId, + std::vector const & products) { + resultId = destId; + resultProducts = products; + + testing::StopEventLoop(); + }); + + testing::RunEventLoop(); + + TEST_EQUAL(resultId, kSofia, ()); + TEST(!resultProducts.empty(), ()); + + for (auto const & p : resultProducts) + TEST_EQUAL(p.m_currency, "GBP", ()); +} + +UNIT_TEST(Viator_SortProducts) +{ + std::vector products = + { + {"1", 10.0, 10, "", 10.0, "", "", "", ""}, + {"2", 9.0, 100, "", 200.0, "", "", "", ""}, + {"3", 9.0, 100, "", 100.0, "", "", "", ""}, + {"4", 9.0, 10, "", 200.0, "", "", "", ""}, + {"5", 9.0, 9, "", 300.0, "", "", "", ""}, + {"6", 8.0, 200, "", 400.0, "", "", "", ""}, + {"7", 7.0, 20, "", 200.0, "", "", "", ""}, + {"8", 7.0, 20, "", 1.0, "", "", "", ""}, + {"9", 7.0, 0, "", 300.0, "", "", "", ""}, + {"10", 7.0, 0, "", 1.0, "", "", "", ""} + }; + + for (size_t i = 0; i < 1000; ++i) + { + std::shuffle(products.begin(), products.end(), std::minstd_rand(std::minstd_rand::default_seed)); + viator::SortProducts(products); + + TEST_EQUAL(products[0].m_title, "1", ()); + TEST_EQUAL(products[1].m_title, "2", ()); + TEST_EQUAL(products[2].m_title, "3", ()); + TEST_EQUAL(products[3].m_title, "4", ()); + TEST_EQUAL(products[4].m_title, "5", ()); + TEST_EQUAL(products[5].m_title, "6", ()); + TEST_EQUAL(products[6].m_title, "7", ()); + TEST_EQUAL(products[7].m_title, "8", ()); + TEST_EQUAL(products[8].m_title, "9", ()); + TEST_EQUAL(products[9].m_title, "10", ()); + } +} +} // namespace diff --git a/pool/shard011/C++/0122021_qbackendnode.cpp b/pool/shard011/C++/0122021_qbackendnode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9855baeb2fc582789c71f230abfa14501e41e3bc --- /dev/null +++ b/pool/shard011/C++/0122021_qbackendnode.cpp @@ -0,0 +1,226 @@ +/**************************************************************************** +** +** Copyright (C) 2014 Klaralvdalens Datakonsult AB (KDAB). +** Contact: https://www.qt.io/licensing/ +** +** This file is part of the Qt3D module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and The Qt Company. For licensing terms +** and conditions see https://www.qt.io/terms-conditions. For further +** information use the contact form at https://www.qt.io/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 3 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL3 included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 3 requirements +** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 2.0 or (at your option) the GNU General +** Public license version 3 or any later version approved by the KDE Free +** Qt Foundation. The licenses are as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 +** included in the packaging of this file. Please review the following +** information to ensure the GNU General Public License requirements will +** be met: https://www.gnu.org/licenses/gpl-2.0.html and +** https://www.gnu.org/licenses/gpl-3.0.html. +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qbackendnode.h" +#include "qbackendnode_p.h" + +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +namespace Qt3DCore { + +/*! \internal */ +QBackendNodeMapper::~QBackendNodeMapper() +{ +} + +QBackendNodePrivate::QBackendNodePrivate(QBackendNode::Mode mode) + : q_ptr(nullptr) + , m_mode(mode) + , m_enabled(false) +{ +} + +QBackendNodePrivate::~QBackendNodePrivate() = default; + +void QBackendNodePrivate::setEnabled(bool enabled) +{ + m_enabled = enabled; +} + +QBackendNodePrivate *QBackendNodePrivate::get(QBackendNode *n) +{ + return n->d_func(); +} + +void QBackendNodePrivate::addedToEntity(QNode *frontend) +{ + Q_UNUSED(frontend); +} + +void QBackendNodePrivate::removedFromEntity(QNode *frontend) +{ + Q_UNUSED(frontend); +} + +void QBackendNodePrivate::componentAdded(QNode *frontend) +{ + Q_UNUSED(frontend); +} + +void QBackendNodePrivate::componentRemoved(QNode *frontend) +{ + Q_UNUSED(frontend); +} + +/*! + * \class Qt3DCore::QBackendNodeMapper + * \inheaderfile Qt3DCore/QBackendNodeMapper + * \inmodule Qt3DCore + * + * \brief Creates and maps backend nodes to their respective frontend nodes. + */ + +/*! + * \fn Qt3DCore::QBackendNode *Qt3DCore::QBackendNodeMapper::create(Qt3DCore::QNodeId id) const + * + * \TODO + * + * \a id + * + * \return created node. + */ + +/*! + * \fn Qt3DCore::QBackendNode * Qt3DCore::QBackendNodeMapper::get(Qt3DCore::QNodeId id) const + * + * \return backend node for the given node \a id. + */ + +/*! + * \fn void Qt3DCore::QBackendNodeMapper::destroy(Qt3DCore::QNodeId id) const + * + * Destroys the backend node for the given node \a id. + */ + +/*! + * \class Qt3DCore::QBackendNode + * \inheaderfile Qt3DCore/QBackendNode + * \inmodule Qt3DCore + * + * \brief The base class for all Qt3D backend nodes. + */ + +/*! + * \enum Qt3DCore::QBackendNode::Mode + * + * The mode for the backend node. + * + * \value ReadOnly + * \value ReadWrite + */ + +QBackendNode::QBackendNode(QBackendNode::Mode mode) + : d_ptr(new QBackendNodePrivate(mode)) +{ + d_ptr->q_ptr = this; +} + +QBackendNode::~QBackendNode() +{ + delete d_ptr; +} + +/*! + * Sets the peer \a id. + */ +void QBackendNode::setPeerId(QNodeId id) noexcept +{ + Q_D(QBackendNode); + d->m_peerId = id; +} + +/*! + * \return the peer id of the backend node. + */ +QNodeId QBackendNode::peerId() const noexcept +{ + Q_D(const QBackendNode); + return d->m_peerId; +} + +/*! + * \return \c true if the backend node is enabled. + */ +bool QBackendNode::isEnabled() const noexcept +{ + Q_D(const QBackendNode); + return d->m_enabled; +} + +/*! + * \return the mode of the backend mode. + */ +QBackendNode::Mode QBackendNode::mode() const noexcept +{ + Q_D(const QBackendNode); + return d->m_mode; +} + +/*! + * \brief QBackendNode::syncFromFrontEnd + * \param frontEnd + * \param firstTime + * + * This is called by the aspect when a \a frontEnd node needs to synchronize it's changes + * with the backend (normally due to property changes). + * + * \a firstTime will be true if the backend node was just created + */ +void QBackendNode::syncFromFrontEnd(const QNode *frontEnd, bool firstTime) +{ + Q_UNUSED(frontEnd); + Q_UNUSED(firstTime); +} + +/*! + * \internal + */ +QBackendNode::QBackendNode(QBackendNodePrivate &dd) + : d_ptr(&dd) +{ + d_ptr->q_ptr = this; +} + +/*! + * Enables or disables the backend node by \a enabled. + */ +void QBackendNode::setEnabled(bool enabled) noexcept +{ + Q_D(QBackendNode); + d->m_enabled = enabled; +} + +} // Qt3D + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0122022_4.cc b/pool/shard011/C++/0122022_4.cc new file mode 100644 index 0000000000000000000000000000000000000000..605c39ec59281662523278ac9f74675cf53e8d41 --- /dev/null +++ b/pool/shard011/C++/0122022_4.cc @@ -0,0 +1,157 @@ +// { dg-do run { target c++14 } } + +// Copyright (C) 2013-2021 Free Software Foundation, Inc. +// +// This file is part of the GNU ISO C++ Library. This library is free +// software; you can redistribute it and/or modify it under the +// terms of the GNU General Public License as published by the +// Free Software Foundation; either version 3, or (at your option) +// any later version. + +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License along +// with this library; see the file COPYING3. If not see +// . + +#include +#include + +struct exception {}; + +int counter = 0; + +struct mixin_counter +{ + mixin_counter() { ++counter; } + mixin_counter(mixin_counter const&) { ++counter; } + ~mixin_counter() { --counter; } +}; + +struct value_type : private mixin_counter +{ + enum state_type + { + zero, + moved_from, + throwing_construction, + throwing_copy, + throwing_copy_assignment, + throwing_move, + throwing_move_assignment, + threw, + }; + + value_type() = default; + + explicit value_type(state_type state_) + : state(state_) + { + throw_if(throwing_construction); + } + + value_type(value_type const& other) + : state(other.state) + { + throw_if(throwing_copy); + } + + value_type& + operator=(value_type const& other) + { + state = other.state; + throw_if(throwing_copy_assignment); + return *this; + } + + value_type(value_type&& other) + : state(other.state) + { + other.state = moved_from; + throw_if(throwing_move); + } + + value_type& + operator=(value_type&& other) + { + state = other.state; + other.state = moved_from; + throw_if(throwing_move_assignment); + return *this; + } + + void throw_if(state_type match) + { + if(state == match) + { + state = threw; + throw exception {}; + } + } + + state_type state = zero; +}; + +int main() +{ + using O = std::experimental::optional; + using S = value_type::state_type; + auto const make = [](S s = S::zero) { return value_type { s }; }; + + enum outcome_type { nothrow, caught, bad_catch }; + + // Check value assignment for engaged optional + + { + O o = make(); + value_type v = make(S::throwing_copy); + o = v; + VERIFY( o && o->state == S::throwing_copy); + } + + { + O o = make(); + value_type v = make(S::throwing_move); + o = std::move(v); + VERIFY( o && o->state == S::throwing_move); + } + + { + outcome_type outcome {}; + O o = make(); + value_type v = make(S::throwing_copy_assignment); + + try + { + o = v; + } + catch(exception const&) + { outcome = caught; } + catch(...) + { outcome = bad_catch; } + + VERIFY( o && o->state == S::threw ); + } + + { + outcome_type outcome {}; + O o = make(); + value_type v = make(S::throwing_move_assignment); + + try + { + o = std::move(v); + } + catch(exception const&) + { outcome = caught; } + catch(...) + { outcome = bad_catch; } + + VERIFY( o && o->state == S::threw ); + } + + VERIFY( counter == 0 ); +} diff --git a/pool/shard011/C++/0122025_main.cpp b/pool/shard011/C++/0122025_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ce48cbbd6768bf6c3970785647eb4d0bc4654f0a --- /dev/null +++ b/pool/shard011/C++/0122025_main.cpp @@ -0,0 +1,243 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int Find_Connector(const char * cStr, const int start, char & result); +void Split_Command(std :: string cStr, std::vector & cmdVector, std::vector & cntVector); +char * Cut_Comment(char * args); + +int Do_EXEC (char * args); +int EXEC (char * args[]); + +int main (int argc, char * argv[]) +{ + char hostname[20]; + gethostname(hostname,256); + char current [MAXPATHLEN]; + char * currentDir=getcwd(current,MAXPATHLEN); + char * username = getlogin(); + + std :: string cmdStr; + do + { + std :: cout << username << "@" << hostname << currentDir << "$ "; + std :: getline (std :: cin, cmdStr); + + if (!cmdStr.empty()) + { + char * cmdCStr = new char[cmdStr.length () + 1]; + std :: strcpy (cmdCStr, cmdStr.c_str()); + cmdCStr[cmdStr.length ()] = '\0'; + + std::vector cmdVector; + std::vector cntVector; + Split_Command(cmdStr, cmdVector, cntVector); + + //Execute commands + int last_status = 0; + for (unsigned int i = 0; i < cmdVector.size(); ++i) + { + if (cntVector[i] == 0) //First cmd or after ';' + { + last_status = Do_EXEC (cmdVector[i]); + } + else if (cntVector[i] == 1 && last_status == 0) //After '&&' + { + last_status = Do_EXEC (cmdVector[i]); + } + else if (cntVector[i] == 2 && last_status != 0) //After '||' + { + last_status = Do_EXEC (cmdVector[i]); + } + if (last_status == -2) + { + //Execute cd + std :: cout << "Executing: cd" << std :: endl; + char * temp=cmdVector[i]; + char directory [MAXPATHLEN]; + directory[0]='/'; + int j=1; + for (unsigned int i = 3;i & cmdVector, std::vector & cntVector) +{ + cntVector.push_back(0); + int i = 0; + int j = 0; + while (i != -1) + { + std :: string tmpStr; + char tmpResult; + int a = 0; + int b = 0; + j = Find_Connector(cStr.c_str(), i, tmpResult); + if (j == -1) + { + b = -1; + } + else if (tmpResult == ';') + { + cntVector.push_back(0); + b = j+2; + } + else if (tmpResult == '&') + { + cntVector.push_back(1); + a = -1; + b = j+3; + } + else if (tmpResult == '|') + { + cntVector.push_back(2); + a = -1; + b = j+3; + } + tmpStr = cStr.substr(i, j - i + a); + char * tmpCStr = new char[tmpStr.length () + 1]; + std :: strcpy (tmpCStr, tmpStr.c_str()); + tmpCStr[tmpStr.length ()] = '\0'; + cmdVector.push_back(tmpCStr); + i = b; + } +} + +char * Cut_Comment(char * args) +{ + int i = 0; + while (args[i] != '\0') + { + if (args[i] == '#') + { + char * tmp = new char[i+1]; + for (int j = 0; j < i; ++j) + { + tmp[j] = args[j]; + } + tmp[i] = '\0'; + return tmp; + } + i++; + } + return args; +} + +int Do_EXEC (char * args) +{ + if (strncmp(args, "exit", 4) == 0) + { + //Exit program + std :: cout << "Executing: exit" << std :: endl; + exit(0); + } + + if (strncmp(args, "cd", 2) == 0) + return -2; + + + char * tmpARGS = Cut_Comment(args); + std :: vector args_vector; + char * pch = strtok (tmpARGS, " "); + while (pch != NULL) + { + args_vector.push_back (pch); + pch = strtok (NULL, " "); + } + args_vector.push_back (0); + int args_size = args_vector.size (); + char * args_result[10]; + for (int i = 0; i < args_size; i++) + { + args_result[i] = args_vector[i]; + } + + return EXEC(args_result); +} + +int EXEC (char * args[]) +{ + //Execute the command + pid_t c_pid, pid; + int status = 0; + c_pid = fork (); + + if (c_pid < 0) + { + perror ("Fork Failed"); + exit (1); + } + else if (c_pid == 0) + { + printf ("Executing: %s\n", args[0]); + execvp (args[0], args); + perror ("Execve Faild"); + exit (1); + } + else if (c_pid > 0) + { + if ((pid = wait (&status)) < 0) + { + perror ("wait"); + exit (1); + } + return status; + } + + return status; +} diff --git a/pool/shard011/C++/0122027_fileviewdelegate.cpp b/pool/shard011/C++/0122027_fileviewdelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f8cd31ef947743f10ef2849e5f748a6dbb0545d --- /dev/null +++ b/pool/shard011/C++/0122027_fileviewdelegate.cpp @@ -0,0 +1,127 @@ +// Copyright 2016 Peter Peters +// +// 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 "fileviewdelegate.h" + +#include +#include + +#include "sum_shared/sumtypes.h" +#include "view/sumstateicons.h" + +const int MARGIN = 2; + +FileViewDelegate::FileViewDelegate(QWidget *parent) : + QStyledItemDelegate(parent) +{ +} + +FileViewDelegate::~FileViewDelegate() +{ +} + +void FileViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + const FileData fd = getFileData(index); + + painter->save(); + if (option.state & QStyle::State_Selected) + { + painter->fillRect(option.rect, option.palette.highlight()); + } + + const int h = fd.isDir ? option.rect.height() / 2 : option.rect.height(); + const int w = option.rect.width() / 4; + + SumStateIcons ssi; + const QList STATES = SumState::getStateList(); + + for(int i=0 ; i<=STATES.size() ; i++) + { + QPixmap p; + int cnt; + + if(i == 0) + { + if(fd.isDir) + { + cnt = fd.theStateCount.value(SumState::UNKNOWN, 0); + } + else + { + cnt = 0; + } + } + else + { + p = ssi.getPixmap(STATES.at(i-1)); + cnt = fd.theStateCount.value(STATES.at(i-1), 0); + + // separator + const bool not_check = fd.theStateCount.value(SumState::NOT_CHECKING, 0)>0; + if(fd.isDir || !not_check) + { + QBrush b = painter->brush(); + painter->setBrush(QBrush(QColor(Qt::lightGray).lighter())); + const int x = option.rect.x() + (i*w); + const int y = option.rect.y() + (h-5)/2; + painter->drawLine(x, y+1, x, y+2); + painter->drawLine(x, y+4, x, y+5); + painter->setBrush(b); + } + } + + if(cnt>0) + { + const int x = option.rect.x() + (i*w) + (w-p.width()) / 2; + const int y = option.rect.y() + (h-p.height()) / 2 + MARGIN; + + painter->drawPixmap(x, y, p); + + if(fd.isDir) + { + painter->drawText(option.rect.x() + i*w, + option.rect.y() + h, + w, h, + Qt::AlignHCenter | Qt::AlignVCenter, QString::number(cnt)); + } + } + } + + painter->restore(); +} + +QSize FileViewDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + QSize s = QStyledItemDelegate::sizeHint(option, index); + if(getFileData(index).isDir) + { + s.rheight() = std::max(s.height(), 14+(2*MARGIN)); + s.rheight() *= 2; + } + return s; +} + +FileData FileViewDelegate::getFileData(const QModelIndex &index) const +{ + Q_ASSERT(index.model()); + + QVariant v = index.model()->data(index); + if (v.canConvert()) + { + return v.value(); + } + + return FileData(false); +} diff --git a/pool/shard011/C++/0122029_PyIExplorerBrowserEvents.cpp b/pool/shard011/C++/0122029_PyIExplorerBrowserEvents.cpp new file mode 100644 index 0000000000000000000000000000000000000000..84c56a238819e0203827fe3ce249b69a571fb2b1 --- /dev/null +++ b/pool/shard011/C++/0122029_PyIExplorerBrowserEvents.cpp @@ -0,0 +1,201 @@ +// This file implements the IExplorerBrowserEvents Interface and Gateway for Python. +// Generated by makegw.py + +#include "shell_pch.h" +#include "PyIExplorerBrowserEvents.h" + +// @doc - This file contains autoduck documentation +// --------------------------------------------------- +// +// Interface Implementation + +PyIExplorerBrowserEvents::PyIExplorerBrowserEvents(IUnknown *pdisp): + PyIUnknown(pdisp) +{ + ob_type = &type; +} + +PyIExplorerBrowserEvents::~PyIExplorerBrowserEvents() +{ +} + +/* static */ IExplorerBrowserEvents *PyIExplorerBrowserEvents::GetI(PyObject *self) +{ + return (IExplorerBrowserEvents *)PyIUnknown::GetI(self); +} + +// @pymethod |PyIExplorerBrowserEvents|OnNavigationPending|Description of OnNavigationPending. +PyObject *PyIExplorerBrowserEvents::OnNavigationPending(PyObject *self, PyObject *args) +{ + IExplorerBrowserEvents *pIEBE = GetI(self); + if ( pIEBE == NULL ) + return NULL; + PCIDLIST_ABSOLUTE pidlFolder; + PyObject *obpidlFolder; + // @pyparm |pidlFolder||Description for pidlFolder + if ( !PyArg_ParseTuple(args, "O:OnNavigationPending", &obpidlFolder) ) + return NULL; + BOOL bPythonIsHappy = TRUE; + if (bPythonIsHappy && !PyObject_AsPCIDLIST_ABSOLUTE( obpidlFolder, &pidlFolder )) bPythonIsHappy = FALSE; + if (!bPythonIsHappy) return NULL; + HRESULT hr; + PY_INTERFACE_PRECALL; + hr = pIEBE->OnNavigationPending( pidlFolder ); + PyObject_FreePCIDLIST_ABSOLUTE(pidlFolder); + + PY_INTERFACE_POSTCALL; + + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIEBE, IID_IExplorerBrowserEvents ); + Py_INCREF(Py_None); + return Py_None; + +} + +// @pymethod |PyIExplorerBrowserEvents|OnViewCreated|Description of OnViewCreated. +PyObject *PyIExplorerBrowserEvents::OnViewCreated(PyObject *self, PyObject *args) +{ + IExplorerBrowserEvents *pIEBE = GetI(self); + if ( pIEBE == NULL ) + return NULL; + // @pyparm |psv||Description for psv + PyObject *obpsv; + IShellView * psv; + if ( !PyArg_ParseTuple(args, "O:OnViewCreated", &obpsv) ) + return NULL; + BOOL bPythonIsHappy = TRUE; + if (bPythonIsHappy && !PyCom_InterfaceFromPyInstanceOrObject(obpsv, IID_IShellView, (void **)&psv, TRUE /* bNoneOK */)) + bPythonIsHappy = FALSE; + if (!bPythonIsHappy) return NULL; + HRESULT hr; + PY_INTERFACE_PRECALL; + hr = pIEBE->OnViewCreated( psv ); + if (psv) psv->Release(); + + PY_INTERFACE_POSTCALL; + + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIEBE, IID_IExplorerBrowserEvents ); + Py_INCREF(Py_None); + return Py_None; + +} + +// @pymethod |PyIExplorerBrowserEvents|OnNavigationComplete|Description of OnNavigationComplete. +PyObject *PyIExplorerBrowserEvents::OnNavigationComplete(PyObject *self, PyObject *args) +{ + IExplorerBrowserEvents *pIEBE = GetI(self); + if ( pIEBE == NULL ) + return NULL; + PCIDLIST_ABSOLUTE pidlFolder; + PyObject *obpidlFolder; + // @pyparm |pidlFolder||Description for pidlFolder + if ( !PyArg_ParseTuple(args, "O:OnNavigationComplete", &obpidlFolder) ) + return NULL; + BOOL bPythonIsHappy = TRUE; + if (bPythonIsHappy && !PyObject_AsPCIDLIST_ABSOLUTE( obpidlFolder, &pidlFolder )) bPythonIsHappy = FALSE; + if (!bPythonIsHappy) return NULL; + HRESULT hr; + PY_INTERFACE_PRECALL; + hr = pIEBE->OnNavigationComplete( pidlFolder ); + PyObject_FreePCIDLIST_ABSOLUTE(pidlFolder); + + PY_INTERFACE_POSTCALL; + + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIEBE, IID_IExplorerBrowserEvents ); + Py_INCREF(Py_None); + return Py_None; + +} + +// @pymethod |PyIExplorerBrowserEvents|OnNavigationFailed|Description of OnNavigationFailed. +PyObject *PyIExplorerBrowserEvents::OnNavigationFailed(PyObject *self, PyObject *args) +{ + IExplorerBrowserEvents *pIEBE = GetI(self); + if ( pIEBE == NULL ) + return NULL; + PCIDLIST_ABSOLUTE pidlFolder; + PyObject *obpidlFolder; + // @pyparm |pidlFolder||Description for pidlFolder + if ( !PyArg_ParseTuple(args, "O:OnNavigationFailed", &obpidlFolder) ) + return NULL; + BOOL bPythonIsHappy = TRUE; + if (bPythonIsHappy && !PyObject_AsPCIDLIST_ABSOLUTE( obpidlFolder, &pidlFolder )) bPythonIsHappy = FALSE; + if (!bPythonIsHappy) return NULL; + HRESULT hr; + PY_INTERFACE_PRECALL; + hr = pIEBE->OnNavigationFailed( pidlFolder ); + PyObject_FreePCIDLIST_ABSOLUTE(pidlFolder); + + PY_INTERFACE_POSTCALL; + + if ( FAILED(hr) ) + return PyCom_BuildPyException(hr, pIEBE, IID_IExplorerBrowserEvents ); + Py_INCREF(Py_None); + return Py_None; + +} + +// @object PyIExplorerBrowserEvents|Description of the interface +static struct PyMethodDef PyIExplorerBrowserEvents_methods[] = +{ + { "OnNavigationPending", PyIExplorerBrowserEvents::OnNavigationPending, 1 }, // @pymeth OnNavigationPending|Description of OnNavigationPending + { "OnViewCreated", PyIExplorerBrowserEvents::OnViewCreated, 1 }, // @pymeth OnViewCreated|Description of OnViewCreated + { "OnNavigationComplete", PyIExplorerBrowserEvents::OnNavigationComplete, 1 }, // @pymeth OnNavigationComplete|Description of OnNavigationComplete + { "OnNavigationFailed", PyIExplorerBrowserEvents::OnNavigationFailed, 1 }, // @pymeth OnNavigationFailed|Description of OnNavigationFailed + { NULL } +}; + +PyComTypeObject PyIExplorerBrowserEvents::type("PyIExplorerBrowserEvents", + &PyIUnknown::type, + sizeof(PyIExplorerBrowserEvents), + PyIExplorerBrowserEvents_methods, + GET_PYCOM_CTOR(PyIExplorerBrowserEvents)); +// --------------------------------------------------- +// +// Gateway Implementation +STDMETHODIMP PyGExplorerBrowserEvents::OnNavigationPending( + /* [in] */ PCIDLIST_ABSOLUTE pidlFolder) +{ + PY_GATEWAY_METHOD; + PyObject *obpidlFolder = PyObject_FromPCIDLIST_ABSOLUTE(pidlFolder, FALSE); + if (obpidlFolder==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("OnNavigationPending"); + HRESULT hr=InvokeViaPolicy("OnNavigationPending", NULL, "O", obpidlFolder); + Py_DECREF(obpidlFolder); + return hr; +} + +STDMETHODIMP PyGExplorerBrowserEvents::OnViewCreated( + /* [in] */ IShellView * psv) +{ + PY_GATEWAY_METHOD; + PyObject *obpsv; + obpsv = PyCom_PyObjectFromIUnknown(psv, IID_IShellView, TRUE); + HRESULT hr=InvokeViaPolicy("OnViewCreated", NULL, "O", obpsv); + Py_XDECREF(obpsv); + return hr; +} + +STDMETHODIMP PyGExplorerBrowserEvents::OnNavigationComplete( + /* [in] */ PCIDLIST_ABSOLUTE pidlFolder) +{ + PY_GATEWAY_METHOD; + PyObject *obpidlFolder = PyObject_FromPCIDLIST_ABSOLUTE(pidlFolder, FALSE); + if (obpidlFolder==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("OnNavigationComplete"); + HRESULT hr=InvokeViaPolicy("OnNavigationComplete", NULL, "O", obpidlFolder); + Py_DECREF(obpidlFolder); + return hr; +} + +STDMETHODIMP PyGExplorerBrowserEvents::OnNavigationFailed( + /* [in] */ PCIDLIST_ABSOLUTE pidlFolder) +{ + PY_GATEWAY_METHOD; + PyObject *obpidlFolder = PyObject_FromPCIDLIST_ABSOLUTE(pidlFolder, FALSE); + if (obpidlFolder==NULL) return MAKE_PYCOM_GATEWAY_FAILURE_CODE("OnNavigationFailed"); + HRESULT hr=InvokeViaPolicy("OnNavigationFailed", NULL, "O", obpidlFolder); + Py_DECREF(obpidlFolder); + return hr; +} + diff --git a/pool/shard011/C++/0122031_test_xml.cpp b/pool/shard011/C++/0122031_test_xml.cpp new file mode 100644 index 0000000000000000000000000000000000000000..67f93d95430b6499fb52f37f7d947093bb3488a8 --- /dev/null +++ b/pool/shard011/C++/0122031_test_xml.cpp @@ -0,0 +1,237 @@ + +#include +#include +#include +#include +#include + +#include "xmlparser.h" + +struct IConfig +{ +public: + virtual bool load(const char* filename) = 0; + virtual bool save(const char* filename) = 0; + virtual std::string dump() = 0; +}; + +template +struct xml_config : public Config, public IConfig +{ +public: + virtual bool load(const char* filename) + { + XMLParser xml; + if (!xml.parseFile(filename)) return false; + + XMLParser::NodePtr root = xml.getRootNode(); + if (!root) return false; + + this->reset(); + return this->parse(xml, root); + } + + virtual bool save(const char* filename) + { + XMLWriter xml; + XMLWriter::NodePtr root = xml.createRootNode("config"); + if (root && this->write(xml, root)) + { + xml.save(filename); + } + return false; + } + + virtual std::string dump() + { + std::string result; + + XMLWriter xml; + XMLWriter::NodePtr root = xml.createRootNode("config"); + if (root && this->write(xml, root)) + { + xml.dump(result); + } + + return result; + } + +public: + template + std::string dumpnode(T& data, const char* nodename) + { + std::string result; + + XMLWriter xml; + XMLWriter::NodePtr root = xml.createRootNode(nodename); + if (root && data.write(xml, root)) + { + xml.dump(result); + } + + return result; + } +}; + +#if 0 +struct Config : public IConfig +{ +public: + std::string master; + int bind; + + struct AppItem + { + std::string name; + std::string& operator () () { return content_; } + const std::string& operator () () const { return content_; } + private: + std::string content_; + }; + + typedef std::map AppMap; + typedef AppMap::iterator AppMapIter; + typedef AppMap::const_iterator AppMapConstIter; + AppMap apps; + + struct ListItem + { + int prop1; + std::string prop2; + + std::string& operator () () { return content_; } + const std::string& operator () () const { return content_; } + private: + std::string content_; + }; + std::vector lists; +public: + bool load(const char* filename); + + XMLWriter write(); + + bool save(const char* filename) + { + return write().save(filename); + } + + std::string dump() + { + std::string text; + write().dump(text); + return text; + } +}; + + +bool Config::load(const char* filename) +{ + XMLParser xml; + if (!xml.parseFile(filename)) return false; + + XMLParser::NodePtr root = xml.getRootNode(); + if (!root) return false; + + XMLParser::NodePtr master_node = xml.getChildNode(root, "master"); + if (master_node) + { + master = xml.getNodeContent(master_node); + } + + XMLParser::NodePtr app_node = xml.getChildNode(root, "app"); + while (app_node) + { + AppItem item; + item.name = xml.getNodeProp(app_node, "name"); + item() = xml.getNodeContent(app_node); + apps.insert(std::make_pair(item.name, item)); + + app_node = xml.getNextNode(app_node, "app"); + } + + XMLParser::NodePtrs listnodes = xml.getChildNodes(root, "list"); + for (size_t i = 0; i < listnodes.size(); i++) + { + ListItem item; + item.prop1 = xml.getNodeProp(listnodes[i], "prop1"); + item.prop2 = xml.getNodeProp(listnodes[i], "prop2"); + item() = xml.getNodeContent(listnodes[i]); + lists.push_back(item); + } + + std::string text; + xml.dump(text); + std::cout << text << std::endl; + + return true; +} + +XMLWriter Config::write() +{ + XMLWriter xml; + XMLWriter::NodePtr root = xml.createRootNode("config"); + + xml.createComment(root, "master"); + xml.createChildNode(root, "master", master.c_str()); + + xml.createComment(root, "apps"); + for (AppMapIter it = apps.begin(); it != apps.end(); ++ it) + { + XMLWriter::NodePtr app_node = xml.createChildNode(root, "app", it->second().c_str()); + if (app_node) + { + xml.createNodeProp(app_node, "name", it->second.name); + } + } + + xml.createComment(root, "list"); + for (size_t i = 0; i < lists.size(); i++) + { + XMLWriter::NodePtr list_node = xml.createChildNode(root, "list", lists[i]().c_str()); + if (list_node) + { + xml.createNodeProp(list_node, "prop1", lists[i].prop1); + xml.createNodeProp(list_node, "prop2", lists[i].prop2); + } + } + + return xml; +} + +#else +#include "test_xml.h" +#endif + + +xml_config cfg; + +int main(int argc, const char* argv[]) +{ + cfg.load("test_xml.xml"); + cfg.load("test_xml.xml"); + std::cout << cfg.dump() << std::endl; + cfg.save("test_xml_out.xml"); + + std::cout << cfg.master() << std::endl; + std::cout << cfg.onlyprop.prop1() << std::endl; + std::cout << cfg.onlyprop.subnode.p2() << std::endl; + + for (Config::Parent::MyVecContIter it = cfg.parent.myVec.begin(); it != cfg.parent.myVec.end(); ++ it) + { + std::cout << it->name() << std::endl; + + for (size_t i = 0; i < it->onlyone.size(); i++) + { + std::cout << it->onlyone[i].p1() << " - " << it->onlyone[i].p2() << std::endl; + } + } + + std::cout << cfg.dumpnode(cfg.parent, "parent") << std::endl; + + cfg.reset(); + std::cout << cfg.dump() << std::endl; + + return 0; +} + + diff --git a/pool/shard011/C++/0122032_tree_regression_tests.cc b/pool/shard011/C++/0122032_tree_regression_tests.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3999fec6989a6cd5ad039354fa2d8ae689c137e --- /dev/null +++ b/pool/shard011/C++/0122032_tree_regression_tests.cc @@ -0,0 +1,212 @@ +/* + + Cadabra: a field-theory motivated computer algebra system. + Copyright (C) 2001-2011 Kasper Peeters + + This program is free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +*/ + +#include "tree.hh" +#include "tree_util.hh" + +#include +#include +#include +#include +#include +#include +#include +#include + +void status_message(const std::string& name, bool res) + { + std::cout << name << "\t: " << (res?"passed":"failed") << std::endl; + } + +int compare_tree(const std::string& name, const tree& tr, const std::string& exp) + { + std::ostringstream str; + kptree::print_tree_bracketed(tr, str); + if(str.str()==exp) { + status_message(name, true); + return 1; + } + else { + status_message(name, false); + std::cout << " expected:" << std::endl << exp << std::endl + << " received:" << std::endl << str.str() << std::endl; + return 0; + } + } + +int compare_subtree(const std::string& name, const tree& tr, tree::iterator it, + const std::string& exp) + { + std::ostringstream str; + kptree::print_subtree_bracketed(tr, it, str); + if(str.str()==exp) { + status_message(name, true); + return 1; + } + else { + status_message(name, false); + std::cout << " expected:" << exp << std::endl + << " received:" << str.str() << std::endl << std::endl; + return 0; + } + } + +int test1() + { + tree tst; + return compare_tree("empty tree ", tst, ""); + } + +int test2() + { + int res=1; + + tree tr; + tree::pre_order_iterator html, body, h1, h3, bh1, mv1, sometext; + + html=tr.set_head("html"); + tr.insert(html,"extra"); + body=tr.append_child(html, "body"); + h1 =tr.append_child(body, "h1"); + bh1 =tr.insert(h1,"before h1"); + sometext = tr.append_child(h1, "some text"); +// tree::sibling_iterator more_text= + tr.append_child(body, "more text"); + + res*=compare_tree("basic algorithms", tr, "extra\nhtml(body(before h1, h1(some text), more text))"); + + tr.swap(bh1); + res*=compare_tree("element swapping", tr, "extra\nhtml(body(h1(some text), before h1, more text))"); + tr.swap(h1); + res*=compare_tree("swapping back ", tr, "extra\nhtml(body(before h1, h1(some text), more text))"); + + tree copytree(h1); + res*=compare_tree("copy constructor", copytree, "h1(some text)"); + + tree::pre_order_iterator it; + it=std::find(tr.begin(),tr.end(),std::string("h1")); + if(it==tr.end()) { + status_message("stl find ", false); + res=0; + } + else res*=compare_subtree("stl find ", tr, it, "h1(some text)"); + + it=std::find(tr.begin(),tr.end(), std::string("kasper")); + if(it!=tr.end()) { + status_message("stl find 2 ", false); + res=0; + } + else status_message("stl find 2 ", true); + + // depth & max_depth + // + if(tr.depth(sometext)==3) + status_message("depth ", true); + else { + status_message("depth ", false); + res=0; + } + + if(tr.max_depth(tr.begin())==0) + status_message("max_depth 1 ", true); + else { + status_message("max_depth 1 ", false); + res=0; + } + if(tr.max_depth(html)==3) + status_message("max_depth 2 ", true); + else { + status_message("max_depth 2 ", false); + res=0; + } + if(tr.max_depth()==3) + status_message("max_depth 3 ", true); + else { + status_message("max_depth 3 ", false); + res=0; + } + tree tr2; + if(tr2.max_depth()==-1) + status_message("max_depth 4 ", true); + else { + status_message("max_depth 4 ", false); + res=0; + } + + + return res; + } + +int test3() + { + int res=1; + + tree tr; + tree::iterator l1,l2,l3,l4,l5,tr1; + + l1=tr.set_head("1"); + l2=tr.append_child(l1,"11"); + tr1=tr.append_child(l1,"12"); + tr.append_child(l1,"13"); + l3=tr.append_child(l1,"14"); + l4=tr.append_child(l2,"111"); + l5=tr.append_child(l3,"141"); + tr.append_child(l4,"1111"); + tr.append_child(l5,"1411"); + tr.append_child(tr1,"bad"); + +// kptree::print_subtree_bracketed(tr, tr.begin(), std::cout); +// std::cout << std::endl; + tree::fixed_depth_iterator fd=tr.begin_fixed(tr.begin(),3); + if(tr.is_valid(fd) && *fd=="1111") status_message("fixed_depth_iterator 1", true); + else { + res=0; + status_message("fixed_depth_iterator 1", false); + } + fd=tr.next_at_same_depth(fd); + if(tr.is_valid(fd) && *fd=="1411") status_message("fixed_depth_iterator 2", true); + else { + res=0; + status_message("fixed_depth_iterator 2", false); + } + fd=tr.next_at_same_depth(fd); + if(tr.is_valid(fd)==false) status_message("fixed_depth_iterator 3", true); + else { + res=0; + status_message("fixed_depth_iterator 3", false); + } + + return res; + } + +int main(int, char **) + { + int result=1; + result*=test1()*test2()*test3(); + + if(result!=1) { + std::cout << "*** Regression tests failed ***" << std::endl; + return -1; + } + else { + std::cout << "Regression tests passed." << std::endl; + return 0; + } + } diff --git a/pool/shard011/C++/0122033_DXGuiSystem.cpp b/pool/shard011/C++/0122033_DXGuiSystem.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da66ddb26e49ea2b7098920d8b51eec05f28244b --- /dev/null +++ b/pool/shard011/C++/0122033_DXGuiSystem.cpp @@ -0,0 +1,142 @@ +#include "DXGuiSystem.h" +#include "../component/WindowSystemComponent.h" +#include "../component/DXWindowSystemComponent.h" +#include "../component/DXRenderingSystemComponent.h" +#include "../component/DXGeometryRenderPassComponent.h" + +#include "ImGuiWrapper.h" +#include "../third-party/ImGui/imgui_impl_win32.h" +#include "../third-party/ImGui/imgui_impl_dx11.h" +#include "ICoreSystem.h" + +extern ICoreSystem* g_pCoreSystem; + +INNO_PRIVATE_SCOPE DXGuiSystemNS +{ + ObjectStatus m_objectStatus = ObjectStatus::SHUTDOWN; + + void showRenderResult(RenderingConfig & renderingConfig); + ImTextureID getFileExplorerIconTextureID(const FileExplorerIconType iconType); + + std::function f_ShowRenderPassResult; + std::function f_GetFileExplorerIconTextureID; +} + +INNO_SYSTEM_EXPORT bool DXGuiSystem::setup() +{ + DXGuiSystemNS::f_ShowRenderPassResult = DXGuiSystemNS::showRenderResult; + DXGuiSystemNS::f_GetFileExplorerIconTextureID = DXGuiSystemNS::getFileExplorerIconTextureID; + + ImGuiWrapper::get().setup(); + + ImGuiWrapper::get().addShowRenderPassResultCallback(&DXGuiSystemNS::f_ShowRenderPassResult); + ImGuiWrapper::get().addGetFileExplorerIconTextureIDCallback(&DXGuiSystemNS::f_GetFileExplorerIconTextureID); + + DXGuiSystemNS::m_objectStatus = ObjectStatus::ALIVE; + return true; +} + +INNO_SYSTEM_EXPORT bool DXGuiSystem::initialize() +{ + ImGui_ImplWin32_Init(DXWindowSystemComponent::get().m_hwnd); + ImGui_ImplDX11_Init(DXRenderingSystemComponent::get().m_device, DXRenderingSystemComponent::get().m_deviceContext); + + ImGuiWrapper::get().initialize(); + + g_pCoreSystem->getLogSystem()->printLog(LogType::INNO_DEV_SUCCESS, "DXGuiSystem has been initialized."); + return true; +} + +INNO_SYSTEM_EXPORT bool DXGuiSystem::update() +{ + ImGui_ImplDX11_NewFrame(); + ImGui_ImplWin32_NewFrame(); + + ImGuiWrapper::get().update(); + + // Rendering + DXRenderingSystemComponent::get().m_deviceContext->OMSetRenderTargets( + 1, + &DXRenderingSystemComponent::get().m_renderTargetView, + NULL); + + DXRenderingSystemComponent::get().m_deviceContext->RSSetViewports( + 1, + &DXRenderingSystemComponent::get().m_viewport); + + ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData()); + + return true; +} + +INNO_SYSTEM_EXPORT bool DXGuiSystem::terminate() +{ + DXGuiSystemNS::m_objectStatus = ObjectStatus::STANDBY; + + ImGui_ImplDX11_Shutdown(); + ImGui_ImplWin32_Shutdown(); + + ImGuiWrapper::get().terminate(); + + DXGuiSystemNS::m_objectStatus = ObjectStatus::SHUTDOWN; + g_pCoreSystem->getLogSystem()->printLog(LogType::INNO_DEV_SUCCESS, "DXGuiSystem has been terminated."); + return true; +} + +INNO_SYSTEM_EXPORT ObjectStatus DXGuiSystem::getStatus() +{ + return DXGuiSystemNS::m_objectStatus; +} + +void DXGuiSystemNS::showRenderResult(RenderingConfig & renderingConfig) +{ + auto l_renderTargetSize = ImVec2((float)WindowSystemComponent::get().m_windowResolution.x / 4.0f, (float)WindowSystemComponent::get().m_windowResolution.y / 4.0f); + + ImGui::Begin("Opaque Pass", 0, ImGuiWindowFlags_AlwaysAutoResize); + { + { + ImGui::BeginChild("World Space Position(RGB) + Metallic(A)", l_renderTargetSize, true, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar); + ImGui::Text("World Space Position(RGB) + Metallic(A)"); + ImGui::Image(ImTextureID(DXGeometryRenderPassComponent::get().m_opaquePass_DXRPC->m_DXTDCs[0]->m_SRV), l_renderTargetSize, ImVec2(0.0, 0.0), ImVec2(1.0, 1.0)); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::BeginChild("World Space Normal(RGB) + Roughness(A)", l_renderTargetSize, true, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar); + ImGui::Text("World Space Normal(RGB) + Roughness(A)"); + ImGui::Image(ImTextureID(DXGeometryRenderPassComponent::get().m_opaquePass_DXRPC->m_DXTDCs[1]->m_SRV), l_renderTargetSize, ImVec2(0.0, 0.0), ImVec2(1.0, 1.0)); + ImGui::EndChild(); + } + { + ImGui::BeginChild("Albedo(RGB) + Ambient Occlusion(A)", l_renderTargetSize, true, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar); + ImGui::Text("Albedo(RGB) + Ambient Occlusion(A)"); + ImGui::Image(ImTextureID(DXGeometryRenderPassComponent::get().m_opaquePass_DXRPC->m_DXTDCs[2]->m_SRV), l_renderTargetSize, ImVec2(0.0, 0.0), ImVec2(1.0, 1.0)); + ImGui::EndChild(); + + ImGui::SameLine(); + + ImGui::BeginChild("Screen Space Motion Vector(RGB) + Transparency(A)", l_renderTargetSize, true, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoScrollbar); + ImGui::Text("Screen Space Motion Vector(RGB) + Transparency(A)"); + ImGui::Image(ImTextureID(DXGeometryRenderPassComponent::get().m_opaquePass_DXRPC->m_DXTDCs[3]->m_SRV), l_renderTargetSize, ImVec2(0.0, 0.0), ImVec2(1.0, 1.0)); + ImGui::EndChild(); + } + } + ImGui::End(); +} + +ImTextureID DXGuiSystemNS::getFileExplorerIconTextureID(const FileExplorerIconType iconType) +{ + switch (iconType) + { + case FileExplorerIconType::OBJ: + return ImTextureID(DXRenderingSystemComponent::get().m_iconTemplate_OBJ->m_SRV); break; + case FileExplorerIconType::PNG: + return ImTextureID(DXRenderingSystemComponent::get().m_iconTemplate_PNG->m_SRV); break; + case FileExplorerIconType::SHADER: + return ImTextureID(DXRenderingSystemComponent::get().m_iconTemplate_SHADER->m_SRV); break; + case FileExplorerIconType::UNKNOWN: + return ImTextureID(DXRenderingSystemComponent::get().m_iconTemplate_UNKNOWN->m_SRV); break; + default: + return nullptr; break; + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0122034_console.cpp b/pool/shard011/C++/0122034_console.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bd85e10c18b9ebc4d86779731f133ab0db67e27c --- /dev/null +++ b/pool/shard011/C++/0122034_console.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include "console.h" + +Console :: Console (QObject * parent) + : QObject (parent) +{} + +namespace console { + + namespace { + static QString recursiveArg(QString const &base, QStringList const &args) + { + if (args.count() == 0) return base; + return recursiveArg(base.arg(args[0]), args.mid(1)); + } + + static QScriptValue formattetOutput(QScriptContext *context, QScriptEngine *engine, QTextStream &stream) + { + if (context->argumentCount() > 0) { + QString const msg = context->argument(0).toString(); + QStringList rest; + for (int i = 1; i < context->argumentCount(); ++i) { + rest << context->argument(i).toString(); + } + stream << recursiveArg(msg, rest) << endl; + } + return engine->undefinedValue(); + } + } + + static QScriptValue raw (QScriptContext *context, QScriptEngine *engine) + { + if (context->argumentCount() == 0) { + context->throwError("Missing argument"); + return engine->undefinedValue(); + } + auto arg = context->argument(0); + QTextStream(stdout) << arg.toString().toUtf8(); + return engine->undefinedValue(); + } + + static QScriptValue log (QScriptContext *context, QScriptEngine *engine) + { + QTextStream stream(stdout); + return formattetOutput (context, engine, stream); + } + + static QScriptValue err (QScriptContext *context, QScriptEngine *engine) + { + QTextStream stream(stderr); + return formattetOutput (context, engine, stream); + } + + static QScriptValue trace (QScriptContext *context, QScriptEngine *engine) + { + QTextStream(stderr) << context->backtrace().join("\n") << endl; + return engine->undefinedValue(); + } + +} // end of namespace + +template +static void registerFunction (QScriptEngine *engine, + QString const & name, + Function fn, + QScriptValue *obj, + QString const & doc = QString()) +{ + auto scriptFunction = engine->newFunction(fn); + if (!doc.isEmpty()) { + scriptFunction.setProperty("^doc", doc); + } + obj->setProperty(name, scriptFunction); +} + +Console :: Console (QScriptEngine * engine) + : QObject (engine) +{ + Q_CHECK_PTR (engine); + auto globalObj = engine->globalObject(); + auto console = engine->newObject(); + globalObj.setProperty("console", console); + + registerFunction(engine, "log", console::log, &console, "Prints to stdout with newline."); + registerFunction(engine, "info", console::log, &console, "Same as console.log."); + registerFunction(engine, "error", console::err, &console, "Same as console.log, but writes to stderr."); + registerFunction(engine, "warn", console::err, &console, "Same as console.log, but writes to stderr."); + registerFunction(engine, "trace", console::trace, &console, "Print stack trace to stderr."); + registerFunction(engine, "raw", console::raw, &console, "Print raw output to stdout, without newline."); +} + +Console :: ~Console() +{ +} diff --git a/pool/shard011/C++/0122035_log_uploader.cc b/pool/shard011/C++/0122035_log_uploader.cc new file mode 100644 index 0000000000000000000000000000000000000000..4837ba192084a2bde5574df94ecf00230e05012f --- /dev/null +++ b/pool/shard011/C++/0122035_log_uploader.cc @@ -0,0 +1,149 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "components/rappor/log_uploader.h" + +#include "base/metrics/histogram.h" +#include "base/metrics/sparse_histogram.h" +#include "net/base/load_flags.h" +#include "net/url_request/url_fetcher.h" + +namespace { + +// The delay, in seconds, between uploading when there are queued logs to send. +const int kUnsentLogsIntervalSeconds = 3; + +// When uploading metrics to the server fails, we progressively wait longer and +// longer before sending the next log. This backoff process helps reduce load +// on a server that is having issues. +// The following is the multiplier we use to expand that inter-log duration. +const double kBackoffMultiplier = 1.1; + +// The maximum backoff multiplier. +const int kMaxBackoffIntervalSeconds = 60 * 60; + +// The maximum number of unsent logs we will keep. +// TODO(holte): Limit based on log size instead. +const size_t kMaxQueuedLogs = 10; + +enum DiscardReason { + UPLOAD_SUCCESS, + UPLOAD_REJECTED, + QUEUE_OVERFLOW, + NUM_DISCARD_REASONS +}; + +} // namespace + +namespace rappor { + +LogUploader::LogUploader(const GURL& server_url, + const std::string& mime_type, + net::URLRequestContextGetter* request_context) + : server_url_(server_url), + mime_type_(mime_type), + request_context_(request_context), + has_callback_pending_(false), + upload_interval_(base::TimeDelta::FromSeconds( + kUnsentLogsIntervalSeconds)) { +} + +LogUploader::~LogUploader() {} + +void LogUploader::QueueLog(const std::string& log) { + queued_logs_.push(log); + if (!IsUploadScheduled() && !has_callback_pending_) + StartScheduledUpload(); +} + +bool LogUploader::IsUploadScheduled() const { + return upload_timer_.IsRunning(); +} + +void LogUploader::ScheduleNextUpload(base::TimeDelta interval) { + if (IsUploadScheduled() || has_callback_pending_) + return; + + upload_timer_.Start( + FROM_HERE, interval, this, &LogUploader::StartScheduledUpload); +} + +void LogUploader::StartScheduledUpload() { + DCHECK(!has_callback_pending_); + has_callback_pending_ = true; + current_fetch_.reset( + net::URLFetcher::Create(server_url_, net::URLFetcher::POST, this)); + current_fetch_->SetRequestContext(request_context_.get()); + current_fetch_->SetUploadData(mime_type_, queued_logs_.front()); + + // We already drop cookies server-side, but we might as well strip them out + // client-side as well. + current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SAVE_COOKIES | + net::LOAD_DO_NOT_SEND_COOKIES); + current_fetch_->Start(); +} + +// static +base::TimeDelta LogUploader::BackOffUploadInterval(base::TimeDelta interval) { + DCHECK_GT(kBackoffMultiplier, 1.0); + interval = base::TimeDelta::FromMicroseconds(static_cast( + kBackoffMultiplier * interval.InMicroseconds())); + + base::TimeDelta max_interval = + base::TimeDelta::FromSeconds(kMaxBackoffIntervalSeconds); + return interval > max_interval ? max_interval : interval; +} + +void LogUploader::OnURLFetchComplete(const net::URLFetcher* source) { + // We're not allowed to re-use the existing |URLFetcher|s, so free them here. + // Note however that |source| is aliased to the fetcher, so we should be + // careful not to delete it too early. + DCHECK_EQ(current_fetch_.get(), source); + scoped_ptr fetch(current_fetch_.Pass()); + + int response_code = source->GetResponseCode(); + + // Log a histogram to track response success vs. failure rates. + UMA_HISTOGRAM_SPARSE_SLOWLY("Rappor.UploadResponseCode", response_code); + + bool upload_succeeded = response_code == 200; + + // Determine whether this log should be retransmitted. + DiscardReason reason = NUM_DISCARD_REASONS; + if (upload_succeeded) { + reason = UPLOAD_SUCCESS; + } else if (response_code == 400) { + reason = UPLOAD_REJECTED; + } else if (queued_logs_.size() > kMaxQueuedLogs) { + reason = QUEUE_OVERFLOW; + } + + if (reason != NUM_DISCARD_REASONS) { + UMA_HISTOGRAM_ENUMERATION("Rappor.DiscardReason", + reason, + NUM_DISCARD_REASONS); + queued_logs_.pop(); + } + + // Error 400 indicates a problem with the log, not with the server, so + // don't consider that a sign that the server is in trouble. + bool server_is_healthy = upload_succeeded || response_code == 400; + OnUploadFinished(server_is_healthy, !queued_logs_.empty()); +} + +void LogUploader::OnUploadFinished(bool server_is_healthy, + bool more_logs_remaining) { + DCHECK(has_callback_pending_); + has_callback_pending_ = false; + // If the server is having issues, back off. Otherwise, reset to default. + if (!server_is_healthy) + upload_interval_ = BackOffUploadInterval(upload_interval_); + else + upload_interval_ = base::TimeDelta::FromSeconds(kUnsentLogsIntervalSeconds); + + if (more_logs_remaining) + ScheduleNextUpload(upload_interval_); +} + +} // namespace rappor diff --git a/pool/shard011/C++/0122036_MinerConfig.cpp b/pool/shard011/C++/0122036_MinerConfig.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2ef6dfc9ef0df664540d2cd0b359e76db2646a64 --- /dev/null +++ b/pool/shard011/C++/0122036_MinerConfig.cpp @@ -0,0 +1,54 @@ +// Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers +// +// This file is part of Bytecoin. +// +// Bytecoin is free software: you can redistribute it and/or modify +// it under the terms of the GNU Lesser General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// Bytecoin 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 Bytecoin. If not, see . + +#include "MinerConfig.h" + +#include "Common/CommandLine.h" + +namespace CryptoNote { + +namespace { +const command_line::arg_descriptor arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true}; +const command_line::arg_descriptor arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true}; +const command_line::arg_descriptor arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true}; +} + +MinerConfig::MinerConfig() { + miningThreads = 0; +} + +void MinerConfig::initOptions(boost::program_options::options_description& desc) { + command_line::add_arg(desc, arg_extra_messages); + command_line::add_arg(desc, arg_start_mining); + command_line::add_arg(desc, arg_mining_threads); +} + +void MinerConfig::init(const boost::program_options::variables_map& options) { + if(command_line::has_arg(options, arg_extra_messages)) { + extraMessages = command_line::get_arg(options, arg_extra_messages); + } + + if (command_line::has_arg(options, arg_start_mining)) { + startMining = command_line::get_arg(options, arg_start_mining); + } + + if (command_line::has_arg(options, arg_mining_threads)) { + miningThreads = command_line::get_arg(options, arg_mining_threads); + } +} + +} //namespace CryptoNote diff --git a/pool/shard011/C++/0122038_mainwindow.cpp b/pool/shard011/C++/0122038_mainwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..86e77a0886aad962ab7159a33c841d3c8f64b6dd --- /dev/null +++ b/pool/shard011/C++/0122038_mainwindow.cpp @@ -0,0 +1,166 @@ +/**************************************************************************** +** +** 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 examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License version 3.0 as published by the Free Software +** Foundation and appearing in the file LICENSE.GPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU General Public License version 3.0 requirements will be +** met: http://www.gnu.org/copyleft/gpl.html. +** +** If you have questions regarding the use of this file, please contact +** Nokia at qt-info@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "mainwindow.h" +#include "xmlsyntaxhighlighter.h" + +//! [0] +MainWindow::MainWindow() : m_fileTree(m_namePool) +{ + setupUi(this); + + new XmlSyntaxHighlighter(fileTree->document()); + + // Set up the font. + { + QFont font("Courier",10); + font.setFixedPitch(true); + + fileTree->setFont(font); + queryEdit->setFont(font); + output->setFont(font); + } + + const QString dir(QLibraryInfo::location(QLibraryInfo::ExamplesPath) + "/xmlpatterns/filetree"); + qDebug() << dir; + + if (QDir(dir).exists()) + loadDirectory(dir); + else + fileTree->setPlainText(tr("Use the Open menu entry to select a directory.")); + + const QStringList queries(QDir(":/queries/", "*.xq").entryList()); + int len = queries.count(); + + for (int i = 0; i < len; ++i) + queryBox->addItem(queries.at(i)); + +} +//! [0] + +//! [2] +void MainWindow::on_queryBox_currentIndexChanged() +{ + QFile queryFile(":/queries/" + queryBox->currentText()); + queryFile.open(QIODevice::ReadOnly); + + queryEdit->setPlainText(QString::fromLatin1(queryFile.readAll())); + evaluateResult(); +} +//! [2] + +//! [3] +void MainWindow::evaluateResult() +{ + if (queryBox->currentText().isEmpty()) + return; + + QXmlQuery query(m_namePool); + query.bindVariable("fileTree", m_fileNode); + query.setQuery(QUrl("qrc:/queries/" + queryBox->currentText())); + + QByteArray formatterOutput; + QBuffer buffer(&formatterOutput); + buffer.open(QIODevice::WriteOnly); + + QXmlFormatter formatter(query, &buffer); + query.evaluateTo(&formatter); + + output->setText(QString::fromLatin1(formatterOutput.constData())); +} +//! [3] + +//! [1] +void MainWindow::on_actionOpenDirectory_triggered() +{ + const QString directoryName = QFileDialog::getExistingDirectory(this); + if (!directoryName.isEmpty()) + loadDirectory(directoryName); +} +//! [1] + +//! [4] +//! [5] +void MainWindow::loadDirectory(const QString &directory) +{ + Q_ASSERT(QDir(directory).exists()); + + m_fileNode = m_fileTree.nodeFor(directory); +//! [5] + + QXmlQuery query(m_namePool); + query.bindVariable("fileTree", m_fileNode); + query.setQuery(QUrl("qrc:/queries/wholeTree.xq")); + + QByteArray output; + QBuffer buffer(&output); + buffer.open(QIODevice::WriteOnly); + + QXmlFormatter formatter(query, &buffer); + query.evaluateTo(&formatter); + + treeInfo->setText((QString(tr("Model of %1 output as XML.")).arg(directory))); + fileTree->setText(QString::fromLatin1(output.constData())); + evaluateResult(); +//! [6] +} +//! [6] +//! [4] + +void MainWindow::on_actionAbout_triggered() +{ + QMessageBox::about(this, tr("About File Tree"), + tr("

Select File->Open Directory and " + "choose a directory. The directory is then " + "loaded into the model, and the model is " + "displayed on the left as XML.

" + + "

From the query menu on the right, select " + "a query. The query is displayed and then run " + "on the model. The results are displayed below " + "the query.

")); +} + + diff --git a/pool/shard011/C++/0122039_ProgressWindow.cpp b/pool/shard011/C++/0122039_ProgressWindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..613400f2fb48cd5c5a5d9c3c447f01e19d3cebc3 --- /dev/null +++ b/pool/shard011/C++/0122039_ProgressWindow.cpp @@ -0,0 +1,192 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2014 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} +*/ + +#include "ProgressWindow.hpp" +#include "Screen/Layout.hpp" +#include "Resources.hpp" + +#ifdef USE_GDI +#include "Screen/VirtualCanvas.hpp" +#else +#include "Screen/Canvas.hpp" +#endif + +ProgressWindow::ProgressWindow(ContainerWindow &parent) + :background_color(COLOR_WHITE), + background_brush(background_color), + position(0) +{ + PixelRect rc = parent.GetClientRect(); + WindowStyle style; + style.Hide(); + Create(parent, rc, style); + + UPixelScalar width = rc.right - rc.left, height = rc.bottom - rc.top; + + // Load progress bar background + bitmap_progress_border.Load(IDB_PROGRESSBORDER); + + // Determine text height +#ifndef USE_GDI + font.Load(_T("Droid Sans"), Layout::SmallScale(10)); + text_height = font.GetHeight(); +#else + VirtualCanvas canvas({1, 1}); + text_height = canvas.GetFontHeight(); +#endif + + // Make progress bar height proportional to window height + UPixelScalar progress_height = height / 20; + UPixelScalar progress_horizontal_border = progress_height / 2; + progress_border_height = progress_height * 2; + + // Initialize message text field + PixelRect message_rc = rc; + message_rc.bottom -= progress_border_height + height / 48; + message_rc.top = message_rc.bottom - text_height; + TextWindowStyle message_style; + message_style.center(); + message.Create(*this, NULL, message_rc, message_style); + +#ifndef USE_GDI + message.SetFont(font); +#endif + + // Initialize progress bar + PixelRect pb_rc; + pb_rc.left = progress_horizontal_border; + pb_rc.right = pb_rc.left + width - progress_height; + pb_rc.top = height - progress_border_height + progress_horizontal_border; + pb_rc.bottom = pb_rc.top + progress_height; + ProgressBarStyle pb_style; + progress_bar.Create(*this, pb_rc, pb_style); + + message.InstallWndProc(); // needed for OnChildColor() + + // Set progress bar step size and range + SetRange(0, 1000); + SetStep(50); + + // Show dialog + ShowOnTop(); +} + +void +ProgressWindow::SetMessage(const TCHAR *text) +{ + AssertNoneLocked(); + AssertThread(); + + message.set_text(text); +} + +void +ProgressWindow::SetRange(unsigned min_value, unsigned max_value) +{ + progress_bar.SetRange(min_value, max_value); +} + +void +ProgressWindow::SetStep(unsigned size) +{ + progress_bar.SetStep(size); +} + +void +ProgressWindow::SetValue(unsigned value) +{ + AssertNoneLocked(); + AssertThread(); + + if (value == position) + return; + + position = value; + progress_bar.SetValue(value); +} + +void +ProgressWindow::Step() +{ + progress_bar.Step(); +} + +void +ProgressWindow::OnResize(PixelSize new_size) +{ + ContainerWindow::OnResize(new_size); + + // Make progress bar height proportional to window height + UPixelScalar progress_height = new_size.cy / 20; + UPixelScalar progress_horizontal_border = progress_height / 2; + progress_border_height = progress_height * 2; + + if (message.IsDefined()) + message.Move(0, + new_size.cy - progress_border_height - text_height - (new_size.cy / 48), + new_size.cx, text_height); + + if (progress_bar.IsDefined()) + progress_bar.Move(progress_horizontal_border, + new_size.cy - progress_border_height + progress_horizontal_border, + new_size.cx - progress_height, + progress_height); + + Invalidate(); +} + +void +ProgressWindow::OnPaint(Canvas &canvas) +{ + canvas.Clear(background_color); + + // Determine window size + const UPixelScalar window_width = canvas.GetWidth(); + const UPixelScalar window_height = canvas.GetHeight(); + + PixelRect logo_rect; + logo_rect.left = 0; + logo_rect.top = 0; + logo_rect.right = window_width; + logo_rect.bottom = window_height - progress_border_height; + logo.draw(canvas, logo_rect); + + // Draw progress bar background + canvas.Stretch(0, (window_height - progress_border_height), + window_width, progress_border_height, + bitmap_progress_border); + + ContainerWindow::OnPaint(canvas); +} + +#ifdef USE_GDI + +const Brush * +ProgressWindow::OnChildColor(Window &window, Canvas &canvas) +{ + canvas.SetTextColor(COLOR_BLACK); + canvas.SetBackgroundColor(background_color); + return &background_brush; +} + +#endif diff --git a/pool/shard011/C++/0122040_ConnectPool.cpp b/pool/shard011/C++/0122040_ConnectPool.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0498f4da331bed944c9dae5ecbc9676b0050a981 --- /dev/null +++ b/pool/shard011/C++/0122040_ConnectPool.cpp @@ -0,0 +1,174 @@ +/* + + Copyright (C) 2007 Gregory Smith + and the "Aleph One" developers. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + This license is contained in the file "COPYING", + which is included with this source code; it is available online at + http://www.gnu.org/licenses/gpl.html + + A pool for non-blocking outbound TCP connections + +*/ + +#include "ConnectPool.h" + +ConnectPool* ConnectPool::m_instance = 0; + +NonblockingConnect::NonblockingConnect(const std::string& address, uint16 port) + : m_address(address), m_port(port), m_thread(0), m_ipSpecified(false) +{ + connect(); +} + +NonblockingConnect::NonblockingConnect(const IPaddress& ip) + : m_ip(ip), m_ipSpecified(true) +{ + connect(); +} + +NonblockingConnect::~NonblockingConnect() +{ + if (m_thread) + { + int status; + SDL_WaitThread(m_thread, &status); + m_thread = 0; + } +} + +void NonblockingConnect::connect() +{ + m_status = Connecting; + m_thread = SDL_CreateThread(connect_thread, this); + if (!m_thread) + { + m_status = ConnectFailed; + } + +} + +int NonblockingConnect::connect_thread(void *p) +{ + NonblockingConnect *nbc = static_cast(p); + return nbc->Thread(); +}; + +int NonblockingConnect::Thread() +{ + if (!m_ipSpecified) + { + if (SDLNet_ResolveHost(&m_ip, const_cast(m_address.c_str()), m_port) < 0) + { + m_status = ResolutionFailed; + return 1; + } + + } + + std::auto_ptr channel(new CommunicationsChannel); + + channel->connect(m_ip); + if (channel->isConnected()) + { + m_channel = channel; + m_status = Connected; + return 0; + } + else + { + m_status = ConnectFailed; + return 2; + } +}; + +ConnectPool::ConnectPool() +{ + for (int i = 0; i < kPoolSize; i++) + { + m_pool[i] = std::pair(0, true); + } +} + +void ConnectPool::fast_free() +{ + for (int i = 0; i < kPoolSize; i++) + { + if (m_pool[i].second) + { + if (m_pool[i].first && m_pool[i].first->done()) + { + delete m_pool[i].first; + m_pool[i].first = 0; + } + } + } +} + +NonblockingConnect* ConnectPool::connect(const std::string& address, uint16 port) +{ + fast_free(); + + for (int i = 0; i < kPoolSize; i++) + { + if (m_pool[i].second && !m_pool[i].first) + { + m_pool[i].second = false; + m_pool[i].first = new NonblockingConnect(address, port); + return m_pool[i].first; + } + } + + return 0; +} + +NonblockingConnect* ConnectPool::connect(const IPaddress& ip) +{ + fast_free(); + + for (int i = 0; i < kPoolSize; i++) + { + if (m_pool[i].second && !m_pool[i].first) + { + m_pool[i].second = false; + m_pool[i].first = new NonblockingConnect(ip); + return m_pool[i].first; + } + } + + return 0; +} + +void ConnectPool::abandon(NonblockingConnect *nbc) +{ + for (int i = 0; i < kPoolSize; i++) + { + if (m_pool[i].first == nbc) + { + m_pool[i].second = true; + } + } +} + +ConnectPool::~ConnectPool() +{ + // uncomment these to allow clean-up at exit +// for (int i = 0; i < kPoolSize; i++) +// { +// if (m_pool[i].first) +// { +// delete m_pool[i]; +// } +// } +} + diff --git a/pool/shard011/C++/0122041_findwebcams.cpp b/pool/shard011/C++/0122041_findwebcams.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e3bcf63ff0799a9cf4fdc087d3771ed0edde658d --- /dev/null +++ b/pool/shard011/C++/0122041_findwebcams.cpp @@ -0,0 +1,236 @@ +// +// Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 +// Free Software Foundation, Inc +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#ifdef HAVE_CONFIG_H +#include "gnashconfig.h" +#endif + +#include "gst/GlibDeprecated.h" + +#include +#include +#include + +#include "rc.h" +#include "gst/gst.h" +#include + +namespace { + //get rc file for webcam selection + gnash::RcInitFile& rcfile = gnash::RcInitFile::getDefaultInstance(); +} + +class data { + public: + data(); + gchar* deviceName; + gchar* deviceType; + gint deviceNumber; + gboolean duplicate; +}; + +data::data() { + deviceName = nullptr; + deviceType = nullptr; + deviceNumber = -1; + duplicate = false; +}; + +gint numDuplicates = 0; + +size_t findVidDevs(std::vector& vidVect) { + gint numdevs = 0; + + //vid test source + GstElement *element; + element = gst_element_factory_make ("videotestsrc", "vidtestsrc"); + + if (element == nullptr) { + vidVect.push_back(nullptr); + numdevs += 1; + } else { + vidVect.push_back(new data); + vidVect[numdevs]->deviceName = g_strdup_printf("videotestsrc"); + vidVect[numdevs]->deviceType = g_strdup_printf("videotestsrc"); + vidVect[numdevs]->deviceNumber = 0; + numdevs += 1; + } + + //video4linux source + GstPropertyProbe *probe; + GValueArray *devarr; + element = nullptr; + + element = gst_element_factory_make ("v4lsrc", "v4lvidsrc"); + probe = GST_PROPERTY_PROBE (element); + devarr = gst_property_probe_probe_and_get_values_name (probe, "device"); + for (size_t i = 0; devarr != nullptr && i < devarr->n_values; ++i) { + GValue *val; + gchar *dev_name = nullptr; + + val = g_value_array_get_nth (devarr, i); + g_object_set (element, "device", g_value_get_string (val), NULL); + gst_element_set_state (element, GST_STATE_PLAYING); + g_object_get (element, "device-name", &dev_name, NULL); + gst_element_set_state (element, GST_STATE_NULL); + if (strcmp(dev_name, "null") == 0) { + std::cout << "no v4l video sources found" << std::endl; + } + else { + vidVect.push_back(new data); + vidVect[numdevs]->deviceType = g_strdup_printf("v4lsrc"); + vidVect[numdevs]->deviceName = dev_name; + vidVect[numdevs]->deviceNumber = numdevs; + numdevs += 1; + } + } + if (devarr) { + g_value_array_free (devarr); + } + + + //video4linux2 source + probe = nullptr; + element = nullptr; + devarr = nullptr; + + element = gst_element_factory_make ("v4l2src", "v4l2vidsrc"); + probe = GST_PROPERTY_PROBE (element); + devarr = gst_property_probe_probe_and_get_values_name (probe, "device"); + for (size_t i = 0; devarr != nullptr && i < devarr->n_values; ++i) { + GValue *val; + gchar *dev_name = nullptr; + + val = g_value_array_get_nth (devarr, i); + g_object_set (element, "device", g_value_get_string (val), NULL); + gst_element_set_state (element, GST_STATE_PLAYING); + g_object_get (element, "device-name", &dev_name, NULL); + gst_element_set_state (element, GST_STATE_NULL); + if (strcmp(dev_name, "null") == 0) { + std::cout << "no v4l2 video sources found." << std::endl; + } + else { + vidVect.push_back(new data); + vidVect[numdevs]->deviceType = g_strdup_printf("v4l2src"); + vidVect[numdevs]->deviceName = dev_name; + vidVect[numdevs]->deviceNumber = numdevs; + //mark duplicates (we like v4l2 sources more than v4l, so if + //they're both detected, mark the v4l source as a duplicate) + for (size_t g=1; g < (vidVect.size()-1); g++) { + if (strcmp(vidVect[numdevs]->deviceName, + vidVect[g]->deviceName) == 0) { + vidVect[g]->duplicate = true; + numDuplicates += 1; + } + } + numdevs += 1; + } + } + if (devarr) { + g_value_array_free (devarr); + } + return numdevs; +} + +int main () { + //initialize gstreamer to probe for devs + gst_init(nullptr, nullptr); + size_t numdevs = 0; + std::vector vidVector; + + int fromrc = rcfile.getWebcamDevice(); + + if (fromrc == -1) { + std::cout << std::endl + << "Use this utility to set your desired default webcam device." << std::endl; + numdevs = findVidDevs(vidVector); + std::cout << std::endl + << "INFO: these devices were ignored because they are supported by both" << std::endl + << "video4linux and video4linux2:" << std::endl << std::endl; + for (size_t i = 0; i < numdevs; ++i) { + if (vidVector[i]->duplicate == true) { + std::cout << " " << vidVector[i]->deviceName + << " (" << vidVector[i]->deviceType << ")" << std::endl; + } + } + std::cout << std::endl + << "Gnash interacts with v4l2 sources better than v4l sources, thus the" << std::endl + << "v4l sources will not be printed in the list below." << std::endl + << std::endl + << "Found " << (numdevs - numDuplicates) + << " video devices: " << std::endl << std::endl; + gint counter = 0; + for (size_t i = 0; i < numdevs; ++i) + { + if (i == 0 && (vidVector[i] != nullptr)) { + std::cout << " " << i + << ". Video Test Source (videotestsrc)" << std::endl; + counter++; + } else if (i == 0 && (vidVector[i] == nullptr)) { + std::cout << "no test video device available"; + } else { + if (vidVector[i]->duplicate != true) { + std::cout << " " << counter << ". " + << vidVector[i]->deviceName + << " (" << vidVector[i]->deviceType << ")" << std::endl; + counter++; + } + } + } + //prompt user for device selection + int dev_select = -1; + std::string fromCin; + do { + dev_select = -1; + std::cout << std::endl + << "Choose the device you would like to use (0-" + << (numdevs - numDuplicates - 1) << "): "; + std::cin >> fromCin; + if (fromCin.size() != 1) { + dev_select = -1; + } else if (fromCin[0] == '0') { + dev_select = 0; + } else { + dev_select = atoi(fromCin.c_str()); + } + if ((dev_select < 0) || (dev_select > ((int)numdevs - numDuplicates - 1))) { + std::cout << "You must make a valid device selection" << std::endl; + } + } while ((dev_select < 0) || (dev_select > ((int)numdevs - numDuplicates - 1))); + std::cout << std::endl + << "To select this camera, add this line to your gnashrc file:" << std::endl + << "set webcamDevice " + << (vidVector[dev_select + numDuplicates]->deviceNumber) << std::endl; + } else { + numdevs = findVidDevs(vidVector); + if ((size_t)fromrc <= (vidVector.size() - 1)) { + std::cout << std::endl + << "The gnashrc file reports default webcam is set to:" << std::endl + << vidVector[fromrc]->deviceName + << " (" << vidVector[fromrc]->deviceType << ")" << std::endl + << "To change this setting, delete the 'set webcamDevice' line" << std::endl + << "from your gnashrc file and re-run this program." << std::endl << std::endl; + } else { + std::cout << std::endl + << "You have an invalid webcam chosen in your gnashrc file." << std::endl + << "Try reattaching the device or deleting the value from gnashrc" << std::endl + << "and running this program again" << std::endl; + } + } + return 0; +} diff --git a/pool/shard011/C++/0122042_qxmlformatter.cpp b/pool/shard011/C++/0122042_qxmlformatter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6442301c2bba1b924c7e85cc83e6b4f3aff2bd29 --- /dev/null +++ b/pool/shard011/C++/0122042_qxmlformatter.cpp @@ -0,0 +1,333 @@ +/**************************************************************************** +** +** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtXMLPatterns module of the Qt Toolkit. +** +** 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 General Public License Usage +** Alternatively, this file may be used under the terms of the GNU +** General Public License versions 2.0 or 3.0 as published by the Free +** Software Foundation and appearing in the file LICENSE.GPL included in +** the packaging of this file. Please review the following information +** to ensure GNU General Public Licensing requirements will be met: +** http://www.fsf.org/licensing/licenses/info/GPLv2.html and +** http://www.gnu.org/copyleft/gpl.html. In addition, as a special +** exception, Nokia gives you certain additional rights. These rights +** are described in the Nokia Qt GPL Exception version 1.3, included in +** the file GPL_EXCEPTION.txt in this package. +** +** Qt for Windows(R) Licensees +** As a special exception, Nokia, as the sole copyright holder for Qt +** Designer, grants users of the Qt/Eclipse Integration plug-in the +** right for the Qt/Eclipse Integration to link to functionality +** provided by Qt Designer and its related libraries. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** +****************************************************************************/ + +#include + +#include "qxmlformatter.h" +#include "qxpathhelper_p.h" +#include "qxmlserializer_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +class QXmlFormatterPrivate : public QXmlSerializerPrivate +{ +public: + inline QXmlFormatterPrivate(const QXmlQuery &q, + QIODevice *const outputDevice); + + int indentationDepth; + int currentDepth; + QString characterBuffer; + QString indentString; + + /** + * Whether we /have/ sent nodes like processing instructions and comments + * to QXmlSerializer. + */ + QStack canIndent; +}; + +QXmlFormatterPrivate::QXmlFormatterPrivate(const QXmlQuery &query, + QIODevice *const outputDevice) : QXmlSerializerPrivate(query, outputDevice) + , indentationDepth(4) + , currentDepth(0) +{ + indentString.reserve(30); + indentString.resize(1); + indentString[0] = QLatin1Char('\n'); + canIndent.push(false); +} + +/*! + \class QXmlFormatter + \brief The QXmlFormatter class is an implementation of QXmlSerializer for transforming XQuery output into formatted XML. + \reentrant + \since 4.4 + \ingroup xml-tools + + QXmlFormatter is a subclass of QXmlSerializer that formats the XML + output to make it easier for humans to read. + + QXmlSerializer outputs XML without adding unnecessary whitespace. + In particular, it does not add \e {newlines} and indentation. + To make the XML output easier to read, QXmlFormatter adds \e{newlines} + and indentation by adding, removing, and modifying + \l{XQuery Sequence}{sequence nodes} that only consist of whitespace. + It also modifies whitespace in other places where it is not + significant; e.g., between attributes and in the document prologue. + + For example, where the base class QXmlSerializer would + output this: + + \quotefile doc/src/snippets/patternist/notIndented.xml + + QXmlFormatter outputs this: + + \quotefile doc/src/snippets/patternist/indented.xml + + If you just want to serialize your XML in a human-readable + format, use QXmlFormatter as it is. The default indentation + level is 4 spaces, but you can set your own indentation value + setIndentationDepth(). + + The \e{newlines} and indentation added by QXmlFormatter are + suitable for common formats, such as XHTML, SVG, or Docbook, + where whitespace is not significant. However, if your XML will + be used as input where whitespace is significant, then you must + write your own subclass of QXmlSerializer or QAbstractXmlReceiver. + + Note that using QXmlFormatter instead of QXmlSerializer will + increase computational overhead and document storage size due + to the insertion of whitespace. + + Note also that the indentation style used by QXmlFormatter + remains loosely defined and may change in future versions of + Qt. If a specific indentation style is required then either + use the base class QXmlSerializer directly, or write your own + subclass of QXmlSerializer or QAbstractXmlReceiver. + Alternatively, you can subclass QXmlFormatter and reimplement + the callbacks there. + + \snippet doc/src/snippets/code/src_xmlpatterns_api_qxmlformatter.cpp 0 +*/ + +/*! + Constructs a formatter that uses the name pool and message + handler in \a query, and writes the result to \a outputDevice + as formatted XML. + + \a outputDevice is passed directly to QXmlSerializer's constructor. + + \sa QXmlSerializer + */ +QXmlFormatter::QXmlFormatter(const QXmlQuery &query, + QIODevice *outputDevice) : QXmlSerializer(new QXmlFormatterPrivate(query, outputDevice)) +{ +} + +/*! + \internal + */ +void QXmlFormatter::startFormattingContent() +{ + Q_D(QXmlFormatter); + if(d->canIndent.top() && QPatternist::XPathHelper::isWhitespaceOnly(d->characterBuffer)) + { + /* Do the hula hula dance. */ + QXmlSerializer::characters(QStringRef(&d->indentString)); + } + else if(!d->characterBuffer.isEmpty()) + { + /* Ao ao. Significant data, we don't touch it. */ + QXmlSerializer::characters(QStringRef(&d->characterBuffer)); + } + + d->characterBuffer.clear(); +} + +/*! + \reimp + */ +void QXmlFormatter::startElement(const QXmlName &name) +{ + Q_D(QXmlFormatter); + startFormattingContent(); + ++d->currentDepth; + d->indentString.append(QString(d->indentationDepth, QLatin1Char(' '))); + d->canIndent.push(true); + + QXmlSerializer::startElement(name); +} + +/*! + \reimp + */ +void QXmlFormatter::endElement() +{ + Q_D(QXmlFormatter); + --d->currentDepth; + d->indentString.chop(d->indentationDepth); + + if(!d->hasClosedElement.top().second) + d->canIndent.top() = false; + + startFormattingContent(); + + d->canIndent.pop(); + d->canIndent.top() = true; + QXmlSerializer::endElement(); +} + +/*! + \reimp + */ +void QXmlFormatter::attribute(const QXmlName &name, + const QStringRef &value) +{ + QXmlSerializer::attribute(name, value); +} + +/*! + \reimp + */ +void QXmlFormatter::comment(const QString &value) +{ + Q_D(QXmlFormatter); + startFormattingContent(); + QXmlSerializer::comment(value); + d->canIndent.top() = true; +} + +/*! + \reimp + */ +void QXmlFormatter::characters(const QStringRef &value) +{ + Q_D(QXmlFormatter); + d->isPreviousAtomic = false; + d->characterBuffer += value.toString(); +} + +/*! + \reimp + */ +void QXmlFormatter::processingInstruction(const QXmlName &name, + const QString &value) +{ + Q_D(QXmlFormatter); + startFormattingContent(); + QXmlSerializer::processingInstruction(name, value); + d->canIndent.top() = true; +} + +/*! + \reimp + */ +void QXmlFormatter::atomicValue(const QVariant &value) +{ + Q_D(QXmlFormatter); + d->canIndent.top() = false; + QXmlSerializer::atomicValue(value); +} + +/*! + \reimp + */ +void QXmlFormatter::startDocument() +{ + QXmlSerializer::startDocument(); +} + +/*! + \reimp + */ +void QXmlFormatter::endDocument() +{ + QXmlSerializer::endDocument(); +} + +/*! + \reimp + */ +void QXmlFormatter::startOfSequence() +{ + QXmlSerializer::startOfSequence(); +} + +/*! + \reimp + */ +void QXmlFormatter::endOfSequence() +{ + Q_D(QXmlFormatter); + + /* Flush any buffered content. */ + if(!d->characterBuffer.isEmpty()) + QXmlSerializer::characters(QStringRef(&d->characterBuffer)); + + d->write('\n'); + QXmlSerializer::endOfSequence(); +} + +/*! + \internal + */ +void QXmlFormatter::item(const QPatternist::Item &item) +{ + Q_D(QXmlFormatter); + + if(item.isAtomicValue()) + { + if(QPatternist::XPathHelper::isWhitespaceOnly(item.stringValue())) + return; + else + { + d->canIndent.top() = false; + startFormattingContent(); + } + } + + QXmlSerializer::item(item); +} + +/*! + Returns the number of spaces QXmlFormatter will output for each + indentation level. The default is four. + + \sa setIndentationDepth() + */ +int QXmlFormatter::indentationDepth() const +{ + Q_D(const QXmlFormatter); + return d->indentationDepth; +} + +/*! + Sets \a depth to be the number of spaces QXmlFormatter will + output for level of indentation. The default is four. + + \sa indentationDepth() + */ +void QXmlFormatter::setIndentationDepth(int depth) +{ + Q_D(QXmlFormatter); + d->indentationDepth = depth; +} + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0122043_capture_tpu_profile.cc b/pool/shard011/C++/0122043_capture_tpu_profile.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b198dbc16e544686e35c1ffee8a7f4d3955dafc --- /dev/null +++ b/pool/shard011/C++/0122043_capture_tpu_profile.cc @@ -0,0 +1,221 @@ +/* Copyright 2017 The TensorFlow Authors All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +==============================================================================*/ + +// Usage: capture_tpu_profile --service_addr="localhost:8466" --logdir=/tmp/log +// +// Initiates a TPU profiling on the TPUProfiler service at service_addr, +// receives and dumps the profile data to a tensorboard log directory. + +#include "grpc++/grpc++.h" + +#include +#include +#include + +#include "tensorflow/contrib/tpu/profiler/dump_tpu_profile.h" +#include "tensorflow/contrib/tpu/profiler/tpu_profiler.grpc.pb.h" +#include "tensorflow/contrib/tpu/profiler/version.h" +#include "tensorflow/core/distributed_runtime/rpc/grpc_util.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/io/path.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/init_main.h" +#include "tensorflow/core/util/command_line_flags.h" + +namespace tensorflow { +namespace tpu { +namespace { + +using ::tensorflow::TPUProfiler; + +constexpr uint64 kMaxEvents = 1000000; + +string GetCurrentTimeStampAsString() { + char s[128]; + std::time_t t = std::time(nullptr); + CHECK_NE(std::strftime(s, sizeof(s), "%F_%T", std::localtime(&t)), 0); + return s; +} + +Status ValidateHostPortPair(const string& host_port) { + uint32 port; + std::vector parts = str_util::Split(host_port, ':'); + // Must be host:port, port must be a number, host must not contain a '/', + // host also must not be empty. + if (parts.size() != 2 || !strings::safe_strtou32(parts[1], &port) || + parts[0].find("/") != string::npos || parts[0].empty()) { + return errors::InvalidArgument("Could not interpret \"", host_port, + "\" as a host-port pair."); + } + return Status::OK(); +} + +// Returns whether the returned trace is empty. +// Failure are handled by CHECK, i.e. abort() +bool Profile(const string& service_addr, const string& logdir, int duration_ms, + const string& repository_root, const string& session_id, + const ProfileOptions& opts) { + ProfileRequest request; + request.set_duration_ms(duration_ms); + request.set_max_events(kMaxEvents); + if (tensorflow::str_util::StartsWith(repository_root, "gs://")) { + // For backward compatibilities, only generate tracetable etc when the + // user provide a GCS path for model directory. + request.set_repository_root(repository_root); + request.set_session_id(session_id); + } + request.add_tools("input_pipeline"); + request.add_tools("overview_page"); + *request.mutable_opts() = opts; + std::cout << "Limiting the number of trace events to " << kMaxEvents + << std::endl; + ::grpc::ClientContext context; + ::grpc::ChannelArguments channel_args; + // TODO(ioeric): use `SetMaxReceiveMessageSize` instead once it's available. + // TODO(qiuminxu): use `NewHostPortGrpcChannel` instead once their + // `ValidateHostPortPair` checks for empty host string case. + channel_args.SetInt(GRPC_ARG_MAX_MESSAGE_LENGTH, + std::numeric_limits::max()); + std::unique_ptr stub = + TPUProfiler::NewStub(::grpc::CreateCustomChannel( + "dns:///" + service_addr, ::grpc::InsecureChannelCredentials(), + channel_args)); + ProfileResponse response; + TF_QCHECK_OK(FromGrpcStatus(stub->Profile(&context, request, &response))); + + if (!response.encoded_trace().empty()) { + TF_CHECK_OK(tensorflow::tpu::WriteTensorboardTPUProfile( + logdir, session_id, "", response, &std::cout)); + // Print this at the end so that it's not buried in irrelevant LOG messages. + std::cout + << "NOTE: using the trace duration " << duration_ms << "ms." + << std::endl + << "Set an appropriate duration (with --duration_ms) if you " + "don't see a full step in your trace or the captured trace is too " + "large." + << std::endl; + } + + return response.encoded_trace().empty(); +} + +// Start a new profiling session that include all the hosts included in +// hostnames, for the time interval of duration_ms. Possibly save the profiling +// result in the directory specified by repository_root and session_id. +bool NewSession(const string& service_addr, + const std::vector& hostnames, + int duration_ms, const string& repository_root, + const string& session_id, const ProfileOptions& opts) { + return true; +} + +} // namespace +} // namespace tpu +} // namespace tensorflow + +int main(int argc, char** argv) { + tensorflow::string FLAGS_service_addr; + tensorflow::string FLAGS_logdir; + tensorflow::string FLAGS_workers_list; + int FLAGS_duration_ms = 2000; + int FLAGS_num_tracing_attempts = 3; + bool FLAGS_include_dataset_ops = true; + std::vector flag_list = { + tensorflow::Flag("service_addr", &FLAGS_service_addr, + "Address of TPU profiler service e.g. localhost:8466"), + tensorflow::Flag("workers_list", &FLAGS_workers_list, + "The list of worker TPUs that we are about to profile " + "in the current session."), + tensorflow::Flag("logdir", &FLAGS_logdir, + "Path of TensorBoard log directory e.g. /tmp/tb_log, " + "gs://tb_bucket"), + tensorflow::Flag("duration_ms", &FLAGS_duration_ms, + "Duration of tracing in ms. Default is 2000ms."), + tensorflow::Flag("num_tracing_attempts", &FLAGS_num_tracing_attempts, + "Automatically retry N times when no trace event " + "is collected. Default is 3."), + tensorflow::Flag("include_dataset_ops", &FLAGS_include_dataset_ops, + "Set to false to profile longer TPU device traces."), + }; + + std::cout << "Welcome to the Cloud TPU Profiler v" << TPU_PROFILER_VERSION + << std::endl; + + tensorflow::string usage = tensorflow::Flags::Usage(argv[0], flag_list); + bool parse_ok = tensorflow::Flags::Parse(&argc, argv, flag_list); + if (!parse_ok || FLAGS_service_addr.empty() || FLAGS_logdir.empty()) { + std::cout << usage.c_str() << std::endl; + return 2; + } + tensorflow::Status status = + tensorflow::tpu::ValidateHostPortPair(FLAGS_service_addr); + if (!status.ok()) { + std::cout << status.error_message() << std::endl; + std::cout << usage.c_str() << std::endl; + return 2; + } + tensorflow::port::InitMain(argv[0], &argc, &argv); + + // Sets the minimum duration_ms and tracing attempts to one. + int duration_ms = std::max(FLAGS_duration_ms, 1); + int remaining_attempts = std::max(FLAGS_num_tracing_attempts, 1); + tensorflow::ProfileOptions opts; + opts.set_include_dataset_ops(FLAGS_include_dataset_ops); + tensorflow::ProfileResponse response; + + // Use the current timestamp as the run name. + tensorflow::string session_id = + tensorflow::tpu::GetCurrentTimeStampAsString(); + constexpr char kProfilePluginDirectory[] = "plugins/profile/"; + tensorflow::string repository_root = + ::tensorflow::io::JoinPath(FLAGS_logdir, kProfilePluginDirectory); + std::vector hostnames = + tensorflow::str_util::Split(FLAGS_workers_list, ","); + + bool empty_trace = false; + while (true) { + std::cout << "Starting to profile TPU traces for " << duration_ms << " ms. " + << "Remaining attempt(s): " << remaining_attempts-- << std::endl; + if (hostnames.empty()) { + empty_trace = tensorflow::tpu::Profile(FLAGS_service_addr, FLAGS_logdir, + duration_ms, repository_root, + session_id, opts); + } else { + tensorflow::string tpu_master = FLAGS_service_addr; + empty_trace = + tensorflow::tpu::NewSession(tpu_master, hostnames, duration_ms, + repository_root, session_id, opts); + } + if (remaining_attempts <= 0 || !empty_trace) break; + std::cout << "No trace event is collected. Automatically retrying." + << std::endl + << std::endl; + } + + if (empty_trace) { + std::cout << "No trace event is collected after " + << FLAGS_num_tracing_attempts << " attempt(s). " + << "Perhaps, you want to try again (with more attempts?)." + << std::endl + << "Tip: increase number of attempts with --num_tracing_attempts." + << std::endl; + // Don't dump profile data if no trace is collected. + return 0; + } + + return 0; +} diff --git a/pool/shard011/C++/0122044_multiply.cc b/pool/shard011/C++/0122044_multiply.cc new file mode 100644 index 0000000000000000000000000000000000000000..8021abc714da8473924d49e860f78a274b0fb9a4 --- /dev/null +++ b/pool/shard011/C++/0122044_multiply.cc @@ -0,0 +1,95 @@ +#include +#include +#include "multiply.h" +#include "matrix.h" +#include "parallel_task.h" + +std::shared_ptr> multiply::call(std::shared_ptr> left, std::shared_ptr> right, + int number_of_threads) const +{ + if (left->columns() != right->rows()) + { + std::stringstream message; + message << "The number of columns in the left metrix (" << left->columns() + << ") is not the same as the number of rows in the right matrix (" + << right->rows() << ")."; + throw std::invalid_argument(message.str()); + } + + row_multiplier multiplier(left->rows(), right->columns()); + + auto task = make_parallel_task(left->row_begin(), right->row_end(), multiplier, right, number_of_threads); + task.start(); + task.complete(); + + return multiplier.get_result(); +} + +int multiply::number_of_arguments() const +{ + return 2; +} + +std::string multiply::get_help() const +{ + return "multiply(A,B) computes the product of two matrices A (m x n) and B (n x p), with A on the left."; +} + +row_multiplier::row_multiplier(std::shared_ptr> right) : right_(right), task_results_() +{ +} + +row_multiplier::row_multiplier(size_t rows, size_t columns) : rows_(rows), current_row_(1), columns_(columns), current_column_(1) +{ + result_matrix_ = std::make_shared>(rows_, columns_); +} + +template +void row_multiplier::map(IteratorType begin, IteratorType end) +{ + for (auto row = begin; row != end; ++row) + for (auto column = right_->column_begin(); column != right_->column_end(); ++column) + task_results_.push_back(multiply_and_add_vector_elements(*row, *column)); +} + +void row_multiplier::reduce(const row_multiplier& other) +{ + for (auto result = other.task_results_.begin(); result != other.task_results_.end(); ++result) + { + (*result_matrix_)(current_row_, current_column_) = *result; + if (current_column_ == columns_) + { + ++current_row_; + current_column_ = 1; + } + else + { + ++current_column_; + } + } +} + +std::shared_ptr> row_multiplier::get_result() const +{ + return result_matrix_; +} + +double row_multiplier::multiply_and_add_vector_elements(const std::vector& left, const std::vector& right) const +{ + auto end = left.end(); + + auto left_it = left.begin(); + auto right_it = right.begin(); + + double result = 0.0; + while (left_it != end) + { + result += *left_it * *right_it; + + ++left_it; + ++right_it; + } + + return result; +} + diff --git a/pool/shard011/C++/0122045_fpdf_sysfontinfo.cpp b/pool/shard011/C++/0122045_fpdf_sysfontinfo.cpp new file mode 100644 index 0000000000000000000000000000000000000000..655c4a22bb096dcc45b8325d42c186b8d19ffd26 --- /dev/null +++ b/pool/shard011/C++/0122045_fpdf_sysfontinfo.cpp @@ -0,0 +1,189 @@ +// Copyright 2014 PDFium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com + +#include "public/fpdf_sysfontinfo.h" + +#include "fpdfsdk/include/fsdk_define.h" +#include "fpdfsdk/include/pdfwindow/PWL_FontMap.h" + +class CFX_ExternalFontInfo final : public IFX_SystemFontInfo { + public: + explicit CFX_ExternalFontInfo(FPDF_SYSFONTINFO* pInfo) : m_pInfo(pInfo) {} + + void Release() override { + if (m_pInfo->Release) + m_pInfo->Release(m_pInfo); + delete this; + } + + FX_BOOL EnumFontList(CFX_FontMapper* pMapper) override { + if (m_pInfo->EnumFonts) { + m_pInfo->EnumFonts(m_pInfo, pMapper); + return TRUE; + } + return FALSE; + } + + void* MapFont(int weight, + FX_BOOL bItalic, + int charset, + int pitch_family, + const FX_CHAR* family, + int& iExact) override { + if (m_pInfo->MapFont) + return m_pInfo->MapFont(m_pInfo, weight, bItalic, charset, pitch_family, + family, &iExact); + return NULL; + } + + void* GetFont(const FX_CHAR* family) override { + if (m_pInfo->GetFont) + return m_pInfo->GetFont(m_pInfo, family); + return NULL; + } + + FX_DWORD GetFontData(void* hFont, + FX_DWORD table, + uint8_t* buffer, + FX_DWORD size) override { + if (m_pInfo->GetFontData) + return m_pInfo->GetFontData(m_pInfo, hFont, table, buffer, size); + return 0; + } + + FX_BOOL GetFaceName(void* hFont, CFX_ByteString& name) override { + if (!m_pInfo->GetFaceName) + return FALSE; + FX_DWORD size = m_pInfo->GetFaceName(m_pInfo, hFont, NULL, 0); + if (size == 0) + return FALSE; + char* buffer = FX_Alloc(char, size); + size = m_pInfo->GetFaceName(m_pInfo, hFont, buffer, size); + name = CFX_ByteString(buffer, size); + FX_Free(buffer); + return TRUE; + } + + FX_BOOL GetFontCharset(void* hFont, int& charset) override { + if (m_pInfo->GetFontCharset) { + charset = m_pInfo->GetFontCharset(m_pInfo, hFont); + return TRUE; + } + return FALSE; + } + + void DeleteFont(void* hFont) override { + if (m_pInfo->DeleteFont) + m_pInfo->DeleteFont(m_pInfo, hFont); + } + + private: + ~CFX_ExternalFontInfo() override {} + + FPDF_SYSFONTINFO* const m_pInfo; +}; + +DLLEXPORT void STDCALL FPDF_AddInstalledFont(void* mapper, + const char* name, + int charset) { + ((CFX_FontMapper*)mapper)->AddInstalledFont(name, charset); +} + +DLLEXPORT void STDCALL FPDF_SetSystemFontInfo(FPDF_SYSFONTINFO* pFontInfoExt) { + if (pFontInfoExt->version != 1) + return; + + CFX_GEModule::Get()->GetFontMgr()->SetSystemFontInfo( + new CFX_ExternalFontInfo(pFontInfoExt)); +} + +DLLEXPORT const FPDF_CharsetFontMap* STDCALL FPDF_GetDefaultTTFMap() { + return CPWL_FontMap::defaultTTFMap; +} + +struct FPDF_SYSFONTINFO_DEFAULT : public FPDF_SYSFONTINFO { + IFX_SystemFontInfo* m_pFontInfo; +}; + +static void DefaultRelease(struct _FPDF_SYSFONTINFO* pThis) { + ((FPDF_SYSFONTINFO_DEFAULT*)pThis)->m_pFontInfo->Release(); +} + +static void DefaultEnumFonts(struct _FPDF_SYSFONTINFO* pThis, void* pMapper) { + ((FPDF_SYSFONTINFO_DEFAULT*)pThis) + ->m_pFontInfo->EnumFontList((CFX_FontMapper*)pMapper); +} + +static void* DefaultMapFont(struct _FPDF_SYSFONTINFO* pThis, + int weight, + int bItalic, + int charset, + int pitch_family, + const char* family, + int* bExact) { + return ((FPDF_SYSFONTINFO_DEFAULT*)pThis) + ->m_pFontInfo->MapFont(weight, bItalic, charset, pitch_family, family, + *bExact); +} + +void* DefaultGetFont(struct _FPDF_SYSFONTINFO* pThis, const char* family) { + return ((FPDF_SYSFONTINFO_DEFAULT*)pThis)->m_pFontInfo->GetFont(family); +} + +static unsigned long DefaultGetFontData(struct _FPDF_SYSFONTINFO* pThis, + void* hFont, + unsigned int table, + unsigned char* buffer, + unsigned long buf_size) { + return ((FPDF_SYSFONTINFO_DEFAULT*)pThis) + ->m_pFontInfo->GetFontData(hFont, table, buffer, buf_size); +} + +static unsigned long DefaultGetFaceName(struct _FPDF_SYSFONTINFO* pThis, + void* hFont, + char* buffer, + unsigned long buf_size) { + CFX_ByteString name; + if (!((FPDF_SYSFONTINFO_DEFAULT*)pThis) + ->m_pFontInfo->GetFaceName(hFont, name)) + return 0; + if (name.GetLength() >= (long)buf_size) + return name.GetLength() + 1; + FXSYS_strcpy(buffer, name); + return name.GetLength() + 1; +} + +static int DefaultGetFontCharset(struct _FPDF_SYSFONTINFO* pThis, void* hFont) { + int charset; + if (!((FPDF_SYSFONTINFO_DEFAULT*)pThis) + ->m_pFontInfo->GetFontCharset(hFont, charset)) + return 0; + return charset; +} + +static void DefaultDeleteFont(struct _FPDF_SYSFONTINFO* pThis, void* hFont) { + ((FPDF_SYSFONTINFO_DEFAULT*)pThis)->m_pFontInfo->DeleteFont(hFont); +} + +DLLEXPORT FPDF_SYSFONTINFO* STDCALL FPDF_GetDefaultSystemFontInfo() { + IFX_SystemFontInfo* pFontInfo = IFX_SystemFontInfo::CreateDefault(nullptr); + if (!pFontInfo) + return NULL; + + FPDF_SYSFONTINFO_DEFAULT* pFontInfoExt = + FX_Alloc(FPDF_SYSFONTINFO_DEFAULT, 1); + pFontInfoExt->DeleteFont = DefaultDeleteFont; + pFontInfoExt->EnumFonts = DefaultEnumFonts; + pFontInfoExt->GetFaceName = DefaultGetFaceName; + pFontInfoExt->GetFont = DefaultGetFont; + pFontInfoExt->GetFontCharset = DefaultGetFontCharset; + pFontInfoExt->GetFontData = DefaultGetFontData; + pFontInfoExt->MapFont = DefaultMapFont; + pFontInfoExt->Release = DefaultRelease; + pFontInfoExt->version = 1; + pFontInfoExt->m_pFontInfo = pFontInfo; + return pFontInfoExt; +} diff --git a/pool/shard011/C++/0122046_con_tngl.cpp b/pool/shard011/C++/0122046_con_tngl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8367b943953b0f2ab8d2c9a6026deb1dce63948d --- /dev/null +++ b/pool/shard011/C++/0122046_con_tngl.cpp @@ -0,0 +1,35 @@ +// +// File = con_tngl.cpp +// + +#include +#include +#include + +#include "con_tngl.h" +#include "misdefs.h" +#include "sincsqrd.h" +#include "typedefs.h" + +using namespace std; + +ContTriangularMagResp::ContTriangularMagResp(istream& uin, ostream& uout) + : ContinWindowResponse(uin, uout) +{ + double amp0, x, value; + double tau, freq, freq_exp, freq_cyc; + + tau = 1.0; + freq_cyc = 2.0; + + for (int n = 0; n < Num_Resp_Pts; n++) { + freq_exp = 1.0 + freq_cyc * (n - Num_Resp_Pts) / ((double)Num_Resp_Pts); + freq = pow((double)10.0, freq_exp); + amp0 = 0.5 * tau; + x = PI * freq * tau / 2.0; + value = 0.5 * tau * sinc_sqrd(x) / amp0; + if (Db_Scale_Enab) + value = 20.0 * log10(value); + (*Response_File) << freq << ", " << value << std::endl; + } +} diff --git a/pool/shard011/C++/0122047_text.cpp b/pool/shard011/C++/0122047_text.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e420d54ceb519fbc095b5cf12a9fac05c9be7758 --- /dev/null +++ b/pool/shard011/C++/0122047_text.cpp @@ -0,0 +1,98 @@ +#include "text.h" + +#include + +using namespace std; + +namespace GL +{ + +Text::Text() +: m_pFont(NULL) +, m_PosX(0.f) +, m_PosY(0.f) +{ + string fontPath = DATADIR"/glover/fonts/arial.ttf"; + m_pFont = new FTGLPolygonFont(fontPath.c_str()); + + if (m_pFont->Error()) + { + delete m_pFont; + throw(logic_error("Failed to open font: " + fontPath)); + } + + m_pFont->FaceSize(24); + setColor(255, 255, 255); +} + +Text::~Text() +{ + delete m_pFont; +} + +void Text::setSize(const int size) +{ + if (m_pFont) + { + m_pFont->FaceSize(size); + } +} + +void Text::setText(const string& text) +{ + m_Text = text; +} + +void Text::setPosition(const float x, const float y) +{ + m_PosX = x; + m_PosY = y; +} + +void Text::setColor(const int r, const int g, const int b, const int a) +{ + m_Color[0] = r / 255.f; + m_Color[1] = g / 255.f; + m_Color[2] = b / 255.f; + m_Color[3] = a / 255.f; +} + +void Text::render() +{ + if (!m_pFont) + { + return; + } + + glMatrixMode(GL_MODELVIEW); + glPushMatrix(); + glLoadIdentity(); + + glPushAttrib(GL_CURRENT_BIT | GL_MULTISAMPLE_BIT_ARB | GL_LIGHTING_BIT); + glEnable(GL_MULTISAMPLE_ARB); + glDisable(GL_LIGHTING); + glDisable(GL_TEXTURE_2D); + + glColor4fv(m_Color); + glTranslatef(m_PosX, m_PosY, 0); + + m_pFont->Render(m_Text.c_str()); + glPopAttrib(); + + glPopMatrix(); +} + +Text::BBox Text::getBBox() +{ + BBox bbox; + + if (m_pFont) + { + m_pFont->BBox(m_Text.c_str(), + bbox.minX, bbox.minY, bbox.minZ, + bbox.maxX, bbox.maxY, bbox.maxZ); + } + return bbox; +} + +} diff --git a/pool/shard011/C++/0122048_CreateEndpointRequest.cpp b/pool/shard011/C++/0122048_CreateEndpointRequest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd3d1cf9c09a3ef45685df12a7f4110df456d8fd --- /dev/null +++ b/pool/shard011/C++/0122048_CreateEndpointRequest.cpp @@ -0,0 +1,72 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include + +#include + +using namespace Aws::SageMaker::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +CreateEndpointRequest::CreateEndpointRequest() : + m_endpointNameHasBeenSet(false), + m_endpointConfigNameHasBeenSet(false), + m_tagsHasBeenSet(false) +{ +} + +Aws::String CreateEndpointRequest::SerializePayload() const +{ + JsonValue payload; + + if(m_endpointNameHasBeenSet) + { + payload.WithString("EndpointName", m_endpointName); + + } + + if(m_endpointConfigNameHasBeenSet) + { + payload.WithString("EndpointConfigName", m_endpointConfigName); + + } + + if(m_tagsHasBeenSet) + { + Array tagsJsonList(m_tags.size()); + for(unsigned tagsIndex = 0; tagsIndex < tagsJsonList.GetLength(); ++tagsIndex) + { + tagsJsonList[tagsIndex].AsObject(m_tags[tagsIndex].Jsonize()); + } + payload.WithArray("Tags", std::move(tagsJsonList)); + + } + + return payload.View().WriteReadable(); +} + +Aws::Http::HeaderValueCollection CreateEndpointRequest::GetRequestSpecificHeaders() const +{ + Aws::Http::HeaderValueCollection headers; + headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "SageMaker.CreateEndpoint")); + return headers; + +} + + + + diff --git a/pool/shard011/C++/0122049_parser_TEST.cc b/pool/shard011/C++/0122049_parser_TEST.cc new file mode 100644 index 0000000000000000000000000000000000000000..e4580cbf01f0d5fd4dd6832784d4dfd598cbc340 --- /dev/null +++ b/pool/shard011/C++/0122049_parser_TEST.cc @@ -0,0 +1,61 @@ +/* vim: set sw=4 sts=4 et foldmethod=syntax : */ + +/* + * Copyright (c) 2007 Markus Geveler + * + * This file is part of the Utility C++ library. LibUtil is free software; + * you can redistribute it and/or modify it under the terms of the GNU General + * Public License version 2, as published by the Free Software Foundation. + * + * LibUtil 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 +#include + +using namespace tests; +using namespace std; + +template +class ParserTest: + public BaseTest +{ + public: + ParserTest(const std::string & tag) : + BaseTest("Parser Test <" + tag + ">") + { + //register_tag(Tag_::name); + } + + virtual void run() const + { + char * t = new char[10]; + //t = "123.123"; + DT_ f = Parser::parse(t); + + DenseVector result = Parser::parse("parser_test_float.txt", 9); + for(int i = 0; i < 9; i++) + { + TEST_CHECK_EQUAL(result[i],i); + } + + DenseMatrix resultm = Parser::parse("parser_test_float_m.txt", 9, 3); + for(int i = 0; i < 9; i++) + { + TEST_CHECK_EQUAL(resultm[0][i],i); + } + std::cout << resultm << std::endl; + + TEST_CHECK(true); + } +}; +ParserTest parser_test_float("float"); +ParserTest parser_test_double("double"); + diff --git a/pool/shard011/C++/0122052_fixed_size_allocator.cpp b/pool/shard011/C++/0122052_fixed_size_allocator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f16e87dd4574f4251e465e8ec368f45a181a6faf --- /dev/null +++ b/pool/shard011/C++/0122052_fixed_size_allocator.cpp @@ -0,0 +1,199 @@ +// NeL - MMORPG Framework +// Copyright (C) 2010 Winch Gate Property Limited +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see . + +#include "stdmisc.h" +#include "nel/misc/fixed_size_allocator.h" + + +namespace NLMISC +{ + +// ***************************************************************************************************************** +CFixedSizeAllocator::CFixedSizeAllocator(uint numBytesPerBlock, uint numBlockPerChunk) +{ + _FreeSpace = NULL; + _NumChunks = 0; + nlassert(numBytesPerBlock > 1); + _NumBytesPerBlock = numBytesPerBlock; + _NumBlockPerChunk = std::max(numBlockPerChunk, (uint) 3); + _NumAlloc = 0; +} + +// ***************************************************************************************************************** +CFixedSizeAllocator::~CFixedSizeAllocator() +{ + if (_NumAlloc != 0) + { + #ifdef NL_DEBUG + nlwarning("%d blocks were not freed", (int) _NumAlloc); + #endif + return; + } + if (_NumChunks > 0) + { + nlassert(_NumChunks == 1); + // delete the left chunk. This should force all the left nodes to be removed from the empty list + delete _FreeSpace->Chunk; + } +} + +// ***************************************************************************************************************** +void *CFixedSizeAllocator::alloc() +{ + if (!_FreeSpace) + { + CChunk *chunk = new CChunk; // link a new chunk to that object + chunk->init(this); + } + ++ _NumAlloc; + return _FreeSpace->unlink(); +} + +// ***************************************************************************************************************** +void CFixedSizeAllocator::free(void *block) +{ + if (!block) return; + /// get the node from the object + CNode *node = (CNode *) ((uint8 *) block - offsetof(CNode, Next)); + // + nlassert(node->Chunk != NULL); + nlassert(node->Chunk->Allocator == this); + // + --_NumAlloc; + node->link(); +} + +// ***************************************************************************************************************** +uint CFixedSizeAllocator::CChunk::getBlockSizeWithOverhead() const +{ + return std::max((uint)(sizeof(CNode) - offsetof(CNode, Next)),(uint)(Allocator->getNumBytesPerBlock())) + offsetof(CNode, Next); +} + +// ***************************************************************************************************************** +CFixedSizeAllocator::CChunk::CChunk() +{ + NumFreeObjs = 0; + Allocator = NULL; +} + +// ***************************************************************************************************************** +CFixedSizeAllocator::CChunk::~CChunk() +{ + nlassert(Allocator != NULL); + for (uint k = 0; k < Allocator->getNumBlockPerChunk(); ++k) + { + getNode(k).unlink(); + } + nlassert(NumFreeObjs == 0); + nlassert(Allocator->_NumChunks > 0); + -- (Allocator->_NumChunks); + delete[] Mem; +} + +// ***************************************************************************************************************** +void CFixedSizeAllocator::CChunk::init(CFixedSizeAllocator *alloc) +{ + nlassert(!Allocator); + nlassert(alloc != NULL); + Allocator = alloc; + // + Mem = new uint8[getBlockSizeWithOverhead() * alloc->getNumBlockPerChunk()]; + // + getNode(0).Chunk = this; + getNode(0).Next = &getNode(1); + getNode(0).Prev = &alloc->_FreeSpace; + // + NumFreeObjs = alloc->getNumBlockPerChunk(); + /// init all the element as a linked list + for (uint k = 1; k < (NumFreeObjs - 1); ++k) + { + getNode(k).Chunk = this; + getNode(k).Next = &getNode(k + 1); + getNode(k).Prev = &getNode(k - 1).Next; + } + + getNode(NumFreeObjs - 1).Chunk = this; + getNode(NumFreeObjs - 1).Next = alloc->_FreeSpace; + getNode(NumFreeObjs - 1).Prev = &(getNode(NumFreeObjs - 2).Next); + + if (alloc->_FreeSpace) { alloc->_FreeSpace->Prev = &getNode(NumFreeObjs - 1).Next; } + alloc->_FreeSpace = &getNode(0); + ++(alloc->_NumChunks); +} + +// ***************************************************************************************************************** +CFixedSizeAllocator::CNode &CFixedSizeAllocator::CChunk::getNode(uint index) +{ + nlassert(Allocator != NULL); + nlassert(index < Allocator->getNumBlockPerChunk()); + return *(CNode *) ((uint8 *) Mem + index * getBlockSizeWithOverhead()); +} + +// ***************************************************************************************************************** +void CFixedSizeAllocator::CChunk::add() +{ + nlassert(Allocator); + // a node of this chunk has been given back + nlassert(NumFreeObjs < Allocator->getNumBlockPerChunk()); + ++ NumFreeObjs; + if (NumFreeObjs == Allocator->getNumBlockPerChunk()) // all objects back ? + { + if (Allocator->_NumChunks > 1) // we want to have at least one chunk left + { + delete this; // kill that object + } + } +} + +// ***************************************************************************************************************** +void CFixedSizeAllocator::CChunk::grab() +{ + // a node of this chunk has been given back + nlassert(NumFreeObjs > 0); + -- NumFreeObjs; +} + +// ***************************************************************************************************************** +void *CFixedSizeAllocator::CNode::unlink() +{ + nlassert(Prev != NULL); + if (Next) { Next->Prev = Prev;} + *Prev = Next; + nlassert(Chunk->NumFreeObjs > 0); + Chunk->grab(); // tells the containing chunk that a node has been allocated + return (void *) &Next; +} + +// ***************************************************************************************************************** +void CFixedSizeAllocator::CNode::link() +{ + // destroy the obj to get back uninitialized memory + nlassert(Chunk); + nlassert(Chunk->Allocator); + + CNode *&head = Chunk->Allocator->_FreeSpace; + Next = head; + Prev = &head; + if (Next) + { + nlassert(Next->Prev = &head); + Next->Prev = &Next; + } + Chunk->Allocator->_FreeSpace = this; + Chunk->add(); +} + +} // NLMISC diff --git a/pool/shard011/C++/0122053_StarWrapper.cpp b/pool/shard011/C++/0122053_StarWrapper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96adb83aea0d0296a73b5c6cb90c6258644db6d4 --- /dev/null +++ b/pool/shard011/C++/0122053_StarWrapper.cpp @@ -0,0 +1,161 @@ +/* + * The big star catalogue extension to Stellarium: + * Author and Copyright: Johannes Gajdosik, 2006, 2007 + * The implementation of most functions in this file + * (getInfoString,getShortInfoString,...) is taken from + * Stellarium, Copyright (C) 2002 Fabien Chereau, + * and therefore the copyright of these belongs to Fabien Chereau. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA. + */ + +#include "StarWrapper.hpp" +#include "ZoneArray.hpp" + +#include "StelUtils.hpp" +#include "StelTranslator.hpp" + +#include +#include + +template inline bool isNan(T value) +{ + return value != value; +} + +template inline bool isInf(T value) +{ + return std::numeric_limits::has_infinity && value == std::numeric_limits::infinity(); +} + +namespace BigStarCatalogExtension { + +QString StarWrapperBase::getInfoString(const StelCore *core, const InfoStringGroup& flags) const +{ + QString str; + QTextStream oss(&str); + + if (flags&Magnitude) + { + oss << q_("Magnitude: %1 (B-V: %2)").arg(QString::number(getVMagnitude(core, false), 'f', 2), QString::number(getBV(), 'f', 2)) << "
"; + if (core->getSkyDrawer()->getFlagHasAtmosphere()) + { + oss << q_("Apparent Magnitude: %1 (by extinction)").arg(QString::number(getVMagnitude(core, true), 'f', 2)) << "
"; + } + } + oss << getPositionInfoString(core, flags); + + StelObject::postProcessInfoString(str, flags); + + return str; +} + + +QString StarWrapper1::getEnglishName(void) const +{ + if (s->hip) + return QString("HIP %1").arg(s->hip); + return StarWrapperBase::getEnglishName(); +} + +QString StarWrapper1::getInfoString(const StelCore *core, const InfoStringGroup& flags) const +{ + QString str; + + QTextStream oss(&str); + if (s->hip) + { + if ((flags&Name) || (flags&CatalogNumber)) + oss << "

"; + + const QString commonNameI18 = StarMgr::getCommonName(s->hip); + const QString sciName = StarMgr::getSciName(s->hip); + + bool nameWasEmpty=true; + if (flags&Name) + { + if (commonNameI18!="" || sciName!="") + { + oss << commonNameI18 << (commonNameI18 == "" ? "" : " "); + if (commonNameI18!="" && sciName!="") + oss << "("; + oss << (sciName=="" ? "" : sciName); + if (commonNameI18!="" && sciName!="") + oss << ")"; + nameWasEmpty=false; + } + } + if ((flags&CatalogNumber) && (flags&Name) && !nameWasEmpty) + oss << " - "; + + if (flags&CatalogNumber || (nameWasEmpty && (flags&Name))) + oss << "HIP " << s->hip; + if (s->componentIds) + oss << " " << StarMgr::convertToComponentIds(s->componentIds); + + if ((flags&Name) || (flags&CatalogNumber)) + oss << "

"; + } + + if (flags&Magnitude) + { + if (core->getSkyDrawer()->getFlagHasAtmosphere()) + oss << q_("Magnitude: %1 (extincted to: %2. B-V: %3)").arg(QString::number(getVMagnitude(core, false), 'f', 2), + QString::number(getVMagnitude(core, true), 'f', 2), + QString::number(s->getBV(), 'f', 2)) << "
"; + else + oss << q_("Magnitude: %1 (B-V: %2)").arg(QString::number(getVMagnitude(core, false), 'f', 2), + QString::number(s->getBV(), 'f', 2)) << "
"; + } + + if ((flags&AbsoluteMagnitude) && s->plx && !isNan(s->plx) && !isInf(s->plx)) + oss << q_("Absolute Magnitude: %1").arg(getVMagnitude(core, false)+5.*(1.+std::log10(0.00001*s->plx)), 0, 'f', 2) << "
"; + + oss << getPositionInfoString(core, flags); + + if (s->spInt && flags&Extra1) + { + oss << q_("Spectral Type: %1").arg(StarMgr::convertToSpectralType(s->spInt)) << "
"; + } + + if ((flags&Distance) && s->plx && !isNan(s->plx) && !isInf(s->plx)) + oss << q_("Distance: %1 Light Years").arg((AU/(SPEED_OF_LIGHT*86400*365.25)) / (s->plx*((0.00001/3600)*(M_PI/180))), 0, 'f', 2) << "
"; + + if (s->plx && flags&Extra2) + oss << q_("Parallax: %1\"").arg(0.00001*s->plx, 0, 'f', 5) << "
"; + + StelObject::postProcessInfoString(str, flags); + + return str; +} + +StelObjectP Star1::createStelObject(const SpecialZoneArray *a, + const SpecialZoneData *z) const { + return StelObjectP(new StarWrapper1(a,z,this), true); +} + +StelObjectP Star2::createStelObject(const SpecialZoneArray *a, + const SpecialZoneData *z) const { + return StelObjectP(new StarWrapper2(a,z,this), true); +} + +StelObjectP Star3::createStelObject(const SpecialZoneArray *a, + const SpecialZoneData *z) const { + return StelObjectP(new StarWrapper3(a,z,this), true); +} + + +} // namespace BigStarCatalogExtension + diff --git a/pool/shard011/C++/0122054_AdhocStatement.cpp b/pool/shard011/C++/0122054_AdhocStatement.cpp new file mode 100644 index 0000000000000000000000000000000000000000..046e4535b856a83b783c6dfb3a890c4e62a9b66d --- /dev/null +++ b/pool/shard011/C++/0122054_AdhocStatement.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2013-2015 DeathCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "AdhocStatement.h" +#include "MySQLConnection.h" + +/*! Basic, ad-hoc queries. */ +BasicStatementTask::BasicStatementTask(const char* sql, bool async) : +m_result(nullptr) +{ + m_sql = strdup(sql); + m_has_result = async; // If the operation is async, then there's a result + if (async) + m_result = new QueryResultPromise(); +} + +BasicStatementTask::~BasicStatementTask() +{ + free((void*)m_sql); + if (m_has_result && m_result != nullptr) + delete m_result; +} + +bool BasicStatementTask::Execute() +{ + if (m_has_result) + { + ResultSet* result = m_conn->Query(m_sql); + if (!result || !result->GetRowCount() || !result->NextRow()) + { + delete result; + m_result->set_value(QueryResult(NULL)); + return false; + } + + m_result->set_value(QueryResult(result)); + return true; + } + + return m_conn->Execute(m_sql); +} diff --git a/pool/shard011/C++/0122055_IssueHash.cpp b/pool/shard011/C++/0122055_IssueHash.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c55c61dd399acd7e5dffe7b15844109032f6a00 --- /dev/null +++ b/pool/shard011/C++/0122055_IssueHash.cpp @@ -0,0 +1,205 @@ +//===---------- IssueHash.cpp - Generate identification hashes --*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// +#include "clang/StaticAnalyzer/Core/IssueHash.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/DeclCXX.h" +#include "clang/Basic/SourceManager.h" +#include "clang/Basic/Specifiers.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/LineIterator.h" +#include "llvm/Support/MD5.h" +#include "llvm/Support/Path.h" + +#include +#include +#include + +using namespace clang; + +// Get a string representation of the parts of the signature that can be +// overloaded on. +static std::string GetSignature(const FunctionDecl *Target) { + if (!Target) + return ""; + std::string Signature; + + // When a flow sensitive bug happens in templated code we should not generate + // distinct hash value for every instantiation. Use the signature from the + // primary template. + if (const FunctionDecl *InstantiatedFrom = + Target->getTemplateInstantiationPattern()) + Target = InstantiatedFrom; + + if (!isa(Target) && !isa(Target) && + !isa(Target)) + Signature.append(Target->getReturnType().getAsString()).append(" "); + Signature.append(Target->getQualifiedNameAsString()).append("("); + + for (int i = 0, paramsCount = Target->getNumParams(); i < paramsCount; ++i) { + if (i) + Signature.append(", "); + Signature.append(Target->getParamDecl(i)->getType().getAsString()); + } + + if (Target->isVariadic()) + Signature.append(", ..."); + Signature.append(")"); + + const auto *TargetT = + llvm::dyn_cast_or_null(Target->getType().getTypePtr()); + + if (!TargetT || !isa(Target)) + return Signature; + + if (TargetT->isConst()) + Signature.append(" const"); + if (TargetT->isVolatile()) + Signature.append(" volatile"); + if (TargetT->isRestrict()) + Signature.append(" restrict"); + + if (const auto *TargetPT = + dyn_cast_or_null(Target->getType().getTypePtr())) { + switch (TargetPT->getRefQualifier()) { + case RQ_LValue: + Signature.append(" &"); + break; + case RQ_RValue: + Signature.append(" &&"); + break; + default: + break; + } + } + + return Signature; +} + +static std::string GetEnclosingDeclContextSignature(const Decl *D) { + if (!D) + return ""; + + if (const auto *ND = dyn_cast(D)) { + std::string DeclName; + + switch (ND->getKind()) { + case Decl::Namespace: + case Decl::Record: + case Decl::CXXRecord: + case Decl::Enum: + DeclName = ND->getQualifiedNameAsString(); + break; + case Decl::CXXConstructor: + case Decl::CXXDestructor: + case Decl::CXXConversion: + case Decl::CXXMethod: + case Decl::Function: + DeclName = GetSignature(dyn_cast_or_null(ND)); + break; + case Decl::ObjCMethod: + // ObjC Methods can not be overloaded, qualified name uniquely identifies + // the method. + DeclName = ND->getQualifiedNameAsString(); + break; + default: + break; + } + + return DeclName; + } + + return ""; +} + +static StringRef GetNthLineOfFile(llvm::MemoryBuffer *Buffer, int Line) { + if (!Buffer) + return ""; + + llvm::line_iterator LI(*Buffer, false); + for (; !LI.is_at_eof() && LI.line_number() != Line; ++LI) + ; + + return *LI; +} + +static std::string NormalizeLine(const SourceManager &SM, FullSourceLoc &L, + const LangOptions &LangOpts) { + static StringRef Whitespaces = " \t\n"; + + StringRef Str = GetNthLineOfFile(SM.getBuffer(L.getFileID(), L), + L.getExpansionLineNumber()); + StringRef::size_type col = Str.find_first_not_of(Whitespaces); + if (col == StringRef::npos) + col = 1; // The line only contains whitespace. + else + col++; + SourceLocation StartOfLine = + SM.translateLineCol(SM.getFileID(L), L.getExpansionLineNumber(), col); + llvm::MemoryBuffer *Buffer = + SM.getBuffer(SM.getFileID(StartOfLine), StartOfLine); + if (!Buffer) + return {}; + + const char *BufferPos = SM.getCharacterData(StartOfLine); + + Token Token; + Lexer Lexer(SM.getLocForStartOfFile(SM.getFileID(StartOfLine)), LangOpts, + Buffer->getBufferStart(), BufferPos, Buffer->getBufferEnd()); + + size_t NextStart = 0; + std::ostringstream LineBuff; + while (!Lexer.LexFromRawLexer(Token) && NextStart < 2) { + if (Token.isAtStartOfLine() && NextStart++ > 0) + continue; + LineBuff << std::string(SM.getCharacterData(Token.getLocation()), + Token.getLength()); + } + + return LineBuff.str(); +} + +static llvm::SmallString<32> GetHashOfContent(StringRef Content) { + llvm::MD5 Hash; + llvm::MD5::MD5Result MD5Res; + SmallString<32> Res; + + Hash.update(Content); + Hash.final(MD5Res); + llvm::MD5::stringifyResult(MD5Res, Res); + + return Res; +} + +std::string clang::GetIssueString(const SourceManager &SM, + FullSourceLoc &IssueLoc, + StringRef CheckerName, StringRef BugType, + const Decl *D, + const LangOptions &LangOpts) { + static StringRef Delimiter = "$"; + + return (llvm::Twine(CheckerName) + Delimiter + + GetEnclosingDeclContextSignature(D) + Delimiter + + Twine(IssueLoc.getExpansionColumnNumber()) + Delimiter + + NormalizeLine(SM, IssueLoc, LangOpts) + Delimiter + BugType) + .str(); +} + +SmallString<32> clang::GetIssueHash(const SourceManager &SM, + FullSourceLoc &IssueLoc, + StringRef CheckerName, StringRef BugType, + const Decl *D, + const LangOptions &LangOpts) { + + return GetHashOfContent( + GetIssueString(SM, IssueLoc, CheckerName, BugType, D, LangOpts)); +} diff --git a/pool/shard011/C++/0122056_gui.cpp b/pool/shard011/C++/0122056_gui.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4510dddcb71badc300abd0312544a001c029572 --- /dev/null +++ b/pool/shard011/C++/0122056_gui.cpp @@ -0,0 +1,111 @@ +/* + * PieToaster is an OpenGL application to edit 3D models in + * Warzone 2100's (an RTS game) PIE 3D model format, which is heavily + * inspired by PieSlicer created by stratadrake. + * Copyright (C) 2007 Carl Hee + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ +#include "gui.h" +#include "config.h" +#include "screen.h" + +TwType g_tw_pieVertexType; +TwType g_tw_pieVector2fType; + +void CAntTweakBarTextField::doFunction() {} + +void CAntTweakBarTextField::addTextBox(const char *name) +{ + if (m_Up) + { + return; + } + + char def[255]; + char barAttr[255]; + + fprintf(stderr, "%s\n", name); + + m_textBar = TwNewBar(name); + + strncpy(m_name, name, strlen(name)); + + snprintf(barAttr, 255, "%s color = '%d %d %d %d' size = '200 100'", name, guiMajorAlpha, guiMajorRed, guiMajorGreen, guiMajorBlue); + TwDefine(barAttr); + + Uint16 positionX = g_Screen.m_width / 2 - 100; + Uint16 positionY = g_Screen.m_height / 2 - 50; + snprintf(barAttr, 255, "%s position = '%d %d'", name, positionX, positionY); + TwDefine(barAttr); + + m_Up = true; + + m_textIndex = 0; + + snprintf(def, 255, " label='%s'", name); + TwAddVarRO(m_textBar, name, TW_TYPE_INT32, &m_textIndex, def); +} + +void CAntTweakBarTextField::incrementChar(Uint16 key) +{ + if (m_textIndex < 255 - 1) + { + char str = (Uint8)key; + + strncpy(&m_text[m_textIndex], &str, 1); + m_textIndex++; + } +} + +void CAntTweakBarTextField::decrementChar() +{ + if (m_textIndex > 0) + { + m_text[m_textIndex] = '\0'; + m_textIndex--; + } +} + +void CAntTweakBarTextField::deleteTextBox() +{ + /*copies chars from mychars to text_pointer location if both + values are not null */ + /* + if (text_pointer && mychars_index) + { + int size = mychars_index; + strncpy(text_pointer, mychars, size); + text_pointer = NULL; + } + */ + + memset(m_text, '\0', 255); + memset(m_name, '\0', 255); + + TwDeleteBar(m_textBar); + m_Up = false; +} + +void CAntTweakBarTextField::updateTextBox(void) +{ + char test[255] = " label='"; + + TwRemoveVar(m_textBar, m_name); + + snprintf(&test[8], m_textIndex, "%s", &m_text[0]); + snprintf(&test[8 + m_textIndex], 1, "\'"); + + TwAddVarRO(m_textBar, m_name, TW_TYPE_INT32, &m_textIndex, test); +} diff --git a/pool/shard011/C++/0122057_TerminateInstanceInAutoScalingGroupResult.cpp b/pool/shard011/C++/0122057_TerminateInstanceInAutoScalingGroupResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7021237ccceabd2b869e7a56d6eb312ee36b0c50 --- /dev/null +++ b/pool/shard011/C++/0122057_TerminateInstanceInAutoScalingGroupResult.cpp @@ -0,0 +1,59 @@ +/* +* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ +#include +#include +#include +#include + +#include + +using namespace Aws::AutoScaling::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; +using namespace Aws; + +TerminateInstanceInAutoScalingGroupResult::TerminateInstanceInAutoScalingGroupResult() +{ +} + +TerminateInstanceInAutoScalingGroupResult::TerminateInstanceInAutoScalingGroupResult(const AmazonWebServiceResult& result) +{ + *this = result; +} + +TerminateInstanceInAutoScalingGroupResult& TerminateInstanceInAutoScalingGroupResult::operator =(const AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (rootNode.GetName() != "TerminateInstanceInAutoScalingGroupResult") + { + resultNode = rootNode.FirstChild("TerminateInstanceInAutoScalingGroupResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode activityNode = resultNode.FirstChild("Activity"); + if(!activityNode.IsNull()) + { + m_activity = activityNode; + } + } + + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + + return *this; +} diff --git a/pool/shard011/C++/0122058_QmitkUSDeviceManagerWidget.cpp b/pool/shard011/C++/0122058_QmitkUSDeviceManagerWidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cde1ae1f0938f429d93334701b056d024aaa74e5 --- /dev/null +++ b/pool/shard011/C++/0122058_QmitkUSDeviceManagerWidget.cpp @@ -0,0 +1,165 @@ +/*=================================================================== + +The Medical Imaging Interaction Toolkit (MITK) + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +//#define _USE_MATH_DEFINES +#include +#include +#include +#include +#include "mitkUSVideoDevice.h" + +const std::string QmitkUSDeviceManagerWidget::VIEW_ID = "org.mitk.views.QmitkUSDeviceManagerWidget"; + +QmitkUSDeviceManagerWidget::QmitkUSDeviceManagerWidget(QWidget* parent, Qt::WindowFlags f): QWidget(parent, f) +{ + m_Controls = NULL; + CreateQtPartControl(this); +} + +QmitkUSDeviceManagerWidget::~QmitkUSDeviceManagerWidget() +{ +} + +//////////////////// INITIALIZATION ///////////////////// + +void QmitkUSDeviceManagerWidget::CreateQtPartControl(QWidget *parent) +{ + if (!m_Controls) + { + // create GUI widgets + m_Controls = new Ui::QmitkUSDeviceManagerWidgetControls; + m_Controls->setupUi(parent); + this->CreateConnections(); + } + + // Initializations + std::string empty = ""; + m_Controls->m_ConnectedDevices->Initialize(mitk::USDevice::US_PROPKEY_LABEL, empty); +} + +void QmitkUSDeviceManagerWidget::CreateConnections() +{ + if ( m_Controls ) + { + connect( m_Controls->m_BtnActivate, SIGNAL( clicked() ), this, SLOT(OnClickedActivateDevice()) ); + //connect( m_Controls->m_BtnDisconnect, SIGNAL( clicked() ), this, SLOT(OnClickedDisconnectDevice()) ); + connect( m_Controls->m_BtnRemove, SIGNAL( clicked() ), this, SLOT(OnClickedRemoveDevice()) ); + connect( m_Controls->m_BtnNewDevice, SIGNAL( clicked() ), this, SLOT(OnClickedNewDevice()) ); + connect( m_Controls->m_ConnectedDevices, SIGNAL( ServiceSelectionChanged(us::ServiceReferenceU) ), this, SLOT(OnDeviceSelectionChanged(us::ServiceReferenceU)) ); + } +} + +///////////// Methods & Slots Handling Direct Interaction ///////////////// + +void QmitkUSDeviceManagerWidget::OnClickedActivateDevice() +{ + mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService(); + if (device.IsNull()) { return; } + + if (device->GetIsActive()) + { + device->Deactivate(); + } + else + { + QApplication::setOverrideCursor(Qt::WaitCursor); + if ( ! device->GetIsConnected() ) { device->Connect(); } + device->Activate(); + QApplication::restoreOverrideCursor(); + + if ( ! device->GetIsActive() ) + { + QMessageBox::warning(this, "Activation failed", "Could not activate device. Check logging for details."); + } + } + + // Manually reevaluate Button logic + OnDeviceSelectionChanged(m_Controls->m_ConnectedDevices->GetSelectedServiceReference()); +} + +void QmitkUSDeviceManagerWidget::OnClickedDisconnectDevice(){ + mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService(); + if (device.IsNull()) { return; } + + if (device->GetIsConnected()) + { + device->Disconnect(); + } + else + { + if ( ! device->Connect() ) + { + QMessageBox::warning(this, "Connecting failed", "Could not connect to device. Check logging for details."); + } + } +} + +void QmitkUSDeviceManagerWidget::OnClickedRemoveDevice() +{ + mitk::USDevice::Pointer device = m_Controls->m_ConnectedDevices->GetSelectedService(); + if (device.IsNull()) { return; } + + if ( device->GetDeviceClass() == "org.mitk.modules.us.USVideoDevice" ) + { + if ( device->GetIsActive() ) { device->Deactivate(); } + if ( device->GetIsConnected() ) { device->Disconnect(); } + + dynamic_cast(device.GetPointer())->UnregisterOnService(); + } +} + +void QmitkUSDeviceManagerWidget::OnClickedNewDevice() +{ + emit NewDeviceButtonClicked(); +} + +void QmitkUSDeviceManagerWidget::OnDeviceSelectionChanged(us::ServiceReferenceU reference){ + if (! reference) + { + m_Controls->m_BtnActivate->setEnabled(false); + m_Controls->m_BtnRemove->setEnabled(false); + return; + } + std::string isConnected = reference.GetProperty( mitk::USDevice::US_PROPKEY_ISCONNECTED ).ToString(); + std::string isActive = reference.GetProperty( mitk::USDevice::US_PROPKEY_ISACTIVE ).ToString(); + + if ( isActive.compare("false") == 0 ) + { + m_Controls->m_BtnActivate->setEnabled(true); + m_Controls->m_BtnActivate->setText("Activate"); + } + else + { + m_Controls->m_BtnActivate->setEnabled(true); + m_Controls->m_BtnActivate->setText("Deactivate"); + } + + std::string deviceClass = reference.GetProperty( mitk::USDevice::US_PROPKEY_CLASS ).ToString(); + m_Controls->m_BtnRemove->setEnabled(deviceClass == "org.mitk.modules.us.USVideoDevice"); +} + +void QmitkUSDeviceManagerWidget::DisconnectAllDevices() +{ + //at the moment disconnects ALL devices. Maybe we only want to disconnect the devices handled by this widget? + us::ModuleContext* thisContext = us::GetModuleContext(); + std::vector > services = thisContext->GetServiceReferences(); + for(std::vector >::iterator it = services.begin(); it != services.end(); ++it) + { + mitk::USDevice* currentDevice = thisContext->GetService(*it); + currentDevice->Disconnect(); + } + MITK_INFO << "Disconnected ALL US devises!"; +} \ No newline at end of file diff --git a/pool/shard011/C++/0122059_qzxing.cpp b/pool/shard011/C++/0122059_qzxing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bf92c55584fdbbf557af1f2e46dd43191857674e --- /dev/null +++ b/pool/shard011/C++/0122059_qzxing.cpp @@ -0,0 +1,214 @@ +#include "QZXing.h" + +#include +#include +#include +#include +#include +#include "CameraImageWrapper.h" +#include "imagehandler.h" +#include + +using namespace zxing; + +QZXing::QZXing(QObject *parent) : QObject(parent) +{ + decoder = new MultiFormatReader(); + /*setDecoder(DecoderFormat_QR_CODE | + DecoderFormat_DATA_MATRIX | + DecoderFormat_UPC_E | + DecoderFormat_UPC_A | + DecoderFormat_EAN_8 | + DecoderFormat_EAN_13 | + DecoderFormat_CODE_128 | + DecoderFormat_CODE_39 | + DecoderFormat_ITF | + DecoderFormat_Aztec);*/ + imageHandler = new ImageHandler(); +} + +QZXing::QZXing(QZXing::DecoderFormat decodeHints, QObject *parent) : QObject(parent) +{ + decoder = new MultiFormatReader(); + imageHandler = new ImageHandler(); + + setDecoder(decodeHints); +} + +void QZXing::setDecoder(const uint &hint) +{ + unsigned int newHints = 0; + + if(hint & DecoderFormat_Aztec) + newHints |= DecodeHints::AZTEC_HINT; + + if(hint & DecoderFormat_CODABAR) + newHints |= DecodeHints::CODABAR_HINT; + + if(hint & DecoderFormat_CODE_39) + newHints |= DecodeHints::CODE_39_HINT; + + if(hint & DecoderFormat_CODE_93) + newHints |= DecodeHints::CODE_93_HINT; + + if(hint & DecoderFormat_CODE_128) + newHints |= DecodeHints::CODE_128_HINT; + + if(hint & DecoderFormat_DATA_MATRIX) + newHints |= DecodeHints::DATA_MATRIX_HINT; + + if(hint & DecoderFormat_EAN_8) + newHints |= DecodeHints::EAN_8_HINT; + + if(hint & DecoderFormat_EAN_13) + newHints |= DecodeHints::EAN_13_HINT; + + if(hint & DecoderFormat_ITF) + newHints |= DecodeHints::ITF_HINT; + + if(hint & DecoderFormat_MAXICODE) + newHints |= DecodeHints::MAXICODE_HINT; + + if(hint & DecoderFormat_PDF_417) + newHints |= DecodeHints::PDF_417_HINT; + + if(hint & DecoderFormat_QR_CODE) + newHints |= DecodeHints::QR_CODE_HINT; + + if(hint & DecoderFormat_RSS_14) + newHints |= DecodeHints::RSS_14_HINT; + + if(hint & DecoderFormat_RSS_EXPANDED) + newHints |= DecodeHints::RSS_EXPANDED_HINT; + + if(hint & DecoderFormat_UPC_A) + newHints |= DecodeHints::UPC_A_HINT; + + if(hint & DecoderFormat_UPC_E) + newHints |= DecodeHints::UPC_E_HINT; + + if(hint & DecoderFormat_UPC_EAN_EXTENSION) + newHints |= DecodeHints::UPC_EAN_EXTENSION_HINT; + + enabledDecoders = newHints; + + emit enabledFormatsChanged(); +} + +QString QZXing::decodeImage(QImage image, int maxWidth, int maxHeight, bool smoothTransformation) +{ + QTime t; + t.start(); + Ref res; + emit decodingStarted(); + + if(image.isNull()) + { + emit decodingFinished(false); + processingTime = -1; + return ""; + } + + try{ + CameraImageWrapper* ciw; + + if(maxWidth > 0 || maxHeight > 0) + ciw = CameraImageWrapper::Factory(image, maxWidth, maxHeight, smoothTransformation); + else + ciw = new CameraImageWrapper(image); + + Ref imageRef(ciw); + GlobalHistogramBinarizer* binz = new GlobalHistogramBinarizer(imageRef); + + Ref bz (binz); + BinaryBitmap* bb = new BinaryBitmap(bz); + + Ref ref(bb); + + res = ((MultiFormatReader*)decoder)->decode(ref, DecodeHints((int)enabledDecoders)); + + QString string = QString(res->getText()->getText().c_str()); + processingTime = t.elapsed(); + emit tagFound(string); + emit decodingFinished(true); + return string; + } + catch(zxing::Exception& e) + { + emit decodingFinished(false); + processingTime = -1; + return ""; + } +} + +QString QZXing::decodeImageFromFile(QString imageFilePath, int maxWidth, int maxHeight, bool smoothTransformation) +{ + //used to have a check if this image exists + //but was removed because if the image file path doesn't point to a valid image + // then the QImage::isNull will return true and the decoding will fail eitherway. + return decodeImage(QImage(imageFilePath), maxWidth, maxHeight, smoothTransformation); +} +/* +QString QZXing::decodeImageQML(QObject *item) +{ + return decodeSubImageQML(item); +} + +QString QZXing::decodeSubImageQML(QObject* item, + const double offsetX, const double offsetY, + const double width, const double height) +{ + if(item == NULL) + { + emit decodingFinished(false); + return ""; + } + + QImage img = ((ImageHandler*)imageHandler)->extractQImage(item, offsetX, offsetY, width, height); + // QImage img; + return(""); + // return decodeImage(img); +} +*/ +QString QZXing::decodeImageQML(const QUrl &imageUrl) +{ + return decodeSubImageQML(imageUrl); +} + +QString QZXing::decodeSubImageQML(const QUrl &imageUrl, + const double offsetX, const double offsetY, + const double width, const double height) +{ + + QString imagePath = imageUrl.path(); + imagePath = imagePath.trimmed(); + QFile file(imagePath); + + if (!file.exists()) { + qDebug() << "[decodeSubImageQML()] The file" << file.fileName() << "does not exist."; + emit decodingFinished(false); + return ""; + } + + QImage img(imageUrl.path()); + + if(!(offsetX == 0 && offsetY == 0 && width == 0 && height == 0)) { + img = img.copy(offsetX, offsetY, width, height); + } + + return decodeImage(img); +} + +int QZXing::getProcessTimeOfLastDecoding() +{ + return processingTime; +} + +uint QZXing::getEnabledFormats() const +{ + return enabledDecoders; +} + + + + diff --git a/pool/shard011/C++/0122060_CameraStreamImpl.cpp b/pool/shard011/C++/0122060_CameraStreamImpl.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4a2cf4a4fda795824d52fe7126bccf81d6b5907 --- /dev/null +++ b/pool/shard011/C++/0122060_CameraStreamImpl.cpp @@ -0,0 +1,114 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "CameraStreamImpl.h" +#include "GeneratedJNINatives.h" +#include "nsCRTGlue.h" +#include "nsThreadUtils.h" +#include "nsXULAppAPI.h" +#include "mozilla/Monitor.h" + +using namespace mozilla; + +namespace mozilla { +namespace net { + +static CameraStreamImpl* mCamera0 = nullptr; +static CameraStreamImpl* mCamera1 = nullptr; + +class CameraStreamImpl::Callback + : public java::GeckoAppShell::CameraCallback::Natives +{ +public: + static void OnFrameData(int32_t aCamera, jni::ByteArray::Param aData) + { + MOZ_ASSERT(NS_IsMainThread()); + + CameraStreamImpl* impl = GetInstance(uint32_t(aCamera)); + if (impl) { + impl->TransmitFrame(aData); + } + } +}; + +/** + * CameraStreamImpl + */ + +void CameraStreamImpl::TransmitFrame(jni::ByteArray::Param aData) { + if (!mCallback) { + return; + } + + JNIEnv* const env = jni::GetGeckoThreadEnv(); + const size_t length = size_t(env->GetArrayLength(aData.Get())); + + if (!length) { + return; + } + + jbyte* const data = env->GetByteArrayElements(aData.Get(), nullptr); + mCallback->ReceiveFrame(reinterpret_cast(data), length); + env->ReleaseByteArrayElements(aData.Get(), data, JNI_ABORT); +} + +CameraStreamImpl* CameraStreamImpl::GetInstance(uint32_t aCamera) { + CameraStreamImpl* res = nullptr; + switch(aCamera) { + case 0: + if (mCamera0) + res = mCamera0; + else + res = mCamera0 = new CameraStreamImpl(aCamera); + break; + case 1: + if (mCamera1) + res = mCamera1; + else + res = mCamera1 = new CameraStreamImpl(aCamera); + break; + } + return res; +} + + +CameraStreamImpl::CameraStreamImpl(uint32_t aCamera) : + mInit(false), mCamera(aCamera) +{ + NS_WARNING("CameraStreamImpl::CameraStreamImpl()"); + mWidth = 0; + mHeight = 0; + mFps = 0; +} + +CameraStreamImpl::~CameraStreamImpl() +{ + NS_WARNING("CameraStreamImpl::~CameraStreamImpl()"); +} + +bool CameraStreamImpl::Init(const nsCString& contentType, const uint32_t& camera, const uint32_t& width, const uint32_t& height, FrameCallback* aCallback) +{ + mCallback = aCallback; + mWidth = width; + mHeight = height; + + Callback::Init(); + jni::IntArray::LocalRef retArray = java::GeckoAppShell::InitCamera( + contentType, int32_t(camera), int32_t(width), int32_t(height)); + nsTArray ret = retArray->GetElements(); + + mWidth = uint32_t(ret[1]); + mHeight = uint32_t(ret[2]); + mFps = uint32_t(ret[3]); + + return !!ret[0]; +} + +void CameraStreamImpl::Close() { + java::GeckoAppShell::CloseCamera(); + mCallback = nullptr; +} + +} // namespace net +} // namespace mozilla diff --git a/pool/shard011/C++/0122061_gesture_stroke_drawer.cpp b/pool/shard011/C++/0122061_gesture_stroke_drawer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5815c61ccd5f733ac8404821e1024414f5475e13 --- /dev/null +++ b/pool/shard011/C++/0122061_gesture_stroke_drawer.cpp @@ -0,0 +1,123 @@ +/***************************************************************** + * This file is part of jot-lib (or "jot" for short): + * + * + * jot-lib 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. + * + * jot-lib 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 jot-lib. If not, see .` + *****************************************************************/ + +#include "geom/gl_view.hpp" + +#include "gesture_stroke_drawer.hpp" + +using mlib::PIXEL; +using mlib::PIXEL_list; + +inline double +pressure_to_grey(double p) +{ + // map stylus pressure to greyscale non-linearly. + + // pressure is in range [0,1] + + // treat all pressures as being at least this: + const double MIN_PRESSURE = 0.3; + + // greyscale color at min pressure + const double GREY0 = 0.6; + + // this function increases in darkness from GREY0 at MIN_PRESSURE + // to black at pressure 1. the square root makes darkness increase + // rapidly for light pressures, then taper off to black as pressure + // nears 1: + return GREY0*(1 - sqrt(max(p, MIN_PRESSURE) - MIN_PRESSURE)); +} + + +GestureStrokeDrawer::GestureStrokeDrawer() +{ + _base_stroke_proto = nullptr; +} + +GestureStrokeDrawer::~GestureStrokeDrawer() +{ + if(_base_stroke_proto) + delete _base_stroke_proto; +} + + +int +GestureStrokeDrawer::draw(const GESTURE* gest, CVIEWptr& v) +{ + + if (Config::get_var_bool("DEBUG_GEST_STROKE_DRAW",false)) + err_msg("GestureStrokeDrawer::draw"); + + if (!_base_stroke_proto) { + cerr << "GestureStrokeDrawer::draw(), WARNING: " << + "Null _base_stroke_proto, aborting" << endl; + return 0; + } + + const PIXEL_list& pts = gest->pts(); + const vector& press = gest->pressures(); + + assert(pts.size() == press.size()); + + const StrokeVertexArray& verts + = _base_stroke_proto->get_verts(); + + _base_stroke_proto->clear(); + + PIXEL prev_pix; + + static bool debug = Config::get_var_bool("DEBUG_GEST_DRAWER",false); + + + for (PIXEL_list::size_type k=0; k< pts.size(); k++) { + if (k>0 && prev_pix == pts[k]) { + if (debug) + cerr << "gesture drawer, dropping duplicate " + << "gesture pixel" << endl; + continue; + } + + _base_stroke_proto->add(pts[k]); + + if ( _base_stroke_proto->get_press_vary_width() ) { + verts[verts.num()-1]._width = (float)press[k]; + + // XXX Hack to hide antialiased lines when the width is small + if ((float)press[k] <= 0.1f) { + verts[verts.num()-1]._alpha = 10.0f*(float)press[k]; + } else { + verts[verts.num()-1]._alpha = 1.0f; + } + } + + if ( _base_stroke_proto->get_press_vary_alpha() ) { + verts[verts.num()-1]._alpha = (float)press[k]; + } + + prev_pix = pts[k]; + } + + if (verts.num() < 2) + return 0; + + _base_stroke_proto->draw_start(); + _base_stroke_proto->draw(v); + _base_stroke_proto->draw_end(); + + return 0; +} diff --git a/pool/shard011/C++/0122063_scimark2.cpp b/pool/shard011/C++/0122063_scimark2.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a5ec0b7649b0df4f7f7dd5bcbe2298233692381 --- /dev/null +++ b/pool/shard011/C++/0122063_scimark2.cpp @@ -0,0 +1,113 @@ +#include "stdafx.h" +#include +#include +#include + +#include "Random.h" +#include "kernel.h" +#include "constants.h" + +void print_banner(void); + +int main(int argc, char *argv[]) +{ + /* default to the (small) cache-contained version */ + + double min_time = RESOLUTION_DEFAULT; + + int FFT_size = FFT_SIZE; + int SOR_size = SOR_SIZE; + int Sparse_size_M = SPARSE_SIZE_M; + int Sparse_size_nz = SPARSE_SIZE_nz; + int LU_size = LU_SIZE; + + + /* run the benchmark */ + + double res[6] = {0.0}; + Random R = new_Random_seed(RANDOM_SEED); + + + if (argc > 1) + { + int current_arg = 1; + + if (strcmp(argv[1], "-help")==0 || + strcmp(argv[1], "-h") == 0) + { + fprintf(stderr, "Usage: [-large] [minimum_time]\n"); + exit(0); + } + + if (strcmp(argv[1], "-large")==0) + { + FFT_size = LG_FFT_SIZE; + SOR_size = LG_SOR_SIZE; + Sparse_size_M = LG_SPARSE_SIZE_M; + Sparse_size_nz = LG_SPARSE_SIZE_nz; + LU_size = LG_LU_SIZE; + + current_arg++; + } + + if (current_arg < argc) + { + min_time = atof(argv[current_arg]); + } + + } + + + print_banner(); + printf("Using %10.2f seconds min time per kenel.\n", min_time); + + FILE *fp; + errno_t err; + if ((err = fopen_s(&fp, "ResultLog.txt", "at")) != 0) + { + fprintf(stderr, "File was not opened\n"); + exit(1); + } + + int NumTimes = 50; + for (int iTime = 0; iTime < NumTimes; iTime++) + { + + res[1] = kernel_measureFFT(FFT_size, min_time, R); + res[2] = kernel_measureSOR(SOR_size, min_time, R); + res[3] = kernel_measureMonteCarlo(min_time, R); + res[4] = kernel_measureSparseMatMult(Sparse_size_M, + Sparse_size_nz, min_time, R); + res[5] = kernel_measureLU(LU_size, min_time, R); + + + + res[0] = (res[1] + res[2] + res[3] + res[4] + res[5]) / 5; + fprintf(fp, "CPP2013,%8.2f\n", res[0]); + + /* print out results */ + printf("Composite Score: %8.2f\n", res[0]); + printf("FFT Mflops: %8.2f (N=%d)\n", res[1], FFT_size); + printf("SOR Mflops: %8.2f (%d x %d)\n", + res[2], SOR_size, SOR_size); + printf("MonteCarlo: Mflops: %8.2f\n", res[3]); + printf("Sparse matmult Mflops: %8.2f (N=%d, nz=%d)\n", res[4], + Sparse_size_M, Sparse_size_nz); + printf("LU Mflops: %8.2f (M=%d, N=%d)\n", res[5], + LU_size, LU_size); + } + + fclose(fp); + Random_delete(R); + + return 0; + +} + +void print_banner() +{ + printf("** **\n"); + printf("** SciMark2 Numeric Benchmark, see http://math.nist.gov/scimark **\n"); + printf("** for details. (Results can be submitted to pozo@nist.gov) **\n"); + printf("** **\n"); +} diff --git a/pool/shard011/C++/0122065_layer_stack.cc b/pool/shard011/C++/0122065_layer_stack.cc new file mode 100644 index 0000000000000000000000000000000000000000..ac99a470163b56000b93a01655665c3eadaeed8f --- /dev/null +++ b/pool/shard011/C++/0122065_layer_stack.cc @@ -0,0 +1,59 @@ +/* layer_stack.cc + Jeremy Barnes, 4 November 2009 + Copyright (c) 2009 Jeremy Barnes. All rights reserved. + + Stack of layers. +*/ + +#include "layer_stack.h" +#include "dense_layer.h" +#include "layer_stack_impl.h" +#include "jml/boosting/registry.h" + +namespace ML { + +template class Layer_Stack; +template class Layer_Stack >; +template class Layer_Stack >; + +namespace { + +Register_Factory > +LAYER_STACK_REGISTER("Layer_Stack"); + +} // file scope + + +#if 0 + +void +DNAE_Stack:: +serialize(ML::DB::Store_Writer & store) const +{ + store << (char)1; // version + store << compact_size_t(size()); + for (unsigned i = 0; i < size(); ++i) + (*this)[i].serialize(store); +} + +void +DNAE_Stack:: +reconstitute(ML::DB::Store_Reader & store) +{ + char version; + store >> version; + if (version != 1) { + cerr << "version = " << (int)version << endl; + throw Exception("DNAE_Stack::reconstitute(): invalid version"); + } + compact_size_t sz(store); + resize(sz); + + for (unsigned i = 0; i < sz; ++i) + (*this)[i].reconstitute(store); +} + +#endif + +} // namespace ML + diff --git a/pool/shard011/C++/0122067_TextEncoding.cpp b/pool/shard011/C++/0122067_TextEncoding.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2dbc89b0c9c48ac5371ef37c89dfc10d8e4fbaaa --- /dev/null +++ b/pool/shard011/C++/0122067_TextEncoding.cpp @@ -0,0 +1,228 @@ +/* + * Copyright (C) 2004, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. + * Copyright (C) 2006 Alexey Proskuryakov + * Copyright (C) 2007-2009 Torch Mobile, Inc. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "wtf/text/TextEncoding.h" + +#include "wtf/text/TextCodec.h" +#include "wtf/text/TextEncodingRegistry.h" +#include +#include +#include +#include +#include + +namespace WTF { + +static const TextEncoding& UTF7Encoding() +{ + static TextEncoding globalUTF7Encoding("UTF-7"); + return globalUTF7Encoding; +} + +TextEncoding::TextEncoding(const char* name) + : m_name(atomicCanonicalTextEncodingName(name)) + , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol()) +{ +} + +TextEncoding::TextEncoding(const String& name) + : m_name(atomicCanonicalTextEncodingName(name)) + , m_backslashAsCurrencySymbol(backslashAsCurrencySymbol()) +{ +} + +String TextEncoding::decode(const char* data, size_t length, bool stopOnError, bool& sawError) const +{ + if (!m_name) + return String(); + + return newTextCodec(*this)->decode(data, length, true, stopOnError, sawError); +} + +CString TextEncoding::encode(const UChar* characters, size_t length, UnencodableHandling handling) const +{ + if (!m_name) + return CString(); + + if (!length) + return ""; + + // FIXME: What's the right place to do normalization? + // It's a little strange to do it inside the encode function. + // Perhaps normalization should be an explicit step done before calling encode. + + const UChar* source = characters; + size_t sourceLength = length; + + Vector normalizedCharacters; + + UErrorCode err = U_ZERO_ERROR; + if (unorm_quickCheck(source, sourceLength, UNORM_NFC, &err) != UNORM_YES) { + // First try using the length of the original string, since normalization to NFC rarely increases length. + normalizedCharacters.grow(sourceLength); + int32_t normalizedLength = unorm_normalize(source, length, UNORM_NFC, 0, normalizedCharacters.data(), length, &err); + if (err == U_BUFFER_OVERFLOW_ERROR) { + err = U_ZERO_ERROR; + normalizedCharacters.resize(normalizedLength); + normalizedLength = unorm_normalize(source, length, UNORM_NFC, 0, normalizedCharacters.data(), normalizedLength, &err); + } + ASSERT(U_SUCCESS(err)); + + source = normalizedCharacters.data(); + sourceLength = normalizedLength; + } + return newTextCodec(*this)->encode(source, sourceLength, handling); +} + +const char* TextEncoding::domName() const +{ + if (noExtendedTextEncodingNameUsed()) + return m_name; + + // We treat EUC-KR as windows-949 (its superset), but need to expose + // the name 'EUC-KR' because the name 'windows-949' is not recognized by + // most Korean web servers even though they do use the encoding + // 'windows-949' with the name 'EUC-KR'. + // FIXME: This is not thread-safe. At the moment, this function is + // only accessed in a single thread, but eventually has to be made + // thread-safe along with usesVisualOrdering(). + static const char* const a = atomicCanonicalTextEncodingName("windows-949"); + if (m_name == a) + return "EUC-KR"; + return m_name; +} + +bool TextEncoding::usesVisualOrdering() const +{ + if (noExtendedTextEncodingNameUsed()) + return false; + + static const char* const a = atomicCanonicalTextEncodingName("ISO-8859-8"); + return m_name == a; +} + +bool TextEncoding::isJapanese() const +{ + return isJapaneseEncoding(m_name); +} + +UChar TextEncoding::backslashAsCurrencySymbol() const +{ + return shouldShowBackslashAsCurrencySymbolIn(m_name) ? 0x00A5 : '\\'; +} + +bool TextEncoding::isNonByteBasedEncoding() const +{ + if (noExtendedTextEncodingNameUsed()) { + return *this == UTF16LittleEndianEncoding() + || *this == UTF16BigEndianEncoding(); + } + + return *this == UTF16LittleEndianEncoding() + || *this == UTF16BigEndianEncoding() + || *this == UTF32BigEndianEncoding() + || *this == UTF32LittleEndianEncoding(); +} + +bool TextEncoding::isUTF7Encoding() const +{ + if (noExtendedTextEncodingNameUsed()) + return false; + + return *this == UTF7Encoding(); +} + +const TextEncoding& TextEncoding::closestByteBasedEquivalent() const +{ + if (isNonByteBasedEncoding()) + return UTF8Encoding(); + return *this; +} + +// HTML5 specifies that UTF-8 be used in form submission when a form is +// is a part of a document in UTF-16 probably because UTF-16 is not a +// byte-based encoding and can contain 0x00. By extension, the same +// should be done for UTF-32. In case of UTF-7, it is a byte-based encoding, +// but it's fraught with problems and we'd rather steer clear of it. +const TextEncoding& TextEncoding::encodingForFormSubmission() const +{ + if (isNonByteBasedEncoding() || isUTF7Encoding()) + return UTF8Encoding(); + return *this; +} + +const TextEncoding& ASCIIEncoding() +{ + static TextEncoding globalASCIIEncoding("ASCII"); + return globalASCIIEncoding; +} + +const TextEncoding& Latin1Encoding() +{ + static TextEncoding globalLatin1Encoding("latin1"); + return globalLatin1Encoding; +} + +const TextEncoding& UTF16BigEndianEncoding() +{ + static TextEncoding globalUTF16BigEndianEncoding("UTF-16BE"); + return globalUTF16BigEndianEncoding; +} + +const TextEncoding& UTF16LittleEndianEncoding() +{ + static TextEncoding globalUTF16LittleEndianEncoding("UTF-16LE"); + return globalUTF16LittleEndianEncoding; +} + +const TextEncoding& UTF32BigEndianEncoding() +{ + static TextEncoding globalUTF32BigEndianEncoding("UTF-32BE"); + return globalUTF32BigEndianEncoding; +} + +const TextEncoding& UTF32LittleEndianEncoding() +{ + static TextEncoding globalUTF32LittleEndianEncoding("UTF-32LE"); + return globalUTF32LittleEndianEncoding; +} + +const TextEncoding& UTF8Encoding() +{ + static TextEncoding globalUTF8Encoding("UTF-8"); + ASSERT(globalUTF8Encoding.isValid()); + return globalUTF8Encoding; +} + +const TextEncoding& WindowsLatin1Encoding() +{ + static TextEncoding globalWindowsLatin1Encoding("WinLatin1"); + return globalWindowsLatin1Encoding; +} + +} // namespace WTF diff --git a/pool/shard011/C++/0122068_cath_score_align.cpp b/pool/shard011/C++/0122068_cath_score_align.cpp new file mode 100644 index 0000000000000000000000000000000000000000..399756b5d0a4e1fa8326ac520484a31bab973879 --- /dev/null +++ b/pool/shard011/C++/0122068_cath_score_align.cpp @@ -0,0 +1,51 @@ +/// \file +/// \brief The cath_score_align_program_exception_wrapper definitions + +/// \copyright +/// CATH Tools - Protein structure comparison tools such as SSAP and SNAP +/// Copyright (C) 2011, Orengo Group, University College London +/// +/// This program is free software: you can redistribute it and/or modify +/// it under the terms of the GNU General Public License as published by +/// the Free Software Foundation, either version 3 of the License, or +/// (at your option) any later version. +/// +/// This program is distributed in the hope that it will be useful, +/// but WITHOUT ANY WARRANTY; without even the implied warranty of +/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +/// GNU General Public License for more details. +/// +/// You should have received a copy of the GNU General Public License +/// along with this program. If not, see . + +#include "cath/cath_score_align/cath_align_scorer.hpp" +#include "cath/cath_score_align/options/cath_score_align_options.hpp" +#include "cath/common/program_exception_wrapper.hpp" + +using namespace ::cath; +using namespace ::cath::common; +using namespace ::cath::opts; +using namespace ::std; + +namespace { + + /// \brief A concrete program_exception_wrapper that implements do_run_program() to parse the options and then pass them to cath_align_scorer::score() + /// + /// Using program_exception_wrapper allows the program to be wrapped in standard last-chance exception handling. + class cath_score_align_program_exception_wrapper final : public program_exception_wrapper { + [[nodiscard]] string_view do_get_program_name() const final { + return "cath-score-align"; + } + + /// \brief Parse the options and then pass them to cath_score_alignr::superpose() + void do_run_program(int argc, char * argv[]) final { + const auto the_cath_score_align_options = make_and_parse_options( argc, argv ); + cath_align_scorer::score(the_cath_score_align_options); + } + }; +} // namespace + +/// \brief A main function for cath_score_align that just calls run_program() on a cath_score_align_program_exception_wrapper +int main(int argc, char * argv[] ) { + return cath_score_align_program_exception_wrapper().run_program( argc, argv ); +} diff --git a/pool/shard011/C++/0122069_narrow_channel_access.cc b/pool/shard011/C++/0122069_narrow_channel_access.cc new file mode 100644 index 0000000000000000000000000000000000000000..57f3baf20e108caad9d661a6acff405663bad29c --- /dev/null +++ b/pool/shard011/C++/0122069_narrow_channel_access.cc @@ -0,0 +1,245 @@ +/* + * 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. + */ + +/*! + * Copyright (c) 2017 by Contributors + * \file narrow_channel_access.cc + * \brief Narrow channel access to a smaller range + * when possible by bringing it to the internal loop. + */ +#include +#include +#include +#include +#include +#include +#include +#include "ir_util.h" + +namespace tvm { +namespace ir { +using namespace arith; + +// Bound deducer for channel access. +class ChannelAccessBound : public IRVisitor { + public: + ChannelAccessBound(const Variable* buf_var, bool read_access) + : buf_var_(buf_var), read_access_(read_access) {} + + void Visit_(const Store* op) final { + if (!read_access_ && buf_var_ == op->buffer_var.get()) { + ret_.emplace_back(EvalSet(op->index, dom_map_)); + } + IRVisitor::Visit_(op); + } + void Visit_(const For* op) final { + CHECK(is_zero(op->min)); + // We know that the extent of the loop won't depend on relaxed scope. + // TODO(tqchen) have a verification pass. + dom_map_[op->loop_var.get()] = IntSet::interval(op->min, op->extent - 1); + IRVisitor::Visit_(op); + } + void Visit_(const Load* op) final { + if (read_access_ && buf_var_ == op->buffer_var.get()) { + ret_.emplace_back(EvalSet(op->index, dom_map_)); + } + IRVisitor::Visit_(op); + } + void Visit_(const Let* op) final { + LOG(FATAL) << "cannot pass through let"; + } + void Visit_(const LetStmt* op) final { + LOG(FATAL) << "cannot pass through let"; + } + IntSet Eval(const Stmt& stmt) { + Visit(stmt); + return Union(ret_); + } + + private: + // The buffer variable. + const Variable* buf_var_; + // read or write + bool read_access_{true}; + // Box + std::vector ret_; + // Domain map. + std::unordered_map dom_map_; +}; + +class ChannelAccessIndexRewriter : public IRMutator { + public: + ChannelAccessIndexRewriter(const Variable* buf_var, + Expr min, + bool read_access) + : buf_var_(buf_var), min_(min), read_access_(read_access) {} + Expr Mutate_(const Load* op, const Expr& e) final { + Expr expr = IRMutator::Mutate_(op, e); + op = expr.as(); + if (read_access_ && buf_var_ == op->buffer_var.get()) { + return Load::make( + op->type, op->buffer_var, ir::Simplify(op->index - min_), + op->predicate); + } else { + return expr; + } + } + Stmt Mutate_(const Store* op, const Stmt& s) final { + Stmt stmt = IRMutator::Mutate_(op, s); + op = stmt.as(); + if (!read_access_ && buf_var_ == op->buffer_var.get()) { + return Store::make( + op->buffer_var, op->value, ir::Simplify(op->index - min_), + op->predicate); + } else { + return stmt; + } + } + + private: + // The buffer variable. + const Variable* buf_var_; + // The min bound. + Expr min_; + // read or write + bool read_access_{true}; +}; + + +// Rewrite channel access pattern. +class ChannelAccessRewriter : public IRMutator { + public: + Stmt Mutate_(const AttrStmt* op, const Stmt& s) final { + Stmt ret; + const AttrStmt* adv = op->body.as(); + if ((op->attr_key == ir::attr::channel_read_scope && + adv && adv->attr_key == ir::attr::channel_read_advance) || + (op->attr_key == ir::attr::channel_write_scope && + adv && adv->attr_key == ir::attr::channel_write_advance)) { + RewriteEntry e; + e.window = op; + e.advance = adv; + e.read_access = op->attr_key == ir::attr::channel_read_scope; + tasks_.push_back(e); + ret = IRMutator::Mutate_(op, s); + if (tasks_.back().rewrite_success) { + ret = ret.as()->body.as()->body; + } + tasks_.pop_back(); + return ret; + } else { + return IRMutator::Mutate_(op, s); + } + } + + Stmt Mutate_(const For* op, const Stmt& s) final { + std::vector tasks; + std::swap(tasks_, tasks); + Stmt body = op->body; + std::vector nest; + for (RewriteEntry& e : tasks) { + body = RewriteAccess(op, body, &e, &nest); + } + + if (!body.same_as(op->body)) { + body = Mutate(body); + body = For::make( + op->loop_var, op->min, op->extent, + op->for_type, op->device_api, body); + body = MergeNest(nest, body); + } else { + CHECK_EQ(nest.size(), 0U); + body = IRMutator::Mutate_(op, s); + } + std::swap(tasks_, tasks); + return body; + } + + private: + struct RewriteEntry { + bool read_access; + const AttrStmt* window; + const AttrStmt* advance; + bool rewrite_success{false}; + }; + + Stmt RewriteAccess(const For* for_op, + Stmt body, + RewriteEntry* e, + std::vector* outer_nest) { + const AttrStmt* adv_op = e->advance; + const Expr& window = e->window->value; + bool read_access = e->read_access; + Var var(for_op->loop_var); + Channel ch(adv_op->node.node_); + ChannelAccessBound acc(ch->handle_var.get(), read_access); + IntSet iset = acc.Eval(for_op->body); + Range r = iset.cover_range(Range::make_by_min_extent(0, window)); + r = Range::make_by_min_extent( + ir::Simplify(r->min), ir::Simplify(r->extent)); + if (ExprUseVar(r->extent, var)) return body; + Array linear_eq = DetectLinearEquation(r->min, {var}); + if (linear_eq.size() == 0) return body; + Expr coeff = linear_eq[0]; + Expr base = linear_eq[1]; + if (!is_zero(base)) return body; + Expr left = ir::Simplify(adv_op->value - coeff * for_op->extent); + if (!analyzer_.CanProve(left >= 0)) return body; + // rewrite access index. + ChannelAccessIndexRewriter rw( + ch->handle_var.get(), var * coeff, read_access); + body = rw.Mutate(body); + + if (read_access) { + body = AttrStmt::make( + ch, ir::attr::channel_read_scope, r->extent, + AttrStmt::make(ch, ir::attr::channel_read_advance, coeff, + body)); + } else { + body = AttrStmt::make( + ch, ir::attr::channel_write_scope, r->extent, + AttrStmt::make(ch, ir::attr::channel_write_advance, coeff, + body)); + } + + if (!is_zero(left)) { + Stmt no_op = Evaluate::make(0); + if (read_access) { + outer_nest->emplace_back( + AttrStmt::make(ch, ir::attr::channel_read_advance, left, no_op)); + } else { + outer_nest->emplace_back( + AttrStmt::make(ch, ir::attr::channel_write_advance, left, no_op)); + } + } + + e->rewrite_success = true; + return body; + } + + arith::Analyzer analyzer_; + std::vector tasks_; +}; + +Stmt NarrowChannelAccess(Stmt stmt) { + return ChannelAccessRewriter().Mutate(stmt); +} + +} // namespace ir +} // namespace tvm diff --git a/pool/shard011/C++/0122070_fault_injector_random.cc b/pool/shard011/C++/0122070_fault_injector_random.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d296a5f39c9244a4171485b8ede6f146995ceb5 --- /dev/null +++ b/pool/shard011/C++/0122070_fault_injector_random.cc @@ -0,0 +1,38 @@ +#include "fault_injector_random.h" +#include "rng.h" + +FaultInjectorRandom::FaultInjectorRandom(UInt32 core_id, MemComponent::component_t mem_component) + : FaultInjector(core_id, mem_component) + , m_rng(rng_seed(0)) +{ + if (mem_component == MemComponent::L1_DCACHE) + m_active = true; + else + m_active = false; +} + +void +FaultInjectorRandom::preRead(IntPtr addr, IntPtr location, UInt32 data_size, Byte *fault, SubsecondTime time) +{ + // Data at virtual address is about to be read with size . + // corresponds to the physical location (cache line) where the data lives. + // Update here according to errors that have accumulated in this memory location. + + // Dummy random fault injector + if (m_active && (rng_next(m_rng) % 0xffff) == 0) + { + UInt32 bit_location = rng_next(m_rng) % data_size; + + printf("Inserting bit %d flip at address %" PRIxPTR " on read access by core %d to component %s\n", + bit_location, addr, m_core_id, MemComponentString(m_mem_component)); + + fault[bit_location / 8] |= 1 << (bit_location % 8); + } +} + +void +FaultInjectorRandom::postWrite(IntPtr addr, IntPtr location, UInt32 data_size, Byte *fault, SubsecondTime time) +{ + // Data at virtual address has just been written to. + // Update here according to errors that occured during the writing of this memory location. +} diff --git a/pool/shard011/C++/0122071_editaddressdialog.cpp b/pool/shard011/C++/0122071_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d7ce2a6c2137907da4f80c355b96db136ae4db0 --- /dev/null +++ b/pool/shard011/C++/0122071_editaddressdialog.cpp @@ -0,0 +1,128 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setDisabled(true); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid dv8coin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + } + + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard011/C++/0122072_tutorial_example.cpp b/pool/shard011/C++/0122072_tutorial_example.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9175d07c8052a9b6664b13fa9728346957599ee0 --- /dev/null +++ b/pool/shard011/C++/0122072_tutorial_example.cpp @@ -0,0 +1,150 @@ +// ========================================================================== +// tutorial_example +// ========================================================================== +// Copyright (c) 2006-2012, Knut Reinert, FU Berlin +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// * Neither the name of Knut Reinert or the FU Berlin nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE +// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH +// DAMAGE. +// +// ========================================================================== +// Author: Your Name +// ========================================================================== + +#include +#include + +#include + +// ========================================================================== +// Classes +// ========================================================================== + +// -------------------------------------------------------------------------- +// Class AppOptions +// -------------------------------------------------------------------------- + +// This struct stores the options from the command line. +// +// You might want to rename this to reflect the name of your app. + +struct AppOptions +{ + // Verbosity level. 0 -- quiet, 1 -- normal, 2 -- verbose, 3 -- very verbose. + int verbosity; + + // The first (and only) argument of the program is stored here. + seqan::CharString text; + + AppOptions() : + verbosity(1) + {} +}; + +// ========================================================================== +// Functions +// ========================================================================== + +// -------------------------------------------------------------------------- +// Function parseCommandLine() +// -------------------------------------------------------------------------- + +seqan::ArgumentParser::ParseResult +parseCommandLine(AppOptions & options, int argc, char const ** argv) +{ + // Setup ArgumentParser. + seqan::ArgumentParser parser("tutorial_example"); + // Set short description, version, and date. + setShortDescription(parser, "Put a Short Description Here"); + setVersion(parser, "0.1"); + setDate(parser, "July 2012"); + + // Define usage line and long description. + addUsageLine(parser, "[\\fIOPTIONS\\fP] \"\\fITEXT\\fP\""); + addDescription(parser, "This is the application skelleton and you should modify this string."); + + // We require one argument. + addArgument(parser, seqan::ArgParseArgument(seqan::ArgParseArgument::STRING, "TEXT")); + + addOption(parser, seqan::ArgParseOption("q", "quiet", "Set verbosity to a minimum.")); + addOption(parser, seqan::ArgParseOption("v", "verbose", "Enable verbose output.")); + addOption(parser, seqan::ArgParseOption("vv", "very-verbose", "Enable very verbose output.")); + + // Add Examples Section. + addTextSection(parser, "Examples"); + addListItem(parser, "\\fBtutorial_example\\fP \\fB-v\\fP \\fItext\\fP", + "Call with \\fITEXT\\fP set to \"text\" with verbose output."); + + // Parse command line. + seqan::ArgumentParser::ParseResult res = seqan::parse(parser, argc, argv); + + // Only extract options if the program will continue after parseCommandLine() + if (res != seqan::ArgumentParser::PARSE_OK) + return res; + + // Extract option values. + if (isSet(parser, "quiet")) + options.verbosity = 0; + if (isSet(parser, "verbose")) + options.verbosity = 2; + if (isSet(parser, "very-verbose")) + options.verbosity = 3; + seqan::getArgumentValue(options.text, parser, 0); + + return seqan::ArgumentParser::PARSE_OK; +} + +// -------------------------------------------------------------------------- +// Function main() +// -------------------------------------------------------------------------- + +// Program entry point. + +int main(int argc, char const ** argv) +{ + // Parse the command line. + seqan::ArgumentParser parser; + AppOptions options; + seqan::ArgumentParser::ParseResult res = parseCommandLine(options, argc, argv); + + // If there was an error parsing or built-in argument parser functionality + // was triggered then we exit the program. The return code is 1 if there + // were errors and 0 if there were none. + if (res != seqan::ArgumentParser::PARSE_OK) + return res == seqan::ArgumentParser::PARSE_ERROR; + + std::cout << "EXAMPLE PROGRAM\n" + << "===============\n\n"; + + // Print the command line arguments back to the user. + if (options.verbosity > 0) + { + std::cout << "__OPTIONS____________________________________________________________________\n" + << '\n' + << "VERBOSITY\t" << options.verbosity << '\n' + << "TEXT \t" << options.text << "\n\n"; + } + + return 0; +} diff --git a/pool/shard011/C++/0122076_sensorfwlightsensor.cpp b/pool/shard011/C++/0122076_sensorfwlightsensor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b49e7b2d8481c76e09ba3a5c49dc0d63ae3096ca --- /dev/null +++ b/pool/shard011/C++/0122076_sensorfwlightsensor.cpp @@ -0,0 +1,71 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtSensors module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "sensorfwlightsensor.h" + +char const * const SensorfwLightSensor::id("sensorfw.lightsensor"); +bool SensorfwLightSensor::m_initDone = false; + +SensorfwLightSensor::SensorfwLightSensor(QSensor *sensor) + : SensorfwSensorBase(sensor) +{ + initSensor(m_initDone); + setReading(&m_reading); +} + +void SensorfwLightSensor::slotDataAvailable(const Unsigned& data) +{ + m_reading.setLux(data.x()); + m_reading.setTimestamp(data.UnsignedData().timestamp_); + newReadingAvailable(); +} + +bool SensorfwLightSensor::doConnect() +{ + return QObject::connect(m_sensorInterface, SIGNAL(ALSChanged(const Unsigned&)), + this, SLOT(slotDataAvailable(const Unsigned&))); +} + + +QString SensorfwLightSensor::sensorName() const +{ + return "alssensor"; +} diff --git a/pool/shard011/C++/0122078_dns_resolver_test.cc b/pool/shard011/C++/0122078_dns_resolver_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e06904be4454c890f72b4eaf170211c25c405204 --- /dev/null +++ b/pool/shard011/C++/0122078_dns_resolver_test.cc @@ -0,0 +1,96 @@ +// Copyright (c) 2009, Whispersoft s.r.l. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Whispersoft s.r.l. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// Author: Cosmin Tudorache + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +////////////////////////////////////////////////////////////////////// + +DEFINE_bool(just_server, + false, + "True runs only the server."); + +#define LOG_TEST LOG_INFO + +uint32 g_pending = 0; +net::Selector* g_selector = NULL; + +void HandleDnsResult(string hostname, bool expected_success, + scoped_ref info) { + CHECK(expected_success == (info.get() != NULL)) + << "For hostname: [" << hostname + << "], expected_success: " << strutil::BoolToString(expected_success) + << ", result: " << info.ToString(); + + LOG_TEST << "Resolved: [" << hostname << "], to: " << info.ToString() + << ", expected_success: " + << strutil::BoolToString(expected_success); + + CHECK_GT(g_pending, 0); + g_pending--; + + if ( g_pending == 0 ) { + g_selector->RunInSelectLoop(NewCallback(g_selector, + &net::Selector::MakeLoopExit));; + } +} + +void TestDnsQuery(const string& hostname, bool expected_success) { + g_pending++; + net::DnsResolve(g_selector, hostname, NewPermanentCallback(&HandleDnsResult, + hostname, expected_success)); +} + +int main(int argc, char ** argv) { + common::Init(argc, argv); + g_selector = new net::Selector(); + + TestDnsQuery("google.com", true); + TestDnsQuery("localhost", true); + TestDnsQuery("asd90fas8df0as8d908asd0", false); + + g_selector->Loop(); + delete g_selector; + g_selector = NULL; + + LOG_INFO << "Pass"; + common::Exit(0); +} diff --git a/pool/shard011/C++/0122079_CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73a.cpp b/pool/shard011/C++/0122079_CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dd32dea3155b229fc818052e8eb2e47977faed77 --- /dev/null +++ b/pool/shard011/C++/0122079_CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73a.cpp @@ -0,0 +1,105 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73a.cpp +Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml +Template File: sources-sink-73a.tmpl.cpp +*/ +/* + * @description + * CWE: 194 Unexpected Sign Extension + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Positive integer + * Sinks: memcpy + * BadSink : Copy strings using memcpy() with the length of data + * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +using namespace std; + +namespace CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(list dataList); + +void bad() +{ + short data; + list dataList; + /* Initialize data */ + data = 0; + /* FLAW: Use a value input from the console using fscanf() */ + fscanf (stdin, "%hd", &data); + /* Put data in a list */ + dataList.push_back(data); + dataList.push_back(data); + dataList.push_back(data); + badSink(dataList); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(list dataList); + +static void goodG2B() +{ + short data; + list dataList; + /* Initialize data */ + data = 0; + /* FIX: Use a positive integer less than &InitialDataSize&*/ + data = 100-1; + /* Put data in a list */ + dataList.push_back(data); + dataList.push_back(data); + dataList.push_back(data); + goodG2BSink(dataList); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE194_Unexpected_Sign_Extension__fscanf_memcpy_73; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C++/0122083_Stream.cpp b/pool/shard011/C++/0122083_Stream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..77413a698bdbea161e706bf41a6b4095ba18cc07 --- /dev/null +++ b/pool/shard011/C++/0122083_Stream.cpp @@ -0,0 +1,173 @@ +/* + Copyright 2011 Julian Schutsch + + This file is part of TRTGarf + + TRTGarf is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + TRTGarf 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 TRTGarf. If not, see . +*/ + +#include "Tools/Stream.hpp" +#include "Tools/Exception.hpp" +#include "Tools/Tools.hpp" +#include "tools.hpp" +#include +#include +#include + +namespace Tools +{ + +ASCIIOutStream::ASCIIOutStream(ASCIIOutStream&) +{ + throw Tools::MsgException("ASCIIOutStream::ASCIIOutStream : Copy not allowed"); +} + +ASCIIInStream::ASCIIInStream(ASCIIInStream&) +{ + throw Tools::MsgException("ASCIIInStream::ASCIIInStream : Copy not allowed"); +} + +ASCIIOutStream& ASCIIOutStream::operator=(ASCIIOutStream& AStream) +{ + throw Tools::MsgException("ASCIIOutStream::operator = : Copy not allowed"); + return AStream; +} + +ASCIIInStream& ASCIIInStream::operator=(ASCIIInStream& AStream) +{ + throw Tools::MsgException("ASCIIInStream::operator = : Copy not allowed"); + return AStream; +} + +ASCIIInStream& ASCIIInStream::operator>>(std::vector& AVector) +{ + std::string s; + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> std::vector : Unexpected end of file"); + getline(FFile,s); + unsigned int Count = atoi(s.c_str()); + std::vector data = SplitString(s); + while(Count!=0) + { + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> std::vector : End of file before end of vector"); + getline(FFile,s); + AVector.push_back(atof(s.c_str())); + Count--; + } + return *this; +} + +ASCIIInStream& ASCIIInStream::operator>>(unsigned int& ANumber) +{ + std::string s; + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> unsigned int : Unexpected end of file"); + getline(FFile,s); + ANumber = atoi(s.c_str()); + return *this; +} + +ASCIIInStream& ASCIIInStream::operator>>(double& ANumber) +{ + std::string s; + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> double : Unexpected end of file"); + getline(FFile,s); + ANumber = atof(s.c_str()); + return *this; +} + +ASCIIInStream& ASCIIInStream::operator>>(const char * AString) +{ + std::string s; + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> const char * : Unexpected end of file"); + getline(FFile,s); + s = UnescapeString(s); + if(s!=AString) throw Tools::MsgException("ASCIIInStream::operator >> const char * : Check failed"); + return *this; +} + +ASCIIInStream& ASCIIInStream::operator>>(std::string& AString) +{ + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::operator >> std::string : Unexpected end of file"); + getline(FFile,AString); + AString = UnescapeString(AString); + return *this; +} + +ASCIIInStream::ASCIIInStream(std::string AFileName) +{ + FFile.open(AFileName.c_str()); + if(!FFile.good()) throw Tools::MsgException("ASCIIInStream::ASCIIInStream : Cannot open file for reading :"+AFileName); +} + +void ASCIIInStream::Close() +{ + FFile.close(); +} + +ASCIIInStream::~ASCIIInStream() +{ + FFile.close(); +} + +ASCIIOutStream& ASCIIOutStream::operator<<(std::vector& AVector) +{ + FFile< +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace log4cxx; +using namespace log4cxx::rolling; +using namespace log4cxx::helpers; +using namespace log4cxx::pattern; + +IMPLEMENT_LOG4CXX_OBJECT(FixedWindowRollingPolicy) + +FixedWindowRollingPolicy::FixedWindowRollingPolicy() : + minIndex(1), maxIndex(7) { +} + +void FixedWindowRollingPolicy::setMaxIndex(int maxIndex1) { + this->maxIndex = maxIndex1; +} + +void FixedWindowRollingPolicy::setMinIndex(int minIndex1) { + this->minIndex = minIndex1; +} + + + +void FixedWindowRollingPolicy::setOption(const LogString& option, + const LogString& value) { + if (StringHelper::equalsIgnoreCase(option, + LOG4CXX_STR("MININDEX"), + LOG4CXX_STR("minindex"))) { + minIndex = OptionConverter::toInt(value, 1); + } else if (StringHelper::equalsIgnoreCase(option, + LOG4CXX_STR("MAXINDEX"), + LOG4CXX_STR("maxindex"))) { + maxIndex = OptionConverter::toInt(value, 7); + } else { + RollingPolicyBase::setOption(option, value); + } +} + +/** + * {@inheritDoc} + */ +void FixedWindowRollingPolicy::activateOptions(Pool& p) { + RollingPolicyBase::activateOptions(p); + + if (maxIndex < minIndex) { + LogLog::warn( + LOG4CXX_STR("MaxIndex cannot be smaller than MinIndex.")); + maxIndex = minIndex; + } + + if ((maxIndex - minIndex) > MAX_WINDOW_SIZE) { + LogLog::warn(LOG4CXX_STR("Large window sizes are not allowed.")); + maxIndex = minIndex + MAX_WINDOW_SIZE; + } + + PatternConverterPtr itc = getIntegerPatternConverter(); + + if (itc == NULL) { + throw IllegalStateException(); + } +} + +/** + * {@inheritDoc} + */ +RolloverDescriptionPtr FixedWindowRollingPolicy::initialize( + const LogString& file, bool append, log4cxx::helpers::Pool& p) { + LogString newActiveFile(file); + explicitActiveFile = false; + + if (file.length() > 0) { + explicitActiveFile = true; + newActiveFile = file; + } + + if (!explicitActiveFile) { + LogString buf; + ObjectPtr obj(new Integer(minIndex)); + formatFileName(obj, buf, p); + newActiveFile = buf; + } + + ActionPtr noAction; + + return new RolloverDescription(newActiveFile, append, noAction, noAction); +} + +/** + * {@inheritDoc} + */ +RolloverDescriptionPtr FixedWindowRollingPolicy::rollover( + const LogString& currentFileName, + log4cxx::helpers::Pool& p) { + RolloverDescriptionPtr desc; + if (maxIndex >= 0) { + int purgeStart = minIndex; + + if (!explicitActiveFile) { + purgeStart++; + } + + if (!purge(purgeStart, maxIndex, p)) { + return desc; + } + + LogString buf; + ObjectPtr obj(new Integer(purgeStart)); + formatFileName(obj, buf, p); + + LogString renameTo(buf); + LogString compressedName(renameTo); + ActionPtr compressAction ; + + if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".gz"))) { + renameTo.resize(renameTo.size() - 3); + compressAction = + new GZCompressAction( + File().setPath(renameTo), File().setPath(compressedName), true); + } else if (StringHelper::endsWith(renameTo, LOG4CXX_STR(".zip"))) { + renameTo.resize(renameTo.size() - 4); + compressAction = + new ZipCompressAction( + File().setPath(renameTo), File().setPath(compressedName), true); + } + + FileRenameActionPtr renameAction = + new FileRenameAction( + File().setPath(currentFileName), File().setPath(renameTo), false); + +#ifdef LOG4CXX_MULTI_PROCESS + desc = new RolloverDescription( + currentFileName, true, renameAction, compressAction); +#else + desc = new RolloverDescription( + currentFileName, false, renameAction, compressAction); +#endif + } + + return desc; +} + +/** + * Get index of oldest log file to be retained. + * @return index of oldest log file. + */ +int FixedWindowRollingPolicy::getMaxIndex() const { + return maxIndex; +} + +/** + * Get index of most recent log file. + * @return index of oldest log file. + */ +int FixedWindowRollingPolicy::getMinIndex() const { + return minIndex; +} + + +/** + * Purge and rename old log files in preparation for rollover + * @param lowIndex low index + * @param highIndex high index. Log file associated with high + * index will be deleted if needed. + * @return true if purge was successful and rollover should be attempted. + */ +bool FixedWindowRollingPolicy::purge(int lowIndex, int highIndex, Pool& p) const { + int suffixLength = 0; + + std::vector renames; + LogString buf; + ObjectPtr obj = new Integer(lowIndex); + formatFileName(obj, buf, p); + + LogString lowFilename(buf); + + if (lowFilename.compare(lowFilename.length() - 3, 3, LOG4CXX_STR(".gz")) == 0) { + suffixLength = 3; + } else if (lowFilename.compare(lowFilename.length() - 4, 4, LOG4CXX_STR(".zip")) == 0) { + suffixLength = 4; + } + + for (int i = lowIndex; i <= highIndex; i++) { + File toRenameCompressed; + toRenameCompressed.setPath(lowFilename); + File toRenameBase; + toRenameBase.setPath(lowFilename.substr(0, lowFilename.length() - suffixLength)); + File* toRename = &toRenameCompressed; + bool isBase = false; + bool exists = toRenameCompressed.exists(p); + + if (suffixLength > 0) { + if (exists) { + if (toRenameBase.exists(p)) { + toRenameBase.deleteFile(p); + } + } else { + toRename = &toRenameBase; + exists = toRenameBase.exists(p); + isBase = true; + } + } + + if (exists) { + // + // if at upper index then + // attempt to delete last file + // if that fails then abandon purge + if (i == highIndex) { + if (!toRename->deleteFile(p)) { + return false; + } + + break; + } + + // + // if intermediate index + // add a rename action to the list + buf.erase(buf.begin(), buf.end()); + obj = new Integer(i + 1); + formatFileName(obj, buf, p); + + LogString highFilename(buf); + LogString renameTo(highFilename); + + if (isBase) { + renameTo = + highFilename.substr(0, highFilename.length() - suffixLength); + } + + renames.push_back(new FileRenameAction(*toRename, File().setPath(renameTo), true)); + lowFilename = highFilename; + } else { + break; + } + } + + // + // work renames backwards + // + for(std::vector::reverse_iterator iter = renames.rbegin(); + iter != renames.rend(); + iter++) { + + try { + if (!(*iter)->execute(p)) { + return false; + } + } catch (std::exception& ex) { + LogLog::warn(LOG4CXX_STR("Exception during purge in RollingFileAppender")); + + return false; + } + } + return true; +} + +#define RULES_PUT(spec, cls) \ +specs.insert(PatternMap::value_type(LogString(LOG4CXX_STR(spec)), (PatternConstructor) cls ::newInstance)) + + +log4cxx::pattern::PatternMap FixedWindowRollingPolicy::getFormatSpecifiers() const { + PatternMap specs; + RULES_PUT("i", IntegerPatternConverter); + RULES_PUT("index", IntegerPatternConverter); + return specs; +} diff --git a/pool/shard011/C++/0122087_Robot.cpp b/pool/shard011/C++/0122087_Robot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..379d7dabe260c199a8b44137b43a2b4d5d65bd34 --- /dev/null +++ b/pool/shard011/C++/0122087_Robot.cpp @@ -0,0 +1,96 @@ +/* + Robot + + -------------------------------------------------------------------------------- + Copyright (c) 2013 Philipp Thun + + Permission is hereby granted, free of charge, to any person obtaining a copy of + this software and associated documentation files (the "Software"), to deal in + the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + -------------------------------------------------------------------------------- +*/ + +#include "Robot.h" + +const int PIN_RIGHT_BRAKE = 9; +const int PIN_RIGHT_DIRECTION = 12; +const int PIN_RIGHT_SPEED = 3; + +const int PIN_LEFT_BRAKE = 8; +const int PIN_LEFT_DIRECTION = 13; +const int PIN_LEFT_SPEED = 11; + +Robot::Robot() { + pinMode(PIN_RIGHT_BRAKE, OUTPUT); + pinMode(PIN_RIGHT_DIRECTION, OUTPUT); + pinMode(PIN_RIGHT_SPEED, OUTPUT); + + pinMode(PIN_LEFT_BRAKE, OUTPUT); + pinMode(PIN_LEFT_DIRECTION, OUTPUT); + pinMode(PIN_LEFT_SPEED, OUTPUT); + + _brake(); +} + +void Robot::drive(boolean forward, int speed, int duration) { + digitalWrite(PIN_RIGHT_BRAKE, LOW); + digitalWrite(PIN_LEFT_BRAKE, LOW); + + if (forward) { + digitalWrite(PIN_RIGHT_DIRECTION, LOW); + digitalWrite(PIN_LEFT_DIRECTION, HIGH); + } + else { + digitalWrite(PIN_RIGHT_DIRECTION, HIGH); + digitalWrite(PIN_LEFT_DIRECTION, LOW); + } + + analogWrite(PIN_RIGHT_SPEED, speed); + analogWrite(PIN_LEFT_SPEED, speed); + + delay(duration); + + _brake(); +} + +void Robot::rotate(boolean clockwise, int speed, int duration) { + digitalWrite(PIN_RIGHT_BRAKE, LOW); + digitalWrite(PIN_LEFT_BRAKE, LOW); + + if (clockwise) { + digitalWrite(PIN_RIGHT_DIRECTION, HIGH); + digitalWrite(PIN_LEFT_DIRECTION, HIGH); + } + else { + digitalWrite(PIN_RIGHT_DIRECTION, LOW); + digitalWrite(PIN_LEFT_DIRECTION, LOW); + } + + analogWrite(PIN_RIGHT_SPEED, speed); + analogWrite(PIN_LEFT_SPEED, speed); + + delay(duration); + + _brake(); +} + +void Robot::_brake() { + digitalWrite(PIN_RIGHT_BRAKE, HIGH); + digitalWrite(PIN_LEFT_BRAKE, HIGH); + + analogWrite(PIN_RIGHT_SPEED, 0); + analogWrite(PIN_LEFT_SPEED, 0); +} diff --git a/pool/shard011/C++/0122088_q3progressbar.cpp b/pool/shard011/C++/0122088_q3progressbar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..34b3dd1e020e532a0c6e8a0cfb6cb10b16e1549a --- /dev/null +++ b/pool/shard011/C++/0122088_q3progressbar.cpp @@ -0,0 +1,464 @@ +/**************************************************************************** +** +** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). +** All rights reserved. +** Contact: Nokia Corporation (qt-info@nokia.com) +** +** This file is part of the Qt3Support module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file may be used under the terms of the GNU Lesser General Public +** License version 2.1 as published by the Free Software Foundation and +** appearing in the file LICENSE.LGPL included in the packaging of this +** file. Please review the following information to ensure the GNU Lesser +** General Public License version 2.1 requirements will be met: +** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Nokia gives you certain additional +** rights. These rights are described in the Nokia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** GNU General Public License Usage +** Alternatively, this file may be used under the terms of the GNU General +** Public License version 3.0 as published by the Free Software Foundation +** and appearing in the file LICENSE.GPL included in the packaging of this +** file. Please review the following information to ensure the GNU General +** Public License version 3.0 requirements will be met: +** http://www.gnu.org/copyleft/gpl.html. +** +** Other Usage +** Alternatively, this file may be used in accordance with the terms and +** conditions contained in a signed written agreement between you and Nokia. +** +** +** +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "q3progressbar.h" +#ifndef QT_NO_PROGRESSBAR +#include "qpainter.h" +#include "qdrawutil.h" +#include "qpixmap.h" +#include "qstyle.h" +#include "qstyleoption.h" +#ifndef QT_NO_ACCESSIBILITY +#include "qaccessible.h" +#endif +#include "qevent.h" +#include + +QT_BEGIN_NAMESPACE + +/*! + \class Q3ProgressBar + \brief The Q3ProgressBar widget provides a horizontal progress bar. + + \compat + + A progress bar is used to give the user an indication of the + progress of an operation and to reassure them that the application + is still running. + + The progress bar uses the concept of \e steps; you give it the + total number of steps and the number of steps completed so far and + it will display the percentage of steps that have been completed. + You can specify the total number of steps in the constructor or + later with setTotalSteps(). The current number of steps is set + with setProgress(). The progress bar can be rewound to the + beginning with reset(). + + If the total is given as 0 the progress bar shows a busy indicator + instead of a percentage of steps. This is useful, for example, + when using QFtp or QHttp to download items when they are unable to + determine the size of the item being downloaded. + + \sa QProgressDialog + + \inlineimage qprogbar-m.png Screenshot in Motif style + \inlineimage qprogbar-w.png Screenshot in Windows style + + \sa QProgressDialog +*/ + + +/*! \obsolete + Constructs a progress bar. + + The total number of steps is set to 100 by default. + + The \a parent, \a name and widget flags, \a f, are passed on to + the QFrame::QFrame() constructor. + + \sa setTotalSteps() +*/ + +Q3ProgressBar::Q3ProgressBar(QWidget *parent, const char *name, Qt::WindowFlags f) + : QFrame(parent, f), + total_steps(100), + progress_val(-1), + percentage(-1), + center_indicator(true), + percentage_visible(true), + d(0) +{ + setObjectName(QLatin1String(name)); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + initFrame(); +} + + +/*! \obsolete + Constructs a progress bar. + + The \a totalSteps is the total number of steps that need to be + completed for the operation which this progress bar represents. + For example, if the operation is to examine 50 files, this value + would be 50. Before examining the first file, call setProgress(0); + call setProgress(50) after examining the last file. + + The \a parent, \a name and widget flags, \a f, are passed to the + QFrame::QFrame() constructor. + + \sa setTotalSteps(), setProgress() +*/ + +Q3ProgressBar::Q3ProgressBar(int totalSteps, QWidget *parent, const char *name, Qt::WindowFlags f) + : QFrame(parent, f), + total_steps(totalSteps), + progress_val(-1), + percentage(-1), + center_indicator(true), + percentage_visible(true), + d(0) +{ + setObjectName(QLatin1String(name)); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + initFrame(); +} +#endif + +/*! + Constructs a progress bar. + + The total number of steps is set to 100 by default. + + The \a parent, and widget flags, \a f, are passed on to + the QFrame::QFrame() constructor. + + \sa setTotalSteps() +*/ + +Q3ProgressBar::Q3ProgressBar(QWidget *parent, Qt::WindowFlags f) + : QFrame(parent, f), + total_steps(100), + progress_val(-1), + percentage(-1), + center_indicator(true), + percentage_visible(true), + d(0) +{ + setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); + initFrame(); +} + + +/*! + Constructs a progress bar. + + The \a totalSteps is the total number of steps that need to be + completed for the operation which this progress bar represents. + For example, if the operation is to examine 50 files, this value + would be 50. Before examining the first file, call setProgress(0); + call setProgress(50) after examining the last file. + + The \a parent, and widget flags, \a f, are passed to the + QFrame::QFrame() constructor. + + \sa setTotalSteps(), setProgress() +*/ + +Q3ProgressBar::Q3ProgressBar(int totalSteps, QWidget *parent, Qt::WindowFlags f) + : QFrame(parent, f), + total_steps(totalSteps), + progress_val(-1), + percentage(-1), + center_indicator(true), + percentage_visible(true), + d(0) +{ + setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed)); + initFrame(); +} + + +/*! + Reset the progress bar. The progress bar "rewinds" and shows no + progress. +*/ + +void Q3ProgressBar::reset() +{ + progress_val = -1; + percentage = -1; + setIndicator(progress_str, progress_val, total_steps); + repaint(); +} + + +/*! + \property Q3ProgressBar::totalSteps + \brief The total number of steps. + + If totalSteps is 0, the progress bar will display a busy + indicator. +*/ + +void Q3ProgressBar::setTotalSteps(int totalSteps) +{ + total_steps = totalSteps; + + // Current progress is invalid if larger than total + if (total_steps < progress_val) + progress_val = -1; + + if (isVisible() && + (setIndicator(progress_str, progress_val, total_steps) || !total_steps)) + repaint(); +} + + +/*! + \property Q3ProgressBar::progress + \brief The current amount of progress + + This property is -1 if progress counting has not started. +*/ + +void Q3ProgressBar::setProgress(int progress) +{ + if (progress == progress_val || + progress < 0 || ((progress > total_steps) && total_steps)) + return; + + int old_progress_val = progress_val; + progress_val = progress; + + if (setIndicator(progress_str, progress_val, total_steps) + || ( total_steps == 0 || (width() * progress_val / total_steps != width() * old_progress_val / total_steps ))) + repaint(); + +#ifndef QT_NO_ACCESSIBILITY + QAccessible::updateAccessibility(this, 0, QAccessible::ValueChanged); +#endif +} + +/*! + \overload + + Sets the amount of progress to \a progress and the total number of + steps to \a totalSteps. + + \sa setTotalSteps() +*/ + +void Q3ProgressBar::setProgress(int progress, int totalSteps) +{ + if (total_steps != totalSteps) + setTotalSteps(totalSteps); + setProgress(progress); +} + +/*! + \property Q3ProgressBar::progressString + \brief the amount of progress as a string + + This property is an empty string if progress counting has not started. +*/ + +static QStyleOptionProgressBar getStyleOption(const Q3ProgressBar *pb) +{ + QStyleOptionProgressBar opt; + opt.init(pb); + opt.rect = pb->contentsRect(); + opt.minimum = 0; + opt.maximum = pb->totalSteps(); + opt.progress = pb->progress(); + if (pb->centerIndicator()) + opt.textAlignment = Qt::AlignCenter; + else + opt.textAlignment = Qt::AlignAuto; + opt.textVisible = pb->percentageVisible(); + opt.text = pb->progressString(); + return opt; +} + +/*! + \reimp +*/ +QSize Q3ProgressBar::sizeHint() const +{ + ensurePolished(); + QFontMetrics fm = fontMetrics(); + QStyleOptionProgressBar opt = getStyleOption(this); + int cw = style()->pixelMetric(QStyle::PM_ProgressBarChunkWidth, &opt, this); + return style()->sizeFromContents(QStyle::CT_ProgressBar, &opt, + QSize(cw * 7 + fm.width(QLatin1Char('0')) * 4, fm.height() + 8), this); +} + +/*! + \reimp +*/ +QSize Q3ProgressBar::minimumSizeHint() const +{ + return sizeHint(); +} + +/*! + \property Q3ProgressBar::centerIndicator + \brief whether the indicator string should be centered +*/ + +void Q3ProgressBar::setCenterIndicator(bool on) +{ + if (on == center_indicator) + return; + center_indicator = on; + repaint(); +} + +/*! + \property Q3ProgressBar::percentageVisible + \brief whether the current progress value is displayed + + The default is true. + + \sa centerIndicator +*/ +void Q3ProgressBar::setPercentageVisible(bool on) +{ + if (on == percentage_visible) + return; + percentage_visible = on; + repaint(); +} + +/*! + \reimp +*/ +void Q3ProgressBar::setVisible(bool visible) +{ + if (visible) + setIndicator(progress_str, progress_val, total_steps); + QFrame::setVisible(visible); +} + +void Q3ProgressBar::initFrame() +{ + setFrameStyle(QFrame::NoFrame); +} + +/*! + \reimp +*/ +void Q3ProgressBar::changeEvent(QEvent *ev) +{ + if(ev->type() == QEvent::StyleChange) + initFrame(); + QFrame::changeEvent(ev); +} + + +/*! + This method is called to generate the text displayed in the center + (or in some styles, to the left) of the progress bar. + + The \a progress may be negative, indicating that the progress bar + is in the "reset" state before any progress is set. + + The default implementation is the percentage of completion or + blank in the reset state. The percentage is calculated based on + the \a progress and \a totalSteps. You can set the \a indicator + text if you wish. + + To allow efficient repainting of the progress bar, this method + should return false if the string is unchanged from the last call + to this function. +*/ + +bool Q3ProgressBar::setIndicator(QString & indicator, int progress, + int totalSteps) +{ + if (!totalSteps) + return false; + if (progress < 0) { + indicator = QString::fromLatin1(""); + return true; + } else { + // Get the values down to something usable. + if (totalSteps > INT_MAX/1000) { + progress /= 1000; + totalSteps /= 1000; + } + + int np = progress * 100 / totalSteps; + if (np != percentage) { + percentage = np; + indicator.sprintf("%d%%", np); + return true; + } else { + return false; + } + } +} + + +/*! + \reimp +*/ +void Q3ProgressBar::paintEvent(QPaintEvent *) +{ + QPainter paint(this); + QPainter *p = &paint; + drawFrame(p); + + QStyleOptionProgressBar opt = getStyleOption(this); + opt.rect = style()->subElementRect(QStyle::SE_ProgressBarGroove, &opt, this); + + style()->drawControl(QStyle::CE_ProgressBarGroove, &opt, p, this); + opt.rect = contentsRect(); + opt.rect = style()->subElementRect(QStyle::SE_ProgressBarContents, &opt, this); + style()->drawControl(QStyle::CE_ProgressBarContents, &opt, p, this); + + if (percentageVisible()) { + opt.rect = contentsRect(); + opt.rect = style()->subElementRect(QStyle::SE_ProgressBarLabel, &opt, this); + style()->drawControl(QStyle::CE_ProgressBarLabel, &opt, p, this); + } +} + +/*! + \fn void Q3ProgressBar::setMargin(int margin) + \since 4.2 + + Sets the width of the margin around the contents of the widget to \a margin. + + This function uses QWidget::setContentsMargins() to set the margin. + \sa margin(), QWidget::setContentsMargins() +*/ + +/*! + \fn int Q3ProgressBar::margin() const + \since 4.2 + + Returns the width of the margin around the contents of the widget. + + This function uses QWidget::getContentsMargins() to get the margin. + \sa setMargin(), QWidget::getContentsMargins() +*/ + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0122090_v4ltestbygqp.cpp b/pool/shard011/C++/0122090_v4ltestbygqp.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26d496e80f9151761523819b43a79e1214b9910c --- /dev/null +++ b/pool/shard011/C++/0122090_v4ltestbygqp.cpp @@ -0,0 +1,55 @@ +#include "itrvision.h" +#include"itrdevice.h" +#include"v4linux.h" +#define _id 0 +#define INDEX 0 +void v4ltestguan() +{ + FILE *fp; + itr_device::v4linux cam; + S32 width,height; + width=640; + height=480; + U8* raw=new U8[3*width*height]; + void *exinfo; + char filename[20]; + // RGB; +// cam.Init(PIC_TYPE); + cam.Open( _id,width,height,2); + // cam.SetTunnel(INDEX); + for(S32 i=0; i<20; i++) + { + cam.FetchFrame(raw,width*height,exinfo); + sprintf(filename,"outyuv%3d.pgm",i); + fp=fopen(filename,"w+"); + if(fp==NULL) + { + printf("fail to open file%d\n",i); + exit(-1); + } + fprintf(fp, "P5\n%d %d 255\n",width,height); + fwrite(raw,width*height, 1, fp); + fclose(fp); + } + cam.Close(); + itr_device::v4linux cam2; + //yuv420 + cam2.Init(itr_device::v4linux::PIC_TYPE(1)); + cam2.Open( _id,width,height,2); + //cam.SetTunnel(INDEX); + for(S32 i=0; i<20; i++) + { + cam2.FetchFrame(raw,width*height*3,exinfo); + sprintf(filename,"outrgb%3d.ppm",i); + fp=fopen(filename,"w+"); + if(fp==NULL) + { + printf("fail to open file%d\n",i); + exit(-1); + } + fprintf(fp, "P6\n%d %d 255\n",width,height); + fwrite(raw,width*height*3, 1, fp); + fclose(fp); + } + cam2.Close(); +} diff --git a/pool/shard011/C++/0122091_jdk_dll.cpp b/pool/shard011/C++/0122091_jdk_dll.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9305196ebb983a63fc8bfe7ff52f8eed542236f4 --- /dev/null +++ b/pool/shard011/C++/0122091_jdk_dll.cpp @@ -0,0 +1,131 @@ + +#include "jdk_world.h" + +#if JDK_IS_MACOSX + +#else + +#if JDK_IS_UNIX || JDK_IS_WINE +#include +#elif JDK_IS_WIN32 +#endif + +#include "jdk_dll.h" + + + +jdk_dll_manager::jdk_dll_manager( const char *fname ) +{ + // Try to open the library now and get any error message. +#if JDK_IS_WIN32 && !JDK_IS_WINE + h=LoadLibraryA( fname ); + if( h==0 ) + { + jdk_sprintf( err, "%08x", (unsigned int)GetLastError() ); + } + else + { + *err=0; + } + +#elif JDK_IS_UNIX || JDK_IS_WINE + h=dlopen( fname, RTLD_NOW ); + err=dlerror(); +#else +#error specify platform +#endif +} + +jdk_dll_manager::~jdk_dll_manager() +{ +#if JDK_IS_WIN32 && !JDK_IS_WINE + if( h ) + { + FreeLibrary(h); + } +#elif JDK_IS_UNIX || JDK_IS_WINE + // close the library if it isn't null + if( h!=0 ) + dlclose(h); +#else +#error specify platform +#endif +} + + +bool jdk_dll_manager::get_symbol( + void **v, + const char *sym_name + ) +{ + // try extract a symbol from the library + // get any error message is there is any + +#if JDK_IS_WIN32 && !JDK_IS_WINE + if( h!=0 ) + { + *v = (void *)GetProcAddress( h, sym_name ); + + if( *v==0 ) + { + jdk_sprintf( err, "%08x", (unsigned int)GetLastError() ); + } + else + { + *err=0; + } + + if( *v!=0 ) + return true; + else + return false; + } + else + { + return false; + } +#elif JDK_IS_UNIX || JDK_IS_WINE + if( h!=0 ) + { + *v = dlsym( h, sym_name ); + err=dlerror(); + if( err==0 ) + return true; + else + return false; + } + else + { + return false; + } +#else +#error specify platform +#endif +} + + +jdk_dll_factory_base::jdk_dll_factory_base( + const char *fname, + const char *factory + ) : jdk_dll_manager(fname) +{ + // try get the factory function if there is no error yet + + factory_func=0; + + if( *last_error()==0 ) + { + get_symbol( (void **)&factory_func, factory ? factory : "factory0" ); + } + +} + + +jdk_dll_factory_base::~jdk_dll_factory_base() +{ +} + +#endif + + + diff --git a/pool/shard011/C++/0122093_berryViewRegistry.cpp b/pool/shard011/C++/0122093_berryViewRegistry.cpp new file mode 100644 index 0000000000000000000000000000000000000000..85c85fa228ba8662dc16b50e1443f2c32a30b2d8 --- /dev/null +++ b/pool/shard011/C++/0122093_berryViewRegistry.cpp @@ -0,0 +1,281 @@ +/*=================================================================== + +BlueBerry Platform + +Copyright (c) German Cancer Research Center, +Division of Medical and Biological Informatics. +All rights reserved. + +This software is distributed WITHOUT ANY WARRANTY; without +even the implied warranty of MERCHANTABILITY or FITNESS FOR +A PARTICULAR PURPOSE. + +See LICENSE.txt or http://www.mitk.org for details. + +===================================================================*/ + +#include + +#include "berryViewRegistry.h" + +#include "berryPlatformUI.h" +#include "berryImageDescriptor.h" +#include "berryWorkbenchPlugin.h" +#include "berryWorkbenchRegistryConstants.h" + +#include "berryPlatform.h" + +namespace berry +{ + +ViewRegistry::ViewCategoryProxy::ViewCategoryProxy( + IViewDescriptorCategoryPtr rawCategory) : + rawCategory(rawCategory) +{ +} + +const std::vector& ViewRegistry::ViewCategoryProxy::GetViews() const +{ + return rawCategory->GetElements(); +} + +const std::string& ViewRegistry::ViewCategoryProxy::GetId() const +{ + return rawCategory->GetId(); +} + +std::vector ViewRegistry::ViewCategoryProxy::GetPath() const +{ + std::vector path; + std::string rawParentPath = rawCategory->GetRawParentPath(); + // nested categories are not supported yet + // assume an empty raw parent path + path.push_back(rawParentPath); + return path; +} + +std::string ViewRegistry::ViewCategoryProxy::GetLabel() const +{ + return rawCategory->GetLabel(); +} + +bool ViewRegistry::ViewCategoryProxy::operator==(const Object* o) const +{ + if (const IViewCategory* other = dynamic_cast(o)) + return this->GetId() == other->GetId(); + + return false; +} + +int ViewRegistry::ViewCategoryProxy::HashCode() +{ + //return GetId().hashCode(); + return 0; +} + +std::string ViewRegistry::EXTENSIONPOINT_UNIQUE_ID = "org.blueberry.ui.views"; + // PlatformUI::PLUGIN_ID + "." + WorkbenchRegistryConstants::PL_VIEWS; + + +Category::Pointer ViewRegistry::InternalFindCategory(const std::string& id) +{ + for (std::vector::iterator itr = categories.begin(); + itr != categories.end(); ++itr) + { + if (id == (*itr)->GetRootPath()) + { + return *itr; + } + } + return IViewDescriptorCategoryPtr(0); +} + +const IExtensionPoint* ViewRegistry::GetExtensionPointFilter() +{ + return Platform::GetExtensionPointService()->GetExtensionPoint(EXTENSIONPOINT_UNIQUE_ID); +} + +const std::string ViewRegistry::TAG_DESCRIPTION = "description"; + +ViewRegistry::ViewRegistry() : + dirtyViewCategoryMappings(true) +{ + miscCategory = new IViewDescriptorCategory(); + this->Add(miscCategory); + + //PlatformUI.getWorkbench().getExtensionTracker().registerHandler(this, + // ExtensionTracker.createExtensionPointFilter(getExtensionPointFilter())); + reader.ReadViews(this); +} + +void ViewRegistry::Add(IViewDescriptorCategoryPtr desc) +{ + /* fix for 1877 */ + if (this->InternalFindCategory(desc->GetId()).IsNull()) + { + dirtyViewCategoryMappings = true; + // Mark categories list as dirty + categories.push_back(desc); +// IConfigurationElement::Pointer element( +// dynamic_cast( +// desc->GetAdapter(typeid(IConfigurationElement)) +// )); +// if (element.IsNull()) +// { +// return; +// } +// PlatformUI::GetWorkbench()->GetExtensionTracker() +// .registerObject(element->GetDeclaringExtension(), desc, +// IExtensionTracker::REF_WEAK); + } +} + +void ViewRegistry::Add(ViewDescriptor::Pointer desc) +{ + for (std::vector::const_iterator itr = views.begin(); + itr != views.end(); ++itr) + { + if (desc.GetPointer() == itr->GetPointer()) return; + } + + views.push_back(desc); + dirtyViewCategoryMappings = true; + //desc.activateHandler(); +} + +void ViewRegistry::Add(StickyViewDescriptor::Pointer desc) +{ + if (std::find(sticky.begin(), sticky.end(), desc) == sticky.end()) + { + sticky.push_back(desc); +// PlatformUI::GetWorkbench()->GetExtensionTracker() +// .registerObject(desc.getConfigurationElement().getDeclaringExtension(), +// desc, IExtensionTracker.REF_WEAK); + } +} + +IViewDescriptor::Pointer ViewRegistry::Find(const std::string& id) const +{ + for (std::vector::const_iterator itr = views.begin(); + itr != views.end(); ++itr) + { + if (id == (*itr)->GetId()) + { + return *itr; + } + } + return IViewDescriptor::Pointer(0); +} + +IViewCategory::Pointer ViewRegistry::FindCategory(const std::string& id) +{ + this->MapViewsToCategories(); + IViewDescriptorCategoryPtr category(this->InternalFindCategory(id)); + if (category.IsNull()) + { + return IViewCategory::Pointer(0); + } + IViewCategory::Pointer cat(new ViewCategoryProxy(category)); + return cat; +} + +std::vector ViewRegistry::GetCategories() +{ + this->MapViewsToCategories(); + std::vector retArray; + for (std::vector::iterator itr = categories.begin(); + itr != categories.end(); ++itr) + { + retArray.push_back(IViewCategory::Pointer(new ViewCategoryProxy(*itr))); + } + return retArray; +} + +std::vector ViewRegistry::GetStickyViews() const +{ + return sticky; +} + +Category::Pointer ViewRegistry::GetMiscCategory() const +{ + return miscCategory; +} + +const std::vector& ViewRegistry::GetViews() const +{ + return views; +} + +void ViewRegistry::MapViewsToCategories() +{ + if (dirtyViewCategoryMappings) + { + dirtyViewCategoryMappings = false; + // clear all category mappings + for (std::vector::iterator i = categories.begin(); + i != categories.end(); ++i) + { + (*i)->Clear(); // this is bad + } + + miscCategory->Clear(); + + for (std::vector::iterator i = views.begin(); + i != views.end(); ++i) + { + IViewDescriptor::Pointer desc(*i); + IViewDescriptorCategoryPtr cat(0); + const std::vector& catPath = desc->GetCategoryPath(); + if (catPath.size() > 0) + { + cat = this->InternalFindCategory(catPath[0]); + } + if (cat.IsNotNull()) + { + if (!cat->HasElement(desc)) + { + cat->AddElement(desc); + } + } + else + { + if (catPath.size() > 0) + { + // If we get here, this view specified a category which + // does not exist. Add this view to the 'Other' category + // but give out a message (to the log only) indicating + // this has been done. + std::string fmt(Poco::Logger::format( + "Category $0 not found for view $1. This view added to ''$2'' category.", + catPath[0], desc->GetId(), miscCategory->GetLabel())); + WorkbenchPlugin::Log(fmt); + } + miscCategory->AddElement(desc); + } + } + } +} + +//void ViewRegistry::AddExtension(IExtensionTracker tracker, +// IExtension addedExtension) +//{ +// IConfigurationElement[] addedElements = addedExtension.getConfigurationElements(); +// for (int i = 0; i < addedElements.length; i++) +// { +// IConfigurationElement element = addedElements[i]; +// if (element.getName().equals(IWorkbenchRegistryConstants.TAG_VIEW)) +// { +// reader.readView(element); +// } +// else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_CATEGORY)) +// { +// reader.readCategory(element); +// } +// else if (element.getName().equals(IWorkbenchRegistryConstants.TAG_STICKYVIEW)) +// { +// reader.readSticky(element); +// } +// } +//} + +} // namespace berry diff --git a/pool/shard011/C++/0122094_web_intents_registry.cc b/pool/shard011/C++/0122094_web_intents_registry.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a8a567281241afb5e369f66ac4752aa0fb0f028 --- /dev/null +++ b/pool/shard011/C++/0122094_web_intents_registry.cc @@ -0,0 +1,199 @@ +// 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 "chrome/browser/intents/web_intents_registry.h" + +#include "base/callback.h" +#include "base/utf_string_conversions.h" +#include "chrome/browser/webdata/web_data_service.h" +#include "net/base/mime_util.h" + +namespace { + +// Compares two mime types for equality. Supports wild cards in both +// |type1| and |type2|. Wild cards are of the form '/*' or '*'. +bool MimeTypesAreEqual(const string16& type1, const string16& type2) { + // We don't have a MIME matcher that allows patterns on both sides + // Instead, we do two comparison, treating each type in turn as a + // pattern. If either one matches, we consider this a MIME match. + if (net::MatchesMimeType(UTF16ToUTF8(type1), UTF16ToUTF8(type2))) + return true; + return net::MatchesMimeType(UTF16ToUTF8(type2), UTF16ToUTF8(type1)); +} + +} // namespace + +using webkit_glue::WebIntentServiceData; + +// Internal object representing all data associated with a single query. +struct WebIntentsRegistry::IntentsQuery { + // Unique query identifier. + QueryID query_id_; + + // Underlying data query. + WebDataService::Handle pending_query_; + + // The consumer for this particular query. + Consumer* consumer_; + + // The particular action to filter for while searching through extensions. + // If |action_| is empty, return all extension-provided intents. + string16 action_; + + // The MIME type that was requested for this intent query. + // Suppports wild cards. + string16 type_; +}; + +WebIntentsRegistry::WebIntentsRegistry() : next_query_id_(0) {} + +WebIntentsRegistry::~WebIntentsRegistry() { + // Cancel all pending queries, since we can't handle them any more. + for (QueryMap::iterator it(queries_.begin()); it != queries_.end(); ++it) { + wds_->CancelRequest(it->first); + delete it->second; + } +} + +void WebIntentsRegistry::Initialize( + scoped_refptr wds, + ExtensionServiceInterface* extension_service) { + wds_ = wds; + extension_service_ = extension_service; +} + +void WebIntentsRegistry::OnWebDataServiceRequestDone( + WebDataService::Handle h, + const WDTypedResult* result) { + DCHECK(result); + DCHECK(result->GetType() == WEB_INTENTS_RESULT); + + QueryMap::iterator it = queries_.find(h); + DCHECK(it != queries_.end()); + + IntentsQuery* query(it->second); + DCHECK(query); + queries_.erase(it); + + IntentServiceList matching_services = static_cast< + const WDResult*>(result)->GetValue(); + + // Loop over all intents in all extensions, collect ones matching the query. + if (extension_service_) { + const ExtensionSet* extensions = extension_service_->extensions(); + if (extensions) { + for (ExtensionSet::const_iterator i(extensions->begin()); + i != extensions->end(); ++i) { + const IntentServiceList& intents((*i)->intents_services()); + for (IntentServiceList::const_iterator j(intents.begin()); + j != intents.end(); ++j) { + if (query->action_.empty() || query->action_ == j->action) + matching_services.push_back(*j); + } + } + } + } + + // Filter out all intents not matching the query type. + IntentServiceList::iterator iter(matching_services.begin()); + while (iter != matching_services.end()) { + if (MimeTypesAreEqual(iter->type, query->type_)) + ++iter; + else + iter = matching_services.erase(iter); + } + + query->consumer_->OnIntentsQueryDone(query->query_id_, matching_services); + delete query; +} + +WebIntentsRegistry::QueryID WebIntentsRegistry::GetIntentProviders( + const string16& action, const string16& mimetype, Consumer* consumer) { + DCHECK(consumer); + DCHECK(wds_.get()); + + IntentsQuery* query = new IntentsQuery; + query->query_id_ = next_query_id_++; + query->consumer_ = consumer; + query->action_ = action; + query->type_ = mimetype; + query->pending_query_ = wds_->GetWebIntentServices(action, this); + queries_[query->pending_query_] = query; + + return query->query_id_; +} + +WebIntentsRegistry::QueryID WebIntentsRegistry::GetAllIntentProviders( + Consumer* consumer) { + DCHECK(consumer); + DCHECK(wds_.get()); + + IntentsQuery* query = new IntentsQuery; + query->query_id_ = next_query_id_++; + query->consumer_ = consumer; + query->type_ = ASCIIToUTF16("*"); + query->pending_query_ = wds_->GetAllWebIntentServices(this); + queries_[query->pending_query_] = query; + + return query->query_id_; +} + +// Trampoline consumer for calls to IntentProviderExists. Forwards existence +// of the provided |service| to the provided |callback|. +class ProviderCheckConsumer : public WebIntentsRegistry::Consumer { + public: + ProviderCheckConsumer(const WebIntentServiceData& service, + const base::Callback& callback) + : callback_(callback), + service_(service) {} + virtual ~ProviderCheckConsumer() {} + + // Gets the list of all providers for a particular action. Check them all + // to see if |provider_| is already registered. + virtual void OnIntentsQueryDone( + WebIntentsRegistry::QueryID id, + const WebIntentsRegistry::IntentServiceList& list) OVERRIDE { + scoped_ptr self_deleter(this); + + for (WebIntentsRegistry::IntentServiceList::const_iterator i = list.begin(); + i != list.end(); ++i) { + if (*i == service_) { + callback_.Run(true); + return; + } + } + + callback_.Run(false); + } + + private: + base::Callback callback_; + WebIntentServiceData service_; +}; + +WebIntentsRegistry::QueryID WebIntentsRegistry::IntentProviderExists( + const WebIntentServiceData& provider, + const base::Callback& callback) { + IntentsQuery* query = new IntentsQuery; + query->query_id_ = next_query_id_++; + query->type_ = ASCIIToUTF16("*"); + query->consumer_ = new ProviderCheckConsumer(provider, callback); + query->pending_query_ = wds_->GetWebIntentServicesForURL( + UTF8ToUTF16(provider.service_url.spec()), this); + queries_[query->pending_query_] = query; + + return query->query_id_; +} + +void WebIntentsRegistry::RegisterIntentProvider( + const WebIntentServiceData& service) { + DCHECK(wds_.get()); + wds_->AddWebIntentService(service); +} + +void WebIntentsRegistry::UnregisterIntentProvider( + const WebIntentServiceData& service) { + DCHECK(wds_.get()); + wds_->RemoveWebIntentService(service); +} diff --git a/pool/shard011/C++/0122097_css_number_interpolation_type.cc b/pool/shard011/C++/0122097_css_number_interpolation_type.cc new file mode 100644 index 0000000000000000000000000000000000000000..e24be066dc7b221ca22880bbab2d7ca7ef8d7757 --- /dev/null +++ b/pool/shard011/C++/0122097_css_number_interpolation_type.cc @@ -0,0 +1,118 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "third_party/blink/renderer/core/animation/css_number_interpolation_type.h" + +#include + +#include "base/memory/ptr_util.h" +#include "base/optional.h" +#include "third_party/blink/renderer/core/animation/number_property_functions.h" +#include "third_party/blink/renderer/core/css/css_numeric_literal_value.h" +#include "third_party/blink/renderer/core/css/resolver/style_builder.h" +#include "third_party/blink/renderer/core/css/resolver/style_resolver_state.h" + +namespace blink { + +class InheritedNumberChecker + : public CSSInterpolationType::CSSConversionChecker { + public: + InheritedNumberChecker(const CSSProperty& property, + base::Optional number) + : property_(property), number_(number) {} + + private: + bool IsValid(const StyleResolverState& state, + const InterpolationValue& underlying) const final { + base::Optional parent_number = + NumberPropertyFunctions::GetNumber(property_, *state.ParentStyle()); + return number_ == parent_number; + } + + const CSSProperty& property_; + const base::Optional number_; +}; + +const CSSValue* CSSNumberInterpolationType::CreateCSSValue( + const InterpolableValue& value, + const NonInterpolableValue*, + const StyleResolverState&) const { + double number = To(value).Value(); + return CSSNumericLiteralValue::Create( + round_to_integer_ ? round(number) : number, + CSSPrimitiveValue::UnitType::kNumber); +} + +InterpolationValue CSSNumberInterpolationType::CreateNumberValue( + double number) const { + return InterpolationValue(std::make_unique(number)); +} + +InterpolationValue CSSNumberInterpolationType::MaybeConvertNeutral( + const InterpolationValue&, + ConversionCheckers&) const { + return CreateNumberValue(0); +} + +InterpolationValue CSSNumberInterpolationType::MaybeConvertInitial( + const StyleResolverState&, + ConversionCheckers& conversion_checkers) const { + base::Optional initial_number = + NumberPropertyFunctions::GetInitialNumber(CssProperty()); + if (!initial_number) + return nullptr; + return CreateNumberValue(*initial_number); +} + +InterpolationValue CSSNumberInterpolationType::MaybeConvertInherit( + const StyleResolverState& state, + ConversionCheckers& conversion_checkers) const { + if (!state.ParentStyle()) + return nullptr; + base::Optional inherited = + NumberPropertyFunctions::GetNumber(CssProperty(), *state.ParentStyle()); + conversion_checkers.push_back( + std::make_unique(CssProperty(), inherited)); + if (!inherited) + return nullptr; + return CreateNumberValue(*inherited); +} + +InterpolationValue CSSNumberInterpolationType::MaybeConvertValue( + const CSSValue& value, + const StyleResolverState*, + ConversionCheckers&) const { + auto* primitive_value = DynamicTo(value); + if (!primitive_value || + !(primitive_value->IsNumber() || primitive_value->IsPercentage())) + return nullptr; + return CreateNumberValue(primitive_value->GetDoubleValue()); +} + +InterpolationValue +CSSNumberInterpolationType::MaybeConvertStandardPropertyUnderlyingValue( + const ComputedStyle& style) const { + base::Optional underlying_number = + NumberPropertyFunctions::GetNumber(CssProperty(), style); + if (!underlying_number) + return nullptr; + return CreateNumberValue(*underlying_number); +} + +void CSSNumberInterpolationType::ApplyStandardPropertyValue( + const InterpolableValue& interpolable_value, + const NonInterpolableValue*, + StyleResolverState& state) const { + double clamped_number = NumberPropertyFunctions::ClampNumber( + CssProperty(), To(interpolable_value).Value()); + if (!NumberPropertyFunctions::SetNumber(CssProperty(), *state.Style(), + clamped_number)) { + StyleBuilder::ApplyProperty( + GetProperty().GetCSSProperty(), state, + *CSSNumericLiteralValue::Create(clamped_number, + CSSPrimitiveValue::UnitType::kNumber)); + } +} + +} // namespace blink diff --git a/pool/shard011/C++/0122098_ruler.cpp b/pool/shard011/C++/0122098_ruler.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0127d7bc9f51d4c1aa627431c0e09520d1272a58 --- /dev/null +++ b/pool/shard011/C++/0122098_ruler.cpp @@ -0,0 +1,255 @@ +#include "drape_frontend/gui/ruler.hpp" + +#include "drape_frontend/animation/show_hide_animation.hpp" +#include "drape_frontend/gui/drape_gui.hpp" +#include "drape_frontend/gui/gui_text.hpp" +#include "drape_frontend/gui/ruler_helper.hpp" +#include "drape_frontend/shader_def.hpp" + +#include "drape/glsl_func.hpp" +#include "drape/glsl_types.hpp" + +#include "std/bind.hpp" + +namespace gui +{ + +namespace +{ + +struct RulerVertex +{ + RulerVertex() = default; + RulerVertex(glsl::vec2 const & pos, glsl::vec2 const & normal, glsl::vec2 const & texCoord) + : m_position(pos) + , m_normal(normal) + , m_texCoord(texCoord) + { + } + + glsl::vec2 m_position; + glsl::vec2 m_normal; + glsl::vec2 m_texCoord; +}; + +dp::BindingInfo GetBindingInfo() +{ + dp::BindingInfo info(3); + uint8_t offset = 0; + offset += dp::FillDecl(0, "a_position", info, offset); + offset += dp::FillDecl(1, "a_normal", info, offset); + offset += dp::FillDecl(2, "a_colorTexCoords", info, offset); + + return info; +} + +template +class BaseRulerHandle : public TBase +{ +public: + BaseRulerHandle(uint32_t id, dp::Anchor anchor, m2::PointF const & pivot, bool isAppearing) + : TBase(id, anchor, pivot) + , m_isAppearing(isAppearing) + , m_isVisibleAtEnd(true) + , m_animation(false, 0.4) + { + } + + bool Update(ScreenBase const & screen) + { + RulerHelper & helper = DrapeGui::GetRulerHelper(); + + TBase::SetIsVisible(true); + bool isVisible = helper.IsVisible(screen); + if (!isVisible) + { + m_animation.HideAnimated(); + m_isVisibleAtEnd = false; + } + else + { + if (helper.IsTextDirty()) + { + m_isAppearing = !m_isAppearing; + if (m_isAppearing) + { + m_animation.ShowAnimated(); + m_isVisibleAtEnd = true; + } + else + { + m_animation.HideAnimated(); + m_isVisibleAtEnd = false; + } + } + } + + bool const result = TBase::Update(screen); + UpdateImpl(screen, helper); + + if (m_animation.IsFinished()) + TBase::SetIsVisible(m_isVisibleAtEnd); + + return result; + } + +protected: + virtual void UpdateImpl(ScreenBase const & /*screen*/, RulerHelper const & /*helper*/) {} + + bool IsAppearing() const { return m_isAppearing; } + float GetOpacity() const { return m_animation.GetT(); } + +private: + bool m_isAppearing; + bool m_isVisibleAtEnd; + df::ShowHideAnimation m_animation; +}; + +class RulerHandle : public BaseRulerHandle +{ + using TBase = BaseRulerHandle; + +public: + RulerHandle(uint32_t id, dp::Anchor anchor, m2::PointF const & pivot, bool appearing) + : TBase(id, anchor, pivot, appearing) + {} + +private: + void UpdateImpl(ScreenBase const & screen, RulerHelper const & helper) override + { + if (IsVisible()) + { + m_size = m2::PointF(helper.GetRulerPixelLength(), 2 * helper.GetRulerHalfHeight()); + if (IsAppearing()) + m_uniforms.SetFloatValue("u_length", helper.GetRulerPixelLength()); + m_uniforms.SetFloatValue("u_position", m_pivot.x, m_pivot.y); + m_uniforms.SetFloatValue("u_opacity", GetOpacity()); + } + } +}; + +class RulerTextHandle : public BaseRulerHandle +{ + using TBase = BaseRulerHandle; + +public: + RulerTextHandle(uint32_t id, dp::Anchor anchor, m2::PointF const & pivot, + bool isAppearing, ref_ptr textures) + : TBase(id, anchor, pivot, isAppearing) + , m_firstUpdate(true) + { + SetTextureManager(textures); + } + + bool Update(ScreenBase const & screen) override + { + SetIsVisible(DrapeGui::GetRulerHelper().IsVisible(screen)); + if (IsVisible() && (DrapeGui::GetRulerHelper().IsTextDirty() || m_firstUpdate)) + { + SetContent(DrapeGui::GetRulerHelper().GetRulerText()); + m_firstUpdate = false; + } + + return TBase::Update(screen); + } + + void SetPivot(glsl::vec2 const & pivot) override + { + RulerHelper & helper = DrapeGui::GetRulerHelper(); + TBase::SetPivot(pivot + glsl::vec2(0.0, helper.GetVerticalTextOffset() - helper.GetRulerHalfHeight())); + } + +protected: + void UpdateImpl(ScreenBase const & /*screen*/, RulerHelper const & /*helper*/) override + { + if (IsVisible()) + m_uniforms.SetFloatValue("u_opacity", GetOpacity()); + } + +private: + bool m_firstUpdate; +}; + +} + +drape_ptr Ruler::Draw(m2::PointF & size, ref_ptr tex) const +{ + ShapeControl control; + size = m2::PointF::Zero(); + DrawRuler(size, control, tex, true); + DrawRuler(size, control, tex, false); + DrawText(size, control, tex, true); + DrawText(size, control, tex, false); + + drape_ptr renderer = make_unique_dp(); + renderer->AddShapeControl(move(control)); + return renderer; +} + +void Ruler::DrawRuler(m2::PointF & size, ShapeControl & control, ref_ptr tex, bool isAppearing) const +{ + buffer_vector data; + + dp::TextureManager::ColorRegion reg; + tex->GetColorRegion(DrapeGui::GetGuiTextFont().m_color, reg); + + glsl::vec2 texCoord = glsl::ToVec2(reg.GetTexRect().Center()); + float h = DrapeGui::GetRulerHelper().GetRulerHalfHeight(); + size += m2::PointF(DrapeGui::GetRulerHelper().GetMaxRulerPixelLength(), 2.0 * h); + + glsl::vec2 normals[] = + { + glsl::vec2(-1.0, 0.0), + glsl::vec2(1.0, 0.0), + }; + + dp::Anchor anchor = m_position.m_anchor; + if (anchor & dp::Left) + normals[0] = glsl::vec2(0.0, 0.0); + else if (anchor & dp::Right) + normals[1] = glsl::vec2(0.0, 0.0); + + data.push_back(RulerVertex(glsl::vec2(0.0, h), normals[0], texCoord)); + data.push_back(RulerVertex(glsl::vec2(0.0, -h), normals[0], texCoord)); + data.push_back(RulerVertex(glsl::vec2(0.0, h), normals[1], texCoord)); + data.push_back(RulerVertex(glsl::vec2(0.0, -h), normals[1], texCoord)); + + auto state = df::CreateGLState(gpu::RULER_PROGRAM, df::RenderState::GuiLayer); + state.SetColorTexture(reg.GetTexture()); + + dp::AttributeProvider provider(1, 4); + provider.InitStream(0, GetBindingInfo(), make_ref(data.data())); + + { + dp::Batcher batcher(dp::Batcher::IndexPerQuad, dp::Batcher::VertexPerQuad); + dp::SessionGuard guard(batcher, bind(&ShapeControl::AddShape, &control, _1, _2)); + batcher.InsertTriangleStrip(state, make_ref(&provider), + make_unique_dp(EGuiHandle::GuiHandleRuler, m_position.m_anchor, + m_position.m_pixelPivot, isAppearing)); + } +} + +void Ruler::DrawText(m2::PointF & size, ShapeControl & control, ref_ptr tex, bool isAppearing) const +{ + string alphabet; + uint32_t maxTextLength; + RulerHelper & helper = DrapeGui::GetRulerHelper(); + helper.GetTextInitInfo(alphabet, maxTextLength); + + MutableLabelDrawer::Params params; + params.m_anchor = + static_cast((m_position.m_anchor & (dp::Right | dp::Left)) | dp::Bottom); + params.m_alphabet = alphabet; + params.m_maxLength = maxTextLength; + params.m_font = DrapeGui::GetGuiTextFont(); + params.m_pivot = m_position.m_pixelPivot + m2::PointF(0.0, helper.GetVerticalTextOffset()); + params.m_handleCreator = [isAppearing, tex](dp::Anchor anchor, m2::PointF const & pivot) + { + return make_unique_dp(EGuiHandle::GuiHandleRulerLabel, anchor, pivot, isAppearing, tex); + }; + + m2::PointF textSize = MutableLabelDrawer::Draw(params, tex, bind(&ShapeControl::AddShape, &control, _1, _2)); + size.y += (textSize.y + abs(helper.GetVerticalTextOffset())); +} + +} diff --git a/pool/shard011/C++/0122099_drm_framebuffer.cc b/pool/shard011/C++/0122099_drm_framebuffer.cc new file mode 100644 index 0000000000000000000000000000000000000000..772786b42ed5c36bb0be1e53c02885764155f179 --- /dev/null +++ b/pool/shard011/C++/0122099_drm_framebuffer.cc @@ -0,0 +1,125 @@ +// Copyright 2018 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/ozone/platform/drm/gpu/drm_framebuffer.h" + +#include + +#include "ui/gfx/buffer_format_util.h" +#include "ui/gfx/linux/drm_util_linux.h" +#include "ui/gfx/linux/gbm_buffer.h" +#include "ui/ozone/platform/drm/common/drm_util.h" +#include "ui/ozone/platform/drm/gpu/drm_device.h" + +namespace ui { + +DrmFramebuffer::AddFramebufferParams::AddFramebufferParams() = default; +DrmFramebuffer::AddFramebufferParams::AddFramebufferParams( + const AddFramebufferParams& other) = default; +DrmFramebuffer::AddFramebufferParams::~AddFramebufferParams() = default; + +// static +scoped_refptr DrmFramebuffer::AddFramebuffer( + scoped_refptr drm_device, + DrmFramebuffer::AddFramebufferParams params) { + uint64_t modifiers[4] = {0}; + if (params.modifier != DRM_FORMAT_MOD_INVALID) { + for (size_t i = 0; i < params.num_planes; ++i) + modifiers[i] = params.modifier; + } + + const auto fourcc_format = GetBufferFormatFromFourCCFormat(params.format); + const uint32_t opaque_format = + GetFourCCFormatForOpaqueFramebuffer(fourcc_format); + // Intel Display Controller won't support AR/B30 framebuffers, only XR/B30, + // but that doesn't matter because anyway those two bits of alpha are useless; + // use the opaque directly in this case. + const bool force_opaque = AlphaBitsForBufferFormat(fourcc_format) == 2; + + const auto drm_format = force_opaque ? opaque_format : params.format; + + uint32_t framebuffer_id = 0; + if (!drm_device->AddFramebuffer2(params.width, params.height, drm_format, + params.handles, params.strides, + params.offsets, modifiers, &framebuffer_id, + params.flags)) { + DPLOG(WARNING) << "AddFramebuffer2"; + return nullptr; + } + + uint32_t opaque_framebuffer_id = 0; + if (opaque_format != drm_format && + !drm_device->AddFramebuffer2(params.width, params.height, opaque_format, + params.handles, params.strides, + params.offsets, modifiers, + &opaque_framebuffer_id, params.flags)) { + DPLOG(WARNING) << "AddFramebuffer2"; + drm_device->RemoveFramebuffer(framebuffer_id); + return nullptr; + } + + return base::MakeRefCounted( + std::move(drm_device), framebuffer_id, drm_format, opaque_framebuffer_id, + opaque_format, params.modifier, params.preferred_modifiers, + gfx::Size(params.width, params.height)); +} + +// static +scoped_refptr DrmFramebuffer::AddFramebuffer( + scoped_refptr drm, + const GbmBuffer* buffer, + const gfx::Size& framebuffer_size, + std::vector preferred_modifiers) { + DCHECK(gfx::Rect(buffer->GetSize()).Contains(gfx::Rect(framebuffer_size))); + AddFramebufferParams params; + params.format = buffer->GetFormat(); + params.modifier = buffer->GetFormatModifier(); + params.width = framebuffer_size.width(); + params.height = framebuffer_size.height(); + params.num_planes = buffer->GetNumPlanes(); + params.preferred_modifiers = preferred_modifiers; + for (size_t i = 0; i < params.num_planes; ++i) { + params.handles[i] = buffer->GetPlaneHandle(i); + params.strides[i] = buffer->GetPlaneStride(i); + params.offsets[i] = buffer->GetPlaneOffset(i); + } + + // AddFramebuffer2 only considers the modifiers if addfb_flags has + // DRM_MODE_FB_MODIFIERS set. We only set that when we've created + // a bo with modifiers, otherwise, we rely on the "no modifiers" + // behavior doing the right thing. + params.flags = 0; + if (drm->allow_addfb2_modifiers() && + params.modifier != DRM_FORMAT_MOD_INVALID) + params.flags |= DRM_MODE_FB_MODIFIERS; + + return AddFramebuffer(std::move(drm), params); +} + +DrmFramebuffer::DrmFramebuffer(scoped_refptr drm_device, + uint32_t framebuffer_id, + uint32_t framebuffer_pixel_format, + uint32_t opaque_framebuffer_id, + uint32_t opaque_framebuffer_pixel_format, + uint64_t format_modifier, + std::vector modifiers, + const gfx::Size& size) + : drm_device_(std::move(drm_device)), + framebuffer_id_(framebuffer_id), + framebuffer_pixel_format_(framebuffer_pixel_format), + opaque_framebuffer_id_(opaque_framebuffer_id), + opaque_framebuffer_pixel_format_(opaque_framebuffer_pixel_format), + format_modifier_(format_modifier), + preferred_modifiers_(modifiers), + size_(size) {} + +DrmFramebuffer::~DrmFramebuffer() { + if (!drm_device_->RemoveFramebuffer(framebuffer_id_)) + PLOG(WARNING) << "RemoveFramebuffer"; + if (opaque_framebuffer_id_ && + !drm_device_->RemoveFramebuffer(opaque_framebuffer_id_)) + PLOG(WARNING) << "RemoveFramebuffer"; +} + +} // namespace ui diff --git a/pool/shard011/C++/0122100_ConditionMonitorGlideTerrain.cpp b/pool/shard011/C++/0122100_ConditionMonitorGlideTerrain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9543abe4c5e46b44e79c057282d6b6a1f367169b --- /dev/null +++ b/pool/shard011/C++/0122100_ConditionMonitorGlideTerrain.cpp @@ -0,0 +1,50 @@ +/* +Copyright_License { + + XCSoar Glide Computer - http://www.xcsoar.org/ + Copyright (C) 2000-2021 The XCSoar Project + A detailed list of copyright holders can be found in the file "AUTHORS". + + This program is free software; you can redistribute it and/or + modify it under the terms of the GNU General Public License + as published by the Free Software Foundation; either version 2 + of the License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. +} + +*/ + +#include "ConditionMonitorGlideTerrain.hpp" +#include "NMEA/Derived.hpp" +#include "Input/InputQueue.hpp" + +bool +ConditionMonitorGlideTerrain::CheckCondition(const NMEAInfo &basic, + const DerivedInfo &calculated, + const ComputerSettings &settings) +{ + if (!calculated.flight.flying || + !calculated.task_stats.task_valid) + return false; + + const GlideResult& res = calculated.task_stats.total.solution_remaining; + if (!res.IsFinalGlide()) + // only give message about terrain warnings if above final glide + return false; + + return calculated.terrain_warning_location.IsValid(); +} + +void +ConditionMonitorGlideTerrain::Notify() +{ + InputEvents::processGlideComputer(GCE_FLIGHTMODE_FINALGLIDE_TERRAIN); +} diff --git a/pool/shard011/C++/0122101_example-stream-CFilterLineEnd.cpp b/pool/shard011/C++/0122101_example-stream-CFilterLineEnd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5dd9b54d3cdf3b3504e0eaeaeb07913c957bb8db --- /dev/null +++ b/pool/shard011/C++/0122101_example-stream-CFilterLineEnd.cpp @@ -0,0 +1,87 @@ +/*! + * \file example-stream-CFilterLineEnd.cpp Example of using the + * CFilterLineEnd class. + * \brief Example of using the CFilterLineEnd class. + * \author Ivan Shynkarenka aka 4ekucT + * \version 1.0 + * \date 17.11.2009 + */ +/*==========================================================================*/ +/* + FILE DESCRIPTION: Example of using the CFilterLineEnd class. + + AUTHOR: Ivan Shynkarenka aka 4ekucT + GROUP: The NULL workgroup + PROJECT: The Depth + PART: Depth stream examples + VERSION: 1.0 + CREATED: 17.11.2009 01:10:45 + + EMAIL: chronoxor@gmail.com + WWW: http://code.google.com/p/depth + + COPYRIGHT: (C) 2005-2010 The NULL workgroup. All Rights Reserved. +*/ +/*--------------------------------------------------------------------------*/ +/* + Copyright (C) 2005-2010 The NULL workgroup. + + This program is free software; you can redistribute it and/or modify it + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., 59 + Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ +/*--------------------------------------------------------------------------*/ +/* + FILE ID: $Id$ + + CHANGE LOG: + + $Log$ +*/ +/*==========================================================================*/ +// Common headers. +#include +#include +#include +/*==========================================================================*/ +// Common namespaces. +using namespace NDepth; +using namespace NDepth::NApplication; +using namespace NDepth::NContainers; +using namespace NDepth::NStream; +using namespace NDepth::NStream::NText; +using namespace NDepth::NString; +/*==========================================================================*/ +class CExample : + public NApplication::IApplication +{ + Tsint main(const CStringBuffer& a_crArguments, const CStringBuffer& a_crEnvironment) + { CALL + IGNORE_UNUSED(a_crArguments); + IGNORE_UNUSED(a_crEnvironment); + + // Use standard output stream of the current process. + CStreamStdOutput stdoutput; + + // Link standard output stream with LineEnd filter. + CFilterLineEnd filter(&stdoutput, 0, 1, stdoutput.isTextMode(), stdoutput.getByteOrder(), stdoutput.getLineEnding()); + + // Write a string into the last filter. + filter.open(IStream::e_OPEN_WRITE); + filter << ASC("Hello world!"); + filter.close(); + + return IApplication::EXIT_WITH_SUCCESS; + } +} the_Application; +/*==========================================================================*/ diff --git a/pool/shard011/C++/0122104_ctkPushButtonTest.cpp b/pool/shard011/C++/0122104_ctkPushButtonTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c313d2a876334ae07df549b8ea7b8df80300f3ec --- /dev/null +++ b/pool/shard011/C++/0122104_ctkPushButtonTest.cpp @@ -0,0 +1,68 @@ +/*========================================================================= + + Library: CTK + + Copyright (c) Kitware 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.txt + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +=========================================================================*/ + +// Qt includes +#include +#include +#include +#include + +#if (QT_VERSION < 0x50000) +#include +#endif + +// CTK includes +#include "ctkPushButton.h" +#include "ctkTest.h" + +//----------------------------------------------------------------------------- +class ctkPushButtonTester : public QObject +{ + Q_OBJECT + +private slots: + + void testDefaults(); +}; + +// ---------------------------------------------------------------------------- +void ctkPushButtonTester::testDefaults() +{ +#if (QT_VERSION < 0x50000) + QApplication::setStyle( new QCleanlooksStyle ); +#endif + + ctkPushButton button("text"); + + QCOMPARE(button.buttonTextAlignment(), Qt::AlignHCenter|Qt::AlignVCenter); + QCOMPARE(button.iconAlignment(), Qt::AlignLeft|Qt::AlignVCenter); + + button.show(); +#if (QT_VERSION >= 0x50000) + QTest::qWaitForWindowActive(&button); +#else + QTest::qWaitForWindowShown(&button); +#endif + //qApp->exec(); +} + +// ---------------------------------------------------------------------------- +CTK_TEST_MAIN(ctkPushButtonTest) +#include "moc_ctkPushButtonTest.cpp" diff --git a/pool/shard011/C++/0122107_EventQueue.cpp b/pool/shard011/C++/0122107_EventQueue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7d2c6f88d08a7bcfb951ddc98bdfa4a958642024 --- /dev/null +++ b/pool/shard011/C++/0122107_EventQueue.cpp @@ -0,0 +1,96 @@ +#include "EventQueue.hpp" +#include "EventSource.hpp" +#include "Event.hpp" +#include + +namespace alcpp +{ + +EventQueue::EventQueue() +{ + queue = al_create_event_queue(); + if (!queue) { + throw std::runtime_error("Failed to create event queue"); + } +} + +EventQueue::~EventQueue() +{ + al_destroy_event_queue(queue); +} + +void EventQueue::Register(EventSource eventSource) +{ + al_register_event_source(queue, eventSource.GetPtr()); +} + +void EventQueue::Unregister(EventSource eventSource) +{ + al_unregister_event_source(queue, eventSource.GetPtr()); +} + +void EventQueue::Pause() +{ + al_pause_event_queue(queue, true); +} + +void EventQueue::Resume() +{ + al_pause_event_queue(queue, false); +} + +bool EventQueue::IsPaused() const +{ + return al_is_event_queue_paused(queue); +} + +bool EventQueue::IsEmpty() const +{ + return al_is_event_queue_empty(queue); +} + +void EventQueue::Flush() +{ + al_flush_event_queue(queue); +} + +Event EventQueue::GetNextEvent() +{ + ALLEGRO_EVENT event; + if (al_get_next_event(queue, &event)) { + return Event(event); + } + return Event(); +} + +Event EventQueue::PeekNextEvent() +{ + ALLEGRO_EVENT event; + if (al_peek_next_event(queue, &event)) { + return Event(event); + } + return Event(); +} + +bool EventQueue::DropNextEvent() +{ + return al_drop_next_event(queue); +} + +Event EventQueue::WaitForEvent() +{ + ALLEGRO_EVENT event; + al_wait_for_event(queue, &event); + return Event(event); +} + +Event EventQueue::WaitForEvent(float seconds) +{ + ALLEGRO_EVENT event; + if (al_wait_for_event_timed(queue, &event, seconds)) { + return Event(event); + } + return Event(); +} + +} \ No newline at end of file diff --git a/pool/shard011/C++/0122109_tst_qmetadatareadercontrol.cpp b/pool/shard011/C++/0122109_tst_qmetadatareadercontrol.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2aeaafa7d646381ee50619b3ef8075185add348a --- /dev/null +++ b/pool/shard011/C++/0122109_tst_qmetadatareadercontrol.cpp @@ -0,0 +1,143 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include +#include +#include + +#include "mockmetadatareadercontrol.h" + +class tst_QMetaDataReaderControl : public QObject +{ + Q_OBJECT + +private slots: + // Test case for QMetaDataReaderControl + void metaDataReaderControlConstructor(); + void metaDataReaderControlAvailableMetaData(); + void metaDataReaderControlExtendedMetaData(); + void metaDataReaderControlIsMetaDataAvailable(); + void metaDataReaderControlMetaData(); + void metaDataReaderControlAvailableExtendedMetaData(); + void metaDataReaderControlMetaDataAvailableChangedSignal(); + void metaDataReaderControlMetaDataChangedSignal(); +}; + +QTEST_MAIN(tst_QMetaDataReaderControl); + +/* Test case for constructor. */ +void tst_QMetaDataReaderControl::metaDataReaderControlConstructor() +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + delete metaData; +} + +/* Test case for availableMetaData() */ +void tst_QMetaDataReaderControl::metaDataReaderControlAvailableMetaData() +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + metaData->availableMetaData() ; + delete metaData; +} + +/* Test case for extendedMetaData */ +void tst_QMetaDataReaderControl::metaDataReaderControlExtendedMetaData () +{ + const QString titleKey(QLatin1String("Title")); + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + metaData->extendedMetaData(titleKey); + delete metaData; +} + +/* Test case for availableMetaData */ +void tst_QMetaDataReaderControl::metaDataReaderControlIsMetaDataAvailable () +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + metaData->availableMetaData(); + delete metaData; +} + +/* Test case for metaData */ +void tst_QMetaDataReaderControl::metaDataReaderControlMetaData () +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + metaData->metaData(QtMultimediaKit::Title); + delete metaData; +} + +/* Test case for availableExtendedMetaData */ +void tst_QMetaDataReaderControl::metaDataReaderControlAvailableExtendedMetaData () +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + metaData->availableExtendedMetaData(); + delete metaData; +} + +/* Test case for signal metaDataAvailableChanged */ +void tst_QMetaDataReaderControl::metaDataReaderControlMetaDataAvailableChangedSignal () +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + QSignalSpy spy(metaData,SIGNAL(metaDataAvailableChanged(bool))); + metaData->setMetaDataAvailable(true); + QVERIFY(spy.count() == 1); + delete metaData; +} + + /* Test case for signal metaDataChanged */ +void tst_QMetaDataReaderControl::metaDataReaderControlMetaDataChangedSignal () +{ + MockMetaDataReaderControl *metaData = new MockMetaDataReaderControl(); + QVERIFY(metaData !=NULL); + QSignalSpy spy(metaData,SIGNAL(metaDataChanged())); + metaData->metaDataChanged(); + QVERIFY(spy.count () == 1); + delete metaData; +} + +#include "tst_qmetadatareadercontrol.moc" + + diff --git a/pool/shard011/C++/0122112_CharacterData.cpp b/pool/shard011/C++/0122112_CharacterData.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31f0d5fa51e987e569084afebeac9ed81f51251e --- /dev/null +++ b/pool/shard011/C++/0122112_CharacterData.cpp @@ -0,0 +1,257 @@ +/* + * Copyright (C) 1999 Lars Knoll (knoll@kde.org) + * (C) 1999 Antti Koivisto (koivisto@kde.org) + * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "config.h" +#include "CharacterData.h" + +#include "ElementTraversal.h" +#include "ExceptionCode.h" +#include "FrameSelection.h" +#include "InspectorInstrumentation.h" +#include "MutationEvent.h" +#include "MutationObserverInterestGroup.h" +#include "MutationRecord.h" +#include "ProcessingInstruction.h" +#include "RenderText.h" +#include "StyleInheritedData.h" +#include "TextBreakIterator.h" +#include + +namespace WebCore { + +void CharacterData::setData(const String& data, ExceptionCode&) +{ + const String& nonNullData = !data.isNull() ? data : emptyString(); + if (m_data == nonNullData) + return; + + Ref protect(*this); + + unsigned oldLength = length(); + + setDataAndUpdate(nonNullData, 0, oldLength, nonNullData.length()); + document().textRemoved(this, 0, oldLength); +} + +String CharacterData::substringData(unsigned offset, unsigned count, ExceptionCode& ec) +{ + checkCharDataOperation(offset, ec); + if (ec) + return String(); + + return m_data.substring(offset, count); +} + +unsigned CharacterData::parserAppendData(const String& string, unsigned offset, unsigned lengthLimit) +{ + unsigned oldLength = m_data.length(); + + ASSERT(lengthLimit >= oldLength); + + unsigned characterLength = string.length() - offset; + unsigned characterLengthLimit = std::min(characterLength, lengthLimit - oldLength); + + // Check that we are not on an unbreakable boundary. + // Some text break iterator implementations work best if the passed buffer is as small as possible, + // see . + // We need at least two characters look-ahead to account for UTF-16 surrogates. + if (characterLengthLimit < characterLength) { + NonSharedCharacterBreakIterator it(StringView(string).substring(offset, (characterLengthLimit + 2 > characterLength) ? characterLength : characterLengthLimit + 2)); + if (!isTextBreak(it, characterLengthLimit)) + characterLengthLimit = textBreakPreceding(it, characterLengthLimit); + } + + if (!characterLengthLimit) + return 0; + + if (string.is8Bit()) + m_data.append(string.characters8() + offset, characterLengthLimit); + else + m_data.append(string.characters16() + offset, characterLengthLimit); + + ASSERT(!renderer() || isTextNode()); + if (isTextNode()) + Style::updateTextRendererAfterContentChange(*toText(this), oldLength, 0); + + document().incDOMTreeVersion(); + // We don't call dispatchModifiedEvent here because we don't want the + // parser to dispatch DOM mutation events. + if (parentNode()) { + ContainerNode::ChildChange change = { + ContainerNode::TextChanged, + ElementTraversal::previousSibling(this), + ElementTraversal::nextSibling(this), + ContainerNode::ChildChangeSourceParser + }; + parentNode()->childrenChanged(change); + } + + return characterLengthLimit; +} + +void CharacterData::appendData(const String& data, ExceptionCode&) +{ + String newStr = m_data; + newStr.append(data); + + setDataAndUpdate(newStr, m_data.length(), 0, data.length()); + + // FIXME: Should we call textInserted here? +} + +void CharacterData::insertData(unsigned offset, const String& data, ExceptionCode& ec) +{ + checkCharDataOperation(offset, ec); + if (ec) + return; + + String newStr = m_data; + newStr.insert(data, offset); + + setDataAndUpdate(newStr, offset, 0, data.length()); + + document().textInserted(this, offset, data.length()); +} + +void CharacterData::deleteData(unsigned offset, unsigned count, ExceptionCode& ec) +{ + checkCharDataOperation(offset, ec); + if (ec) + return; + + unsigned realCount; + if (offset + count > length()) + realCount = length() - offset; + else + realCount = count; + + String newStr = m_data; + newStr.remove(offset, realCount); + + setDataAndUpdate(newStr, offset, count, 0); + + document().textRemoved(this, offset, realCount); +} + +void CharacterData::replaceData(unsigned offset, unsigned count, const String& data, ExceptionCode& ec) +{ + checkCharDataOperation(offset, ec); + if (ec) + return; + + unsigned realCount; + if (offset + count > length()) + realCount = length() - offset; + else + realCount = count; + + String newStr = m_data; + newStr.remove(offset, realCount); + newStr.insert(data, offset); + + setDataAndUpdate(newStr, offset, count, data.length()); + + // update the markers for spell checking and grammar checking + document().textRemoved(this, offset, realCount); + document().textInserted(this, offset, data.length()); +} + +String CharacterData::nodeValue() const +{ + return m_data; +} + +bool CharacterData::containsOnlyWhitespace() const +{ + return m_data.containsOnlyWhitespace(); +} + +void CharacterData::setNodeValue(const String& nodeValue, ExceptionCode& ec) +{ + setData(nodeValue, ec); +} + +void CharacterData::setDataAndUpdate(const String& newData, unsigned offsetOfReplacedData, unsigned oldLength, unsigned newLength) +{ + String oldData = m_data; + m_data = newData; + + ASSERT(!renderer() || isTextNode()); + if (isTextNode()) + Style::updateTextRendererAfterContentChange(*toText(this), offsetOfReplacedData, oldLength); + + if (nodeType() == PROCESSING_INSTRUCTION_NODE) + toProcessingInstruction(this)->checkStyleSheet(); + + if (document().frame()) + document().frame()->selection().textWasReplaced(this, offsetOfReplacedData, oldLength, newLength); + + document().incDOMTreeVersion(); + dispatchModifiedEvent(oldData); +} + +void CharacterData::dispatchModifiedEvent(const String& oldData) +{ + if (std::unique_ptr mutationRecipients = MutationObserverInterestGroup::createForCharacterDataMutation(*this)) + mutationRecipients->enqueueMutationRecord(MutationRecord::createCharacterData(*this, oldData)); + + if (!isInShadowTree()) { + if (parentNode()) { + ContainerNode::ChildChange change = { + ContainerNode::TextChanged, + ElementTraversal::previousSibling(this), + ElementTraversal::nextSibling(this), + ContainerNode::ChildChangeSourceAPI + }; + parentNode()->childrenChanged(change); + } + if (document().hasListenerType(Document::DOMCHARACTERDATAMODIFIED_LISTENER)) + dispatchScopedEvent(MutationEvent::create(eventNames().DOMCharacterDataModifiedEvent, true, 0, oldData, m_data)); + dispatchSubtreeModifiedEvent(); + } +#if ENABLE(INSPECTOR) + InspectorInstrumentation::characterDataModified(&document(), this); +#endif +} + +void CharacterData::checkCharDataOperation(unsigned offset, ExceptionCode& ec) +{ + ec = 0; + + // INDEX_SIZE_ERR: Raised if the specified offset is negative or greater than the number of 16-bit + // units in data. + if (offset > length()) { + ec = INDEX_SIZE_ERR; + return; + } +} + +int CharacterData::maxCharacterOffset() const +{ + return static_cast(length()); +} + +bool CharacterData::offsetInCharacters() const +{ + return true; +} + +} // namespace WebCore diff --git a/pool/shard011/C++/0122113_room.cpp b/pool/shard011/C++/0122113_room.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ace5d5b1b72ad3c75d70fdc3715b2c0ee5fe189f --- /dev/null +++ b/pool/shard011/C++/0122113_room.cpp @@ -0,0 +1,86 @@ +#include "room.h" +#include +#include "creature.h" + +using namespace std; + +Room::Room(const char* name, const char* description) : Entity(name, description, nullptr) +{ + Type = ROOM; +} + +Room::~Room() +{ +} + +void Room::Look() const +{ + cout << Name << endl << Description << endl; + + list entities; + FindAll(ITEM, entities); + + if (entities.size() > 0) + { + cout << "Items here:" << endl; + for (Entity* entity : entities) + { + cout << " - " << entity->Name << endl; + } + } + + entities.clear(); + FindAll(CREATURE, entities); + + if (entities.size() > 0) + { + cout << "You are not alone:" << endl; + for (Entity* entity : entities) + { + cout << " - " << entity->Name; + if (!((Creature*)entity)->IsAlive()) + { + cout << " (dead)"; + } + + cout << endl; + } + } + + entities.clear(); + FindAll(EXIT, entities); + + if (entities.size() > 0) + { + cout << "Exits here:" << endl; + for (Entity* entity : entities) + { + Exit* exit = (Exit*)entity; + cout << " - Direction " << exit->GetExitDirectionFrom(this) << " you go to " << exit->GetExitDestinationFrom(this)->Name; + if (exit->Locked) + { + cout << " (locked)"; + } + else if (exit->Closed) + { + cout << " (closed)"; + } + cout << endl; + } + } + + cout << endl; +} + +Exit* Room::GetExitAt(const string& direction) +{ + for (Entity* entity : SubEntities) + { + if (entity-> Type == EXIT && ((Exit*)entity)->GetExitDirectionFrom(this) == direction) + { + return (Exit*)entity; + } + } + + return nullptr; +} diff --git a/pool/shard011/C++/0122117_RemoveSourceIdentifierFromSubscriptionResult.cpp b/pool/shard011/C++/0122117_RemoveSourceIdentifierFromSubscriptionResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78c3844ccae1bdfa5e2499d756ac34c155056f35 --- /dev/null +++ b/pool/shard011/C++/0122117_RemoveSourceIdentifierFromSubscriptionResult.cpp @@ -0,0 +1,64 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::RDS::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +RemoveSourceIdentifierFromSubscriptionResult::RemoveSourceIdentifierFromSubscriptionResult() +{ +} + +RemoveSourceIdentifierFromSubscriptionResult::RemoveSourceIdentifierFromSubscriptionResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +RemoveSourceIdentifierFromSubscriptionResult& RemoveSourceIdentifierFromSubscriptionResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (!rootNode.IsNull() && (rootNode.GetName() != "RemoveSourceIdentifierFromSubscriptionResult")) + { + resultNode = rootNode.FirstChild("RemoveSourceIdentifierFromSubscriptionResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode eventSubscriptionNode = resultNode.FirstChild("EventSubscription"); + if(!eventSubscriptionNode.IsNull()) + { + m_eventSubscription = eventSubscriptionNode; + } + } + + if (!rootNode.IsNull()) { + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::RDS::Model::RemoveSourceIdentifierFromSubscriptionResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + } + return *this; +} diff --git a/pool/shard011/C++/0122118_settings.cpp b/pool/shard011/C++/0122118_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7a3f200fc8c715b955c8dd60b78bc4a0b807367d --- /dev/null +++ b/pool/shard011/C++/0122118_settings.cpp @@ -0,0 +1,119 @@ +/* + PsychoPlug + ESP8266 based remote outlet with standalone timer and MQTT integration + + Copyright (C) 2017 Earle F. Philhower, III + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include "settings.h" +#include "password.h" +#include "log.h" + +static byte CalcSettingsChecksum(); + +Settings settings; + + +void StartSettings() +{ + EEPROM.begin(sizeof(settings)+2); +} + +void StopSettings() +{ + EEPROM.commit(); + EEPROM.end(); +} + +bool LoadSettings(bool reset) +{ + bool ok = false; + + StartSettings(); + + // Try and read from "EEPROM", if that fails use defaults + byte *p = (byte *)&settings; + for (unsigned int i=0; i + +#include + +#include "pybind11/pybind11.h" +#include "tensorflow/c/eager/abstract_context.h" +#include "tensorflow/c/eager/abstract_function.h" +#include "tensorflow/c/eager/abstract_operation.h" +#include "tensorflow/c/eager/abstract_tensor_handle.h" +#include "tensorflow/c/eager/c_api.h" +#include "tensorflow/c/eager/c_api_internal.h" +#include "tensorflow/c/eager/c_api_unified_experimental.h" +#include "tensorflow/c/eager/c_api_unified_experimental_internal.h" +#include "tensorflow/c/eager/immediate_execution_context.h" +#include "tensorflow/c/eager/immediate_execution_tensor_handle.h" +#include "tensorflow/c/eager/tfe_context_internal.h" +#include "tensorflow/c/eager/tfe_tensorhandle_internal.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/llvm_rtti/llvm_rtti.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/python/eager/pywrap_tensor.h" +#include "tensorflow/python/lib/core/pybind11_lib.h" +#include "tensorflow/python/lib/core/pybind11_status.h" +#include "tensorflow/python/lib/core/safe_ptr.h" + +namespace py = pybind11; + +using tensorflow::AbstractContext; +using tensorflow::AbstractContextPtr; +using tensorflow::AbstractFunction; +using tensorflow::AbstractOperation; +using tensorflow::AbstractOperationPtr; +using tensorflow::AbstractTensorHandle; +using tensorflow::AbstractTensorHandlePtr; +using tensorflow::OutputList; + +using tensorflow::tracing::TracingContext; +using tensorflow::tracing::TracingOperation; +using tensorflow::tracing::TracingTensorHandle; + +using tensorflow::ImmediateContextPtr; +using tensorflow::ImmediateExecutionContext; +using tensorflow::ImmediateExecutionTensorHandle; + +using tensorflow::dyn_cast; +using tensorflow::isa; +using tensorflow::unwrap; +using tensorflow::wrap; + +using tensorflow::DataType; +using tensorflow::make_safe; +using tensorflow::MaybeRaiseRegisteredFromStatus; +using tensorflow::MaybeRaiseRegisteredFromTFStatus; +using tensorflow::Pyo; +using tensorflow::Safe_TF_StatusPtr; +using tensorflow::Status; +using tensorflow::string; +using tensorflow::TFE_TensorHandleToNumpy; +using tensorflow::core::RefCountPtr; + +using tensorflow::errors::Internal; +using tensorflow::errors::InvalidArgument; + +PYBIND11_MODULE(_unified_api, m) { + // Context creation functions. + m.def("SetTracingImplementation", [](const char* impl) { + Safe_TF_StatusPtr status = make_safe(TF_NewStatus()); + TF_SetTracingImplementation(impl, status.get()); + MaybeRaiseRegisteredFromStatus(status->status); + }); + m.def("NewTracingContext", [](const char* fn_name) { + Safe_TF_StatusPtr status = make_safe(TF_NewStatus()); + auto* ctx = unwrap(TF_CreateFunction(fn_name, status.get())); + MaybeRaiseRegisteredFromTFStatus(status.get()); + if (!ctx) { + MaybeRaiseRegisteredFromStatus( + Internal("TF_CreateFunction returned nullptr")); + } + if (!isa(ctx)) { + // TODO(srbs): Add a helper to convert the kind enum to a user-friendly + // string. + MaybeRaiseRegisteredFromStatus( + Internal("TF_CreateFunction must return a TracingContext, found ", + ctx->getKind())); + } + return dyn_cast(ctx); + }); + m.def("EagerContextToImmediateExecutionContext", [](py::handle& obj) { + TFE_Context* ctx = + static_cast(PyCapsule_GetPointer(obj.ptr(), nullptr)); + if (!ctx) { + MaybeRaiseRegisteredFromStatus(InvalidArgument("TFE_Context is nullptr")); + } + return unwrap(ctx); + }); + + // Unified execution context. + py::class_(m, "AbstractContext") + .def("CreateOperation", + [](AbstractContext* self, const char* op, + const char* raw_device_name) { + auto operation = self->CreateOperation(); + operation->Reset(op, raw_device_name); + return operation; + }) + .def("RegisterFunction", + [](AbstractContext* self, AbstractFunction* f) { + Status s = self->RegisterFunction(f); + MaybeRaiseRegisteredFromStatus(s); + }) + .def("RemoveFunction", [](AbstractContext* self, const string& func) { + Status s = self->RemoveFunction(func); + MaybeRaiseRegisteredFromStatus(s); + }); + + py::class_(m, "TracingContext") + .def("AddParameter", + [](TracingContext* self, DataType dtype) { + TracingTensorHandle* handle = nullptr; + // TODO(srbs): Add shape argument to this function. + tensorflow::PartialTensorShape shape; + Status s = self->AddParameter(dtype, shape, &handle); + MaybeRaiseRegisteredFromStatus(s); + return static_cast(handle); + }) + .def("Finalize", [](TracingContext* self, py::handle& outputs) { + // TODO(srbs): Using OutputList seems like an overkill here. Should we + // simply pass in an absl::Span? + OutputList output_list; + if (outputs.ptr() != Py_None) { + if (!PyList_Check(outputs.ptr())) { + MaybeRaiseRegisteredFromStatus( + InvalidArgument("must provide a list of Tensors as inputs")); + } + Py_ssize_t len = PyList_Size(outputs.ptr()); + output_list.outputs.resize(len); + for (Py_ssize_t i = 0; i < len; ++i) { + PyObject* elem = PyList_GetItem(outputs.ptr(), i); + if (!elem) { + MaybeRaiseRegisteredFromStatus( + InvalidArgument("Tensor at index ", i, " is None.")); + } + py::handle elem_h = elem; + AbstractTensorHandle* handle = elem_h.cast(); + if (!isa(handle)) { + MaybeRaiseRegisteredFromStatus(InvalidArgument( + "Tensor at index ", i, " is not a graph tensor.")); + } + output_list.outputs[i] = handle; + } + } + AbstractFunction* f = nullptr; + Status s = self->Finalize(&output_list, &f); + MaybeRaiseRegisteredFromStatus(s); + return f; + }); + + // Note: This does not take ownership of the C++ context, the lifetime of + // which is managed by the python `Context` and is expected to outlive this + // object. + // TODO(srbs): Make AbstractContext refcounted so that the above comment is + // not needed. + py::class_> + ImmediateExecutionContext(m, "ImmediateExecutionContext"); + + // Unified execution operation. + py::class_(m, "AbstractOperation") + .def("Reset", + [](AbstractOperation* self, const char* op, + const char* raw_device_name) { + Status s = self->Reset(op, raw_device_name); + MaybeRaiseRegisteredFromStatus(s); + }) + .def("SetOpName", + [](AbstractOperation* self, const char* op_name) { + // TODO(srbs): We could provide SetOpName on TracingOperation + // but then we need to do a hasattr check or try/pass in python. + if (isa(self)) { + auto tracing_op = reinterpret_cast(self); + Status s = tracing_op->SetOpName(op_name); + MaybeRaiseRegisteredFromStatus(s); + } + }) + .def("Name", &AbstractOperation::Name) + .def("DeviceName", &AbstractOperation::DeviceName) + .def("SetDeviceName", + [](AbstractOperation* self, const char* name) { + Status s = self->SetDeviceName(name); + MaybeRaiseRegisteredFromStatus(s); + }) + .def("AddInput", + [](AbstractOperation* self, AbstractTensorHandle* input) { + Status s = self->AddInput(input); + MaybeRaiseRegisteredFromStatus(s); + }) + .def("SetAttrType", + [](AbstractOperation* self, const char* attr_name, DataType value) { + Status s = self->SetAttrType(attr_name, value); + MaybeRaiseRegisteredFromStatus(s); + }) + .def("Execute", [](AbstractOperation* self, int num_outputs) { + std::vector outputs(num_outputs); + MaybeRaiseRegisteredFromStatus( + self->Execute(absl::MakeSpan(outputs), &num_outputs)); + return outputs; + }); + + // Unified execution tensor handle. + py::class_( + m, "AbstractTensorHandle") + .def("DataType", &AbstractTensorHandle::DataType) + .def("numpy", [](AbstractTensorHandle* self) { + // TODO(srbs): Export this on ImmediateExecutionTensorHandle only. + if (!isa(self)) { + // TODO(srbs): Add a helper to convert the kind enum to a + // user-friendly string. + MaybeRaiseRegisteredFromStatus(Internal( + "AbstractTensorHandle.numpy() must be called with an ", + "ImmediateExecutionTensorHandle found type: ", self->getKind())); + } + TF_Status s; + TFE_TensorHandle* handle = + wrap(dyn_cast(self)); + auto result = TFE_TensorHandleToNumpy(handle, &s); + MaybeRaiseRegisteredFromStatus(s.status); + return Pyo(result); + }); + + m.def("EagerTensorToImmediateExecutionTensorHandle", [](py::object handle) { + if (!EagerTensor_CheckExact(handle.ptr())) { + MaybeRaiseRegisteredFromStatus( + InvalidArgument("EagerTensorToImmediateExecutionTensorHandle called " + "with non-EagerTensor.")); + } + TFE_TensorHandle* eager_tensor = EagerTensor_Handle(handle.ptr()); + auto t = static_cast(unwrap(eager_tensor)); + t->Ref(); + return t; + }); + + py::class_> AbstractFunction( + m, "AbstractFunction"); +} diff --git a/pool/shard011/C++/0122121_GroupTracks.cc b/pool/shard011/C++/0122121_GroupTracks.cc new file mode 100644 index 0000000000000000000000000000000000000000..94f70586d3ec275d4584d7e68c9e8777dd57eec6 --- /dev/null +++ b/pool/shard011/C++/0122121_GroupTracks.cc @@ -0,0 +1,37 @@ +#include "GroupTracks.h" + +GroupTracks::GroupTracks() { + _edges[0] = 0.0; + _edges[1] = 0.0; +} + +GroupTracks::GroupTracks( TrackExtended * track ) { + _trackARVec.push_back( track ); + _edges[0] = 0.0; + _edges[1] = 0.0; +} + +GroupTracks::~GroupTracks() {} + +void GroupTracks::addTrackExtended( TrackExtended * track ) { + _trackARVec.push_back( track ); +} + +void GroupTracks::ClearTrackExtendedVec() { + _trackARVec.clear(); +} + +TrackExtendedVec & GroupTracks::getTrackExtendedVec() { + return _trackARVec; +} + +void GroupTracks::setEdges(float * edges) { + + _edges[0] = edges[0]; + _edges[1] = edges[1]; + +} + +float * GroupTracks::getEdges() { + return _edges; +} diff --git a/pool/shard011/C++/0122122_CatDpsDruidStrategy.cpp b/pool/shard011/C++/0122122_CatDpsDruidStrategy.cpp new file mode 100644 index 0000000000000000000000000000000000000000..777d3cbad3978cac16720d4ecb70259ea4b9dd32 --- /dev/null +++ b/pool/shard011/C++/0122122_CatDpsDruidStrategy.cpp @@ -0,0 +1,145 @@ +#include "../../../pchdef.h" +#include "../../playerbot.h" +#include "DruidMultipliers.h" +#include "CatDpsDruidStrategy.h" + +using namespace ai; + +class CatDpsDruidStrategyActionNodeFactory : public NamedObjectFactory +{ +public: + CatDpsDruidStrategyActionNodeFactory() + { + creators["faerie fire (feral)"] = &faerie_fire_feral; + creators["melee"] = &melee; + creators["feral charge - cat"] = &feral_charge_cat; + creators["cat form"] = &cat_form; + creators["claw"] = &claw; + creators["mangle (cat)"] = &mangle_cat; + creators["rake"] = &rake; + creators["ferocious bite"] = &ferocious_bite; + creators["rip"] = &rip; + } +private: + static ActionNode* faerie_fire_feral(PlayerbotAI* ai) + { + return new ActionNode ("faerie fire (feral)", + /*P*/ NULL, + /*A*/ NULL, + /*C*/ NULL); + } + static ActionNode* melee(PlayerbotAI* ai) + { + return new ActionNode ("melee", + /*P*/ NextAction::array(0, new NextAction("feral charge - cat"), NULL), + /*A*/ NULL, + /*C*/ NULL); + } + static ActionNode* feral_charge_cat(PlayerbotAI* ai) + { + return new ActionNode ("feral charge - cat", + /*P*/ NULL, + /*A*/ NextAction::array(0, new NextAction("reach melee"), NULL), + /*C*/ NULL); + } + static ActionNode* cat_form(PlayerbotAI* ai) + { + return new ActionNode ("cat form", + /*P*/ NULL, + /*A*/ NULL, + /*C*/ NULL); + } + static ActionNode* claw(PlayerbotAI* ai) + { + return new ActionNode ("claw", + /*P*/ NULL, + /*A*/ NextAction::array(0, new NextAction("melee"), NULL), + /*C*/ NULL); + } + static ActionNode* mangle_cat(PlayerbotAI* ai) + { + return new ActionNode ("mangle (cat)", + /*P*/ NULL, + /*A*/ NextAction::array(0, new NextAction("claw"), NULL), + /*C*/ NULL); + } + static ActionNode* rake(PlayerbotAI* ai) + { + return new ActionNode ("rake", + /*P*/ NULL, + /*A*/ NULL, + /*C*/ NULL); + } + static ActionNode* ferocious_bite(PlayerbotAI* ai) + { + return new ActionNode ("ferocious bite", + /*P*/ NULL, + /*A*/ NextAction::array(0, new NextAction("rip"), NULL), + /*C*/ NULL); + } + static ActionNode* rip(PlayerbotAI* ai) + { + return new ActionNode ("rip", + /*P*/ NULL, + /*A*/ NextAction::array(0, new NextAction("ferocious bite"), NULL), + /*C*/ NULL); + } +}; + +CatDpsDruidStrategy::CatDpsDruidStrategy(PlayerbotAI* ai) : FeralDruidStrategy(ai) +{ + actionNodeFactories.Add(new CatDpsDruidStrategyActionNodeFactory()); +} + +NextAction** CatDpsDruidStrategy::getDefaultActions() +{ + return NextAction::array(0, new NextAction("mangle (cat)", ACTION_NORMAL + 1), + new NextAction("claw", ACTION_NORMAL + 1), NULL); +} + +void CatDpsDruidStrategy::InitTriggers(std::list &triggers) +{ + FeralDruidStrategy::InitTriggers(triggers); + + triggers.push_back(new TriggerNode( + "cat form", + NextAction::array(0, new NextAction("cat form", ACTION_MOVE + 2), NULL))); + + triggers.push_back(new TriggerNode( + "rake", + NextAction::array(0, new NextAction("rake", ACTION_NORMAL + 5), NULL))); + + triggers.push_back(new TriggerNode( + "combo points available", + NextAction::array(0, new NextAction("ferocious bite", ACTION_NORMAL + 9), + new NextAction("rip", ACTION_NORMAL + 9), NULL))); + + triggers.push_back(new TriggerNode( + "medium threat", + NextAction::array(0, new NextAction("cower", ACTION_EMERGENCY + 1), NULL))); + + triggers.push_back(new TriggerNode( + "faerie fire (feral)", + NextAction::array(0, new NextAction("faerie fire (feral)", ACTION_HIGH + 1), NULL))); + + triggers.push_back(new TriggerNode( + "tiger's fury", + NextAction::array(0, new NextAction("tiger's fury", ACTION_EMERGENCY + 1), NULL))); + + triggers.push_back(new TriggerNode( + "entangling roots", + NextAction::array(0, new NextAction("entangling roots on cc", ACTION_HIGH + 1), NULL))); + + triggers.push_back(new TriggerNode( + "low health", + NextAction::array(0, new NextAction("barkskin", ACTION_HIGH + 1), NULL))); + +} + +void CatAoeDruidStrategy::InitTriggers(std::list &triggers) +{ + triggers.push_back(new TriggerNode( + "medium aoe", + NextAction::array(0, new NextAction("swipe (cat)", ACTION_HIGH + 2), NULL))); +} + diff --git a/pool/shard011/C++/0122123_logfile.cpp b/pool/shard011/C++/0122123_logfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..009cef659768dec8982712bb02b328adef5d2f50 --- /dev/null +++ b/pool/shard011/C++/0122123_logfile.cpp @@ -0,0 +1,86 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (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.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is mozilla.org code. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "xp.h" + +#include "logfile.h" + +CLogFile::CLogFile() : + m_hFile(NULL) +{ + m_szFileName[0] = '\0'; +} + +CLogFile::~CLogFile() +{ + if(m_hFile != NULL) + close(); +} + +BOOL CLogFile::create(LPSTR szFileName, BOOL bDeleteExisting) +{ + strcpy(m_szFileName, szFileName); + + if(XP_IsFile(m_szFileName)) + { + if(!bDeleteExisting) + return FALSE; + } + + m_hFile = XP_CreateFile(m_szFileName); + return (m_hFile != NULL); +} + +void CLogFile::close() +{ + if(m_hFile != NULL) + { + XP_CloseFile(m_hFile); + m_hFile = NULL; + } +} + +DWORD CLogFile::write(LPSTR szBuf) +{ + return XP_WriteFile(m_hFile, szBuf, strlen(szBuf)); +} + +void CLogFile::flush() +{ + XP_FlushFileBuffers(m_hFile); +} + diff --git a/pool/shard011/C++/0122126_ex16.6.cpp b/pool/shard011/C++/0122126_ex16.6.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a9b5e88384a11e49bb9052f3d1708dec02af45ef --- /dev/null +++ b/pool/shard011/C++/0122126_ex16.6.cpp @@ -0,0 +1,22 @@ +#include + +template +T* begin(const T(&arr)[size]) +{ + return arr; +} + +template +T* end(const T (&arr)[size]) +{ + return arr + size; +} + +int main() +{ + std::string s[] = {"ssss", "ss", "ss", "Ssssssssszz"}; + std::cout << *(begin(s)+1) << std::endl; + std::cout << *(end(s) - 1) << std::endl; + + return 0; +} diff --git a/pool/shard011/C++/0122127_ref_memory.cc b/pool/shard011/C++/0122127_ref_memory.cc new file mode 100644 index 0000000000000000000000000000000000000000..02464b6df25597116473277f9f637760906fdf5d --- /dev/null +++ b/pool/shard011/C++/0122127_ref_memory.cc @@ -0,0 +1,158 @@ +// Copyright (c) 2017 ASMlover. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list ofconditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in +// the documentation and/or other materialsprovided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +#include +#include +#include +#include "object.h" +#include "ref_memory.h" + +namespace gc { + +void* RefMemory::alloc(std::size_t n) { + return Chaos::MemoryPool::get_instance().alloc(n); +} + +void RefMemory::dealloc(BaseObject* obj) { + Chaos::MemoryPool::get_instance().dealloc(obj); +} + +void RefMemory::inc(BaseObject* ref) { + if (ref != nullptr) + inc_objects_.push(ref); +} + +void RefMemory::dec(BaseObject* ref) { + if (ref != nullptr) + dec_objects_.push(ref); +} + +void RefMemory::write(BaseObject* target, BaseObject* obj, bool is_first) { + // only for pair object + auto* pair = Chaos::down_cast(target); + inc(obj); + if (is_first) { + dec(pair->first()); + pair->set_first(obj); + } + else { + dec(pair->second()); + pair->set_second(obj); + } +} + +void RefMemory::apply_increments(void) { + while (!inc_objects_.empty()) { + auto* obj = inc_objects_.top(); + inc_objects_.pop(); + obj->inc_ref(); + } +} + +void RefMemory::scan_counting(void) { + while (!dec_objects_.empty()) { + auto* obj = dec_objects_.top(); + dec_objects_.pop(); + if (obj->dec_def() == 0 && obj->is_pair()) { + auto append_fn = [this](BaseObject* ob) { + if (ob != nullptr) + dec_objects_.push(ob); + }; + + append_fn(Chaos::down_cast(obj)->first()); + append_fn(Chaos::down_cast(obj)->second()); + } + } +} + +void RefMemory::sweep_counting(void) { + for (auto it = objects_.begin(); it != objects_.end();) { + if ((*it)->ref() == 0) { + dealloc(*it); + objects_.erase(it++); + } + else { + ++it; + } + } +} + +RefMemory& RefMemory::get_instance(void) { + static RefMemory ins; + return ins; +} + +void RefMemory::collect_counting(void) { + auto old_count = objects_.size(); + + apply_increments(); + scan_counting(); + sweep_counting(); + + std::cout + << "[" << old_count - objects_.size() << "] objects collected, " + << "[" << objects_.size() << "] objects remaining." << std::endl; +} + +BaseObject* RefMemory::put_in(int value) { + if (objects_.size() >= kMaxObjects) + collect_counting(); + + auto* obj = new (alloc(sizeof(Int))) Int(); + obj->set_value(value); + + roots_.push_back(obj); + objects_.push_back(obj); + inc(obj); + + return obj; +} + +BaseObject* RefMemory::put_in(BaseObject* first, BaseObject* second) { + if (objects_.size() >= kMaxObjects) + collect_counting(); + + auto* obj = new (alloc(sizeof(Pair))) Pair(); + if (first != nullptr) + write(obj, first, true); + if (second != nullptr) + write(obj, second, false); + + roots_.push_back(obj); + objects_.push_back(obj); + inc(obj); + + return obj; +} + +BaseObject* RefMemory::fetch_out(void) { + auto* obj = roots_.back(); + roots_.pop_back(); + dec(obj); + return obj; +} + +} diff --git a/pool/shard011/C++/0122129_CWaterRPCs.cpp b/pool/shard011/C++/0122129_CWaterRPCs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8e28b13deff13e6c6cc72709b30e8c526c4f334e --- /dev/null +++ b/pool/shard011/C++/0122129_CWaterRPCs.cpp @@ -0,0 +1,98 @@ +/***************************************************************************** + * + * PROJECT: Multi Theft Auto v1.0 + * LICENSE: See LICENSE in the top level directory + * FILE: mods/deathmatch/logic/rpc/CWaterRPCs.cpp + * PURPOSE: Water remote procedure calls + * + * Multi Theft Auto is available from http://www.multitheftauto.com/ + * + *****************************************************************************/ + +#include +#include "CWaterRPCs.h" + +void CWaterRPCs::LoadFunctions() +{ + AddHandler(SET_WORLD_WATER_LEVEL, SetWorldWaterLevel, "SetWorldWaterLevel"); + AddHandler(RESET_WORLD_WATER_LEVEL, ResetWorldWaterLevel, "ResetWorldWaterLevel"); + AddHandler(SET_ELEMENT_WATER_LEVEL, SetElementWaterLevel, "SetElementWaterLevel"); + AddHandler(SET_ALL_ELEMENT_WATER_LEVEL, SetAllElementWaterLevel, "SetAllElementWaterLevel"); + AddHandler(SET_WATER_VERTEX_POSITION, SetWaterVertexPosition, "SetWaterVertexPosition"); + AddHandler(SET_WATER_COLOR, SetWaterColor, "SetWaterColor"); + AddHandler(RESET_WATER_COLOR, ResetWaterColor, "ResetWaterColor"); +} + +void CWaterRPCs::SetWorldWaterLevel(NetBitStreamInterface& bitStream) +{ + float fLevel; + bool bIncludeWorldNonSeaLevel; + + if (bitStream.Read(fLevel) && bitStream.ReadBit(bIncludeWorldNonSeaLevel)) + { + m_pWaterManager->SetWorldWaterLevel(fLevel, NULL, bIncludeWorldNonSeaLevel); + } +} + +void CWaterRPCs::ResetWorldWaterLevel(NetBitStreamInterface& bitStream) +{ + m_pWaterManager->ResetWorldWaterLevel(); +} + +void CWaterRPCs::SetElementWaterLevel(CClientEntity* pSource, NetBitStreamInterface& bitStream) +{ + float fLevel; + + if (bitStream.Read(fLevel)) + { + // (water, level) + CClientWater* pWater = m_pWaterManager->Get(pSource->GetID()); + if (pWater) + { + pWater->SetLevel(fLevel); + } + } +} + +void CWaterRPCs::SetAllElementWaterLevel(NetBitStreamInterface& bitStream) +{ + float fLevel; + + if (bitStream.Read(fLevel)) + { + m_pWaterManager->SetAllElementWaterLevel(fLevel, NULL); + } +} + +void CWaterRPCs::SetWaterVertexPosition(CClientEntity* pSource, NetBitStreamInterface& bitStream) +{ + unsigned char ucVertexID; + short sX; + short sY; + float fZ; + + if (bitStream.Read(ucVertexID) && bitStream.Read(sX) && bitStream.Read(sY) && bitStream.Read(fZ)) + { + CClientWater* pWater = m_pWaterManager->Get(pSource->GetID()); + if (pWater && ucVertexID < pWater->GetNumVertices()) + { + CVector vecPosition(sX, sY, fZ); + pWater->SetVertexPosition(ucVertexID, vecPosition); + } + } +} + +void CWaterRPCs::SetWaterColor(NetBitStreamInterface& bitStream) +{ + unsigned char ucRed, ucGreen, ucBlue, ucAlpha; + + if (bitStream.Read(ucRed) && bitStream.Read(ucGreen) && bitStream.Read(ucBlue) && bitStream.Read(ucAlpha)) + { + CStaticFunctionDefinitions::SetWaterColor(ucRed, ucGreen, ucBlue, ucAlpha); + } +} + +void CWaterRPCs::ResetWaterColor(NetBitStreamInterface& bitStream) +{ + CStaticFunctionDefinitions::ResetWaterColor(); +} diff --git a/pool/shard011/C++/0122131_xlib.cpp b/pool/shard011/C++/0122131_xlib.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2def3a3f3ed5af209d75635aae1a33ee40aa676e --- /dev/null +++ b/pool/shard011/C++/0122131_xlib.cpp @@ -0,0 +1,154 @@ +#ifndef RUBY_INPUT_MOUSE_XLIB +#define RUBY_INPUT_MOUSE_XLIB + +namespace ruby { + +struct InputMouseXlib { + HID::Mouse hid; + + uintptr_t handle = 0; + + Display* display = nullptr; + Window rootWindow; + Cursor invisibleCursor; + unsigned screenWidth = 0; + unsigned screenHeight = 0; + + struct Mouse { + bool acquired = false; + signed numerator = 0; + signed denominator = 0; + signed threshold = 0; + unsigned relativeX = 0; + unsigned relativeY = 0; + } ms; + + bool acquire() { + if(acquired()) return true; + + if(XGrabPointer(display, handle, True, 0, GrabModeAsync, GrabModeAsync, rootWindow, invisibleCursor, CurrentTime) == GrabSuccess) { + //backup existing cursor acceleration settings + XGetPointerControl(display, &ms.numerator, &ms.denominator, &ms.threshold); + + //disable cursor acceleration + XChangePointerControl(display, True, False, 1, 1, 0); + + //center cursor (so that first relative poll returns 0, 0 if mouse has not moved) + XWarpPointer(display, None, rootWindow, 0, 0, 0, 0, screenWidth / 2, screenHeight / 2); + + return ms.acquired = true; + } else { + return ms.acquired = false; + } + } + + bool unacquire() { + if(acquired()) { + //restore cursor acceleration and release cursor + XChangePointerControl(display, True, True, ms.numerator, ms.denominator, ms.threshold); + XUngrabPointer(display, CurrentTime); + ms.acquired = false; + } + return true; + } + + bool acquired() { + return ms.acquired; + } + + void assign(unsigned groupID, unsigned inputID, int16_t value) { + auto& group = hid.group[groupID]; + if(group.input[inputID].value == value) return; + if(input.onChange) input.onChange(hid, groupID, inputID, group.input[inputID].value, value); + group.input[inputID].value = value; + } + + void poll(vector& devices) { + Window rootReturn; + Window childReturn; + signed rootXReturn = 0; + signed rootYReturn = 0; + signed windowXReturn = 0; + signed windowYReturn = 0; + unsigned maskReturn = 0; + XQueryPointer(display, handle, &rootReturn, &childReturn, &rootXReturn, &rootYReturn, &windowXReturn, &windowYReturn, &maskReturn); + + if(acquired()) { + XWindowAttributes attributes; + XGetWindowAttributes(display, handle, &attributes); + + //absolute -> relative conversion + assign(HID::Mouse::GroupID::Axis, 0, (int16_t)(rootXReturn - screenWidth / 2)); + assign(HID::Mouse::GroupID::Axis, 1, (int16_t)(rootYReturn - screenHeight / 2)); + + if(hid.axis().input[0].value != 0 || hid.axis().input[1].value != 0) { + //if mouse moved, re-center mouse for next poll + XWarpPointer(display, None, rootWindow, 0, 0, 0, 0, screenWidth / 2, screenHeight / 2); + } + } else { + assign(HID::Mouse::GroupID::Axis, 0, (int16_t)(rootXReturn - ms.relativeX)); + assign(HID::Mouse::GroupID::Axis, 1, (int16_t)(rootYReturn - ms.relativeY)); + + ms.relativeX = rootXReturn; + ms.relativeY = rootYReturn; + } + + assign(HID::Mouse::GroupID::Button, 0, (bool)(maskReturn & Button1Mask)); + assign(HID::Mouse::GroupID::Button, 1, (bool)(maskReturn & Button2Mask)); + assign(HID::Mouse::GroupID::Button, 2, (bool)(maskReturn & Button3Mask)); + assign(HID::Mouse::GroupID::Button, 3, (bool)(maskReturn & Button4Mask)); + assign(HID::Mouse::GroupID::Button, 4, (bool)(maskReturn & Button5Mask)); + + devices.append(&hid); + } + + bool init(uintptr_t handle) { + this->handle = handle; + display = XOpenDisplay(0); + rootWindow = DefaultRootWindow(display); + + XWindowAttributes attributes; + XGetWindowAttributes(display, rootWindow, &attributes); + screenWidth = attributes.width; + screenHeight = attributes.height; + + //Xlib: because XShowCursor(display, false) would just be too easy + //create invisible cursor for use when mouse is acquired + Pixmap pixmap; + XColor black, unused; + static char invisibleData[8] = {0}; + Colormap colormap = DefaultColormap(display, DefaultScreen(display)); + XAllocNamedColor(display, colormap, "black", &black, &unused); + pixmap = XCreateBitmapFromData(display, handle, invisibleData, 8, 8); + invisibleCursor = XCreatePixmapCursor(display, pixmap, pixmap, &black, &black, 0, 0); + XFreePixmap(display, pixmap); + XFreeColors(display, colormap, &black.pixel, 1, 0); + + ms.acquired = false; + ms.relativeX = 0; + ms.relativeY = 0; + + hid.id = 2; + + hid.axis().append({"X"}); + hid.axis().append({"Y"}); + + hid.button().append({"Left"}); + hid.button().append({"Middle"}); + hid.button().append({"Right"}); + hid.button().append({"Up"}); + hid.button().append({"Down"}); + + return true; + } + + void term() { + unacquire(); + XFreeCursor(display, invisibleCursor); + XCloseDisplay(display); + } +}; + +} + +#endif diff --git a/pool/shard011/C++/0122132_message.cpp b/pool/shard011/C++/0122132_message.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7b1a9c2b5d65dd7d26555e7a58fafafc235869dd --- /dev/null +++ b/pool/shard011/C++/0122132_message.cpp @@ -0,0 +1,75 @@ +/* This file is part of the KDE project. + + Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). + + This library is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2.1 or 3 of the License. + + 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, see . +*/ + +#include + +#include "message.h" + + +QT_BEGIN_NAMESPACE + +static int wuchi = qRegisterMetaType(); + +namespace Phonon +{ +namespace Gstreamer +{ + +/*! + \class gstreamer::Message + \internal +*/ +Message::Message(): + m_message(0), + m_source(0) +{} + +Message::Message(GstMessage* message, MediaObject *source): + m_message(message), + m_source(source) +{ + Q_ASSERT(m_message); + gst_message_ref(m_message); +} + +Message::Message(const Message &other) +{ + m_message = other.m_message; + gst_message_ref(m_message); + m_source = other.m_source; +} + +Message::~Message() +{ + gst_message_unref(m_message); +} + +GstMessage* Message::rawMessage() const +{ + return m_message; +} + +MediaObject *Message::source() const +{ + return m_source; +} + +} // ns gstreamer +} // ns phonon + +QT_END_NAMESPACE + diff --git a/pool/shard011/C++/0122133_mobilemainwindow.cpp b/pool/shard011/C++/0122133_mobilemainwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..64763071d338bc820f96c3c9b048618b0a288861 --- /dev/null +++ b/pool/shard011/C++/0122133_mobilemainwindow.cpp @@ -0,0 +1,106 @@ +/* + Copyright 2010 Stephan Martin, Dominik Gummel + + This file is part of Multidisplay. + + Multidisplay 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. + + Multidisplay 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 Multidisplay. If not, see . +*/ + +#include "mobilemainwindow.h" +#include "ui_mobilemainwindow.h" + +#include +#include + +#ifdef Q_WS_MAEMO_5 + #include + #include +#endif + + +MobileMainWindow::MobileMainWindow(QWidget *parent) : + QMainWindow(parent), + ui(new Ui::MobileMainWindow) +{ + ui->setupUi(this); +#ifdef Q_WS_MAEMO_5 + setAttribute(Qt::WA_Maemo5StackedWindow); + + //broken on N900 ! + //http://doc.qt.nokia.com/qt-maemo-4.6/gestures-overview.html + grabGesture(Qt::PanGesture); + grabGesture(Qt::PinchGesture); + grabGesture(Qt::SwipeGesture); +#endif + +#if defined (Q_WS_MAEMO_5) + screensaver = new QSystemScreenSaver (this); + screensaver->setScreenSaverInhibit (); + qDebug() << "Screensaver deactivated"; +#endif + +} + +MobileMainWindow::~MobileMainWindow() +{ + delete ui; +} + + +void MobileMainWindow::showStatusMessage (QString msg) { + //http://doc.qt.nokia.com/qt-maemo-4.6/qmaemo5informationbox.html#details + qDebug() << "status msg " << msg; +#ifdef Q_WS_MAEMO_5 + QMaemo5InformationBox::information ( this, msg, 0 ); +#endif +} + +void MobileMainWindow::closeEvent(QCloseEvent *event) { + emit writeSettings(); + event->accept(); + QMainWindow::closeEvent ( event ); +} + +bool MobileMainWindow::event(QEvent *event) +{ + if (event->type() == QEvent::Gesture) { + qDebug() << "gesture"; + return gestureEvent(static_cast(event)); + } + return QWidget::event(event); +} + +bool MobileMainWindow::gestureEvent(QGestureEvent *event) +{ + if (QGesture *swipe = event->gesture(Qt::SwipeGesture)) +// swipeTriggered(static_cast(swipe)); + qDebug() << "swipe"; + else if (QGesture *pan = event->gesture(Qt::PanGesture)) +// panTriggered(static_cast(pan)); + qDebug() << "pan"; + if (QGesture *pinch = event->gesture(Qt::PinchGesture)) +// pinchTriggered(static_cast(pinch)); + qDebug() << "pinch"; + return true; +} + +void MobileMainWindow::showExpanded() { +#ifdef Q_OS_SYMBIAN + showFullScreen(); +#elif defined(Q_WS_MAEMO_5) + showMaximized(); +#else + show(); +#endif +} diff --git a/pool/shard011/C++/0122134_imageinfotasksplitter.cpp b/pool/shard011/C++/0122134_imageinfotasksplitter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ec081bbe78a56beaa5fda58f40d99e31e235e596 --- /dev/null +++ b/pool/shard011/C++/0122134_imageinfotasksplitter.cpp @@ -0,0 +1,71 @@ +/* ============================================================ + * + * This file is a part of digiKam project + * http://www.digikam.org + * + * Date : 2012-01-18 + * Description : image info task splitter + * + * Copyright (C) 2012 by Marcel Wiesweg + * + * This program is free software; you can redistribute it + * and/or modify it under the terms of the GNU General + * Public License as published by the Free Software Foundation; + * either version 2, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * ============================================================ */ + +// Local includes + +#include "imageinfotasksplitter.h" +#include "parallelworkers.h" + +namespace Digikam +{ + +ImageInfoTaskSplitter::ImageInfoTaskSplitter(const FileActionImageInfoList& list) + : FileActionImageInfoList(list) +{ + int parts = ParallelWorkers::optimalWorkerCount(); + m_n = qMax(1, list.size() / parts); +} + +ImageInfoTaskSplitter::~ImageInfoTaskSplitter() +{ +} + +FileActionImageInfoList ImageInfoTaskSplitter::next() +{ + QList list; + + if (size() <= m_n) + { + list = *this; + clear(); + } + else + { + list.reserve(m_n); + + // qCopy does not work with QList + for (int i=0; i < m_n; i++) + list << at(i); + + erase(begin(), begin() + m_n); + } + + return FileActionImageInfoList::continueTask(list, progress()); +} + +bool ImageInfoTaskSplitter::hasNext() const +{ + return !isEmpty(); +} + +} // namespace Digikam diff --git a/pool/shard011/C++/0122137_Media.cpp b/pool/shard011/C++/0122137_Media.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cea06ebc6e55a823125bf8c9c569bacb1999d130 --- /dev/null +++ b/pool/shard011/C++/0122137_Media.cpp @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2008-2010 Appcelerator, Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Media.h" + +#include + +#include + +namespace Titanium { + +Media::Media(KObjectRef global) : + StaticBoundObject("Media"), + global(global) +{ + /** + * @tiapi(method=True,name=Media.createSound,since=0.2) Creates a sound object + * @tiarg(for=Media.createSound,name=path,type=String) path or url to the sound file + * @tiresult(for=Media.createSound,type=Media.Sound) a Sound object + */ + this->SetMethod("createSound", &Media::_CreateSound); + /** + * @tiapi(method=True,name=Media.beep,since=0.2) Causes the system to beep + */ + this->SetMethod("beep", &Media::_Beep); +} + +Media::~Media() +{ +} + +void Media::_CreateSound(const ValueList& args, KValueRef result) +{ + if (args.size()!=1) + throw ValueException::FromString("createSound takes 1 parameter"); + + std::string path(args.at(0)->ToString()); + result->SetObject(this->CreateSound(path)); +} + +void Media::_Beep(const ValueList& args, KValueRef result) +{ + this->Beep(); +} + +} // namespace Titanium diff --git a/pool/shard011/C++/0122140_dist_etherlink.cc b/pool/shard011/C++/0122140_dist_etherlink.cc new file mode 100644 index 0000000000000000000000000000000000000000..01f21d1365b8a3bc30a20f535f29a1998b39c3c7 --- /dev/null +++ b/pool/shard011/C++/0122140_dist_etherlink.cc @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2015 ARM Limited + * All rights reserved + * + * The license below extends only to copyright in the software and shall + * not be construed as granting a license to any other intellectual + * property including but not limited to intellectual property relating + * to a hardware implementation of the functionality of the software + * licensed hereunder. You may use the software subject to the license + * terms below provided that you ensure that this notice is replicated + * unmodified and in its entirety in all distributions of the software, + * modified or unmodified, in source code or in binary form. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer; + * redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution; + * neither the name of the copyright holders nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Authors: Gabor Dozsa + */ + +/* @file + * Device module for a full duplex ethernet link for dist gem5 simulations. + */ + +#include "dev/net/dist_etherlink.hh" + +#include +#include +#include + +#include +#include +#include +#include + +#include "base/random.hh" +#include "base/trace.hh" +#include "debug/DistEthernet.hh" +#include "debug/DistEthernetPkt.hh" +#include "debug/EthernetData.hh" +#include "dev/net/dist_iface.hh" +#include "dev/net/etherdump.hh" +#include "dev/net/etherint.hh" +#include "dev/net/etherlink.hh" +#include "dev/net/etherobject.hh" +#include "dev/net/etherpkt.hh" +#include "dev/net/tcp_iface.hh" +#include "params/EtherLink.hh" +#include "sim/core.hh" +#include "sim/serialize.hh" +#include "sim/system.hh" + +using namespace std; + +DistEtherLink::DistEtherLink(const Params *p) + : EtherObject(p), linkDelay(p->delay) +{ + DPRINTF(DistEthernet,"DistEtherLink::DistEtherLink() " + "link delay:%llu ticksPerByte:%f\n", p->delay, p->speed); + + txLink = new TxLink(name() + ".link0", this, p->speed, p->delay_var, + p->dump); + rxLink = new RxLink(name() + ".link1", this, p->delay, p->dump); + + Tick sync_repeat; + if (p->sync_repeat != 0) { + if (p->sync_repeat != p->delay) + warn("DistEtherLink(): sync_repeat is %lu and linkdelay is %lu", + p->sync_repeat, p->delay); + sync_repeat = p->sync_repeat; + } else { + sync_repeat = p->delay; + } + + // create the dist (TCP) interface to talk to the peer gem5 processes. + distIface = new TCPIface(p->server_name, p->server_port, + p->dist_rank, p->dist_size, + p->sync_start, sync_repeat, this, + p->dist_sync_on_pseudo_op, p->is_switch, + p->num_nodes); + + localIface = new LocalIface(name() + ".int0", txLink, rxLink, distIface); +} + +DistEtherLink::~DistEtherLink() +{ + delete txLink; + delete rxLink; + delete localIface; + delete distIface; +} + +EtherInt* +DistEtherLink::getEthPort(const std::string &if_name, int idx) +{ + if (if_name != "int0") { + return nullptr; + } else { + panic_if(localIface->getPeer(), "interface already connected to"); + } + return localIface; +} + +void +DistEtherLink::serialize(CheckpointOut &cp) const +{ + distIface->serializeSection(cp, "distIface"); + txLink->serializeSection(cp, "txLink"); + rxLink->serializeSection(cp, "rxLink"); +} + +void +DistEtherLink::unserialize(CheckpointIn &cp) +{ + distIface->unserializeSection(cp, "distIface"); + txLink->unserializeSection(cp, "txLink"); + rxLink->unserializeSection(cp, "rxLink"); +} + +void +DistEtherLink::init() +{ + DPRINTF(DistEthernet,"DistEtherLink::init() called\n"); + distIface->init(rxLink->doneEvent(), linkDelay); +} + +void +DistEtherLink::startup() +{ + DPRINTF(DistEthernet,"DistEtherLink::startup() called\n"); + distIface->startup(); +} + +void +DistEtherLink::RxLink::setDistInt(DistIface *m) +{ + assert(!distIface); + distIface = m; +} + +void +DistEtherLink::RxLink::rxDone() +{ + assert(!busy()); + + // retrieve the packet that triggered the receive done event + packet = distIface->packetIn(); + + if (dump) + dump->dump(packet); + + DPRINTF(DistEthernetPkt, "DistEtherLink::DistLink::rxDone() " + "packet received: len=%d\n", packet->length); + DDUMP(EthernetData, packet->data, packet->length); + + localIface->sendPacket(packet); + + packet = nullptr; +} + +void +DistEtherLink::TxLink::txDone() +{ + if (dump) + dump->dump(packet); + + packet = nullptr; + assert(!busy()); + + localIface->sendDone(); +} + +bool +DistEtherLink::TxLink::transmit(EthPacketPtr pkt) +{ + if (busy()) { + DPRINTF(DistEthernet, "packet not sent, link busy\n"); + return false; + } + + packet = pkt; + Tick delay = (Tick)ceil(((double)pkt->simLength * ticksPerByte) + 1.0); + if (delayVar != 0) + delay += random_mt.random(0, delayVar); + + // send the packet to the peers + assert(distIface); + distIface->packetOut(pkt, delay); + + // schedule the send done event + parent->schedule(doneEvent, curTick() + delay); + + return true; +} + +void +DistEtherLink::Link::serialize(CheckpointOut &cp) const +{ + bool packet_exists = (packet != nullptr); + SERIALIZE_SCALAR(packet_exists); + if (packet_exists) + packet->serialize("packet", cp); + + bool event_scheduled = event->scheduled(); + SERIALIZE_SCALAR(event_scheduled); + if (event_scheduled) { + Tick event_time = event->when(); + SERIALIZE_SCALAR(event_time); + } +} + +void +DistEtherLink::Link::unserialize(CheckpointIn &cp) +{ + bool packet_exists; + UNSERIALIZE_SCALAR(packet_exists); + if (packet_exists) { + packet = make_shared(); + packet->unserialize("packet", cp); + } + + bool event_scheduled; + UNSERIALIZE_SCALAR(event_scheduled); + if (event_scheduled) { + Tick event_time; + UNSERIALIZE_SCALAR(event_time); + parent->schedule(*event, event_time); + } +} + +DistEtherLink::LocalIface::LocalIface(const std::string &name, + TxLink *tx, + RxLink *rx, + DistIface *m) : + EtherInt(name), txLink(tx) +{ + tx->setLocalInt(this); + rx->setLocalInt(this); + tx->setDistInt(m); + rx->setDistInt(m); +} + +DistEtherLink * +DistEtherLinkParams::create() +{ + return new DistEtherLink(this); +} + + diff --git a/pool/shard011/C++/0122141_Problem_18.cpp b/pool/shard011/C++/0122141_Problem_18.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3aca4a03f997e6dda5483d1461a65c230c69a117 --- /dev/null +++ b/pool/shard011/C++/0122141_Problem_18.cpp @@ -0,0 +1,80 @@ +#include +#include +#include +#include +#include + +using namespace std; + +const int MATRIX_SIZE = 15; + +int main() +{ + clock_t time_begin = clock(); + + int a[MATRIX_SIZE][MATRIX_SIZE] = {0}; + + // open file, store matrix into array 'a' + ifstream fin("Problem#18_data.txt", ios_base::in); + if (fin.is_open()) + { + for (int i = 0; i < MATRIX_SIZE; i++) + { + for (int j = 0; j <= i; j++) + { + fin >> a[i][j]; + } + } + + fin.close(); + } + else + { + cerr << "Cannot Open File ! Please Check Your Filename" << endl; + } + + /* Greedy Algorithm + * If we know the top to ith layer max path sum; for every number + * in i+1 th layer, we choose the max adjacent max path sum above, + * add it the number. + * we got the the top to i+1 th layer max path sum + */ + int maxPathSum[MATRIX_SIZE][MATRIX_SIZE] = {0}; + maxPathSum[0][0] = a[0][0]; + for (int i = 1; i < MATRIX_SIZE; i++) + { + for (int j = 0; j <= i; j++) + { + int preLeftMaxPathSum = 0; + int preMidMaxPathSum = 0; + if (j - 1 >= 0) + { + preLeftMaxPathSum = maxPathSum[i-1][j-1]; + } + preMidMaxPathSum = maxPathSum[i-1][j]; + + int tmpMax = max(preLeftMaxPathSum, preMidMaxPathSum); + + maxPathSum[i][j] = a[i][j] + tmpMax; + } + } + + + cout << "The Last Row:" << endl; + int result = 0; + for (int j = 0; j < MATRIX_SIZE; j++) + { + cout << maxPathSum[MATRIX_SIZE-1][j] << " "; + if (maxPathSum[MATRIX_SIZE-1][j] > result) + { + result = maxPathSum[MATRIX_SIZE-1][j]; + } + } + cout << endl; + cout << "The Max Path Sum: " << result << endl; + + clock_t time_end = clock(); + double time_cost = (double)(time_end - time_begin) / CLOCKS_PER_SEC; + cout << "TIME COST: " << time_cost << " s" << endl; + return 0; +} diff --git a/pool/shard011/C++/0122142_ProgressTab.cpp b/pool/shard011/C++/0122142_ProgressTab.cpp new file mode 100644 index 0000000000000000000000000000000000000000..42d303f255e7da40acf5bf56e57f7402be192da9 --- /dev/null +++ b/pool/shard011/C++/0122142_ProgressTab.cpp @@ -0,0 +1,69 @@ +/* Simple Chat + * Copyright (c) 2008-2014 Alexander Sedov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include "ChatCore.h" +#include "QProgressIndicator/QProgressIndicator.h" +#include "sglobal.h" +#include "ui/ChatIcons.h" +#include "ui/tabs/ProgressTab.h" + +ProgressTab::ProgressTab(TabWidget *parent) + : AbstractTab(PROGRESS_TAB, LS(PROGRESS_TAB), parent) +{ + QFrame *frame = new QFrame(this); +# if defined(Q_OS_WIN32) + frame->setStyleSheet(LS("QFrame{background-color:#fff;}")); +# endif + + m_progress = new QProgressIndicator(frame); + m_progress->setAnimationDelay(100); + m_progress->setMinimumSize(100, 100); + m_progress->startAnimation(); + + QHBoxLayout *mainLay = new QHBoxLayout(this); + mainLay->addWidget(frame); + mainLay->setMargin(0); + + QHBoxLayout *frameLay = new QHBoxLayout(frame); + frameLay->addWidget(m_progress, Qt::AlignCenter); + + setIcon(SCHAT_ICON(SmallLogo)); + retranslateUi(); +} + + +void ProgressTab::retranslateUi() +{ + setText(tr("Starting...")); +} + + +AbstractTab *ProgressTabCreator::create(const QVariant &data, TabWidget *parent) const +{ + Q_UNUSED(data) + return new ProgressTab(parent); +} + + +void ProgressTabCreator::reload(AbstractTab *tab, const QVariant &data) const +{ + Q_UNUSED(tab) + Q_UNUSED(data); +} diff --git a/pool/shard011/C++/0122144_output.cpp b/pool/shard011/C++/0122144_output.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17845de91c3dfffc8e5098bd714306c3fefc31ff --- /dev/null +++ b/pool/shard011/C++/0122144_output.cpp @@ -0,0 +1,140 @@ +#include +#include + +#include +#include +#include +#include +#include +#include +#include "output.h" +#include "read_stats.h" + +/* + * Text constants for output + */ + +// output filenames +static const char * SEQC_READLENGTH_FILE = "readlength.tsv"; +static const char * SEQC_POS_QUAL_FILE = "per_pos_qual.tsv"; +static const char * SEQC_POS_GC_CONTENT_FILE = "pos_gc_content.tsv"; +static const char * SEQC_POS_N_CONTENT_FILE = "pos_n_content.tsv"; +static const char * SEQC_POS_NUC_DIST_FILE = "pos_nuc_dist.tsv"; +static const char * SEQC_SEQ_GC_CONTENT_FILE = "seq_gc_content.tsv"; +static const char * SEQC_SEQ_QUAL_DIST_FILE = "seq_qual.tsv"; +static const char * SEQC_SUMMARY_FILE = "summary.tsv"; + +// textual conventions +static const char * SEQC_END_MODULE_LN = ">>END_MODULE"; + +/** + * wrapper: actually writes statistics info to files. + */ +int TSVWriter::writeAll(ReadStats & stats, std::string const outdir){ + if (mkdir("testout",0744) != 0) { + std::cerr << "Error creating output directory: " << strerror( errno ) << std::endl; + + exit(-1); + } + + std::ofstream ofStream; + + {// ReadLength Distribution + ofStream.open((outdir + "/" + SEQC_READLENGTH_FILE).c_str()); + std::stringstream ss; + writeReadLength(stats, ss); + ofStream << ss.str(); + ofStream.close(); + } + + + {// Per Position-in-Read Quality Statistics + ofStream.open((outdir + "/" + SEQC_POS_QUAL_FILE).c_str()); + std::stringstream ss; + writePerPosQual(stats, ss); + ofStream << ss.str(); + ofStream.close(); + } + +} + +/** + * create the content that goes into the sequence length distribution statistics + */ +void TSVWriter::writeReadLength(ReadStats & stats, std::stringstream & ss) +{ + // write out stats + ss << ">>Sequence Length Distribution\tpass" << std::endl; + ss << "#Length\tCount" << std::endl; + std::map::iterator iter; + + for(iter=stats.readLenCount.begin();iter != stats.readLenCount.end(); iter++){ + ss << iter->first << "\t" << iter->second << std::endl; + } + + ss << SEQC_END_MODULE_LN << std::endl; + +}; + +void TSVWriter::writePerPosQual(ReadStats & stats, std::stringstream & ss) +{ + unsigned score_offset = 64; + ss << ">>Per base sequence quality\tfail" << std::endl; + ss << "Base Mean Median Lower Quartile Upper Quartile 10th Percentile 90th Percentile" + << std::endl; + + //per position in read: + for(unsigned pos = 0; pos < length(stats.scoreCount); ++pos){ + // we have to know how many there are counted in total + // so we can pick specific quantiles later + unsigned total_scores = 0; + + //we'll cumulate counts here so we have easier access later + seqan::String intervals; + + //we need to add all scores to calc mean + unsigned score_sum = 0; + + //we'll collect 20 quantiles here + seqan::String quantiles; + + for(unsigned score = 0; score < length(stats.scoreCount[0]); ++score){ + total_scores += stats.scoreCount[pos][score]; + seqan::append(intervals,total_scores); + score_sum += stats.scoreCount[pos][score]*score; + // mean: add all scores and divide by n + + if(stats.scoreCount[pos][score]>0){ + ss << "In Pos " << pos << " score " << score << " counted: " + << stats.scoreCount[pos][score] << std::endl; + } + + } + ss << "total scores in pos " << pos << ": " << total_scores << std::endl; + ss << "total sum of scores in pos " << pos << ": " << score_sum << std::endl; + if(total_scores > 0){ + ss << "mean of scores in pos " << pos << ": " << score_sum/total_scores << std::endl; + } + + //this will only work if we have more than 20 reads + unsigned steps = total_scores/20; + + unsigned interval_pos = 0; + for (unsigned scores_counted=0; scores_counted <= total_scores; scores_counted+=steps){ +// if(interval[interval_pos]) + } + + // median: get score at pos n/2 + + // Lower quartile: get score at pos n/4 + // Upper quartile: get score at pos 3n/4 + // 10th Percentile: get score at pos n/10 + // 90th Percentile: get score at pos 9n/10 + + ss << std::endl; + } + + + + //" +}; diff --git a/pool/shard011/C++/0122146_juce_Base64.cpp b/pool/shard011/C++/0122146_juce_Base64.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dd0adbfea262b3b0cac7bbf1747225dd8357975 --- /dev/null +++ b/pool/shard011/C++/0122146_juce_Base64.cpp @@ -0,0 +1,164 @@ +/* + ============================================================================== + + This file is part of the JUCE library. + Copyright (c) 2017 - ROLI Ltd. + + JUCE is an open source library subject to commercial or open-source + licensing. + + The code included in this file is provided under the terms of the ISC license + http://www.isc.org/downloads/software-support-policy/isc-license. Permission + To use, copy, modify, and/or distribute this software for any purpose with or + without fee is hereby granted provided that the above copyright notice and + this permission notice appear in all copies. + + JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER + EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE + DISCLAIMED. + + ============================================================================== +*/ + +namespace juce +{ + +bool Base64::convertToBase64 (OutputStream& base64Result, const void* sourceData, size_t sourceDataSize) +{ + static const char lookup[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + auto* source = static_cast (sourceData); + + while (sourceDataSize > 0) + { + char frame[4]; + auto byte0 = *source++; + frame[0] = lookup [(byte0 & 0xfcu) >> 2]; + uint32 bits = (byte0 & 0x03u) << 4; + + if (sourceDataSize > 1) + { + auto byte1 = *source++; + frame[1] = lookup[bits | ((byte1 & 0xf0u) >> 4)]; + bits = (byte1 & 0x0fu) << 2; + + if (sourceDataSize > 2) + { + auto byte2 = *source++; + frame[2] = lookup[bits | ((byte2 & 0xc0u) >> 6)]; + frame[3] = lookup[byte2 & 0x3fu]; + sourceDataSize -= 3; + } + else + { + frame[2] = lookup[bits]; + frame[3] = '='; + sourceDataSize = 0; + } + } + else + { + frame[1] = lookup[bits]; + frame[2] = '='; + frame[3] = '='; + sourceDataSize = 0; + } + + if (! base64Result.write (frame, 4)) + return false; + } + + return true; +} + +bool Base64::convertFromBase64 (OutputStream& binaryOutput, StringRef base64TextInput) +{ + for (auto s = base64TextInput.text; ! s.isEmpty();) + { + uint8 data[4]; + + for (int i = 0; i < 4; ++i) + { + auto c = (uint32) s.getAndAdvance(); + + if (c >= 'A' && c <= 'Z') c -= 'A'; + else if (c >= 'a' && c <= 'z') c -= 'a' - 26; + else if (c >= '0' && c <= '9') c += 52 - '0'; + else if (c == '+') c = 62; + else if (c == '/') c = 63; + else if (c == '=') { c = 64; if (i <= 1) return false; } + else return false; + + data[i] = (uint8) c; + } + + binaryOutput.writeByte ((char) ((data[0] << 2) | (data[1] >> 4))); + + if (data[2] < 64) + { + binaryOutput.writeByte ((char) ((data[1] << 4) | (data[2] >> 2))); + + if (data[3] < 64) + binaryOutput.writeByte ((char) ((data[2] << 6) | data[3])); + } + } + + return true; +} + +String Base64::toBase64 (const void* sourceData, size_t sourceDataSize) +{ + MemoryOutputStream m ((sourceDataSize * 4) / 3 + 3); + bool ok = convertToBase64 (m, sourceData, sourceDataSize); + jassert (ok); // should always succeed for this simple case + ignoreUnused (ok); + return m.toString(); +} + +String Base64::toBase64 (const String& text) +{ + return toBase64 (text.toRawUTF8(), strlen (text.toRawUTF8())); +} + + +//============================================================================== +//============================================================================== +#if JUCE_UNIT_TESTS + +class Base64Tests : public UnitTest +{ +public: + Base64Tests() : UnitTest ("Base64 class", "Text") {} + + static MemoryBlock createRandomData (Random& r) + { + MemoryOutputStream m; + + for (int i = r.nextInt (400); --i >= 0;) + m.writeByte ((char) r.nextInt (256)); + + return m.getMemoryBlock(); + } + + void runTest() override + { + beginTest ("Base64"); + + auto r = getRandom(); + + for (int i = 1000; --i >= 0;) + { + auto original = createRandomData (r); + auto asBase64 = Base64::toBase64 (original.getData(), original.getSize()); + MemoryOutputStream out; + expect (Base64::convertFromBase64 (out, asBase64)); + auto result = out.getMemoryBlock(); + expect (result == original); + } + } +}; + +static Base64Tests base64Tests; + +#endif + +} // namespace juce diff --git a/pool/shard011/C++/0122147_createshortcutdlg.cpp b/pool/shard011/C++/0122147_createshortcutdlg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..634c3bba16e25c025b90ff0b2c39af94b847b4ac --- /dev/null +++ b/pool/shard011/C++/0122147_createshortcutdlg.cpp @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2003-2017 Rony Shapiro . + * All rights reserved. Use of the code is allowed under the + * Artistic License 2.0 terms, as specified in the LICENSE file + * distributed with this code, or available from + * http://www.opensource.org/licenses/artistic-license-2.0.php + */ + +/** \file createshortcutdlg.cpp +* +*/ +// For compilers that support precompilation, includes "wx/wx.h". +#include "wx/wxprec.h" + +#ifdef __BORLANDC__ +#pragma hdrstop +#endif + +#ifndef WX_PRECOMP +#include "wx/wx.h" +#endif + +////@begin includes +////@end includes + +#include "createshortcutdlg.h" +#include "core/ItemData.h" +#include "./wxutils.h" + +#ifdef __WXMSW__ +#include +#endif + +////@begin XPM images +////@end XPM images + +/*! + * CreateShortcutDlg type definition + */ + +IMPLEMENT_CLASS( CreateShortcutDlg, wxDialog ) + +/*! + * CreateShortcutDlg event table definition + */ + +BEGIN_EVENT_TABLE( CreateShortcutDlg, wxDialog ) + +////@begin CreateShortcutDlg event table entries + EVT_BUTTON( wxID_OK, CreateShortcutDlg::OnOkClick ) + +////@end CreateShortcutDlg event table entries + +END_EVENT_TABLE() + +/*! + * CreateShortcutDlg constructors + */ + +CreateShortcutDlg::CreateShortcutDlg(wxWindow* parent, PWScore &core, + CItemData *base, + wxWindowID id, const wxString& caption, + const wxPoint& pos, const wxSize& size, + long style) +: m_core(core), m_base(base), m_ui(dynamic_cast(parent)) +{ + ASSERT(m_base != NULL); + ASSERT(m_ui != NULL); + Init(); + Create(parent, id, caption, pos, size, style); +} + +/*! + * CreateShortcutDlg creator + */ + +bool CreateShortcutDlg::Create( wxWindow* parent, wxWindowID id, const wxString& caption, const wxPoint& pos, const wxSize& size, long style ) +{ +////@begin CreateShortcutDlg creation + SetExtraStyle(wxWS_EX_BLOCK_EVENTS); + wxDialog::Create( parent, id, caption, pos, size, style ); + + CreateControls(); + if (GetSizer()) + { + GetSizer()->SetSizeHints(this); + } + Centre(); +////@end CreateShortcutDlg creation + ItemFieldsToDialog(); + return true; +} + +void CreateShortcutDlg::ItemFieldsToDialog() +{ + // Populate the combo box + std::vector aryGroups; + m_core.GetAllGroups(aryGroups); + for (size_t igrp = 0; igrp < aryGroups.size(); igrp++) { + m_groupCtrl->Append(aryGroups[igrp].c_str()); + } + // XXX TBD: Determine if there's a current + // group that we can pre-select for user, e.g., + // we're invoked via right-click n a node +} + +/*! + * CreateShortcutDlg destructor + */ + +CreateShortcutDlg::~CreateShortcutDlg() +{ +////@begin CreateShortcutDlg destruction +////@end CreateShortcutDlg destruction +} + +/*! + * Member initialisation + */ + +void CreateShortcutDlg::Init() +{ +////@begin CreateShortcutDlg member initialisation + m_groupCtrl = NULL; +////@end CreateShortcutDlg member initialisation +} + +/*! + * Control creation for CreateShortcutDlg + */ + +void CreateShortcutDlg::CreateControls() +{ +////@begin CreateShortcutDlg content construction + CreateShortcutDlg* itemDialog1 = this; + + wxBoxSizer* itemBoxSizer2 = new wxBoxSizer(wxVERTICAL); + itemDialog1->SetSizer(itemBoxSizer2); + + wxStaticText* itemStaticText3 = new wxStaticText( itemDialog1, wxID_STATIC, _("Please specify the name & group\n for shortcut to "), wxDefaultPosition, wxDefaultSize, 0 ); + itemBoxSizer2->Add(itemStaticText3, 0, wxALIGN_LEFT|wxALL, 5); + + wxGridSizer* itemGridSizer4 = new wxGridSizer(3, 2, 0, 0); + itemBoxSizer2->Add(itemGridSizer4, 0, wxALIGN_CENTER_HORIZONTAL|wxALL, 5); + + wxStaticText* itemStaticText5 = new wxStaticText( itemDialog1, wxID_STATIC, _("Group:"), wxDefaultPosition, wxDefaultSize, 0 ); + itemGridSizer4->Add(itemStaticText5, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxArrayString m_groupCtrlStrings; + m_groupCtrl = new wxComboBox( itemDialog1, ID_COMBOBOX4, wxEmptyString, wxDefaultPosition, wxDefaultSize, m_groupCtrlStrings, wxCB_DROPDOWN ); + itemGridSizer4->Add(m_groupCtrl, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxStaticText* itemStaticText7 = new wxStaticText( itemDialog1, wxID_STATIC, _("Title:"), wxDefaultPosition, wxDefaultSize, 0 ); + itemGridSizer4->Add(itemStaticText7, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxTextCtrl* itemTextCtrl8 = new wxTextCtrl( itemDialog1, ID_TEXTCTRL18, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + itemGridSizer4->Add(itemTextCtrl8, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxStaticText* itemStaticText9 = new wxStaticText( itemDialog1, wxID_STATIC, _("Username:"), wxDefaultPosition, wxDefaultSize, 0 ); + itemGridSizer4->Add(itemStaticText9, 0, wxALIGN_LEFT|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxTextCtrl* itemTextCtrl10 = new wxTextCtrl( itemDialog1, ID_TEXTCTRL19, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0 ); + itemGridSizer4->Add(itemTextCtrl10, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5); + + wxStdDialogButtonSizer* itemStdDialogButtonSizer11 = new wxStdDialogButtonSizer; + + itemBoxSizer2->Add(itemStdDialogButtonSizer11, 0, wxGROW|wxALL, 5); + wxButton* itemButton12 = new wxButton( itemDialog1, wxID_OK, _("&OK"), wxDefaultPosition, wxDefaultSize, 0 ); + itemStdDialogButtonSizer11->AddButton(itemButton12); + + wxButton* itemButton13 = new wxButton( itemDialog1, wxID_CANCEL, _("&Cancel"), wxDefaultPosition, wxDefaultSize, 0 ); + itemStdDialogButtonSizer11->AddButton(itemButton13); + + wxButton* itemButton14 = new wxButton( itemDialog1, wxID_HELP, _("&Help"), wxDefaultPosition, wxDefaultSize, 0 ); + itemStdDialogButtonSizer11->AddButton(itemButton14); + + itemStdDialogButtonSizer11->Realize(); + + // Set validators + itemStaticText3->SetValidator( wxGenericValidator(& m_heading) ); + itemTextCtrl8->SetValidator( wxGenericValidator(& m_title) ); + itemTextCtrl10->SetValidator( wxGenericValidator(& m_user) ); +////@end CreateShortcutDlg content construction +} + +/*! + * Should we show tooltips? + */ + +bool CreateShortcutDlg::ShowToolTips() +{ + return true; +} + +/*! + * Get bitmap resources + */ + +wxBitmap CreateShortcutDlg::GetBitmapResource( const wxString& WXUNUSED(name) ) +{ + // Bitmap retrieval +////@begin CreateShortcutDlg bitmap retrieval + return wxNullBitmap; +////@end CreateShortcutDlg bitmap retrieval +} + +/*! + * Get icon resources + */ + +wxIcon CreateShortcutDlg::GetIconResource( const wxString& WXUNUSED(name) ) +{ + // Icon retrieval +////@begin CreateShortcutDlg icon retrieval + return wxNullIcon; +////@end CreateShortcutDlg icon retrieval +} + +/*! + * wxEVT_COMMAND_BUTTON_CLICKED event handler for wxID_OK + */ + +void CreateShortcutDlg::OnOkClick( wxCommandEvent& /* evt */ ) +{ + if (Validate() && TransferDataFromWindow()) { + bool valid = !m_title.empty(); + + if (!valid) + return; + + CItemData shortcut; + shortcut.SetShortcut(); + shortcut.CreateUUID(); + shortcut.SetPassword(wxT("[Shortcut]")); + const wxString group = m_groupCtrl->GetValue(); + + if (!group.empty()) + shortcut.SetGroup(tostringx(group)); + shortcut.SetTitle(tostringx(m_title)); + if (!m_user.empty()) + shortcut.SetUser(tostringx(m_user)); + time_t t; + time(&t); + shortcut.SetCTime(t); + shortcut.SetXTime(time_t(0)); + shortcut.SetStatus(CItemData::ES_ADDED); + + m_core.Execute(AddEntryCommand::Create(&m_core, shortcut, + m_base->GetUUID())); + } + EndModal(wxID_OK); +} diff --git a/pool/shard011/C++/0122150_DescribeWorkingStorageResult.cpp b/pool/shard011/C++/0122150_DescribeWorkingStorageResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a13861917144811a332d71e187edf08a6dd638b3 --- /dev/null +++ b/pool/shard011/C++/0122150_DescribeWorkingStorageResult.cpp @@ -0,0 +1,65 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::StorageGateway::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +DescribeWorkingStorageResult::DescribeWorkingStorageResult() : + m_workingStorageUsedInBytes(0), + m_workingStorageAllocatedInBytes(0) +{ +} + +DescribeWorkingStorageResult::DescribeWorkingStorageResult(const Aws::AmazonWebServiceResult& result) : + m_workingStorageUsedInBytes(0), + m_workingStorageAllocatedInBytes(0) +{ + *this = result; +} + +DescribeWorkingStorageResult& DescribeWorkingStorageResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("GatewayARN")) + { + m_gatewayARN = jsonValue.GetString("GatewayARN"); + + } + + if(jsonValue.ValueExists("DiskIds")) + { + Array diskIdsJsonList = jsonValue.GetArray("DiskIds"); + for(unsigned diskIdsIndex = 0; diskIdsIndex < diskIdsJsonList.GetLength(); ++diskIdsIndex) + { + m_diskIds.push_back(diskIdsJsonList[diskIdsIndex].AsString()); + } + } + + if(jsonValue.ValueExists("WorkingStorageUsedInBytes")) + { + m_workingStorageUsedInBytes = jsonValue.GetInt64("WorkingStorageUsedInBytes"); + + } + + if(jsonValue.ValueExists("WorkingStorageAllocatedInBytes")) + { + m_workingStorageAllocatedInBytes = jsonValue.GetInt64("WorkingStorageAllocatedInBytes"); + + } + + + + return *this; +} diff --git a/pool/shard011/C++/0122151_main.cpp b/pool/shard011/C++/0122151_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..17011a208f81eb7060278a8ec0939aa7aec5819c --- /dev/null +++ b/pool/shard011/C++/0122151_main.cpp @@ -0,0 +1,56 @@ +/********************************************************************* + * Módulo 1. Curso de Experto en Desarrollo de Videojuegos + * Autor: David Vallejo Fernández David.Vallejo@uclm.es + * + * Código modificado a partir de Managing Game States with OGRE + * http://www.ogre3d.org/tikiwiki/Managing+Game+States+with+OGRE + * Inspirado en Managing Game States in C++ + * http://gamedevgeek.com/tutorials/managing-game-states-in-c/ + * + * You can redistribute and/or modify this file under the terms of the + * GNU General Public License ad published by the Free Software + * Foundation, either version 3 of the License, or (at your option) + * and later version. See . + * + * This file is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + *********************************************************************/ + +#define UNUSED_VARIABLE(x) (void)x + +#include "GameManager.h" +#include "IntroState.h" +#include "PlayState.h" +#include "PauseState.h" + +#include + +using namespace std; + +int main () { + + GameManager* game = new GameManager(); + IntroState* introState = new IntroState(); + PlayState* playState = new PlayState(); + PauseState* pauseState = new PauseState(); + + UNUSED_VARIABLE(introState); + UNUSED_VARIABLE(playState); + UNUSED_VARIABLE(pauseState); + + try + { + // Inicializa el juego y transición al primer estado. + game->start(IntroState::getSingletonPtr()); + } + catch (Ogre::Exception& e) + { + std::cerr << "Excepción detectada: " << e.getFullDescription(); + } + + delete game; + + return 0; +} diff --git a/pool/shard011/C++/0122152_libprissc.cc b/pool/shard011/C++/0122152_libprissc.cc new file mode 100644 index 0000000000000000000000000000000000000000..a5f87329ed826d12686379c826c917bb229d286c --- /dev/null +++ b/pool/shard011/C++/0122152_libprissc.cc @@ -0,0 +1,117 @@ +/*************************************************************************************[libprissc.cc] +Copyright (c) 2014, Norbert Manthey, LGPL v2, see LICENSE +**************************************************************************************************/ + +#include "pfolio/PSolver.h" +#include "pfolio/libprissc.h" + +using namespace Riss; + +/** struct that stores the necessary data for a preprocessor */ +struct libpriss { + Riss::vec currentClause; + Riss::vec assumptions; + Riss::PSolver* solver; + Riss::lbool lastResult; + libpriss() : lastResult(l_Undef) {} // default constructor to ensure everything is set to 0 +}; + +// #pragma GCC visibility push(hidden) +// #pragma GCC visibility push(default) +// #pragma GCC visibility pop // now we should have default! + +extern "C" { + + /** initialize a solver instance, and return a pointer to the maintain structure + * @param threads number of threads that should be used (1 <= threads <= 64), will be adjusted if not in these bounds! + */ + void* + priss_init(int& threads, const char* presetConfig) + { + if (threads < 1) { threads = 1; } // make sure that the number of available threads makes sense ... + else if (threads > 64) { threads = 64; } + libpriss* priss = new libpriss; + priss->solver = new Riss::PSolver(0, presetConfig, threads); // overwrite threads of configuration with the given parameter + return priss; + } + + /** free the resources of the solver, set the pointer to 0 afterwards */ + void + priss_destroy(void*& priss) + { + libpriss* solver = (libpriss*) priss; + delete solver->solver; + solver->currentClause.clear(true); + solver->assumptions.clear(true); + delete solver; + priss = 0; + } + + /** add a literal to the solver, if lit == 0, end the clause and actually add it */ + int priss_add(void* priss, const int& lit) + { + libpriss* solver = (libpriss*) priss; + bool ret = false; + if (lit != 0) { solver->currentClause.push(lit > 0 ? mkLit(lit - 1, false) : mkLit(-lit - 1, true)); } + else { // add the current clause, and clear the vector + // reserve variables in the solver + for (int i = 0 ; i < solver->currentClause.size(); ++i) { + const Lit l2 = solver->currentClause[i]; + const Var v = var(l2); + while (solver->solver->nVars() <= v) { solver->solver->newVar(); } + } + ret = solver->solver->addClause_(solver->currentClause); + solver->currentClause.clear(); + } + return ret ? 1 : 0; + } + + /** add the given literal to the assumptions for the next solver call */ + void + priss_assume(void* priss, const int& lit) + { + libpriss* solver = (libpriss*) priss; + solver->assumptions.push(lit > 0 ? mkLit(lit - 1, false) : mkLit(-lit - 1, true)); + } + + /** solve the formula that is currently present (priss_add) under the specified assumptions since the last call + * Note: clears the assumptions after the solver run finished + * @param nOfConflicts number of conflicts that are allowed for this SAT solver run (-1 = infinite) + * @return status of the SAT call: 10 = satisfiable, 20 = unsatisfiable, 0 = not finished within number of conflicts + */ + int + priss_sat(void* priss, const int& nOfConflicts) + { + libpriss* solver = (libpriss*) priss; + if (nOfConflicts == -1) { solver->solver->budgetOff(); } + else { solver->solver->setConfBudget(nOfConflicts); } + + // make sure the assumptions fit into the memory of the solver! + for (int i = 0 ; i < solver->assumptions.size(); ++ i) { + while (var(solver->assumptions[i]) >= solver->solver->nVars()) { solver->solver->newVar(); } + } + + lbool ret = solver->solver->solveLimited(solver->assumptions); + solver->assumptions.clear(); // clear assumptions after the solver call finished + solver->lastResult = ret; // store last solver result + return ret == l_False ? 20 : (ret == l_Undef ? 0 : 10); // return UNSAT, UNKNOWN or SAT, depending on solver result + } + + /** return the polarity of a variable in the model of the last solver run (if the result was sat) */ + int + priss_deref(const void* priss, const int& lit) + { + const Var v = lit > 0 ? lit - 1 : -lit - 1; + libpriss* solver = (libpriss*) priss; + assert(solver->lastResult == l_True && "can deref literals only after SAT result"); + lbool vValue = l_Undef; + if (v < solver->solver->model.size()) { vValue = solver->solver->model[v]; } + return (lit < 0) ? (vValue == l_False ? 1 : (vValue == l_True ? -1 : 0)) : (vValue == l_False ? -1 : (vValue == l_True ? 1 : 0)); + } + + +} + +// #pragma GCC visibility pop + +//#pragma GCC visibility pop diff --git a/pool/shard011/C++/0122154_checkbox.cpp b/pool/shard011/C++/0122154_checkbox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..537daa42813f5ea7ad0fe9f98931a14b2f2e2af8 --- /dev/null +++ b/pool/shard011/C++/0122154_checkbox.cpp @@ -0,0 +1,127 @@ +///////////////////////////////////////////////////////////////////////////// +// Name: src/qt/checkbox.cpp +// Author: Peter Most, Mariano Reingart +// Copyright: (c) 2009 wxWidgets dev team +// Licence: wxWindows licence +///////////////////////////////////////////////////////////////////////////// + +// For compilers that support precompilation, includes "wx.h". +#include "wx/wxprec.h" + +#include "wx/checkbox.h" +#include "wx/qt/private/utils.h" +#include "wx/qt/private/converter.h" +#include "wx/qt/private/winevent.h" + +class wxQtCheckBox : public wxQtEventSignalHandler< QCheckBox, wxCheckBox > +{ +public: + wxQtCheckBox( wxWindow *parent, wxCheckBox *handler ); + +private: + void clicked( bool checked ); +}; + +wxQtCheckBox::wxQtCheckBox( wxWindow *parent, wxCheckBox *handler ) + : wxQtEventSignalHandler< QCheckBox, wxCheckBox >( parent, handler ) +{ + connect(this, &QCheckBox::clicked, this, &wxQtCheckBox::clicked); +} + +void wxQtCheckBox::clicked( bool checked ) +{ + wxCheckBox *handler = GetHandler(); + if ( handler ) + { + wxCommandEvent event( wxEVT_CHECKBOX, handler->GetId() ); + if (!handler->Is3rdStateAllowedForUser() && + checkState() == Qt::PartiallyChecked) + setCheckState(Qt::Checked); + + event.SetInt( checked ); + EmitEvent( event ); + } +} + + +wxCheckBox::wxCheckBox() +{ +} + +wxCheckBox::wxCheckBox( wxWindow *parent, wxWindowID id, const wxString& label, + const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, + const wxString& name ) +{ + Create( parent, id, label, pos, size, style, validator, name ); +} + +bool wxCheckBox::Create(wxWindow *parent, wxWindowID id, const wxString& label, + const wxPoint& pos, const wxSize& size, long style, const wxValidator& validator, + const wxString& name ) +{ + m_qtCheckBox = new wxQtCheckBox( parent, this ); + m_qtCheckBox->setText( wxQtConvertString( label ) ); + + // Do the initialization here as WXValidateStyle may fail in unit tests + bool ok = QtCreateControl( parent, id, pos, size, style, validator, name ); + + WXValidateStyle(&style); + + if ( style & wxCHK_2STATE ) + m_qtCheckBox->setTristate( false ); + else if ( style & wxCHK_3STATE ) + m_qtCheckBox->setTristate( true ); + if ( style & wxALIGN_RIGHT ) + m_qtCheckBox->setLayoutDirection( Qt::RightToLeft ); + + return ok; +} + + +void wxCheckBox::SetValue(bool value) +{ + m_qtCheckBox->setChecked( value ); +} + +bool wxCheckBox::GetValue() const +{ + return m_qtCheckBox->isChecked(); +} + +void wxCheckBox::DoSet3StateValue(wxCheckBoxState state) +{ + switch (state) + { + case wxCHK_UNCHECKED: + m_qtCheckBox->setCheckState(Qt::Unchecked); + break; + + case wxCHK_CHECKED: + m_qtCheckBox->setCheckState(Qt::Checked); + break; + + case wxCHK_UNDETERMINED: + m_qtCheckBox->setCheckState(Qt::PartiallyChecked); + break; + } +} + +wxCheckBoxState wxCheckBox::DoGet3StateValue() const +{ + switch (m_qtCheckBox->checkState()) + { + case Qt::Unchecked: + return wxCHK_UNCHECKED; + + case Qt::Checked: + return wxCHK_CHECKED; + + case Qt::PartiallyChecked: + return wxCHK_UNDETERMINED; + } +} + +QCheckBox *wxCheckBox::GetHandle() const +{ + return m_qtCheckBox; +} diff --git a/pool/shard011/C++/0122156_drcachesim_unit_tests.cpp b/pool/shard011/C++/0122156_drcachesim_unit_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bdd82a6e2d9ed9ee0a4200afa46b2032d2ddaaac --- /dev/null +++ b/pool/shard011/C++/0122156_drcachesim_unit_tests.cpp @@ -0,0 +1,145 @@ +/* ********************************************************** + * Copyright (c) 2016-2018 Google, Inc. All rights reserved. + * **********************************************************/ + +/* + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * * Neither the name of Google, Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL GOOGLE, INC. OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + */ + +// Unit tests for drcachesim +#include +#include +#include "simulator/cache_simulator.h" +#include "../common/memref.h" + +static cache_simulator_knobs_t +make_test_knobs() +{ + cache_simulator_knobs_t knobs; + knobs.num_cores = 1; + knobs.L1I_size = 32 * 64; + knobs.L1D_size = 32 * 64; + knobs.L1I_assoc = 32; + knobs.L1D_assoc = 32; + knobs.LL_size = 32 * 64; + knobs.LL_assoc = 32; + knobs.data_prefetcher = "none"; + return knobs; +} + +void +unit_test_warmup_fraction() +{ + cache_simulator_knobs_t knobs = make_test_knobs(); + knobs.warmup_fraction = 0.5; + cache_simulator_t cache_sim(knobs); + + // Feed it some memrefs, warmup fraction is set to 0.5 where the capacity at + // each level is 32 lines each. The first 16 memrefs warm up the cache and + // the 17th allows us to check for the warmup_fraction. + std::string error; + for (int i = 0; i < 16 + 1; i++) { + memref_t ref; + ref.data.type = TRACE_TYPE_READ; + ref.data.size = 8; + ref.data.addr = i * 128; + if (!cache_sim.process_memref(ref)) { + std::cerr << "drcachesim unit_test_warmup_fraction failed: " + << cache_sim.get_error_string() << "\n"; + exit(1); + } + } + + if (!cache_sim.check_warmed_up()) { + std::cerr << "drcachesim unit_test_warmup_fraction failed\n"; + exit(1); + } +} + +void +unit_test_warmup_refs() +{ + cache_simulator_knobs_t knobs = make_test_knobs(); + knobs.warmup_refs = 16; + cache_simulator_t cache_sim(knobs); + + // Feed it some memrefs, warmup refs = 16 where the capacity at + // each level is 32 lines each. The first 16 memrefs warm up the cache and + // the 17th allows us to check. + std::string error; + for (int i = 0; i < 16 + 1; i++) { + memref_t ref; + ref.data.type = TRACE_TYPE_READ; + ref.data.size = 8; + ref.data.addr = i * 128; + if (!cache_sim.process_memref(ref)) { + std::cerr << "drcachesim unit_test_warmup_fraction failed: " + << cache_sim.get_error_string() << "\n"; + exit(1); + } + } + + if (!cache_sim.check_warmed_up()) { + std::cerr << "drcachesim unit_test_warmup_refs failed\n"; + exit(1); + } +} + +void +unit_test_sim_refs() +{ + cache_simulator_knobs_t knobs = make_test_knobs(); + knobs.sim_refs = 8; + cache_simulator_t cache_sim(knobs); + + std::string error; + for (int i = 0; i < 16; i++) { + memref_t ref; + ref.data.type = TRACE_TYPE_READ; + ref.data.size = 8; + ref.data.addr = i * 128; + if (!cache_sim.process_memref(ref)) { + std::cerr << "drcachesim unit_test_sim_refs failed: " + << cache_sim.get_error_string() << "\n"; + exit(1); + } + } + + if (cache_sim.remaining_sim_refs() != 0) { + std::cerr << "drcachesim unit_test_sim_refs failed\n"; + exit(1); + } +} + +int +main(int argc, const char *argv[]) +{ + unit_test_warmup_fraction(); + unit_test_warmup_refs(); + unit_test_sim_refs(); + return 0; +} diff --git a/pool/shard011/C++/0122158_ListScheduledAuditsResult.cpp b/pool/shard011/C++/0122158_ListScheduledAuditsResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee35b9bee3efc186cae5afee6ec064e0211cf0c8 --- /dev/null +++ b/pool/shard011/C++/0122158_ListScheduledAuditsResult.cpp @@ -0,0 +1,59 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::IoT::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +ListScheduledAuditsResult::ListScheduledAuditsResult() +{ +} + +ListScheduledAuditsResult::ListScheduledAuditsResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +ListScheduledAuditsResult& ListScheduledAuditsResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("scheduledAudits")) + { + Array scheduledAuditsJsonList = jsonValue.GetArray("scheduledAudits"); + for(unsigned scheduledAuditsIndex = 0; scheduledAuditsIndex < scheduledAuditsJsonList.GetLength(); ++scheduledAuditsIndex) + { + m_scheduledAudits.push_back(scheduledAuditsJsonList[scheduledAuditsIndex].AsObject()); + } + } + + if(jsonValue.ValueExists("nextToken")) + { + m_nextToken = jsonValue.GetString("nextToken"); + + } + + + + return *this; +} diff --git a/pool/shard011/C++/0122159_HTMLSanitizer.cpp b/pool/shard011/C++/0122159_HTMLSanitizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..027ece2c1a2f53aa10a5171002d60951d394e2dd --- /dev/null +++ b/pool/shard011/C++/0122159_HTMLSanitizer.cpp @@ -0,0 +1,138 @@ +#include "stdafx.h" +#include "HTMLSanitizer.h" +#include "Helper.h" + +//https://html5sec.org/ +const char* szForbiddenContent[] = { + "script", //noscript/onbeforescriptexecute + "style", + "svg", + "audio", + "video", + "head", + "math", + "template", + "form", //formaction + "input", //oninput + "onerror", + "frame", //iframe/noframe/frameset + "img", + "marquee", + "applet", + "object", + "embed", + "math", + "href", + "onfocus", + "onresize", + "onactivate", + "onscroll", + "onwebkittransitionend", + "onanimationstart", + "ontoggle", + "details", + "table", + + nullptr +}; + +//Maybe the way we search for 'safe' words is to safe, but better safe then sorry +std::string HTMLSanitizer::Sanitize(const std::string& szText) +{ + std::string ret; + std::string tmpstr(szText); + + do + { + size_t pos_start = tmpstr.find('<'); + if (pos_start == std::string::npos) + { + ret += tmpstr; + return ret; + } + + ret += tmpstr.substr(0, pos_start); + tmpstr = tmpstr.substr(pos_start); + + size_t pos_end = tmpstr.find('>'); + if (pos_end == std::string::npos) + { + ret += tmpstr; + return ret; + } + + std::string tag = tmpstr.substr(0, pos_end + 1); + std::string org_tag(tag); + tmpstr = tmpstr.substr(pos_end + 1); + + //See if we have a forbidden tag, if yes remove it + stdlower(tag); + + size_t ii = 0; + bool bHaveForbiddenTag = false; + while (szForbiddenContent[ii] != NULL) + { + if (tag.find(szForbiddenContent[ii]) != std::string::npos) + { + bHaveForbiddenTag = true; + break; + } + ii++; + } + if (!bHaveForbiddenTag) + ret += org_tag; + } while (1); + //will never be reached + return ret; +} + +std::wstring HTMLSanitizer::Sanitize(const std::wstring& szText) +{ + std::wstring ret; + std::wstring tmpstr(szText); + + do + { + size_t pos_start = tmpstr.find('<'); + if (pos_start == std::wstring::npos) + { + ret += tmpstr; + return ret; + } + + ret += tmpstr.substr(0, pos_start); + tmpstr = tmpstr.substr(pos_start); + + size_t pos_end = tmpstr.find('>'); + if (pos_end == std::wstring::npos) + { + ret += tmpstr; + return ret; + } + + std::wstring tag = tmpstr.substr(0, pos_end + 1); + std::wstring org_tag(tag); + tmpstr = tmpstr.substr(pos_end + 1); + + //See if we have a forbidden tag, if yes remove it + stdlower(tag); + + size_t ii = 0; + bool bHaveForbiddenTag = false; + while (szForbiddenContent[ii] != NULL) + { + std::string s(szForbiddenContent[ii]); + std::wstring wsTmp(s.begin(), s.end()); + if (tag.find(wsTmp) != std::wstring::npos) + { + bHaveForbiddenTag = true; + break; + } + ii++; + } + if (!bHaveForbiddenTag) + ret += org_tag; + } while (1); + //will never be reached + return ret; +} \ No newline at end of file diff --git a/pool/shard011/C++/0122160_Basic.cpp b/pool/shard011/C++/0122160_Basic.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d838ddd8adc37bc1012b25b10a29fd4c0eb07f8e --- /dev/null +++ b/pool/shard011/C++/0122160_Basic.cpp @@ -0,0 +1,75 @@ +/* +This file is part of octoDrone. + +octoDrone 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. + +octoDrone 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 octoDrone. If not, see . +*/ + +///Basic messaging protocol for testing where nodes receive all messages sent if they are within range + +#include "Basic.hpp" +#include +#include +#include "Basic_message.hpp" +#include +#include +#include + +Basic::Basic(Environment* env, std::atomic_flag* flag): CommMod(env){ + RANGE = 1000000.0f; + lock = flag; +} + +///The main communications loop which handles incomming and outgoing messages +/** + * Every loop we send any messages that are waiting to be sent + * Then we deliver any messages that we have received + */ +void Basic::comm_function(){ + while(true){ + while (!inQueue.empty()){ + std::string message = inQueue.front(); + inQueue.pop(); + Message* to_push = new Basic_message(message); + messageable->push_message(to_push); + log("rec'd message"); + } + + while (!outQueue.empty()){ + Message* message = outQueue.front(); + outQueue.pop(); + + if (message->to_string() == "KILL"){ + log("exiting"); + return; + } + + double xpos = messageable->getX(); + double ypos = messageable->getY();; + double zpos = messageable->getZ(); + environment->broadcast(message->to_string(), xpos, ypos, zpos, RANGE, this); + log("broadcast message"); + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } +} + +///Helper function to log internal information +/** + * Makes use of the stdout lock we were passed on creation to make sure that only one thread is printing at any one time + */ +void Basic::log(std::string log_message){ + while (lock->test_and_set()){} + std::cout << "basic: " << log_message << std::endl; + lock->clear(); +} diff --git a/pool/shard011/C++/0122161_qnodenamespaceresolver.cpp b/pool/shard011/C++/0122161_qnodenamespaceresolver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6295ec84be33b8667b8a877fa16818bdd39a092e --- /dev/null +++ b/pool/shard011/C++/0122161_qnodenamespaceresolver.cpp @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the QtXmlPatterns module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial License Usage +** Licensees holding valid commercial Qt licenses may use this file in +** accordance with the commercial license agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Digia. For licensing terms and +** conditions see http://qt.digia.com/licensing. For further information +** use the contact form at http://qt.digia.com/contact-us. +** +** GNU Lesser General Public License Usage +** Alternatively, this file may be used under the terms of the GNU Lesser +** General Public License version 2.1 as published by the Free Software +** Foundation and appearing in the file LICENSE.LGPL included in the +** packaging of this file. Please review the following information to +** ensure the GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** 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. +** +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qitem_p.h" +#include "qnamepool_p.h" + +#include "qnodenamespaceresolver_p.h" + +QT_BEGIN_NAMESPACE + +using namespace QPatternist; + +NodeNamespaceResolver::NodeNamespaceResolver(const Item &item) : m_node(item.asNode()) +{ + Q_ASSERT(!m_node.isNull()); +} + +void NodeNamespaceResolver::addBinding(const QXmlName nb) +{ + Q_UNUSED(nb); + Q_ASSERT_X(false, Q_FUNC_INFO, "Calling this function for this sub-class makes little sense."); +} + +QXmlName::NamespaceCode NodeNamespaceResolver::lookupNamespaceURI(const QXmlName::PrefixCode prefix) const +{ + const QXmlName::NamespaceCode ns = m_node.namespaceForPrefix(prefix); + + if(ns == NoBinding) + { + if(prefix == StandardPrefixes::empty) + return StandardNamespaces::empty; + else + return NoBinding; + } + else + return ns; +} + +NamespaceResolver::Bindings NodeNamespaceResolver::bindings() const +{ + Q_ASSERT_X(false, Q_FUNC_INFO, "Not implemented."); + return NamespaceResolver::Bindings(); +} + +QT_END_NAMESPACE diff --git a/pool/shard011/C++/0122165_tst_paradoxmindaysvssamedaytest.cpp b/pool/shard011/C++/0122165_tst_paradoxmindaysvssamedaytest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..030d46811a49ede17aef9598836db2ddb6af111c --- /dev/null +++ b/pool/shard011/C++/0122165_tst_paradoxmindaysvssamedaytest.cpp @@ -0,0 +1,150 @@ +/*************************************************************************** + * * + * This program is free software: you can redistribute it and/or modify * + * it under the terms of the GNU Affero General Public License as * + * published by the Free Software Foundation, either version 3 of the * + * License, or (at your option) any later version. * + * * + ***************************************************************************/ + +#include + +#include "constraints/paradoxmindaysvssameday.h" + +#include "generate_pre.h" +#include "timetable.h" +Timetable gt; // Just to please generate_pre.cpp that yet require it. It must be not used in tests + +class ParadoxMinDaysVsSameDayTest : public QObject +{ + Q_OBJECT + +public: + ParadoxMinDaysVsSameDayTest(); + ~ParadoxMinDaysVsSameDayTest(); + +private: + Rules &rules; + void populate_basic_data(); + +private slots: + void init(); + void cleanup(); + void test_generate_error_message(); + void test_generate_multiple_error_messages(); + void test_reset_properly(); +}; + +ParadoxMinDaysVsSameDayTest::ParadoxMinDaysVsSameDayTest() + : rules(gt.rules) +{ + +} + +ParadoxMinDaysVsSameDayTest::~ParadoxMinDaysVsSameDayTest() +{ + +} + +void ParadoxMinDaysVsSameDayTest::populate_basic_data() +{ + QStringList teachers; + QStringList activitytags; + QStringList studentsnames; + QString subject("subject1"); + + Rules &rules = gt.rules; + if (!rules.initialized) + rules.init(); + Subject *psubject = new Subject(); + psubject->name = subject; + rules.addSubjectFast(psubject); + rules.addSimpleActivityFast(12345, 12345, teachers, subject, activitytags, studentsnames, 1, 1, true, false, 10, 10); + rules.addSimpleActivityFast(23456, 23456, teachers, subject, activitytags, studentsnames, 1, 1, true, false, 10, 10); + rules.addSimpleActivityFast(34567, 34567, teachers, subject, activitytags, studentsnames, 1, 1, true, false, 10, 10); + rules.computeInternalStructure(); + + ConstraintBasicCompulsoryTime * ctr = new ConstraintBasicCompulsoryTime(); + rules.addTimeConstraint(ctr); + ConstraintBasicCompulsorySpace * sctr = new ConstraintBasicCompulsorySpace(); + rules.addSpaceConstraint(sctr); +} + +void ParadoxMinDaysVsSameDayTest::init() +{ + rules.init(); + populate_basic_data(); +} + +void ParadoxMinDaysVsSameDayTest::cleanup() +{ + rules.kill(); +} + +void ParadoxMinDaysVsSameDayTest::test_generate_error_message() +{ + QList acts; + acts << 12345 << 23456; + + TimeConstraint * ctr = new ConstraintMinDaysBetweenActivities(100, false, 2, acts, 1); + rules.addTimeConstraint(ctr); + ctr = new ConstraintActivitiesSameStartingDay(100, 2, acts); + rules.addTimeConstraint(ctr); + rules.computeInternalStructure(); + + ParadoxMinDaysVsSameDay paradox; + processTimeSpaceConstraints(NULL); + bool result = paradox.prepare(rules); + QVERIFY2(!result, "Paradox found"); + + QCOMPARE(paradox.getErrors().size(), 1); +} + +void ParadoxMinDaysVsSameDayTest::test_generate_multiple_error_messages() +{ + QList acts; + acts << 12345 << 23456 << 34567; + + TimeConstraint * ctr = new ConstraintMinDaysBetweenActivities(100, false, 3, acts, 1); + rules.addTimeConstraint(ctr); + ctr = new ConstraintActivitiesSameStartingDay(100, 2, QList() << 12345 << 23456); + rules.addTimeConstraint(ctr); + ctr = new ConstraintActivitiesSameStartingDay(100, 2, QList() << 34567 << 23456); + rules.addTimeConstraint(ctr); + rules.computeInternalStructure(); + + ParadoxMinDaysVsSameDay paradox; + processTimeSpaceConstraints(NULL); + bool result = paradox.prepare(rules); + QVERIFY2(!result, "Paradox found"); + + QCOMPARE(paradox.getErrors().size(), 2); +} + +void ParadoxMinDaysVsSameDayTest::test_reset_properly() +{ + QList acts; + acts << 12345 << 23456; + + TimeConstraint * ctr = new ConstraintMinDaysBetweenActivities(100, false, 2, acts, 1); + rules.addTimeConstraint(ctr); + ctr = new ConstraintActivitiesSameStartingDay(100, 2, acts); + rules.addTimeConstraint(ctr); + rules.computeInternalStructure(); + + ParadoxMinDaysVsSameDay paradox; + processTimeSpaceConstraints(NULL); + bool result = paradox.prepare(rules); + QVERIFY2(!result, "Paradox found"); + + QCOMPARE(paradox.getErrors().size(), 1); + + result = paradox.prepare(rules); + QVERIFY2(!result, "Paradox found"); + + QCOMPARE(paradox.getErrors().size(), 1); +} + +QTEST_APPLESS_MAIN(ParadoxMinDaysVsSameDayTest) + +#include "tst_paradoxmindaysvssamedaytest.moc" diff --git a/pool/shard011/C++/0122166_wavfile.cpp b/pool/shard011/C++/0122166_wavfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..613db4ef9de4ffbe2b2849ec6f0ba8e43e6c397f --- /dev/null +++ b/pool/shard011/C++/0122166_wavfile.cpp @@ -0,0 +1,145 @@ +/*************************************************************************** + copyright : (C) 2008 by Scott Wheeler + email : wheeler@kde.org + ***************************************************************************/ + +/*************************************************************************** + * This library is free software; you can redistribute it and/or modify * + * it under the terms of the GNU Lesser General Public License version * + * 2.1 as published by the Free Software Foundation. * + * * + * This library is distributed in the hope that it will be useful, but * + * WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * + * Lesser General Public License for more details. * + * * + * You should have received a copy of the GNU Lesser General Public * + * License along with this library; if not, write to the Free Software * + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * + * 02110-1301 USA * + * * + * Alternatively, this file is available under the Mozilla Public * + * License Version 1.1. You may obtain a copy of the License at * + * http://www.mozilla.org/MPL/ * + ***************************************************************************/ + +#include +#include +#include +#include +#include + +#include "wavfile.h" + +using namespace TagLib; + +class RIFF::WAV::File::FilePrivate +{ +public: + FilePrivate() : + properties(0), + tag(0), + tagChunkID("ID3 ") + { + + } + + ~FilePrivate() + { + delete properties; + delete tag; + } + + Properties *properties; + ID3v2::Tag *tag; + ByteVector tagChunkID; +}; + +//////////////////////////////////////////////////////////////////////////////// +// public members +//////////////////////////////////////////////////////////////////////////////// + +RIFF::WAV::File::File(FileName file, bool readProperties, + Properties::ReadStyle propertiesStyle) : RIFF::File(file, LittleEndian) +{ + d = new FilePrivate; + if(isOpen()) + read(readProperties, propertiesStyle); +} + +RIFF::WAV::File::File(IOStream *stream, bool readProperties, + Properties::ReadStyle propertiesStyle) : RIFF::File(stream, LittleEndian) +{ + d = new FilePrivate; + if(isOpen()) + read(readProperties, propertiesStyle); +} + +RIFF::WAV::File::~File() +{ + delete d; +} + +ID3v2::Tag *RIFF::WAV::File::tag() const +{ + return d->tag; +} + +PropertyMap RIFF::WAV::File::properties() const +{ + return d->tag->properties(); +} + +PropertyMap RIFF::WAV::File::setProperties(const PropertyMap &properties) +{ + return d->tag->setProperties(properties); +} + + +RIFF::WAV::Properties *RIFF::WAV::File::audioProperties() const +{ + return d->properties; +} + +bool RIFF::WAV::File::save() +{ + if(readOnly()) { + debug("RIFF::WAV::File::save() -- File is read only."); + return false; + } + + if(!isValid()) { + debug("RIFF::WAV::File::save() -- Trying to save invalid file."); + return false; + } + + setChunkData(d->tagChunkID, d->tag->render()); + + return true; +} + +//////////////////////////////////////////////////////////////////////////////// +// private members +//////////////////////////////////////////////////////////////////////////////// + +void RIFF::WAV::File::read(bool readProperties, Properties::ReadStyle propertiesStyle) +{ + ByteVector formatData; + uint streamLength = 0; + for(uint i = 0; i < chunkCount(); i++) { + if(chunkName(i) == "ID3 " || chunkName(i) == "id3 ") { + d->tagChunkID = chunkName(i); + d->tag = new ID3v2::Tag(this, chunkOffset(i)); + } + else if(chunkName(i) == "fmt " && readProperties) + formatData = chunkData(i); + else if(chunkName(i) == "data" && readProperties) + streamLength = chunkDataSize(i); + } + + if(!formatData.isEmpty()) + d->properties = new Properties(formatData, streamLength, propertiesStyle); + + if(!d->tag) + d->tag = new ID3v2::Tag; +} diff --git a/pool/shard011/C++/0122170_communicator.cc b/pool/shard011/C++/0122170_communicator.cc new file mode 100644 index 0000000000000000000000000000000000000000..46949793a206e847443d122b3b2a0e6437e33a11 --- /dev/null +++ b/pool/shard011/C++/0122170_communicator.cc @@ -0,0 +1,148 @@ +/* + PowerDNS Versatile Database Driven Nameserver + Copyright (C) 2002-2011 PowerDNS.COM BV + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License version 2 as + published by the Free Software Foundation; + + Additionally, the license of this program contains a special + exception which allows to distribute the program in binary form when + it is linked against OpenSSL. + + 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 St, Fifth Floor, Boston, MA 02110-1301 USA +*/ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif +#include "packetcache.hh" +#include "utility.hh" +#include +#include "communicator.hh" +#include +#include +#include "dnsbackend.hh" +#include "ueberbackend.hh" +#include "packethandler.hh" +#include "resolver.hh" +#include "logger.hh" +#include "dns.hh" +#include "arguments.hh" +#include "packetcache.hh" +#include + +// #include "namespaces.hh" + +void CommunicatorClass::retrievalLoopThread(void) +{ + for(;;) { + d_suck_sem.wait(); + SuckRequest sr; + { + Lock l(&d_lock); + if(d_suckdomains.empty()) + continue; + + sr=d_suckdomains.front(); + d_suckdomains.pop_front(); + } + suck(sr.domain,sr.master); + } +} + +void CommunicatorClass::go() +{ + try { + PacketHandler::s_allowNotifyFrom.toMasks(::arg()["allow-notify-from"] ); + } + catch(PDNSException &e) { + L< parts; + stringtok(parts, ::arg()["also-notify"], ", \t"); + for (vector::const_iterator iter = parts.begin(); iter != parts.end(); ++iter) { + try { + ComboAddress caIp(*iter, 53); + d_alsoNotify.insert(caIp.toStringWithPort()); + } + catch(PDNSException &e) { + L< + */ + +#include + +#include "utility.h" +#include "strutil.h" +#include "testing_macros.hpp" + +using namespace std; + +void test_normalize_path() +{ + string p1("//a/./b"); + auto p1fixes = moose::normalizePath(p1); + std::cout << p1 << " " << p1fixes << std::endl; + + string p2("//a/./././///b"); + auto p2fixes = moose::normalizePath(p2); + std::cout << p2 << " " << p2fixes << std::endl; + ASSERT_EQ( p2fixes, "/a/b", "PATH"); +} + +int main(int argc, const char *argv[]) +{ + test_normalize_path(); + return 0; +} + diff --git a/pool/shard011/C++/0122172_CWE127_Buffer_Underread__char_declare_loop_72b.cpp b/pool/shard011/C++/0122172_CWE127_Buffer_Underread__char_declare_loop_72b.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2d811286b2c2f195721d5559337f6c9c83296701 --- /dev/null +++ b/pool/shard011/C++/0122172_CWE127_Buffer_Underread__char_declare_loop_72b.cpp @@ -0,0 +1,75 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__char_declare_loop_72b.cpp +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-72b.tmpl.cpp +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sinks: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +#include + +using namespace std; + +namespace CWE127_Buffer_Underread__char_declare_loop_72 +{ + +#ifndef OMITBAD + +void badSink(vector dataVector) +{ + /* copy data out of dataVector */ + char * data = dataVector[2]; + { + size_t i; + char dest[100]; + memset(dest, 'C', 100-1); /* fill with 'C's */ + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + for (i = 0; i < 100; i++) + { + dest[i] = data[i]; + } + /* Ensure null termination */ + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(vector dataVector) +{ + char * data = dataVector[2]; + { + size_t i; + char dest[100]; + memset(dest, 'C', 100-1); /* fill with 'C's */ + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + for (i = 0; i < 100; i++) + { + dest[i] = data[i]; + } + /* Ensure null termination */ + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITGOOD */ + +} /* close namespace */ diff --git a/pool/shard011/C++/0122175_main.cpp b/pool/shard011/C++/0122175_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3f9680720d3b64a3dbb5f8ed04954eff5e03f048 --- /dev/null +++ b/pool/shard011/C++/0122175_main.cpp @@ -0,0 +1,148 @@ +// +// Copyright (c) 2012, University of Erlangen-Nuremberg +// Copyright (c) 2012, Siemens AG +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are met: +// +// 1. Redistributions of source code must retain the above copyright notice, this +// list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright notice, +// this list of conditions and the following disclaimer in the documentation +// and/or other materials provided with the distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// + +#include "hipacc.hpp" + +#include +#include + + +#ifndef IMAGE_BASE_PATH +# define IMAGE_BASE_PATH "" +#endif + + +#define WIDTH 1600 +#define HEIGHT 900 + +#define PACK_INT + +#ifdef PACK_INT +# define data_t uint +# define pack(a, b, c, d) \ + (uint)((uint)(a) | (uint)(b) << 8 | (uint)(c) << 16 | (uint)(d) << 24) +#else +# define data_t uchar4 +# define pack(a, b, c, d) \ + ((uchar4){(uchar)a, (uchar)b, (uchar)c, (uchar)d}) +#endif + + +using namespace hipacc; +using namespace hipacc::math; + + +class Mandelbrot : public Kernel { + private: + const int width, height; + const float scale, ox, oy; + + public: + Mandelbrot(IterationSpace &iter, const int w, const int h, + const float s, const float ox, const float oy) + : Kernel(iter), width(w), height(h), scale(s), ox(ox), oy(oy) {} + + void kernel() { + float x0 = ((float)x() / (float)width * 3.5f) / scale - 2.5f + ox; + float y0 = ((float)y() / (float)height * 2.0f) / scale - 1.0f + oy; + float x = 0; + float y = 0; + int iteration = 0; + int max_iteration = 1000; + + while ((x*x + y*y < 2*2) && (iteration < max_iteration)) { + float xtemp = x*x - y*y + x0; + y = 2*x*y + y0; + x = xtemp; + ++iteration; + } + + uchar rout = 0; + uchar gout = 0; + uchar bout = 0; + if (iteration < max_iteration) { + float mu = (float)iteration + 1.0f - logf(logf(sqrtf(x*x + y*y))) / logf(2.0f); + int c = (int)(mu / max_iteration * 768); + if (c >= 512) { + bout = c - 512; + gout = 255 - rout; + } else if (c >= 256) { + gout = c - 256; + rout = 255 - gout; + } else { + rout = c; + } + } + output() = pack(bout, gout, rout, 255); + } +}; + + +/************************************************************************* + * Main function * + *************************************************************************/ +HIPACC_CODEGEN int main(int argc, const char **argv) { + const int width = WIDTH; + const int height = HEIGHT; + float timing = 0; + + data_t *output; + + std::cout << "Calculating Hipacc Mandelbrot ..." << std::endl; + + //************************************************************************// + + // output image of width x height pixels + Image out(width, height); + + IterationSpace iter(out); + + const int max_steps = 1000; + for (int i = 0; i <= max_steps; ++i) { + float step = (float)i/max_steps; + float scale = 1.00f+step*9; + + Mandelbrot mandelbrot(iter, width, height, scale, step*.6f*width/100/scale, step*height/100/scale); + mandelbrot.execute(); + + timing = hipacc_last_kernel_timing(); + std::cout << "Hipacc: " << timing << " ms, " + << (width*height/timing)/1000 << " Mpixel/s" << std::endl; + + // get pointer to result data + output = out.data(); + + if (i == 0 || i == max_steps) { + save_data(width, height, 4, (uchar*)output, "output.jpg"); + } + + show_data(width, height, 4, (uchar*)output, "output.jpg", 1); + } + + //************************************************************************// + + return EXIT_SUCCESS; +} diff --git a/pool/shard011/C++/0122176_usblink_queue.cpp b/pool/shard011/C++/0122176_usblink_queue.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb494c936fec726671d73e9033aec58cc0b61e54 --- /dev/null +++ b/pool/shard011/C++/0122176_usblink_queue.cpp @@ -0,0 +1,231 @@ +#include +#include +#include +#include +#include + +#include "usblink_queue.h" + +struct usblink_queue_action { + enum { + PUT_FILE, + SEND_OS, + DIRLIST, + MOVE, + DEL_FILE, + NEW_DIR, + DEL_DIR, + GET_FILE + } action; + + //Members only used if the appropriate action is set + std::string filepath; + std::string path; + usblink_progress_cb progress_callback = nullptr; + usblink_dirlist_cb dirlist_callback = nullptr; + void *user_data; +}; + +static std::atomic_bool busy; +static std::queue usblink_queue; + +static void dirlist_callback(struct usblink_file *f, bool is_error, void *user_data) +{ + assert(!usblink_queue.empty()); + assert(usblink_queue.front().user_data == user_data); + assert(usblink_queue.front().action == usblink_queue_action::DIRLIST); + + if(usblink_queue.front().dirlist_callback != nullptr) + usblink_queue.front().dirlist_callback(f, is_error, user_data); + + if(!f) + { + usblink_queue.pop(); + busy = false; + } +} + +static void progress_callback(int progress, void *user_data) +{ + assert(!usblink_queue.empty()); + assert(usblink_queue.front().user_data == user_data); + if(usblink_queue.front().progress_callback != nullptr) + { + auto action = usblink_queue.front().action; + if(action == usblink_queue_action::PUT_FILE + || action == usblink_queue_action::SEND_OS + || action == usblink_queue_action::MOVE + || action == usblink_queue_action::NEW_DIR + || action == usblink_queue_action::DEL_DIR + || action == usblink_queue_action::DEL_FILE + || action == usblink_queue_action::GET_FILE) + usblink_queue.front().progress_callback(progress, user_data); + else + assert(false); + } + + if(progress < 0 || progress == 100) + { + usblink_queue.pop(); + busy = false; + } +} + +void usblink_queue_do() +{ + bool b = false; + if(!usblink_connected || usblink_queue.empty() || !busy.compare_exchange_strong(b, true)) + return; + + usblink_queue_action action = usblink_queue.front(); + switch(action.action) + { + case usblink_queue_action::PUT_FILE: + if(!usblink_put_file(action.filepath.c_str(), action.path.c_str(), progress_callback, action.user_data)) + { + progress_callback(-1, action.user_data); + busy = false; + } + break; + case usblink_queue_action::SEND_OS: + if(!usblink_send_os(action.filepath.c_str(), progress_callback, action.user_data)) + { + progress_callback(-1, action.user_data); + busy = false; + } + break; + case usblink_queue_action::DIRLIST: + usblink_dirlist(action.path.c_str(), dirlist_callback, action.user_data); + break; + case usblink_queue_action::MOVE: + usblink_move(action.filepath.c_str(), action.path.c_str(), progress_callback, action.user_data); + break; + case usblink_queue_action::NEW_DIR: + usblink_new_dir(action.path.c_str(), progress_callback, action.user_data); + break; + case usblink_queue_action::DEL_DIR: + usblink_delete(action.path.c_str(), true, progress_callback, action.user_data); + break; + case usblink_queue_action::DEL_FILE: + usblink_delete(action.path.c_str(), false, progress_callback, action.user_data); + break; + case usblink_queue_action::GET_FILE: + if(!usblink_get_file(action.path.c_str(), action.filepath.c_str(), progress_callback, action.user_data)) + { + progress_callback(-1, action.user_data); + busy = false; + } + } +} + +void usblink_queue_reset() +{ + while(!usblink_queue.empty()) + { + // Treat as error + usblink_queue_action action = usblink_queue.front(); + if(action.dirlist_callback) + action.dirlist_callback(nullptr, true, action.user_data); + else if(action.progress_callback) + action.progress_callback(-1, action.user_data); + + usblink_queue.pop(); + } + + busy = false; + + usblink_reset(); +} + +void usblink_queue_add(usblink_queue_action &action) +{ + usblink_queue.push(action); + + if(!usblink_connected) + usblink_connect(); +} + +void usblink_queue_delete(std::string path, bool is_dir, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = is_dir ? usblink_queue_action::DEL_DIR : usblink_queue_action::DEL_FILE; + action.user_data = user_data; + action.path = path; + action.progress_callback = callback; + + usblink_queue_add(action); +} + +void usblink_queue_dirlist(std::string path, usblink_dirlist_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::DIRLIST; + action.user_data = user_data; + action.path = path; + action.dirlist_callback = callback; + + usblink_queue_add(action); +} + +void usblink_queue_download(std::string path, std::string destpath, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::GET_FILE; + action.user_data = user_data; + action.filepath = destpath; + action.path = path; + action.progress_callback = callback; + + usblink_queue_add(action); +} + +void usblink_queue_put_file(std::string filepath, std::string folder, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::PUT_FILE; + action.user_data = user_data; + action.filepath = filepath; + action.path = folder; + action.progress_callback = callback; + + usblink_queue_add(action); +} + +void usblink_queue_send_os(const char *filepath, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::SEND_OS; + action.user_data = user_data; + action.filepath = filepath; + action.progress_callback = callback; + + usblink_queue_add(action); +} + +void usblink_queue_new_dir(std::string path, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::NEW_DIR; + action.user_data = user_data; + action.path = path; + action.progress_callback = callback, + + usblink_queue_add(action); +} + +void usblink_queue_move(std::string old_path, std::string new_path, usblink_progress_cb callback, void *user_data) +{ + usblink_queue_action action; + action.action = usblink_queue_action::MOVE; + action.user_data = user_data; + action.filepath = old_path; + action.path = new_path; + action.progress_callback = callback, + + usblink_queue_add(action); +} + +unsigned int usblink_queue_size() +{ + return usblink_queue.size(); +} diff --git a/pool/shard011/C++/0122178_rdo_ie.cpp b/pool/shard011/C++/0122178_rdo_ie.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b3482bca4cc3e0aad2db751f04db36b63a03133b --- /dev/null +++ b/pool/shard011/C++/0122178_rdo_ie.cpp @@ -0,0 +1,87 @@ +// ---------------------------------------------------------------------------- PCH +#include "converter/smr2rdox/pch.h" +// ----------------------------------------------------------------------- INCLUDES +#include +// ----------------------------------------------------------------------- SYNOPSIS +#include "converter/smr2rdox/runtime/rdo_ie.h" +#include "simulator/runtime/rdo_runtime.h" +// -------------------------------------------------------------------------------- + +OPEN_RDO_RUNTIME_NAMESPACE + +// -------------------------------------------------------------------------------- +// -------------------- RDOPatternIrregEvent +// -------------------------------------------------------------------------------- +RDOPatternIrregEvent::RDOPatternIrregEvent(bool trace) + : RDOPattern(trace) + , m_timeCalc(NULL ) +{} + +double RDOPatternIrregEvent::getNextTimeInterval(const LPRDORuntime& pRuntime) +{ + double time_next = m_timeCalc->calcValue(pRuntime).getDouble(); + if (time_next >= 0) + { + return time_next; + } + pRuntime->error().push(rdo::format("Попытка запланировать событие в прошлом. Выражение времени для $Time имеет отрицательное значение: %f", time_next), m_timeCalc->srcInfo()); + return 0; +} + +// -------------------------------------------------------------------------------- +// -------------------- RDOIrregEvent +// -------------------------------------------------------------------------------- +RDOIrregEvent::RDOIrregEvent(RDOPatternIrregEvent* pPattern, bool trace, const std::string& name) + : RDOActivityPattern(pPattern, trace, name) +{ + setTrace(trace); + setTraceID(std::size_t(~0)); +} + +void RDOIrregEvent::onStart(const LPRDORuntime& pRuntime) +{ + onBeforeIrregularEvent(pRuntime); +} + +void RDOIrregEvent::onStop(const LPRDORuntime& pRuntime) +{ + pRuntime->removeTimePoint(this); +} + +bool RDOIrregEvent::onCheckCondition(const LPRDORuntime& /*pRuntime*/) +{ + return false; +} + +IBaseOperation::ResultCode RDOIrregEvent::onDoOperation(const LPRDORuntime& /*pRuntime*/) +{ + return IBaseOperation::ResultCode::CANNOT_RUN; +} + +void RDOIrregEvent::convertEvent(const LPRDORuntime& /*pRuntime*/) +{ + NEVER_REACH_HERE; +} + +void RDOIrregEvent::onBeforeIrregularEvent(const LPRDORuntime& /*pRuntime*/) +{ + NEVER_REACH_HERE; +} + +void RDOIrregEvent::onAfterIrregularEvent(const LPRDORuntime& /*pRuntime*/) +{ + NEVER_REACH_HERE; +} + +double RDOIrregEvent::getNextTimeInterval(const LPRDORuntime& pRuntime) +{ + pRuntime->setCurrentActivity(this); + return m_pPattern->getNextTimeInterval(pRuntime); +} + +IBaseOperation::ResultCode RDOIrregEvent::onContinue(const LPRDORuntime& /*pRuntime*/) +{ + return IBaseOperation::ResultCode::CANNOT_RUN; +} + +CLOSE_RDO_RUNTIME_NAMESPACE diff --git a/pool/shard011/C++/0122180_client_app_browser.cc b/pool/shard011/C++/0122180_client_app_browser.cc new file mode 100644 index 0000000000000000000000000000000000000000..428acf4210c9bd424818b5c501010ea3c394ca21 --- /dev/null +++ b/pool/shard011/C++/0122180_client_app_browser.cc @@ -0,0 +1,85 @@ +// Copyright (c) 2013 The Chromium Embedded Framework 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 "appshell/browser/client_app_browser.h" + +#include "include/base/cef_logging.h" +#include "include/cef_cookie.h" +#include "appshell/common/client_switches.h" + +namespace client { + +ClientAppBrowser::ClientAppBrowser() { + CreateDelegates(delegates_); +} + +void ClientAppBrowser::OnBeforeCommandLineProcessing( + const CefString& process_type, + CefRefPtr command_line) { + // Pass additional command-line flags to the browser process. + if (process_type.empty()) { + // Pass additional command-line flags when off-screen rendering is enabled. + if (command_line->HasSwitch(switches::kOffScreenRenderingEnabled)) { + // If the PDF extension is enabled then cc Surfaces must be disabled for + // PDFs to render correctly. + // See https://bitbucket.org/chromiumembedded/cef/issues/1689 for details. + if (!command_line->HasSwitch("disable-extensions") && + !command_line->HasSwitch("disable-pdf-extension")) { + command_line->AppendSwitch("disable-surfaces"); + } + + // Use software rendering and compositing (disable GPU) for increased FPS + // and decreased CPU usage. This will also disable WebGL so remove these + // switches if you need that capability. + // See https://bitbucket.org/chromiumembedded/cef/issues/1257 for details. + if (!command_line->HasSwitch(switches::kEnableGPU)) { + command_line->AppendSwitch("disable-gpu"); + command_line->AppendSwitch("disable-gpu-compositing"); + } + + // Synchronize the frame rate between all processes. This results in + // decreased CPU usage by avoiding the generation of extra frames that + // would otherwise be discarded. The frame rate can be set at browser + // creation time via CefBrowserSettings.windowless_frame_rate or changed + // dynamically using CefBrowserHost::SetWindowlessFrameRate. In cefclient + // it can be set via the command-line using `--off-screen-frame-rate=XX`. + // See https://bitbucket.org/chromiumembedded/cef/issues/1368 for details. + command_line->AppendSwitch("enable-begin-frame-scheduling"); + } + + DelegateSet::iterator it = delegates_.begin(); + for (; it != delegates_.end(); ++it) + (*it)->OnBeforeCommandLineProcessing(this, command_line); + } +} + +void ClientAppBrowser::OnContextInitialized() { + // Register cookieable schemes with the global cookie manager. + CefRefPtr manager = + CefCookieManager::GetGlobalManager(NULL); + DCHECK(manager.get()); + manager->SetSupportedSchemes(cookieable_schemes_, NULL); + + print_handler_ = CreatePrintHandler(); + + DelegateSet::iterator it = delegates_.begin(); + for (; it != delegates_.end(); ++it) + (*it)->OnContextInitialized(this); +} + +void ClientAppBrowser::OnBeforeChildProcessLaunch( + CefRefPtr command_line) { + DelegateSet::iterator it = delegates_.begin(); + for (; it != delegates_.end(); ++it) + (*it)->OnBeforeChildProcessLaunch(this, command_line); +} + +void ClientAppBrowser::OnRenderProcessThreadCreated( + CefRefPtr extra_info) { + DelegateSet::iterator it = delegates_.begin(); + for (; it != delegates_.end(); ++it) + (*it)->OnRenderProcessThreadCreated(this, extra_info); +} + +} // namespace client diff --git a/pool/shard011/C++/0122184_PufferfishTestLookup.cpp b/pool/shard011/C++/0122184_PufferfishTestLookup.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f35e4c8428d35666dcd56b520522398ae6dc5de7 --- /dev/null +++ b/pool/shard011/C++/0122184_PufferfishTestLookup.cpp @@ -0,0 +1,123 @@ +#include "FastxParser.hpp" +#include +#include +#include +#include +#include + +#include "CLI/Timer.hpp" +#include "CanonicalKmer.hpp" +#include "CanonicalKmerIterator.hpp" +#include "PufferFS.hpp" +#include "ScopedTimer.hpp" +#include "Util.hpp" +#include "jellyfish/mer_dna.hpp" +#include "spdlog/spdlog.h" + +#include "ProgOpts.hpp" +#include "PufferfishIndex.hpp" +#include "PufferfishSparseIndex.hpp" +#include "Util.hpp" + +namespace kmers = combinelib::kmers; + +template +int doPufferfishTestLookup(IndexT& pi, pufferfish::ValidateOptions& validateOpts) { + CanonicalKmer::k(pi.k()); + int k = pi.k(); + (void)k; + size_t found = 0; + size_t notFound = 0; + size_t totalHits = 0; + { + CLI::AutoTimer timer{"searching kmers", CLI::Timer::Big}; + std::vector read_file = {validateOpts.refFile}; + fastx_parser::FastxParser parser(read_file, 1, 1); + parser.start(); + // Get the read group by which this thread will + // communicate with the parser (*once per-thread*) + size_t rn{0}; + pufferfish::util::QueryCache qc; + pufferfish::CanonicalKmerIterator kit_end; + auto rg = parser.getReadGroup(); + while (parser.refill(rg)) { + // Here, rg will contain a chunk of read pairs + // we can process. + for (auto& rp : rg) { + // kmer_pos = 0; + if (rn % 500000 == 0) { + std::cerr << "rn : " << rn << "\n"; + std::cerr << "found = " << found << ", notFound = " << notFound + << ", total hits = " << totalHits << "\n"; + } + ++rn; + auto& r1 = rp.seq; + /* + CanonicalKmer mer; + bool valid = true; + int lastinvalid = -1; + for (size_t i = 0; i < r1.length(); ++i) { + int c = kmers::codeForChar(r1[i]); + if (c != -1) { + mer.shiftFw(r1[i]); + valid = (i - lastinvalid >= k); + } else { + lastinvalid = i; + valid = false; + } + if (i >= k - 1 and valid) { + auto phits = pi.getRefPos(mer); + if (phits.empty()) { + ++notFound; + } else { + ++found; + bool cor = false; + uint32_t clen = 0; + std::vector wrongPos; + for (auto& rpos : phits.refRange) { + ++totalHits; + } + } + } + } + */ + + pufferfish::CanonicalKmerIterator kit1(r1); + for (; kit1 != kit_end; ++kit1) { + auto phits = pi.getRefPos(kit1->first, qc); + if (phits.empty()) { + ++notFound; + } else { + ++found; + totalHits += phits.refRange.size(); + } + } + } + } + } + std::cerr << "found = " << found << ", not found = " << notFound << "\n"; + std::cerr << "total hits = " << totalHits << "\n"; + return 0; +} + +int pufferfishTestLookup(pufferfish::ValidateOptions& validateOpts) { + auto indexDir = validateOpts.indexDir; + std::string indexType; + { + std::ifstream infoStream(indexDir + "/info.json"); + cereal::JSONInputArchive infoArchive(infoStream); + infoArchive(cereal::make_nvp("sampling_type", indexType)); + std::cerr << "Index type = " << indexType << '\n'; + infoStream.close(); + } + + if (indexType == "sparse") { + PufferfishSparseIndex pi(validateOpts.indexDir); + return doPufferfishTestLookup(pi, validateOpts); + } else if (indexType == "dense") { + PufferfishIndex pi(validateOpts.indexDir); + return doPufferfishTestLookup(pi, validateOpts); + } + return 0; +} + diff --git a/pool/shard011/C++/0122185_filecreate.cpp b/pool/shard011/C++/0122185_filecreate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..07f7f10ad1604f1da22dafc41ee131fa0d98afd9 --- /dev/null +++ b/pool/shard011/C++/0122185_filecreate.cpp @@ -0,0 +1,349 @@ +// license:BSD-3-Clause +// copyright-holders:Nathan Woods +/*************************************************************************** + + ui/filecreate.cpp + + MAME's clunky built-in file manager + + TODO + - Support image creation arguments + +***************************************************************************/ + +#include "emu.h" + +#include "ui/filecreate.h" +#include "ui/ui.h" +#include "ui/utils.h" + +#include "imagedev/floppy.h" + +#include "zippath.h" + +#include + + +namespace ui { +/*************************************************************************** +CONSTANTS +***************************************************************************/ + +// conditional compilation to enable chosing of image formats - this is not +// yet fully implemented +#define ENABLE_FORMATS 0 + +// itemrefs for key menu items +#define ITEMREF_NEW_IMAGE_NAME ((void *) 0x0001) +#define ITEMREF_CREATE ((void *) 0x0002) +#define ITEMREF_FORMAT ((void *) 0x0003) +#define ITEMREF_NO ((void *) 0x0004) +#define ITEMREF_YES ((void *) 0x0005) + + +/*************************************************************************** +MENU HELPERS +***************************************************************************/ + +/*************************************************************************** +CONFIRM SAVE AS MENU +***************************************************************************/ + +//------------------------------------------------- +// ctor +//------------------------------------------------- + +menu_confirm_save_as::menu_confirm_save_as(mame_ui_manager &mui, render_container &container, bool *yes) + : menu(mui, container) +{ + m_yes = yes; + *m_yes = false; +} + + +//------------------------------------------------- +// dtor +//------------------------------------------------- + +menu_confirm_save_as::~menu_confirm_save_as() +{ +} + + +//------------------------------------------------- +// populate +//------------------------------------------------- + +void menu_confirm_save_as::populate(float &customtop, float &custombottom) +{ + item_append(_("File Already Exists - Override?"), FLAG_DISABLE, nullptr); + item_append(menu_item_type::SEPARATOR); + item_append(_("No"), 0, ITEMREF_NO); + item_append(_("Yes"), 0, ITEMREF_YES); +} + +//------------------------------------------------- +// handle - confirm save as menu +//------------------------------------------------- + +void menu_confirm_save_as::handle() +{ + // process the menu + const event *event = process(0); + + // process the event + if ((event != nullptr) && (event->iptkey == IPT_UI_SELECT)) + { + if (event->itemref == ITEMREF_YES) + *m_yes = true; + + // no matter what, pop out + stack_pop(); + } +} + + + +/*************************************************************************** +FILE CREATE MENU +***************************************************************************/ + +//------------------------------------------------- +// ctor +//------------------------------------------------- + +menu_file_create::menu_file_create(mame_ui_manager &mui, render_container &container, device_image_interface *image, std::string ¤t_directory, std::string ¤t_file, bool &ok) + : menu(mui, container) + , m_ok(ok) + , m_current_directory(current_directory) + , m_current_file(current_file) + , m_current_format(nullptr) +{ + m_image = image; + m_ok = true; + + m_filename.reserve(1024); + m_filename = core_filename_extract_base(current_file); +} + + +//------------------------------------------------- +// dtor +//------------------------------------------------- + +menu_file_create::~menu_file_create() +{ +} + + +//------------------------------------------------- +// custom_render - perform our special rendering +//------------------------------------------------- + +void menu_file_create::custom_render(void *selectedref, float top, float bottom, float origx1, float origy1, float origx2, float origy2) +{ + extra_text_render(top, bottom, origx1, origy1, origx2, origy2, + m_current_directory, + std::string_view()); +} + + +//------------------------------------------------- +// populate - populates the file creator menu +//------------------------------------------------- + +void menu_file_create::populate(float &customtop, float &custombottom) +{ + std::string buffer; + const image_device_format *format; + const std::string *new_image_name; + + // append the "New Image Name" item + if (get_selection_ref() == ITEMREF_NEW_IMAGE_NAME) + { + buffer = m_filename + "_"; + new_image_name = &buffer; + } + else + { + new_image_name = &m_filename; + } + item_append(_("New Image Name:"), *new_image_name, 0, ITEMREF_NEW_IMAGE_NAME); + + // do we support multiple formats? + if (ENABLE_FORMATS) format = m_image->formatlist().front().get(); + if (ENABLE_FORMATS && (format != nullptr)) + { + item_append(_("Image Format:"), m_current_format->description(), 0, ITEMREF_FORMAT); + m_current_format = format; + } + + // finish up the menu + item_append(menu_item_type::SEPARATOR); + item_append(_("Create"), 0, ITEMREF_CREATE); + + customtop = ui().get_line_height() + 3.0f * ui().box_tb_border(); +} + + +//------------------------------------------------- +// handle - file creator menu +//------------------------------------------------- + +void menu_file_create::handle() +{ + // process the menu + const event *event = process(0); + + // process the event + if (event) + { + // handle selections + switch (event->iptkey) + { + case IPT_UI_SELECT: + if ((event->itemref == ITEMREF_CREATE) || (event->itemref == ITEMREF_NEW_IMAGE_NAME)) + { + std::string tmp_file(m_filename); + if (tmp_file.find('.') != -1 && tmp_file.find('.') < tmp_file.length() - 1) + { + m_current_file = m_filename; + stack_pop(); + } + else + ui().popup_time(1, "%s", _("Please enter a file extension too")); + } + break; + + case IPT_SPECIAL: + if (get_selection_ref() == ITEMREF_NEW_IMAGE_NAME) + { + input_character(m_filename, event->unichar, &osd_is_valid_filename_char); + reset(reset_options::REMEMBER_POSITION); + } + break; + case IPT_UI_CANCEL: + m_ok = false; + break; + } + } +} + + +/*************************************************************************** +SELECT FORMAT MENU +***************************************************************************/ + +//------------------------------------------------- +// ctor +//------------------------------------------------- + +menu_select_format::menu_select_format(mame_ui_manager &mui, render_container &container, floppy_image_format_t **formats, int ext_match, int total_usable, int *result) + : menu(mui, container) +{ + m_formats = formats; + m_ext_match = ext_match; + m_total_usable = total_usable; + m_result = result; +} + + +//------------------------------------------------- +// dtor +//------------------------------------------------- + +menu_select_format::~menu_select_format() +{ +} + + +//------------------------------------------------- +// populate +//------------------------------------------------- + +void menu_select_format::populate(float &customtop, float &custombottom) +{ + item_append(_("Select image format"), FLAG_DISABLE, nullptr); + for (int i = 0; i < m_total_usable; i++) + { + const floppy_image_format_t *fmt = m_formats[i]; + + if (i && i == m_ext_match) + item_append(menu_item_type::SEPARATOR); + item_append(fmt->description(), fmt->name(), 0, (void *)(uintptr_t)i); + } +} + + +//------------------------------------------------- +// handle +//------------------------------------------------- + +void menu_select_format::handle() +{ + // process the menu + const event *event = process(0); + if (event != nullptr && event->iptkey == IPT_UI_SELECT) + { + *m_result = int(uintptr_t(event->itemref)); + stack_pop(); + } +} + + +/*************************************************************************** +SELECT FORMAT MENU +***************************************************************************/ + +//------------------------------------------------- +// ctor +//------------------------------------------------- + +menu_select_floppy_init::menu_select_floppy_init(mame_ui_manager &mui, render_container &container, const std::vector &fs, int *result) + : menu(mui, container), + m_fs(fs), + m_result(result) + +{ +} + + +//------------------------------------------------- +// dtor +//------------------------------------------------- + +menu_select_floppy_init::~menu_select_floppy_init() +{ +} + + +//------------------------------------------------- +// populate +//------------------------------------------------- + +void menu_select_floppy_init::populate(float &customtop, float &custombottom) +{ + item_append(_("Select initial contents"), FLAG_DISABLE, nullptr); + int id = 0; + for (const auto &fmt : m_fs) + item_append(fmt.m_description, fmt.m_name, 0, (void *)(uintptr_t)(id++)); +} + + +//------------------------------------------------- +// handle +//------------------------------------------------- + +void menu_select_floppy_init::handle() +{ + // process the menu + const event *event = process(0); + if (event != nullptr && event->iptkey == IPT_UI_SELECT) + { + *m_result = int(uintptr_t(event->itemref)); + stack_pop(); + } +} + + +} // namespace ui diff --git a/pool/shard011/C++/0122186_838.push-dominoes.cpp b/pool/shard011/C++/0122186_838.push-dominoes.cpp new file mode 100644 index 0000000000000000000000000000000000000000..befe0af45e3e5e8a4f08bac5e46147b5f052b97e --- /dev/null +++ b/pool/shard011/C++/0122186_838.push-dominoes.cpp @@ -0,0 +1,133 @@ +/* + * @lc app=leetcode id=838 lang=cpp + * + * [838] Push Dominoes + * + * https://leetcode.com/problems/push-dominoes/description/ + * + * algorithms + * Medium (50.23%) + * Total Accepted: 42.9K + * Total Submissions: 82.8K + * Testcase Example: '"RR.L"' + * + * There are n dominoes in a line, and we place each domino vertically upright. + * In the beginning, we simultaneously push some of the dominoes either to the + * left or to the right. + * + * After each second, each domino that is falling to the left pushes the + * adjacent domino on the left. Similarly, the dominoes falling to the right + * push their adjacent dominoes standing on the right. + * + * When a vertical domino has dominoes falling on it from both sides, it stays + * still due to the balance of the forces. + * + * For the purposes of this question, we will consider that a falling domino + * expends no additional force to a falling or already fallen domino. + * + * You are given a string dominoes representing the initial state where: + * + * + * dominoes[i] = 'L', if the i^th domino has been pushed to the left, + * dominoes[i] = 'R', if the i^th domino has been pushed to the right, and + * dominoes[i] = '.', if the i^th domino has not been pushed. + * + * + * Return a string representing the final state. + * + * + * Example 1: + * + * + * Input: dominoes = "RR.L" + * Output: "RR.L" + * Explanation: The first domino expends no additional force on the second + * domino. + * + * + * Example 2: + * + * + * Input: dominoes = ".L.R...LR..L.." + * Output: "LL.RR.LLRRLL.." + * + * + * + * Constraints: + * + * + * n == dominoes.length + * 1 <= n <= 10^5 + * dominoes[i] is either 'L', 'R', or '.'. + * + * + */ + +#include "common.hpp" + +class Solution { +public: + string pushDominoes(string dominoes) { + char left_domino = 'L'; + int left_ptr = 0; + int right_ptr = 0; + while (left_ptr < dominoes.size()) + { + // find the right domino not equal to '.' + while (right_ptr < dominoes.size() && dominoes[right_ptr] == '.') + { + right_ptr += 1; + } + if (right_ptr == dominoes.size()) { + // at the end. if the left is right. push all to the right. otherwise, stand still + if (left_domino == 'R') { + for (size_t i = left_ptr; i < right_ptr; i++) + { + dominoes[i] = 'R'; + } + } + left_ptr = right_ptr; + } else { + if (right_ptr > left_ptr) { + if (left_domino == 'L') { + // L....L + if (dominoes[right_ptr] == 'L') { + for (size_t i = left_ptr; i < right_ptr; i++) + { + dominoes[i] = 'L'; + } + } // else they stand still: L....R + } else if (left_domino == 'R') { + // R.....R + if (dominoes[right_ptr] == 'R') { + for (size_t i = left_ptr; i < right_ptr; i++) + { + dominoes[i] = 'R'; + } + } else { + // R.....L + int temp_left = left_ptr; + int temp_right = right_ptr - 1; + while (temp_left < temp_right) + { + dominoes[temp_left] = 'R'; + dominoes[temp_right] = 'L'; + temp_left += 1; + temp_right -= 1; + } + } + } + } + + left_domino = dominoes[right_ptr]; + right_ptr += 1; + left_ptr = right_ptr; + } + } + return dominoes; + } +}; + +int main() { + std::cout << Solution().pushDominoes("RR.L") << std::endl; +} \ No newline at end of file diff --git a/pool/shard011/C++/0122188_accumulator.cc b/pool/shard011/C++/0122188_accumulator.cc new file mode 100644 index 0000000000000000000000000000000000000000..3b56ce2b54e9cef178b7b6807aa3f04b0aa79624 --- /dev/null +++ b/pool/shard011/C++/0122188_accumulator.cc @@ -0,0 +1,118 @@ +// Copyright 2017 Google 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 "sling/task/accumulator.h" + +#include "sling/base/logging.h" +#include "sling/string/numbers.h" +#include "sling/task/reducer.h" +#include "sling/util/fingerprint.h" +#include "sling/util/mutex.h" + +namespace sling { +namespace task { + +void Accumulator::Init(Channel *output, int num_buckets) { + output_ = output; + buckets_.clear(); + buckets_.resize(num_buckets); + + Task *task = output->producer().task(); + num_slots_used_ = task->GetCounter("accumulator_slots_used"); + num_collisions_ = task->GetCounter("accumulator_collisions"); +} + +void Accumulator::Increment(Text key, int64 count) { + uint64 fp = Fingerprint(key.data(), key.size()); + uint32 b = (fp ^ (fp >> 32)) % buckets_.size(); + MutexLock lock(&mu_); + Bucket &bucket = buckets_[b]; + if (fp != bucket.hash || key != bucket.key) { + if (bucket.count != 0) { + output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); + bucket.count = 0; + num_collisions_->Increment(); + } else { + num_slots_used_->Increment(); + } + bucket.hash = fp; + bucket.key.assign(key.data(), key.size()); + + } + bucket.count += count; +} + +void Accumulator::Increment(uint64 key, int64 count) { + uint64 b = (key ^ (key >> 32)) % buckets_.size(); + MutexLock lock(&mu_); + Bucket &bucket = buckets_[b]; + if (key != bucket.hash) { + if (bucket.count != 0) { + output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); + bucket.count = 0; + num_collisions_->Increment(); + } else { + num_slots_used_->Increment(); + } + bucket.hash = key; + bucket.key = SimpleItoa(key); + } + bucket.count += count; +} + +void Accumulator::Flush() { + MutexLock lock(&mu_); + for (Bucket &bucket : buckets_) { + if (bucket.count != 0) { + output_->Send(new Message(bucket.key, SimpleItoa(bucket.count))); + bucket.count = 0; + } + bucket.key.clear(); + } +} + +void SumReducer::Start(Task *task) { + Reducer::Start(task); + task->Fetch("threshold", &threshold_); + if (threshold_ > 0) { + num_keys_discarded_ = task->GetCounter("keys_discarded"); + num_counts_discarded_ = task->GetCounter("counts_discarded"); + } +} + +void SumReducer::Reduce(const ReduceInput &input) { + int64 sum = 0; + for (Message *m : input.messages()) { + int64 count; + const Slice &value = m->value(); + CHECK(safe_strto64_base(value.data(), value.size(), &count, 10)); + sum += count; + } + if (sum >= threshold_) { + Aggregate(input.shard(), input.key(), sum); + } else { + if (num_keys_discarded_) num_keys_discarded_->Increment(); + if (num_counts_discarded_) num_counts_discarded_->Increment(sum); + } +} + +void SumReducer::Aggregate(int shard, const Slice &key, uint64 sum) { + Output(shard, new Message(key, SimpleItoa(sum))); +} + +REGISTER_TASK_PROCESSOR("sum-reducer", SumReducer); + +} // namespace task +} // namespace sling + diff --git a/pool/shard011/C++/0122190_set_and_get_variables_exists.cpp b/pool/shard011/C++/0122190_set_and_get_variables_exists.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18fe1f5f334a4dffbe14830056778d1a41db3050 --- /dev/null +++ b/pool/shard011/C++/0122190_set_and_get_variables_exists.cpp @@ -0,0 +1,20 @@ +#define SOL_CHECK_ARGUMENTS 1 +#include + +#include "../../assert.hpp" + +int main(int, char*[]) { + sol::state lua; + lua.open_libraries(sol::lib::base); + + lua.script("exists = 250"); + + int first_try = lua.get_or("exists", 322); + c_assert(first_try == 250); + + lua.set("exists", sol::lua_nil); + int second_try = lua.get_or("exists", 322); + c_assert(second_try == 322); + + return 0; +} diff --git a/pool/shard011/C++/0122191_AvailableProcessorFeature.cpp b/pool/shard011/C++/0122191_AvailableProcessorFeature.cpp new file mode 100644 index 0000000000000000000000000000000000000000..70071386ca6255fb80878d3970585490b2b8f155 --- /dev/null +++ b/pool/shard011/C++/0122191_AvailableProcessorFeature.cpp @@ -0,0 +1,104 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +#include + +using namespace Aws::Utils::Xml; +using namespace Aws::Utils; + +namespace Aws +{ +namespace RDS +{ +namespace Model +{ + +AvailableProcessorFeature::AvailableProcessorFeature() : + m_nameHasBeenSet(false), + m_defaultValueHasBeenSet(false), + m_allowedValuesHasBeenSet(false) +{ +} + +AvailableProcessorFeature::AvailableProcessorFeature(const XmlNode& xmlNode) : + m_nameHasBeenSet(false), + m_defaultValueHasBeenSet(false), + m_allowedValuesHasBeenSet(false) +{ + *this = xmlNode; +} + +AvailableProcessorFeature& AvailableProcessorFeature::operator =(const XmlNode& xmlNode) +{ + XmlNode resultNode = xmlNode; + + if(!resultNode.IsNull()) + { + XmlNode nameNode = resultNode.FirstChild("Name"); + if(!nameNode.IsNull()) + { + m_name = Aws::Utils::Xml::DecodeEscapedXmlText(nameNode.GetText()); + m_nameHasBeenSet = true; + } + XmlNode defaultValueNode = resultNode.FirstChild("DefaultValue"); + if(!defaultValueNode.IsNull()) + { + m_defaultValue = Aws::Utils::Xml::DecodeEscapedXmlText(defaultValueNode.GetText()); + m_defaultValueHasBeenSet = true; + } + XmlNode allowedValuesNode = resultNode.FirstChild("AllowedValues"); + if(!allowedValuesNode.IsNull()) + { + m_allowedValues = Aws::Utils::Xml::DecodeEscapedXmlText(allowedValuesNode.GetText()); + m_allowedValuesHasBeenSet = true; + } + } + + return *this; +} + +void AvailableProcessorFeature::OutputToStream(Aws::OStream& oStream, const char* location, unsigned index, const char* locationValue) const +{ + if(m_nameHasBeenSet) + { + oStream << location << index << locationValue << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; + } + + if(m_defaultValueHasBeenSet) + { + oStream << location << index << locationValue << ".DefaultValue=" << StringUtils::URLEncode(m_defaultValue.c_str()) << "&"; + } + + if(m_allowedValuesHasBeenSet) + { + oStream << location << index << locationValue << ".AllowedValues=" << StringUtils::URLEncode(m_allowedValues.c_str()) << "&"; + } + +} + +void AvailableProcessorFeature::OutputToStream(Aws::OStream& oStream, const char* location) const +{ + if(m_nameHasBeenSet) + { + oStream << location << ".Name=" << StringUtils::URLEncode(m_name.c_str()) << "&"; + } + if(m_defaultValueHasBeenSet) + { + oStream << location << ".DefaultValue=" << StringUtils::URLEncode(m_defaultValue.c_str()) << "&"; + } + if(m_allowedValuesHasBeenSet) + { + oStream << location << ".AllowedValues=" << StringUtils::URLEncode(m_allowedValues.c_str()) << "&"; + } +} + +} // namespace Model +} // namespace RDS +} // namespace Aws diff --git a/pool/shard011/C++/0122195_RegisterContextFreeBSD_x86_64.cpp b/pool/shard011/C++/0122195_RegisterContextFreeBSD_x86_64.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4bbbd5c3d0a661e69f5b08cf8159af765aab6965 --- /dev/null +++ b/pool/shard011/C++/0122195_RegisterContextFreeBSD_x86_64.cpp @@ -0,0 +1,148 @@ +//===-- RegisterContextFreeBSD_x86_64.cpp ----------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===---------------------------------------------------------------------===// + +#include "RegisterContextFreeBSD_x86_64.h" +#include "RegisterContextFreeBSD_i386.h" +#include "RegisterContextPOSIX_x86.h" +#include + +using namespace lldb_private; +using namespace lldb; + +// http://svnweb.freebsd.org/base/head/sys/x86/include/reg.h +typedef struct _GPR { + uint64_t r15; + uint64_t r14; + uint64_t r13; + uint64_t r12; + uint64_t r11; + uint64_t r10; + uint64_t r9; + uint64_t r8; + uint64_t rdi; + uint64_t rsi; + uint64_t rbp; + uint64_t rbx; + uint64_t rdx; + uint64_t rcx; + uint64_t rax; + uint32_t trapno; + uint16_t fs; + uint16_t gs; + uint32_t err; + uint16_t es; + uint16_t ds; + uint64_t rip; + uint64_t cs; + uint64_t rflags; + uint64_t rsp; + uint64_t ss; +} GPR; + +struct DBG { + uint64_t dr[16]; /* debug registers */ + /* Index 0-3: debug address registers */ + /* Index 4-5: reserved */ + /* Index 6: debug status */ + /* Index 7: debug control */ + /* Index 8-15: reserved */ +}; + +struct UserArea { + GPR gpr; + FPR fpr; + DBG dbg; +}; + +#define DR_OFFSET(reg_index) (LLVM_EXTENSION offsetof(DBG, dr[reg_index])) + +//--------------------------------------------------------------------------- +// Include RegisterInfos_x86_64 to declare our g_register_infos_x86_64 +// structure. +//--------------------------------------------------------------------------- +#define DECLARE_REGISTER_INFOS_X86_64_STRUCT +#include "RegisterInfos_x86_64.h" +#undef DECLARE_REGISTER_INFOS_X86_64_STRUCT + +static std::vector &GetSharedRegisterInfoVector() { + static std::vector register_infos; + return register_infos; +} + +static const RegisterInfo * +GetRegisterInfo_i386(const lldb_private::ArchSpec &arch) { + static std::vector g_register_infos( + GetSharedRegisterInfoVector()); + + // Allocate RegisterInfo only once + if (g_register_infos.empty()) { + // Copy the register information from base class + std::unique_ptr reg_interface( + new RegisterContextFreeBSD_i386(arch)); + const RegisterInfo *base_info = reg_interface->GetRegisterInfo(); + g_register_infos.insert(g_register_infos.end(), &base_info[0], + &base_info[k_num_registers_i386]); + +//--------------------------------------------------------------------------- +// Include RegisterInfos_x86_64 to update the g_register_infos structure +// with x86_64 offsets. +//--------------------------------------------------------------------------- +#define UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS +#include "RegisterInfos_x86_64.h" +#undef UPDATE_REGISTER_INFOS_I386_STRUCT_WITH_X86_64_OFFSETS + } + + return &g_register_infos[0]; +} + +static const RegisterInfo * +PrivateGetRegisterInfoPtr(const lldb_private::ArchSpec &target_arch) { + switch (target_arch.GetMachine()) { + case llvm::Triple::x86: + return GetRegisterInfo_i386(target_arch); + case llvm::Triple::x86_64: + return g_register_infos_x86_64; + default: + assert(false && "Unhandled target architecture."); + return nullptr; + } +} + +static uint32_t +PrivateGetRegisterCount(const lldb_private::ArchSpec &target_arch) { + switch (target_arch.GetMachine()) { + case llvm::Triple::x86: + // This vector should have already been filled. + assert(!GetSharedRegisterInfoVector().empty() && + "i386 register info vector not filled."); + return static_cast(GetSharedRegisterInfoVector().size()); + case llvm::Triple::x86_64: + return static_cast(sizeof(g_register_infos_x86_64) / + sizeof(g_register_infos_x86_64[0])); + default: + assert(false && "Unhandled target architecture."); + return 0; + } +} + +RegisterContextFreeBSD_x86_64::RegisterContextFreeBSD_x86_64( + const ArchSpec &target_arch) + : lldb_private::RegisterInfoInterface(target_arch), + m_register_info_p(PrivateGetRegisterInfoPtr(target_arch)), + m_register_count(PrivateGetRegisterCount(target_arch)) {} + +size_t RegisterContextFreeBSD_x86_64::GetGPRSize() const { return sizeof(GPR); } + +const RegisterInfo *RegisterContextFreeBSD_x86_64::GetRegisterInfo() const { + return m_register_info_p; +} + +uint32_t RegisterContextFreeBSD_x86_64::GetRegisterCount() const { + return m_register_count; +} diff --git a/pool/shard011/C++/0122196_CreateFleetResult.cpp b/pool/shard011/C++/0122196_CreateFleetResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c3314d8d5a9ec22bada2d0123f07e500e1d5de99 --- /dev/null +++ b/pool/shard011/C++/0122196_CreateFleetResult.cpp @@ -0,0 +1,61 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::RoboMaker::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +CreateFleetResult::CreateFleetResult() +{ +} + +CreateFleetResult::CreateFleetResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +CreateFleetResult& CreateFleetResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("arn")) + { + m_arn = jsonValue.GetString("arn"); + + } + + if(jsonValue.ValueExists("name")) + { + m_name = jsonValue.GetString("name"); + + } + + if(jsonValue.ValueExists("createdAt")) + { + m_createdAt = jsonValue.GetDouble("createdAt"); + + } + + if(jsonValue.ValueExists("tags")) + { + Aws::Map tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); + for(auto& tagsItem : tagsJsonMap) + { + m_tags[tagsItem.first] = tagsItem.second.AsString(); + } + } + + + + return *this; +} diff --git a/pool/shard011/C++/0122201_ReaderWriterFreeType.cpp b/pool/shard011/C++/0122201_ReaderWriterFreeType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f64a1e7f68639a589591a8636a25daf6cda13969 --- /dev/null +++ b/pool/shard011/C++/0122201_ReaderWriterFreeType.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +#include + +#include "FreeTypeLibrary.h" + +class ReaderWriterFreeType : public osgDB::ReaderWriter +{ + public: + ReaderWriterFreeType() + { + supportsExtension("ttf","true type font format"); + supportsExtension("ttc","true type format"); + supportsExtension("pfb","type1 binary format"); + supportsExtension("pfa","type2 ascii format"); + supportsExtension("cid","Postscript CID-Fonts format"); + supportsExtension("cff","OpenType format"); + supportsExtension("cef","OpenType format"); + supportsExtension("fon","Windows bitmap fonts format"); + supportsExtension("fnt","Windows bitmap fonts format"); + + supportsOption("monochrome","Select monochrome font."); + } + + virtual const char* className() const { return "FreeType Font Reader/Writer"; } + + static unsigned int getFlags(const osgDB::ReaderWriter::Options* options) + { + unsigned int flags = 0; + if (options && options->getOptionString().find("monochrome") != std::string::npos) + { + flags |= FT_LOAD_MONOCHROME; + } + + return flags; + } + + virtual ReadResult readObject(const std::string& file, const osgDB::ReaderWriter::Options* options) const + { + std::string ext = osgDB::getLowerCaseFileExtension(file); + if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED; + + std::string fileName = osgDB::findDataFile( file, options ); + if (fileName.empty()) return ReadResult::FILE_NOT_FOUND; + + FreeTypeLibrary* freeTypeLibrary = FreeTypeLibrary::instance(); + if (!freeTypeLibrary) + { + osg::notify(osg::WARN)<<"Warning:: cannot create freetype font after freetype library has been deleted."<getPluginData("3D")) ) + return freeTypeLibrary->getFont3D(fileName,0,getFlags(options)); + else + return freeTypeLibrary->getFont(fileName,0,getFlags(options)); + } + + virtual ReadResult readObject(std::istream& stream, const osgDB::ReaderWriter::Options* options) const + { + FreeTypeLibrary* freeTypeLibrary = FreeTypeLibrary::instance(); + if (!freeTypeLibrary) + { + osg::notify(osg::WARN)<<"Warning:: cannot create freetype font after freetype library has been deleted."<getFont(stream, 0, getFlags(options)); + } +}; + +// now register with Registry to instantiate the above +// reader/writer. +REGISTER_OSGPLUGIN(freetype, ReaderWriterFreeType) diff --git a/pool/shard011/C++/0122203_tcp_data_test.cpp b/pool/shard011/C++/0122203_tcp_data_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..395f10f7fbd0f19a30bcb4ee5f9f2da3d788aa21 --- /dev/null +++ b/pool/shard011/C++/0122203_tcp_data_test.cpp @@ -0,0 +1,286 @@ + +#define TEST_CASE + +#include + +#include "../logger_stb/logger.h" +#include "../../../src/tcp_data.cpp" + +using namespace boost::unit_test_framework; + +//--test class-- +class tcp_data_test : public l7vs::tcp_data +{ +public: + tcp_data_test() { + } + ~tcp_data_test() { + } +}; + +//--test case-- +void constractor_test() +{ + + BOOST_MESSAGE("----- constractor test start -----"); + + tcp_data_test test_obj; + + // unit_test [1] constractor test initialize member test "endpoint_info" + std::cout << "[1] constractor test initialize member test \"endpoint_info\"" << std::endl; + BOOST_CHECK_EQUAL(test_obj.get_endpoint(), boost::asio::ip::tcp::endpoint()); + + // unit_test [2] constractor test initialize member test "data" + std::cout << "[2] constractor test initialize member test \"data_size\"" << std::endl; + BOOST_CHECK_EQUAL(test_obj.get_size(), std::size_t(0)); + + // unit_test [3] constractor test initialize member test "send_size" + std::cout << "[3] constractor test initialize member test \"send_size\"" << std::endl; + BOOST_CHECK_EQUAL(test_obj.get_send_size(), std::size_t(0)); + + // unit_test [4] constractor test initialize member test "data" + std::cout << "[4] constractor test initialize member test \"data\"" << std::endl; + boost::array< char , MAX_BUFFER_SIZE> init_data; + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + init_data[i] = '\0'; + + boost::array< char , MAX_BUFFER_SIZE>& chk_data = test_obj.get_data(); + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + BOOST_CHECK_EQUAL(init_data[i] , chk_data[i]); + + BOOST_MESSAGE("----- constractor test end -----"); +} + +void endpoint_function_test() +{ + BOOST_MESSAGE("----- endpoint setter & getter test start -----"); + + tcp_data_test test_obj; + + boost::asio::ip::tcp::endpoint ref_endpoint; + boost::asio::ip::tcp::endpoint chk_endpoint; + + // unit_test [1] endpoint setter & getter test ip=\"0.0.0.0\" port=0 + std::cout << "[1] endpoint setter & getter test ip=\"0.0.0.0\" port=0" << std::endl; + ref_endpoint.address(boost::asio::ip::address::from_string("0.0.0.0")); + ref_endpoint.port(0); + test_obj.set_endpoint(ref_endpoint); + chk_endpoint = test_obj.get_endpoint(); + BOOST_CHECK_EQUAL(ref_endpoint, chk_endpoint); + + // unit_test [2] endpoint setter & getter test ip=\"255.255.255.255\" port=USHRT_MAX + std::cout << "[2] endpoint setter & getter test ip=\"255.255.255.255\" port=USHRT_MAX" << std::endl; + ref_endpoint.address(boost::asio::ip::address::from_string("255.255.255.255")); + ref_endpoint.port(USHRT_MAX); + test_obj.set_endpoint(ref_endpoint); + chk_endpoint = test_obj.get_endpoint(); + BOOST_CHECK_EQUAL(ref_endpoint, chk_endpoint); + + // unit_test [3] endpoint setter & getter test ip=\"128.128.128.128\" port=USHRT_MAX / 2 + std::cout << "[3] endpoint setter & getter test ip=\"128.128.128.128\" port=USHRT_MAX / 2" << std::endl; + ref_endpoint.address(boost::asio::ip::address::from_string("128.128.128.128")); + ref_endpoint.port(USHRT_MAX / 2); + test_obj.set_endpoint(ref_endpoint); + chk_endpoint = test_obj.get_endpoint(); + BOOST_CHECK_EQUAL(ref_endpoint, chk_endpoint); + + BOOST_MESSAGE("----- endpoint setter & getter test end -----"); +} + +void initialize_test() +{ + + BOOST_MESSAGE("----- initialize test start -----"); + + tcp_data_test test_obj; + + // unit_test [1] initialize test initialize member test "endpoint_info" + std::cout << "[1] initialize test initialize member test \"endpoint_info\"" << std::endl; + + boost::asio::ip::tcp::endpoint set_endpoint; + boost::asio::ip::tcp::endpoint chk_endpoint; + + set_endpoint.address(boost::asio::ip::address::from_string("255.255.255.255")); + set_endpoint.port(USHRT_MAX); + test_obj.set_endpoint(set_endpoint); + + chk_endpoint = test_obj.get_endpoint(); + BOOST_CHECK(boost::asio::ip::tcp::endpoint() != chk_endpoint); + + test_obj.initialize(); + + chk_endpoint = test_obj.get_endpoint(); + + BOOST_CHECK_EQUAL(boost::asio::ip::tcp::endpoint(), chk_endpoint); + + + size_t ref_size = ULONG_MAX; + boost::array< char , MAX_BUFFER_SIZE> ref_data; + for (int i = 0; i < MAX_BUFFER_SIZE; i++) { + ref_data[i] = CHAR_MAX; + } + + test_obj.set_size(ref_size); + test_obj.set_send_size(ref_size); + test_obj.set_data(ref_data); + + test_obj.initialize(); + + // unit_test [2] initialize test initialize member test "data_size" + std::cout << "[2] initialize test initialize member test \"data_size\"" << std::endl; + BOOST_CHECK_EQUAL(test_obj.get_size(), std::size_t(0)); + + // unit_test [3] initialize test initialize member test "send_size" + std::cout << "[3] initialize test initialize member test \"send_size\"" << std::endl; + BOOST_CHECK_EQUAL(test_obj.get_send_size(), std::size_t(0)); + + // unit_test [4] initialize test initialize member test "data" + std::cout << "[4] initialize test initialize member test \"data\"" << std::endl; + boost::array< char , MAX_BUFFER_SIZE> init_data; + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + init_data[i] = '\0'; + boost::array< char , MAX_BUFFER_SIZE>& chk_data = test_obj.get_data(); + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + BOOST_CHECK_EQUAL(init_data[i] , chk_data[i]); + + BOOST_MESSAGE("----- initialize test end -----"); +} + +void data_size_function_test() +{ + BOOST_MESSAGE("----- data size setter & getter test start -----"); + + tcp_data_test test_obj; + + size_t set_size; + size_t get_size; + + // unit_test [1] data size setter & getter test set min(0) + std::cout << "[1] data size setter & getter test set min(0)" << std::endl; + set_size = 0; + test_obj.set_size(set_size); + get_size = test_obj.get_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [2] data size setter & getter test set max(MAX_BUFFER_SIZE) + std::cout << "[2] data size setter & getter test set max(MAX_BUFFER_SIZE)" << std::endl; + set_size = MAX_BUFFER_SIZE; + test_obj.set_size(set_size); + get_size = test_obj.get_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [3] data size setter & getter test set mid(MAX_BUFFER_SIZE / 2) + std::cout << "[3] data size setter & getter test set mid(MAX_BUFFER_SIZE / 2)" << std::endl; + set_size = MAX_BUFFER_SIZE / 2; + test_obj.set_size(set_size); + get_size = test_obj.get_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [4] data size setter & getter test set over max(MAX_BUFFER_SIZE + 1) + std::cout << "[4] data size setter & getter test set over max(MAX_BUFFER_SIZE + 1)" << std::endl; + set_size = MAX_BUFFER_SIZE + 1; + l7vs::Logger::putLogError_category = l7vs::LOG_CAT_NONE; + l7vs::Logger::putLogError_id = 0; + test_obj.set_size(set_size); + BOOST_CHECK_EQUAL(l7vs::LOG_CAT_L7VSD_SESSION, l7vs::Logger::putLogError_category); + BOOST_CHECK_EQUAL(0001, l7vs::Logger::putLogError_id); + std::cout << l7vs::Logger::putLogError_message << std::endl; + get_size = test_obj.get_size(); + BOOST_CHECK(MAX_BUFFER_SIZE == get_size); + + BOOST_MESSAGE("----- data size setter & getter test end -----"); +} + +void send_size_function_test() +{ + BOOST_MESSAGE("----- send size setter & getter test start -----"); + + tcp_data_test test_obj; + + size_t set_size; + size_t get_size; + + // unit_test [1] send size setter & getter test set min(0) + std::cout << "[1] send size setter & getter test set min(0)" << std::endl; + set_size = 0; + test_obj.set_send_size(set_size); + get_size = test_obj.get_send_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [2] send size setter & getter test set max(MAX_BUFFER_SIZE) + std::cout << "[2] send size setter & getter test set max(MAX_BUFFER_SIZE)" << std::endl; + set_size = MAX_BUFFER_SIZE; + test_obj.set_send_size(set_size); + get_size = test_obj.get_send_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [3] send size setter & getter test set mid(MAX_BUFFER_SIZE / 2) + std::cout << "[3] send size setter & getter test set mid(MAX_BUFFER_SIZE / 2)" << std::endl; + set_size = MAX_BUFFER_SIZE / 2; + test_obj.set_send_size(set_size); + get_size = test_obj.get_send_size(); + BOOST_CHECK_EQUAL(set_size, get_size); + + // unit_test [4] send size setter & getter test set over max(MAX_BUFFER_SIZE + 1) + std::cout << "[4] send size setter & getter test set over max(MAX_BUFFER_SIZE + 1)" << std::endl; + set_size = MAX_BUFFER_SIZE + 1; + l7vs::Logger::putLogError_category = l7vs::LOG_CAT_NONE; + l7vs::Logger::putLogError_id = 0; + test_obj.set_send_size(set_size); + BOOST_CHECK_EQUAL(l7vs::LOG_CAT_L7VSD_SESSION, l7vs::Logger::putLogError_category); + BOOST_CHECK_EQUAL(0002, l7vs::Logger::putLogError_id); + std::cout << l7vs::Logger::putLogError_message << std::endl; + get_size = test_obj.get_send_size(); + BOOST_CHECK(MAX_BUFFER_SIZE == get_size); + + + BOOST_MESSAGE("----- send size setter & getter test end -----"); +} + +void data_function_test() +{ + BOOST_MESSAGE("----- data setter & getter test start -----"); + + tcp_data_test test_obj; + + // unit_test [1] data setter & getter test + std::cout << "[1] data setter & getter test" << std::endl; + boost::array< char , MAX_BUFFER_SIZE> ref_data; + + for (int set_char = CHAR_MIN; set_char <= CHAR_MAX; set_char++) { +// std::cout << "char code["; +// std::cout << set_char; +// std::cout << "] test" << std::endl; + + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + ref_data[i] = set_char; + + test_obj.set_data(ref_data); + boost::array< char , MAX_BUFFER_SIZE>& chk_data = test_obj.get_data(); + + for (int i = 0; i < MAX_BUFFER_SIZE; i++) + BOOST_CHECK_EQUAL(ref_data[i], chk_data[i]); + } + + BOOST_MESSAGE("----- data setter & getter test end -----"); +} + +test_suite *init_unit_test_suite(int argc, char *argv[]) +{ + + test_suite *ts = BOOST_TEST_SUITE("l7vs::tcp_data class test"); + + ts->add(BOOST_TEST_CASE(&constractor_test)); + ts->add(BOOST_TEST_CASE(&initialize_test)); + ts->add(BOOST_TEST_CASE(&endpoint_function_test)); + + ts->add(BOOST_TEST_CASE(&data_size_function_test)); + ts->add(BOOST_TEST_CASE(&send_size_function_test)); + ts->add(BOOST_TEST_CASE(&data_function_test)); + + + + framework::master_test_suite().add(ts); + + return NULL; +} diff --git a/pool/shard011/C++/0122206_cli.cpp b/pool/shard011/C++/0122206_cli.cpp new file mode 100644 index 0000000000000000000000000000000000000000..abe4fc700de8ca0abbb5d237178f7c8ffc74ab79 --- /dev/null +++ b/pool/shard011/C++/0122206_cli.cpp @@ -0,0 +1,111 @@ +/* + Copyright (c) openheap, uplusware + uplusware@gmail.com +*/ +#include "cli.h" +#include + +#define WELCOME_MSG "**********************************************************\r\n" \ + "* Welcome to Use eRisemail Server On Linux/Unix *\r\n" \ + "* Powered by uplusware *\r\n" \ + "**********************************************************\r\n" + +#define BYE_MSG "\r\n" \ + "------------------------- Bye ----------------------------\r\n" + +CLI::CLI() +{ + +} + +CLI::~CLI() +{ + +} + +void CLI::Run() +{ + if(!CMailBase::LoadConfig((char*)"/etc/erisemail/erisemail.conf")) + { + printf("Load Configuration Failed\n"); + return; + } + string strline; + int vlen = m_queueList.size(); + for(int x = 0; x < vlen; x++) + { + m_queueList[x].qid = mq_open(m_queueList[x].name, O_RDWR); + printf("%s %d\n",m_queueList[x].name, m_queueList[x].qid); + if(m_queueList[x].qid == -1) + { + goto END; + } + mq_attr attr; + mq_getattr(m_queueList[x].qid, &attr); + } + printf(WELCOME_MSG); + + while(1) + { + printf("CLI# "); + getline(cin, strline); + if(!Parse((char*)strline.c_str())) + break; + } +END: + for(int x = 0; x < vlen; x++) + { + if(m_queueList[x].qid > 0) + mq_close(m_queueList[x].qid); + } +} + +BOOL CLI::Parse(char* text) +{ + BOOL ret = TRUE; + stQueueMsg qMsg; + string strline = text; + strtrim(strline); + if((strline == "exit")||(strline == "quit")) + { + printf("Bye.\n"); + ret = FALSE; + } + else if(strline == "stop") + { + qMsg.cmd = MSG_EXIT; + int vlen = m_queueList.size(); + for(int x = 0; x < vlen; x++) + { + int rc = mq_send(m_queueList[x].qid, (const char*)&qMsg, sizeof(stQueueMsg), 0); + if(rc < 0) + { + if(errno != EINTR) + { + perror("error"); + } + } + } + ret = FALSE; + } + else if(strncasecmp(strline.c_str(), "adduser", sizeof("adduser") - 1) == 0) + { + + } + else if(strncasecmp(strline.c_str(), "addgroup", sizeof("addgroup") - 1) == 0) + { + + } + else if(strncasecmp(strline.c_str(), "deluser", sizeof("deluser") - 1) == 0) + { + + } + else if(strncasecmp(strline.c_str(), "delgroup", sizeof("delgroup") - 1) == 0) + { + + } + else + printf("unknown command.\n"); + return ret; +} + diff --git a/pool/shard011/C++/0122207_Ncurses.cpp b/pool/shard011/C++/0122207_Ncurses.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1fcc058b1793a9133f0bdee8010913ae9d63623c --- /dev/null +++ b/pool/shard011/C++/0122207_Ncurses.cpp @@ -0,0 +1,75 @@ +#include + +bool Ncurses::init() +{ + initscr(); + // TODO check for failing + + cbreak(); // Character input doesnt require the key anymore + curs_set(0); // Makes the blinking cursor invisible + noecho(); // Wont print the keys received through input + nodelay(stdscr, TRUE); // Wont wait for input + keypad(stdscr, TRUE); // Support for extra keys (life F1, F2, ... ) + + // Ncurses' global variable meaning number of milliseconds + // to wait after the user presses ESC. + // + // VIM uses 25ms, so should you. + // Source: http://en.chys.info/2009/09/esdelay-ncurses/ + ESCDELAY = 25; + + refresh(); // Refresh the layout (prints whats in the layout bu + return true; +} + +void Ncurses::exit() +{ + erase(); + refresh(); + endwin(); +} + +void Ncurses::delay_ms(int delay) +{ + napms(delay); +} + +int Ncurses::getInput(int delay_ms) +{ + // Will use select() function + int retval = 0; + int c = 0; + + fd_set input; + struct timeval timeout; + + timeout.tv_sec = 0; + timeout.tv_usec = delay_ms * 1000; // microseconds + + // If #delay_ms is -1, we'll wait infinitely + // (sending NULL to #select()) + struct timeval* timeout_p = NULL; + if (delay_ms != -1) + timeout_p = &timeout; + + FD_ZERO(&input); + FD_SET(STDIN_FILENO, &input); + + // This function is somewhat complex + // check 'man select' for info + retval = select(FD_SETSIZE, &input, NULL, NULL, timeout_p); + + // Ncurses' function that works without delay + // (because we nodelay()'ed) + c = getch(); + + if ((retval == 1) && (c == ERR)) // ERROR + return -1; + + if (retval == 0) + return ERR; //engine.input.none; + + return c; +} + + diff --git a/pool/shard011/C++/0122208_tsv.cpp b/pool/shard011/C++/0122208_tsv.cpp new file mode 100644 index 0000000000000000000000000000000000000000..582db1f10a372dd0ba135c71ff35d6ab3e50b789 --- /dev/null +++ b/pool/shard011/C++/0122208_tsv.cpp @@ -0,0 +1,137 @@ +/*************************************************************** + * Name: tsv.cpp + * Purpose: Handles tsv files, and functions + * Author: () + * Created: 2009-03-16 + * Copyright: () + * License: + **************************************************************/ + +#include "tsv.h" + +#include + +#include +#include +#include +#include +using namespace std; + +string tsvFileName; +float tsvMax = 0, tsvMin = 0; +int tsvLen = 0; + +tsv::tsv(wxString filename) +{ + tsvFileName = filename.mb_str(wxConvUTF8); +} + +tsv::~tsv() +{ +} + +float tsv::getMin() +{ + return tsvMin; +} + +float tsv::getMax() +{ + return tsvMax; +} + +void tsv::setFileName(wxString filename, wxProgressDialog* progDlg, float start, float end) +{ + tsvFileName = filename.mb_str(wxConvUTF8); + progDlg->Update(start,_("Finding Length")); + findLength(); + progDlg->Update(start,_("Parsing ") + filename); + loadtsv(progDlg, start, end); +} + +const char* tsv::getFileName() +{ + return tsvFileName.c_str(); +} + +void tsv::findLength() +{ + int i = 0; + string line; + ifstream file (tsvFileName.c_str()); + while (!file.eof()) + { + getline (file,line); + i++; + } + tsvLen = i; + file.close(); +} + +void tsv::loadtsv(wxProgressDialog* progDlg, float start, float end) +{ + // Initialize variables + int k = 0; + float max = 0, min = 0; + bool haveMin = false; + string line; + clear(); + + // Input filestream + ifstream file (tsvFileName.c_str()); + + // Parse SDEM + while (!file.eof()) + { + // Get line of file. + getline (file,line); + + // temp vector to convert from tsv + list tsvLine; + + // counters + unsigned int i = 0, j = 0; + + // seperate loops for initial char, and final + for (; i < line.length(); i = j) + { + for (; j < line.length() && line.at(j) != '\t'; j++){} + + // take string from i to j, and conversound volume doesnt savet it to a float + string num = line.substr(i, j - i); + istringstream buffer(num); + float temp; + buffer >> temp; + + // keep track of max and min + if (temp > max) { max = temp; } + if (!haveMin || temp < min) + { + // non-existent point correction + if (temp > -10000) + { + min = temp; + haveMin = true; + } + } + + // store and incriment + tsvLine.push_back(temp); + j++; + } + + k++; + if (k % 50 == 1) progDlg->Update(start + (k * ((end - start) / tsvLen))); + + // insert line to sdem + if (tsvLine.size() > 0) + push_back(tsvLine); + } + + // close the sdem + file.close(); + + // store max/min + tsvMax = max; + tsvMin = min; +} diff --git a/pool/shard011/C++/0122209_StumpClassifierCompact.cpp b/pool/shard011/C++/0122209_StumpClassifierCompact.cpp new file mode 100644 index 0000000000000000000000000000000000000000..304060edaacebf78e32e900bb2c45beff2c027ef --- /dev/null +++ b/pool/shard011/C++/0122209_StumpClassifierCompact.cpp @@ -0,0 +1,50 @@ +#include "inc/classifiers/simple/StumpClassifierCompact.h" +#include + +static float double_to_float(double src) +{ + if (src > (double)std::numeric_limits().max()) + return std::numeric_limits().max(); + if (src < (double)std::numeric_limits().lowest()) + return std::numeric_limits().lowest(); + + return (float)src; +} + + +StumpClassifierTwoRectCompact::StumpClassifierTwoRectCompact() +{ + _threshold = 0.0f; + + _signed_confidence[0] = 0.0f; + _signed_confidence[1] = 0.0f; +} + + +StumpClassifierTwoRectCompact::StumpClassifierTwoRectCompact(const HaarFeatureTwoRectCompact &feature, double threshold, double result_on_less, double result_on_greater) +{ + _feature = feature; + _threshold = double_to_float(threshold); + + _signed_confidence[0] = double_to_float(result_on_greater); + _signed_confidence[1] = double_to_float(result_on_less); +} + + + +StumpClassifierThreeRectCompact::StumpClassifierThreeRectCompact() +{ + _threshold = 0.0f; + + _signed_confidence[0] = 0.0f; + _signed_confidence[1] = 0.0f; +} + +StumpClassifierThreeRectCompact::StumpClassifierThreeRectCompact(const HaarFeatureThreeRectCompact &feature, double threshold, double result_on_less, double result_on_greater) +{ + _feature = feature; + _threshold = double_to_float(threshold); + + _signed_confidence[0] = double_to_float(result_on_greater); + _signed_confidence[1] = double_to_float(result_on_less); +} \ No newline at end of file diff --git a/pool/shard011/C++/0122210_sphere.cpp b/pool/shard011/C++/0122210_sphere.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f65c0b2309438f05f844cbc5a65df6e7ebfce0a6 --- /dev/null +++ b/pool/shard011/C++/0122210_sphere.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2013 - 2014 by Mark de Wever + * Part of the simulator project. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY. + * + * See the COPYING file for more details. + */ + +#include "modules/grid/sphere.hpp" + +#include "modules/grid/stream.hpp" +#include "modules/logger/logger.hpp" + +#include + +#include + +REGISTER_LOGGER_MODULE("/unit_test/modules/grid") + +using namespace grid; + +static void test_sphere_1(const tint radius) +{ + TRACE_PARAMETERS(radius); + + const std::vector unique{sphere(radius, false)}; + const std::vector fast{sphere_raw(radius)}; + + BOOST_REQUIRE_LT(unique.size(), fast.size()); + + std::set u; + std::copy(unique.begin(), unique.end(), std::inserter(u, u.begin())); + + BOOST_CHECK_EQUAL(unique.size(), u.size()); + + + std::set f; + std::copy(fast.begin(), fast.end(), std::inserter(f, f.begin())); + + BOOST_CHECK_LT(f.size(), fast.size()); + BOOST_CHECK_EQUAL(f.size(), u.size()); + BOOST_CHECK_EQUAL_COLLECTIONS(f.begin(), f.end(), u.begin(), u.end()); +} + +static void test_sphere_1() +{ + TRACE; + + BOOST_CHECK_EQUAL(sphere(0, false).size(), 0); + + for(tint i{1}; i < 42; ++i) { + test_sphere_1(i); + } +} + +BOOST_AUTO_TEST_CASE(test_modules_grid_sphere) +{ + TRACE; + + test_sphere_1(); +} diff --git a/pool/shard011/C++/0122211_uwdriftposition.cpp b/pool/shard011/C++/0122211_uwdriftposition.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f51458703c7671ec963bb9381d7a88e1403f9f44 --- /dev/null +++ b/pool/shard011/C++/0122211_uwdriftposition.cpp @@ -0,0 +1,274 @@ +// +// Copyright (c) 2017 Regents of the SIGNET lab, University of Padova. +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. Neither the name of the University of Padova (SIGNET lab) nor the +// names of its contributors may be used to endorse or promote products +// derived from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR +// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; +// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR +// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// + +/** + * @file uwdriftposition.cpp + * @author Giovanni Toso + * @version 1.0.0 + * + * \brief Implementation of UWDRIFTPOSITION class. + * + * Implementation of UWDRIFTPOSITION class. + */ + +#include "uwdriftposition.h" + +#include + +/** + * Adds the module for UwDriftPositionClass in ns2. + */ +static class UwDriftPositionClass : public TclClass +{ +public: + UwDriftPositionClass() + : TclClass("Position/UWDRIFT") + { + } + + TclObject * + create(int, const char *const *) + { + return (new UwDriftPosition()); + } +} class_uwdriftposition; + +UwDriftPosition::UwDriftPosition() + : Position() + , xFieldWidth_(0) + , yFieldWidth_(0) + , zFieldWidth_(0) + , boundx_(0) + , boundy_(1) + , boundz_(1) + , speed_horizontal_(0) + , speed_longitudinal_(0) + , speed_vertical_(0) + , alpha_(0) + , deltax_(0) + , deltay_(0) + , deltaz_(0) + , starting_speed_x_(0) + , starting_speed_y_(0) + , starting_speed_z_(0) + , updateTime_(0) + , nextUpdateTime_(0.0) +{ + bind("xFieldWidth_", &xFieldWidth_); + bind("yFieldWidth_", &yFieldWidth_); + bind("zFieldWidth_", &zFieldWidth_); + bind("boundx_", &boundx_); + bind("boundy_", &boundy_); + bind("boundz_", &boundz_); + bind("speed_horizontal_", &speed_horizontal_); + bind("speed_longitudinal_", &speed_longitudinal_); + bind("speed_vertical_", &speed_vertical_); + bind("alpha_", &alpha_); + bind("deltax_", &deltax_); + bind("deltay_", &deltay_); + bind("deltaz_", &deltaz_); + bind("starting_speed_x_", &starting_speed_x_); + bind("starting_speed_y_", &starting_speed_y_); + bind("starting_speed_z_", &starting_speed_z_); + bind("updateTime_", &updateTime_); + bind("debug_", &debug_); + old_speed_x_ = starting_speed_x_; + old_speed_y_ = starting_speed_y_; + old_speed_z_ = starting_speed_z_; + srand((unsigned) time(0)); +} + +UwDriftPosition::~UwDriftPosition() +{ +} + +int +UwDriftPosition::command(int argc, const char *const *argv) +{ + return Position::command(argc, argv); +} + +void +UwDriftPosition::update(const double &now) +{ + double t; + + for (t = nextUpdateTime_; t < now; t += updateTime_) { + // Calculate new speed + double vx_ = (alpha_ * old_speed_x_) + + (1 - alpha_) * (speed_horizontal_ + + deltax_ * (rand() / (static_cast( + RAND_MAX) + + 1.0)) * + getSign()); + double vy_ = (alpha_ * old_speed_y_) + + (1 - alpha_) * (speed_longitudinal_ + + deltay_ * (rand() / (static_cast( + RAND_MAX) + + 1.0)) * + getSign()); + double vz_ = (alpha_ * old_speed_z_) + + (1 - alpha_) * (speed_vertical_ + + deltaz_ * (rand() / (static_cast( + RAND_MAX) + + 1.0)) * + getSign()); + + // Save the new speed in a variable + old_speed_x_ = vx_; + old_speed_y_ = vy_; + old_speed_z_ = vz_; + + // Calculate new position + double newx_ = x_ + (vx_ * updateTime_); + // cout << "-------->" << y_ << " + " << "(" << vy_ << " * " << + // updateTime_ << ")"; + double newy_ = y_ + (vy_ * updateTime_); + // cout << " = " << newy_ << endl; + double newz_ = z_ + (vz_ * updateTime_); + + // verify whether the new position has to be re-computed in order + // to maintain node position within the simulation field + + // Bounds check + if (boundx_ == 1) { + if (newx_ > xFieldWidth_) { + // newx_ = x_ + (- vx_ * updateTime_); + newx_ = (2 * xFieldWidth_) - newx_; + old_speed_x_ = (-old_speed_x_); // The sign of the current speed + // is inverted = Rebounce + speed_horizontal_ = (-speed_horizontal_); // The sign of the + // horizontal speed is + // inverted = Rebounce + // behaviour + } else if (newx_ < 0) { + // newx_ = x_ + (- vx_ * updateTime_); + newx_ = -newx_; + old_speed_x_ = (-old_speed_x_); + speed_horizontal_ = (-speed_horizontal_); + } + } + if (boundy_ == 1) { + if (newy_ > yFieldWidth_) { + // cout << "newy_ = " << newy_ << ". yFieldWidth_ = " << + // yFieldWidth_ << endl; + // newy_ = y_ + (- vy_ * updateTime_); + newy_ = (2 * yFieldWidth_) - newy_; + old_speed_y_ = (-old_speed_y_); + speed_longitudinal_ = (-speed_longitudinal_); + // cout << "newy_ = " << newy_ << ". yFieldWidth_ = " << + // yFieldWidth_ << endl; + } else if (newy_ < 0) { + // newy_ = y_ + (- vy_ * updateTime_); + newy_ = -newy_; + old_speed_y_ = (-old_speed_y_); + speed_longitudinal_ = (-speed_longitudinal_); + } + } + if (boundz_ == 1) { + if (newz_ < (-zFieldWidth_)) { + // cout << "newz_ = " << newz_ << ". zFieldWidth_ = " << - + // zFieldWidth_ << endl; + // newz_ = z_ + (- vz_ * updateTime_); + newz_ = (-zFieldWidth_) - (newz_ + (zFieldWidth_)); + old_speed_z_ = -old_speed_z_; + speed_vertical_ = (-speed_vertical_); + // cout << "newz_ = " << newz_ << ". zFieldWidth_ = " << - + // zFieldWidth_ << endl; + } else if (newz_ > 0) { + // cout << "newz_ = " << newz_ << ". zFieldWidth_ = " << - + // zFieldWidth_ << endl; + // newz_ = z_ + (- vz_ * updateTime_); + newz_ = -newz_; + old_speed_z_ = -old_speed_z_; + speed_vertical_ = (-speed_vertical_); + // cout << "newz_ = " << newz_ << ". zFieldWidth_ = " << - + // zFieldWidth_ << endl; + } + } + if (debug_ > 10) { + printf("X:%.3f->%.3f Y:%.3f->%.3f Z:%.3f->%.3f\n", + x_, + newx_, + y_, + newy_, + z_, + newz_); + } + x_ = newx_; + y_ = newy_; + z_ = newz_; + } + nextUpdateTime_ = t; + if (debug_ > 10) + printf("nextUpdateTime = %f, now %f, updateTime %f\n", + nextUpdateTime_, + now, + updateTime_); +} + +short +UwDriftPosition::getSign() const +{ + double rand_sign = (rand() / (static_cast(RAND_MAX) + 1.0)); + if (rand_sign < 0.5) { + return 1; + } else if (rand_sign > 0.5) { + return -1; + } else { // rand_sign == 0.5 + return getSign(); + } +} + +double +UwDriftPosition::getX() +{ + double now = Scheduler::instance().clock(); + if (now > nextUpdateTime_) + update(now); + return (x_); +} + +double +UwDriftPosition::getY() +{ + double now = Scheduler::instance().clock(); + if (now > nextUpdateTime_) + update(now); + return (y_); +} + +double +UwDriftPosition::getZ() +{ + double now = Scheduler::instance().clock(); + if (now > nextUpdateTime_) + update(now); + return (z_); +} diff --git a/pool/shard011/C++/0122217_CreateTapesResult.cpp b/pool/shard011/C++/0122217_CreateTapesResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14f15a1273d6715b20a7b92b61387997fa5d0682 --- /dev/null +++ b/pool/shard011/C++/0122217_CreateTapesResult.cpp @@ -0,0 +1,53 @@ +/* +* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +* +* Licensed under the Apache License, Version 2.0 (the "License"). +* You may not use this file except in compliance with the License. +* A copy of the License is located at +* +* http://aws.amazon.com/apache2.0 +* +* or in the "license" file accompanying this file. This file is distributed +* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either +* express or implied. See the License for the specific language governing +* permissions and limitations under the License. +*/ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::StorageGateway::Model; +using namespace Aws::Utils::Json; +using namespace Aws::Utils; +using namespace Aws; + +CreateTapesResult::CreateTapesResult() +{ +} + +CreateTapesResult::CreateTapesResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +CreateTapesResult& CreateTapesResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + JsonView jsonValue = result.GetPayload().View(); + if(jsonValue.ValueExists("TapeARNs")) + { + Array tapeARNsJsonList = jsonValue.GetArray("TapeARNs"); + for(unsigned tapeARNsIndex = 0; tapeARNsIndex < tapeARNsJsonList.GetLength(); ++tapeARNsIndex) + { + m_tapeARNs.push_back(tapeARNsJsonList[tapeARNsIndex].AsString()); + } + } + + + + return *this; +} diff --git a/pool/shard011/C++/0122219_helpers.cpp b/pool/shard011/C++/0122219_helpers.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6086743b37664d4cbece398a9f9c7f1e081f2d0 --- /dev/null +++ b/pool/shard011/C++/0122219_helpers.cpp @@ -0,0 +1,159 @@ +//////////////////////////////////////////// +/// +/// WraithOne +/// www.Dark-Abyss.net +/// +/// ZFX Action 2014 +/// +/// Theme: Career, Cell +/// +//////////////////////////////////////////// +#include + +SDL_Surface* LoadSurface(SDL_Renderer* renderer, const char* fileName) +{ + SDL_Surface* Surf = nullptr; + + // Load the image + Surf = IMG_Load(fileName); + if (Surf == nullptr) + { + std::cout << "LoadImage Error: " << IMG_GetError() << std::endl; + } + + return Surf; +} + +SDL_Texture* LoadImage(SDL_Renderer* renderer, const char* fileName) +{ + SDL_Surface* loadSurf = nullptr; + SDL_Texture* texture = nullptr; + + // Load the image + loadSurf = IMG_Load(fileName); + if (loadSurf == nullptr) + { + std::cout << "LoadImage Error: " << IMG_GetError() << std::endl; + + return texture; + } + + // Create texture from surface + texture = SDL_CreateTextureFromSurface(renderer, loadSurf); + if (texture == nullptr) + { + std::cout << "LoadImage Error: " << SDL_GetError() << std::endl; + SDL_FreeSurface(loadSurf); + + return texture; + } + SDL_FreeSurface(loadSurf); + + return texture; +} + +SDL_Rect FillRect(int x, int y, int w, int h) +{ + SDL_Rect temp; + + temp.x = x; + temp.y = y; + temp.w = w; + temp.h = h; + + return temp; +} + +void InttoText(SDL_Renderer* renderer, TTF_Font* font, SDL_Point position, int number, Uint8 r, Uint8 g, Uint8 b) +{ + SDL_Texture* tempTex = nullptr; + SDL_Surface* tempSurf = nullptr; + + std::string text = std::to_string(number); + + SDL_Color color = { r, g, b }; + + if (!(tempSurf = TTF_RenderText_Solid(font, text.c_str(), color))) + { + std::cout << "InttiText Error: " << TTF_GetError() << std::endl; + } + else + { + // Create texture from surface + tempTex = SDL_CreateTextureFromSurface(renderer, tempSurf); + if (tempTex == nullptr) + { + std::cout << "InttiText Error: " << SDL_GetError() << std::endl; + SDL_FreeSurface(tempSurf); + + } + else + { + SDL_Rect srcRect = tempSurf->clip_rect; + SDL_Rect dstRect = {position.x,position.y,srcRect.w,srcRect.h}; + + SDL_RenderCopy(renderer, tempTex, NULL, &dstRect); + } + + SDL_FreeSurface(tempSurf); + SDL_DestroyTexture(tempTex); + } + +} + +bool ColorIntersects(SDL_Surface* surface, SDL_Rect rect, SDL_Color color) +{ + // Convert to 32bit + Uint32* pixels = (Uint32*)surface->pixels; + for (int y = rect.y; y < (rect.y + rect.h); y++) + { + for (int x = rect.x; x < (rect.x + rect.w); x++) + { + Uint32 temp = pixels[(y * surface->w) + x]; + Uint32 rgba = *((Uint32*)&color); + + if (temp == rgba) + { + return true; + } + } + } + return false; +} + +SDL_Color translate_color(Uint32 int_color) +{ +#if SDL_BYTEORDER == SDL_BIG_ENDIAN + SDL_Color color = { (int_color & 0x00ff0000) / 0x10000, + (int_color & 0x0000ff00) / 0x100, + (int_color & 0x000000ff), + 0 }; +#else + SDL_Color color = { (int_color & 0x000000ff), + (int_color &0x0000ff00) / 0x100, + (int_color & 0x00ff0000) / 0x10000, + 0 }; +#endif + return color; +} + +bool RectIntersects(SDL_Rect first, SDL_Rect second) +{ + // X Axis + if (first.x >= second.x && first.x <= (second.x + second.w) || (first.x + first.w) >= second.x && (first.x + first.w) <= (second.x + second.w)) + { + // Y Axis + if (first.y >= second.y && first.y <= (second.y + second.h) || (first.y + first.h) >= second.y && (first.y + first.h) <= (second.y + second.h)) + { + return true; + } + else + { + return false; + } + } + else + { + return false; + } +} \ No newline at end of file diff --git a/pool/shard011/C++/0122221_atk_python.cpp b/pool/shard011/C++/0122221_atk_python.cpp new file mode 100644 index 0000000000000000000000000000000000000000..05e0040708b22558387ea4511c40143604a26b81 --- /dev/null +++ b/pool/shard011/C++/0122221_atk_python.cpp @@ -0,0 +1,225 @@ +// K-3D +// Copyright (c) 1995-2009, Timothy M. Shead +// +// Contact: tshead@k-3d.com +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public +// License as published by the Free Software Foundation; either +// version 2 of the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public +// License along with this program; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include + +using namespace boost::python; + +namespace k3d +{ + +namespace python +{ + +namespace detail +{ + +boost::python::object wrap(AtkObject* Object); + +/// Converts the given string to a name suitable as Python function name +/** + * TODO: Move this to the SDK, so the conversion is always consistent? + */ +const k3d::string_t script_name(const k3d::string_t& Name) +{ + return boost::replace_all_copy(Name, " ", "_"); +} + +const k3d::int32_t action_index(AtkAction* Action, const k3d::string_t& ActionName) +{ + return_val_if_fail(Action, -1); + for(k3d::uint_t i = 0; i != atk_action_get_n_actions(Action); ++i) + { + if(std::string(atk_action_get_name(Action, i)) == ActionName) + return i; + } + return -1; +} + +/// Performs the action with the given name. Requires Self to be an AtkAction and the action must exist (caller needs to check this) +k3d::bool_t do_named_action(atk_object_wrapper& Self, const k3d::string_t& ActionName) +{ + AtkObject* atk_object = Self.wrapped_ptr(); + return_val_if_fail(ATK_IS_ACTION(atk_object), false); + AtkAction* action = ATK_ACTION(atk_object); + k3d::int32_t action_idx = action_index(action, ActionName); + return_val_if_fail(action_idx > -1, false); + k3d::bool_t result = atk_action_do_action(action, action_idx); + k3d::user_interface().synchronize(); + return result; +} + +/// Proxy for click action +static void click(atk_object_wrapper& Self) +{ + do_named_action(Self, "click"); +} + +k3d::bool_t has_action(AtkObject* Object, const k3d::string_t& ActionName) +{ + if(!ATK_IS_ACTION(Object)) + return false; + return action_index(ATK_ACTION(Object), ActionName) > -1; +} + +void define_action_methods(AtkObject* Object, boost::python::object& Instance) +{ + if(ATK_IS_ACTION(Object)) + { + if(has_action(Object, "click")) + { + utility::add_method(utility::make_function(&click, ""), "click", Instance); + } + } +} + +/// Get the item with role Role and name Key +static object get_item_name(atk_object_wrapper& Self, const string_t& Key, const AtkRole Role) +{ + AtkObject* atk_obj = Self.wrapped_ptr(); + AtkObject* found = 0; + for(k3d::uint_t i = 0; i != atk_object_get_n_accessible_children(atk_obj); ++i) + { + AtkObject* child = atk_object_ref_accessible_child(atk_obj, i); + const gchar* name_ptr = atk_object_get_name(child); + const k3d::string_t name_str(name_ptr ? name_ptr : ""); + if(name_str == Key && atk_object_get_role(child) == Role) + { + if(found) + throw std::runtime_error("Duplicate value for key: " + Key); + found = child; + } + } + + if(!found) + throw std::runtime_error("unknown key: " + Key); + + return wrap(found); +} + +/// Get the item with index Key and role Role, with indices counted within children of the same type +static object get_item_idx(atk_object_wrapper& Self, const k3d::uint_t Key, const AtkRole Role) +{ + AtkObject* atk_obj = Self.wrapped_ptr(); + const k3d::uint_t child_count = atk_object_get_n_accessible_children(atk_obj); + if(Key >= child_count) + throw std::runtime_error("index out of range: " + Key); + k3d::uint_t idx = 0; + for(k3d::uint_t i = 0; i != child_count; ++i) + { + AtkObject* child = atk_object_ref_accessible_child(atk_obj, i); + if(atk_object_get_role(child) == Role) + { + if(idx == Key) + return wrap(child); + ++idx; + } + } + std::stringstream error; + error << "No child with role " << atk_role_get_name(Role) << " at index " << Key; + throw std::runtime_error(error.str()); +} + +template +static object get_item(atk_object_wrapper& Self, object Key) +{ + if(PyString_Check(Key.ptr())) + return get_item_name(Self, boost::python::extract(Key), static_cast(Role::value)); + else if(PyInt_Check(Key.ptr())) + return get_item_idx(Self, boost::python::extract(Key), static_cast(Role::value)); + else + throw std::runtime_error("Item lookup key must be a string or an integer"); +} + +class role_method_creator +{ +public: + role_method_creator(boost::python::object& Instance) : m_instance(Instance) + { + } + + template void operator()(T RoleIdx) + { + const string_t role_name(atk_role_get_name(static_cast(RoleIdx.value))); + const string_t function_name(script_name(role_name)); + const string_t doc1 = "Get a " + role_name + " by name."; + const string_t doc2 = "Get a " + role_name + " by index."; + utility::add_method(utility::make_function(&get_item, doc1.c_str()), function_name, m_instance); + } +private: + boost::python::object& m_instance; +}; + +/// Wrap an AtkObject, adding additional dynamic methods for any actions it may have +boost::python::object wrap(AtkObject* Object) +{ + boost::python::object wrapped = k3d::python::wrap(Object); + + role_method_creator creator(wrapped); + boost::mpl::for_each >(creator); + + define_action_methods(Object, wrapped); + return wrapped; +} + +} // namespace detail + +static k3d::string_t name(atk_object_wrapper& Self) +{ + const gchar* the_name = atk_object_get_name(Self.wrapped_ptr()); + if(!the_name) + return ""; + return k3d::string_t(the_name); +} + +class atk +{ +public: + static object root() + { + return detail::wrap(atk_get_root()); + } +}; + +void define_class_atk_object() +{ + + scope outer = class_("atk", no_init) + .def("root", &atk::root, "Returns the root ATK object for the K-3D application") + .staticmethod("root"); + + class_("object", + "Wraps an ATK object", no_init) + .def("name", &name, "Get the name of the ATK object"); +} + +} // namespace python + +} // namespace k3d diff --git a/pool/shard011/C++/0122227_FrictionSurface.cpp b/pool/shard011/C++/0122227_FrictionSurface.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9c59bca32c927686443912bf5748a7cd03e5d54c --- /dev/null +++ b/pool/shard011/C++/0122227_FrictionSurface.cpp @@ -0,0 +1,82 @@ +////////////////////////////////////////////////////////////////////////////// +// Copyright 2004-2013, SenseGraphics AB +// +// This file is part of HAPI. +// +// HAPI 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. +// +// HAPI 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 HAPI; if not, write to the Free Software +// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +// +// A commercial license is also available. Please contact us at +// www.sensegraphics.com for more information. +// +// +/// \file FrictionSurface.cpp +/// \brief cpp file for FrictionSurface +/// +// +////////////////////////////////////////////////////////////////////////////// + +#include +#include + +using namespace HAPI; + +FrictionSurface::FrictionSurface( HAPIFloat _stiffness, + HAPIFloat _damping, + HAPIFloat _static_friction, + HAPIFloat _dynamic_friction, + bool _use_relative_values, + bool _use_ref_count_lock ) : +HAPIFrictionSurface( _stiffness, _damping, _static_friction, + _dynamic_friction, _use_relative_values, + _use_ref_count_lock ) { +} + +void FrictionSurface::getProxyMovement( ContactInfo &contact_info ) { + if( H3DUtil::H3DAbs( static_friction ) < Constants::epsilon && + H3DUtil::H3DAbs( dynamic_friction ) < Constants::epsilon ) { + // SmoothSurface + Vec3 local_probe = contact_info.localProbePosition(); + contact_info.setLocalProxyMovement( Vec2( local_probe.x , local_probe.z ) ); + } else { + // FrictionalSurface + // Friction model calculation modeled after the information in + // section 4 of "Haptic Interaction in Virtual Environments" by + // Diego C. Ruspini, Krasimir Kolarov and Oussama Khatib. + // Published 1997. + Vec3 local_probe = contact_info.localProbePosition(); + HAPIFloat local_stiffness = stiffness; + if( use_relative_values ) { + local_stiffness = stiffness * + contact_info.hapticsDevice()->getMaxStiffness(); + } + Vec3 force = local_probe * -local_stiffness; + Vec2 force_t( force.x, force.z ); + //This part is needed to compile on linux. + Vec2 local_probe_2d = Vec2( local_probe.x, local_probe.z ); + + setLocalProxyMovement( contact_info, + force_t.length(), + force.y, + local_probe_2d, + static_friction, + dynamic_friction ); + + } +} + +void FrictionSurface::getForces( ContactInfo &contact_info ) { + getForcesInternal( contact_info, contact_info.globalOrigin(), + stiffness, damping, use_relative_values ); +} diff --git a/pool/shard011/C++/0122231_plugin_get_javascript_url_test.cc b/pool/shard011/C++/0122231_plugin_get_javascript_url_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..74d01f13c59e6061da06e5720582938ff703f9d3 --- /dev/null +++ b/pool/shard011/C++/0122231_plugin_get_javascript_url_test.cc @@ -0,0 +1,118 @@ +// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "webkit/glue/plugins/test/plugin_get_javascript_url_test.h" + +#include "base/basictypes.h" + +// url for "self". +#define SELF_URL "javascript:window.location+\"\"" +// The identifier for the self url stream. +#define SELF_URL_STREAM_ID 1 + +// The identifier for the fetched url stream. +#define FETCHED_URL_STREAM_ID 2 + +// The maximum chunk size of stream data. +#define STREAM_CHUNK 197 + +namespace NPAPIClient { + +ExecuteGetJavascriptUrlTest::ExecuteGetJavascriptUrlTest(NPP id, NPNetscapeFuncs *host_functions) + : PluginTest(id, host_functions), + test_started_(false) { +} + +NPError ExecuteGetJavascriptUrlTest::SetWindow(NPWindow* pNPWindow) { + if (!test_started_) { + std::string url = SELF_URL; + HostFunctions()->geturlnotify(id(), url.c_str(), "_top", + reinterpret_cast(SELF_URL_STREAM_ID)); + test_started_ = true; + } + return NPERR_NO_ERROR; +} + +NPError ExecuteGetJavascriptUrlTest::NewStream(NPMIMEType type, NPStream* stream, + NPBool seekable, uint16* stype) { + if (stream == NULL) + SetError("NewStream got null stream"); + + COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), + cast_validity_check); + unsigned long stream_id = reinterpret_cast(stream->notifyData); + switch (stream_id) { + case SELF_URL_STREAM_ID: + break; + default: + SetError("Unexpected NewStream callback"); + break; + } + return NPERR_NO_ERROR; +} + +int32 ExecuteGetJavascriptUrlTest::WriteReady(NPStream *stream) { + return STREAM_CHUNK; +} + +int32 ExecuteGetJavascriptUrlTest::Write(NPStream *stream, int32 offset, int32 len, + void *buffer) { + if (stream == NULL) + SetError("Write got null stream"); + if (len < 0 || len > STREAM_CHUNK) + SetError("Write got bogus stream chunk size"); + + COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), + cast_validity_check); + unsigned long stream_id = reinterpret_cast(stream->notifyData); + switch (stream_id) { + case SELF_URL_STREAM_ID: + self_url_.append(static_cast(buffer), len); + break; + default: + SetError("Unexpected write callback"); + break; + } + // Pretend that we took all the data. + return len; +} + + +NPError ExecuteGetJavascriptUrlTest::DestroyStream(NPStream *stream, NPError reason) { + if (stream == NULL) + SetError("NewStream got null stream"); + + COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(stream->notifyData), + cast_validity_check); + unsigned long stream_id = reinterpret_cast(stream->notifyData); + switch (stream_id) { + case SELF_URL_STREAM_ID: + // don't care + break; + default: + SetError("Unexpected NewStream callback"); + break; + } + return NPERR_NO_ERROR; +} + +void ExecuteGetJavascriptUrlTest::URLNotify(const char* url, NPReason reason, void* data) { + COMPILE_ASSERT(sizeof(unsigned long) <= sizeof(data), + cast_validity_check); + unsigned long stream_id = reinterpret_cast(data); + switch (stream_id) { + case SELF_URL_STREAM_ID: + if (strcmp(url, SELF_URL) != 0) + SetError("URLNotify reported incorrect url for SELF_URL"); + if (self_url_.empty()) + SetError("Failed to obtain window location."); + SignalTestCompleted(); + break; + default: + SetError("Unexpected NewStream callback"); + break; + } +} + +} // namespace NPAPIClient diff --git a/pool/shard011/C++/0122233_PluginProcessor.cpp b/pool/shard011/C++/0122233_PluginProcessor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f64c8acc38e3be49a4b2981ac61b25c2d3f00a46 --- /dev/null +++ b/pool/shard011/C++/0122233_PluginProcessor.cpp @@ -0,0 +1,212 @@ +/* + ============================================================================== + + This file was auto-generated! + + It contains the basic framework code for a JUCE plugin processor. + + ============================================================================== +*/ + +#include "PluginProcessor.h" +#include "PluginEditor.h" + + +//============================================================================== +TestOrfanidisBiquadAudioProcessor::TestOrfanidisBiquadAudioProcessor() + : gain {nullptr}, + frequency {nullptr}, + bandwidth {nullptr} +{ + addParameter (gain = new AudioParameterFloat {"GainID", "Gain", -36.0f, 36.0f, 0.0f}); + addParameter (frequency = new AudioParameterFloat {"FrequencyID", "Frequency", 0.0f, 1.0f, 0.5f}); + addParameter (bandwidth = new AudioParameterFloat {"BandwidthID", "Bandwidth", 0.03f, 6.0f, 0.707f}); + + xn_1.resize (8, 0); // state for up to 8 chans + xn_2.resize (8, 0); + yn_1.resize (8, 0); + yn_2.resize (8, 0); +} + +TestOrfanidisBiquadAudioProcessor::~TestOrfanidisBiquadAudioProcessor() +{ +} + +//============================================================================== +const String TestOrfanidisBiquadAudioProcessor::getName() const +{ + return JucePlugin_Name; +} + +bool TestOrfanidisBiquadAudioProcessor::acceptsMidi() const +{ + #if JucePlugin_WantsMidiInput + return true; + #else + return false; + #endif +} + +bool TestOrfanidisBiquadAudioProcessor::producesMidi() const +{ + #if JucePlugin_ProducesMidiOutput + return true; + #else + return false; + #endif +} + +double TestOrfanidisBiquadAudioProcessor::getTailLengthSeconds() const +{ + return 0.0; +} + +int TestOrfanidisBiquadAudioProcessor::getNumPrograms() +{ + return 1; // NB: some hosts don't cope very well if you tell them there are 0 programs, + // so this should be at least 1, even if you're not really implementing programs. +} + +int TestOrfanidisBiquadAudioProcessor::getCurrentProgram() +{ + return 0; +} + +void TestOrfanidisBiquadAudioProcessor::setCurrentProgram (int index) +{ +} + +const String TestOrfanidisBiquadAudioProcessor::getProgramName (int index) +{ + return String(); +} + +void TestOrfanidisBiquadAudioProcessor::changeProgramName (int index, const String& newName) +{ +} + +//============================================================================== +void TestOrfanidisBiquadAudioProcessor::prepareToPlay (double sampleRate, int samplesPerBlock) +{ + // Use this method as the place to do any pre-playback + // initialisation that you need.. + + xn_1.assign(8, 0); // clear unit delays + xn_2.assign(8, 0); + yn_1.assign(8, 0); + yn_2.assign(8, 0); + + coeffs.setRate (sampleRate); +} + +void TestOrfanidisBiquadAudioProcessor::releaseResources() +{ + // When playback stops, you can use this as an opportunity to free up any + // spare memory, etc. +} + +#ifndef JucePlugin_PreferredChannelConfigurations +bool TestOrfanidisBiquadAudioProcessor::setPreferredBusArrangement (bool isInput, int bus, const AudioChannelSet& preferredSet) +{ + // Reject any bus arrangements that are not compatible with your plugin + + const int numChannels = preferredSet.size(); + + #if JucePlugin_IsMidiEffect + if (numChannels != 0) + return false; + #elif JucePlugin_IsSynth + if (isInput || (numChannels != 1 && numChannels != 2)) + return false; + #else + if (numChannels != 1 && numChannels != 2) + return false; + + if (! AudioProcessor::setPreferredBusArrangement (! isInput, bus, preferredSet)) + return false; + #endif + + return AudioProcessor::setPreferredBusArrangement (isInput, bus, preferredSet); +} +#endif + +void TestOrfanidisBiquadAudioProcessor::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages) +{ + const int totalNumInputChannels = getTotalNumInputChannels(); + const int totalNumOutputChannels = getTotalNumOutputChannels(); + + // In case we have more outputs than inputs, this code clears any output + // channels that didn't contain input data, (because these aren't + // guaranteed to be empty - they may contain garbage). + // This is here to avoid people getting screaming feedback + // when they first compile a plugin, but obviously you don't need to keep + // this code if your algorithm always overwrites all the output channels. + for (int i = totalNumInputChannels; i < totalNumOutputChannels; ++i) + buffer.clear (i, 0, buffer.getNumSamples()); + + // This is the place where you'd normally do the guts of your plugin's + // audio processing... + + coeffs.calculate(*gain, *frequency, *bandwidth); + + const double b0 = coeffs.b0(); + const double b1 = coeffs.b1(); + const double b2 = coeffs.b2(); + const double a1 = coeffs.a1(); + const double a2 = coeffs.a2(); + + float** yn = buffer.getArrayOfWritePointers(); + + for (int s = 0; s < buffer.getNumSamples(); ++s) + { + for (int c = 0; c < totalNumInputChannels; ++c) + { + yn[c][s] += denormal; + + const double xn = static_cast (yn[c][s]); // perform calcs at double + + // direct form 1 + yn[c][s] = static_cast (b0*xn + b1*xn_1[c] + b2*xn_2[c] + - a1*yn_1[c] - a2*yn_2[c]); + + xn_2[c] = xn_1[c]; // advance delay networks + xn_1[c] = xn; + yn_2[c] = yn_1[c]; + yn_1[c] = yn[c][s]; + } + } + + denormal *= -1; // avoid removal by DC filter +} + +//============================================================================== +bool TestOrfanidisBiquadAudioProcessor::hasEditor() const +{ + return true; // (change this to false if you choose to not supply an editor) +} + +AudioProcessorEditor* TestOrfanidisBiquadAudioProcessor::createEditor() +{ + return new TestOrfanidisBiquadAudioProcessorEditor (*this); +} + +//============================================================================== +void TestOrfanidisBiquadAudioProcessor::getStateInformation (MemoryBlock& destData) +{ + // You should use this method to store your parameters in the memory block. + // You could do that either as raw data, or use the XML or ValueTree classes + // as intermediaries to make it easy to save and load complex data. +} + +void TestOrfanidisBiquadAudioProcessor::setStateInformation (const void* data, int sizeInBytes) +{ + // You should use this method to restore your parameters from this memory block, + // whose contents will have been created by the getStateInformation() call. +} + +//============================================================================== +// This creates new instances of the plugin.. +AudioProcessor* JUCE_CALLTYPE createPluginFilter() +{ + return new TestOrfanidisBiquadAudioProcessor(); +} diff --git a/pool/shard011/C++/0122234_kis_script_decoration.cc b/pool/shard011/C++/0122234_kis_script_decoration.cc new file mode 100644 index 0000000000000000000000000000000000000000..abc332b121e9d4111f015f39e1ad703b57f2984f --- /dev/null +++ b/pool/shard011/C++/0122234_kis_script_decoration.cc @@ -0,0 +1,52 @@ +/* + * This file is part of Krita + * + * Copyright (c) 2008 Cyrille Berger + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +#include "kis_script_decoration.h" + +#include + +#include + +struct KisScriptDecoration::Private { + Kross::Action* action; +}; + +KisScriptDecoration::KisScriptDecoration(Kross::Action* _action, KisView2* _view) : + KisCanvasDecoration(_action->name(), _action->text(), _view), d(new Private) +{ + d->action = _action; +} + +KisScriptDecoration::~KisScriptDecoration() +{ + delete d; +} + +void KisScriptDecoration::drawDecoration(QPainter& gc, const QRectF& updateRect, const KisCoordinatesConverter *converter) +{ + dbgScript << "Call to drawDecoration"; + + QVariantList list; + list << qVariantFromValue((void*)&gc) + << updateRect + << qVariantFromValue((void*)converter); + + d->action->callFunction("drawDecoration", list); +} diff --git a/pool/shard011/C++/0122235_editaddressdialog.cpp b/pool/shard011/C++/0122235_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ed2aa80db58d0e97969602e5e315fc183a6754ef --- /dev/null +++ b/pool/shard011/C++/0122235_editaddressdialog.cpp @@ -0,0 +1,130 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setDisabled(true); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + + tr("The entered address \"%1\" is not a valid Coine address.").arg(ui->addressEdit->text()), + + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + } + + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard011/C++/0122236_Config.cpp b/pool/shard011/C++/0122236_Config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c54becaa81c057e352767e272889aa90c6e8771 --- /dev/null +++ b/pool/shard011/C++/0122236_Config.cpp @@ -0,0 +1,100 @@ +// 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. +// The use and distribution terms for this software are covered by the Eclipse +// Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) which +// can be found in the file epl-v10.html at the root of this distribution. +// By using this software in any fashion, you are agreeing to be bound by the +// terms of this license. You must not remove this notice, or any other, from +// this software. +// Copyright (c) 2013-2016, Kenneth Leung. All rights reserved. + +#include "Splash.h" +#include "Config.h" +NS_BEGIN(bazuka) + +////////////////////////////////////////////////////////////////////////////// +// +owner Config::reify() { + auto c = mc_new(Config); + c->initAssets(); + c->initLevels(); + c->initCsts(); + return c; +} + +////////////////////////////////////////////////////////////////////////////// +// +void Config::initLevels() { + auto d= getLevel("1"); + auto j= j::json({ }); + d->setObject(f::JsonObj::create(j), CFG); +} + +////////////////////////////////////////////////////////////////////////////// +// +void Config::initCsts() { + _game_id= "31b3f51c-d0e8-4ec4-8a04-8896e22c070b"; + _app_id = "bazuka"; + + addCst("ENEMY+FIRE+DELAY", CC_FLOAT(1.8f)); + addCst("ENEMY+SPAWN+DELAY", CC_INT(3000)); + + addCst("BG+SCROLL", CC_FLOAT(3.0)); +} + +////////////////////////////////////////////////////////////////////////////// +// +void Config::initAssets() { + + addAtlas("cc-pics", CC_STR("pics/sprite_sheet.plist")); + addImage("cc-pics", CC_STR("pics/sprite_sheet.png")); + + addAtlas("game-pics", CC_STR("pics/images.plist")); + addImage("game-pics", CC_STR("pics/images.png")); + + addImage("game.bg", CC_STR("pics/bg.jpg")); + + addEffect("enemyKill", CC_STR("sfx/enemyKill.wav")); + addEffect("fireRocket", CC_STR("sfx/fireRocket.wav")); + addEffect("gunshot", CC_STR("sfx/gunshot.wav")); + addEffect("playerKill", CC_STR("sfx/playerKill.wav")); + addEffect("pop", CC_STR("sfx/pop.wav")); + addEffect("rocketExplode", CC_STR("sfx/rocketExplode.wav")); + + addMusic("background", CC_STR("sfx/bgMusic.wav")); + + addFont("title", CC_STR("fonts/en/SFCollegiate.fnt")); + addFont("btns", CC_STR("fonts/en/Hiruko.fnt")); + addFont("pixel", CC_STR("fonts/en/04b30.fnt")); + addFont("text", CC_STR("fonts/en/Verdana.ttf")); +} + +////////////////////////////////////////////////////////////////////////////// +// +void Config::handleResolution(const CCT_SZ &rs) { +} + +////////////////////////////////////////////////////////////////////////////// +// +float Config::scaleFont(float p) { + return p/128.0 * _scale; +} + +////////////////////////////////////////////////////////////////////////////// +// +void Config::runOnce() { + cacheSprites("game-pics"); + cacheSprites("cc-pics"); +} + +////////////////////////////////////////////////////////////////////////////// +// +c::Scene* Config::prelude() { + return Splash::reify(); +} + + +NS_END + + diff --git a/pool/shard011/C++/0122237_SetRadarLODAction.cpp b/pool/shard011/C++/0122237_SetRadarLODAction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ba530ee17cf8155603d1033bd505b36037301999 --- /dev/null +++ b/pool/shard011/C++/0122237_SetRadarLODAction.cpp @@ -0,0 +1,40 @@ +/* +** Copyright (C) 1999 Microsoft Corporation. All Rights Reserved. +** +** File: setradarlodaction.cpp +** +** Author: +** +** Description: +** Implementation of the training library "setradarlodaction" interface. +** +** History: +*/ +#include "pch.h" +#include "SetRadarLODAction.h" + +namespace Training +{ + //------------------------------------------------------------------------------ + // class methods + //------------------------------------------------------------------------------ + /* void */ SetRadarLODAction::SetRadarLODAction (RadarImage::RadarLOD radarLOD) : + m_radarLOD (radarLOD) + { + } + + //------------------------------------------------------------------------------ + /* void */ SetRadarLODAction::~SetRadarLODAction (void) + { + } + + //------------------------------------------------------------------------------ + void SetRadarLODAction::Execute (void) + { + TrekWindow* window = GetWindow (); + if (window->GetRadarMode () != static_cast (m_radarLOD)) + GetWindow ()->SetRadarMode (static_cast (m_radarLOD)); + } + + //------------------------------------------------------------------------------ +} diff --git a/pool/shard011/C++/0122239_motion_event_coalescer.cc b/pool/shard011/C++/0122239_motion_event_coalescer.cc new file mode 100644 index 0000000000000000000000000000000000000000..779c1c0ef05cd2dd86f093a8c2a1f44043e2f9e8 --- /dev/null +++ b/pool/shard011/C++/0122239_motion_event_coalescer.cc @@ -0,0 +1,82 @@ +// Copyright (c) 2010 The Chromium OS 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 "window_manager/motion_event_coalescer.h" + +#include "base/logging.h" +#include "window_manager/event_loop.h" + +namespace window_manager { + +MotionEventCoalescer::MotionEventCoalescer(EventLoop* event_loop, + Closure* cb, + int timeout_ms) + : event_loop_(event_loop), + timeout_id_(-1), + timeout_ms_(timeout_ms), + have_queued_position_(false), + position_(-1, -1), + cb_(cb), + synchronous_(false) { + CHECK(cb); + CHECK(timeout_ms > 0); +} + +MotionEventCoalescer::~MotionEventCoalescer() { + if (IsRunning()) + StopInternal(false); +} + +void MotionEventCoalescer::Start() { + if (timeout_id_ >= 0) { + LOG(WARNING) << "Ignoring request to start coalescer while timer " + << "is already running"; + return; + } + if (!synchronous_) { + timeout_id_ = event_loop_->AddTimeout( + NewPermanentCallback(this, &MotionEventCoalescer::HandleTimeout), + 0, timeout_ms_); + } + have_queued_position_ = false; + position_.reset(-1, -1); +} + +void MotionEventCoalescer::Stop() { + if (!synchronous_) + StopInternal(true); +} + +void MotionEventCoalescer::StorePosition(const Point& pos) { + if (pos == position_) + return; + position_ = pos; + have_queued_position_ = true; + if (synchronous_) + HandleTimeout(); +} + +void MotionEventCoalescer::StopInternal(bool maybe_run_callback) { + if (timeout_id_ < 0) { + LOG(WARNING) << "Ignoring request to stop coalescer while timer " + << "isn't running"; + return; + } + event_loop_->RemoveTimeout(timeout_id_); + timeout_id_ = -1; + + // Invoke the handler one last time to catch any events that came in + // after the final run. + if (maybe_run_callback) + HandleTimeout(); +} + +void MotionEventCoalescer::HandleTimeout() { + if (have_queued_position_) { + cb_->Run(); + have_queued_position_ = false; + } +} + +} // namespace window_manager diff --git a/pool/shard011/C++/0122240_denoising.cpp b/pool/shard011/C++/0122240_denoising.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a7bc0d554f4a26c17f6be8fb3ec87da62fc8c85 --- /dev/null +++ b/pool/shard011/C++/0122240_denoising.cpp @@ -0,0 +1,209 @@ +// Denoising using Fields of Experts [1]. This example problem also comes +// with Ceres Solver, a solver for nonlinear least squares problems and +// can be used for comparing the two solvers. +// +// [1] S. Roth and M.J. Black. “Fields of Experts.” International Journal of +// Computer Vision, 82(2):205–229, 2009. + +#include +#include +#include +#include +#include +#include + +#include +#include + +// pgm_image uses Google Glog, specifically the +// CHECK macro. +#define CHECK(arg) spii_assert(arg) +#include "pgm_image.h" +using ceres::examples::PGMImage; + +#include "fields_of_experts.h" + +const double sigma = 20.0; + +// This Term is used to build the data term. +// +// f_i(x) = a · (x_i - b)^2 +// +class QuadraticTerm + : public spii::SizedTerm<1> +{ +public: + QuadraticTerm(double a_, double b_) + // 0.5 to agree with Ceres. + : a{0.5 * a_}, b{b_} + { } + + double evaluate(double * const * const x) const override + { + return a * (x[0][0] - b) * (x[0][0] - b); + } + + double evaluate(double * const * const x, + std::vector* gradient) const override + { + (*gradient)[0][0] = 2.0 * a * x[0][0] - 2.0 * a * b; + return evaluate(x); + } + + double evaluate(double * const * const x, + std::vector* gradient, + std::vector< std::vector >* hessian) const override + { + (*hessian)[0][0](0, 0) = 2.0 * a; + return evaluate(x, gradient); + } + +private: + double a, b; +}; + +// Creates a Fields of Experts MAP function. +void create_functions(const FieldsOfExperts& foe, + const PGMImage& image, + spii::Function* function, + PGMImage* solution) +{ + // Create the data term + const double coefficient = 1 / (2.0 * sigma * sigma); + for (int index = 0; index < image.NumPixels(); ++index) + { + auto term = + std::make_shared(coefficient, + image.PixelFromLinearIndex(index)); + function->add_term(term, solution->MutablePixelFromLinearIndex(index)); + } + + // Create terms for regularization. One is needed for each filter. + std::vector> foe_terms(foe.num_filters()); + for (int alpha_index = 0; alpha_index < foe.num_filters(); ++alpha_index) { + foe_terms[alpha_index] = foe.new_term(alpha_index); + } + + // Add FoE regularization for each patch in the image. + for (int x = 0; x < image.width() - (foe.size() - 1); ++x) { + for (int y = 0; y < image.height() - (foe.size() - 1); ++y) { + // Build a vector with the pixel indices of this patch. + std::vector pixels; + const std::vector& x_delta_indices = foe.get_x_delta_indices(); + const std::vector& y_delta_indices = foe.get_y_delta_indices(); + for (int i = 0; i < foe.num_variables(); ++i) { + double* pixel = solution->MutablePixel(x + x_delta_indices[i], + y + y_delta_indices[i]); + pixels.push_back(pixel); + } + // For this patch with coordinates (x, y), we will add foe.NumFilters() + // terms to the objective function. + for (int alpha_index = 0; alpha_index < foe.num_filters(); ++alpha_index) { + function->add_term(foe_terms[alpha_index], + pixels); + } + } + } +} + +void minimize_function(const spii::Function& function, PGMImage* solution) +{ + spii::LBFGSSolver solver; + solver.function_improvement_tolerance = 1e-3; + + solver.maximum_iterations = 1000; + + int iteration = 0; + solver.callback_function = + [&](const spii::CallbackInformation& info) -> bool + { + if (++iteration % 10 == 0) { + // Uncomment to save solution every 10 iterations. + //function.copy_global_to_user(*info.x); + //std::stringstream sout; + //sout << "output-" << iteration << ".pgm"; + //spii::check(solution->WriteToFile(sout.str()), "Writing failed."); + } + return true; + }; + + solver.log_function = + [](const std::string& str) + { + std::cout << str << std::endl; + }; + + spii::SolverResults results; + solver.solve(function, &results); + + function.print_timing_information(std::cout); + std::cout << results << std::endl; + + // Make the solution stay in [0, 255]. + for (int x = 0; x < solution->width(); ++x) { + for (int y = 0; y < solution->height(); ++y) { + *solution->MutablePixel(x, y) = + std::min(255.0, std::max(0.0, solution->Pixel(x, y))); + } + } +} + +int main_function(int argc, char** argv) +{ + using namespace spii; + using namespace std; + + auto foe_file_name = "2x2.foe"; + if (argc > 1) { + foe_file_name = argv[1]; + } + + auto input_file_name = "ceres_noisy.pgm"; + if (argc > 2) { + input_file_name = argv[2]; + } + + // Load the Fields of Experts filters from file. + Timer foe_timer("Loading FoE file"); + FieldsOfExperts foe(foe_file_name); + foe_timer.OK(); + + // Read the images + Timer image_timer("Loading images"); + PGMImage image(input_file_name); + check(image.width() > 0, "Reading input image failed."); + PGMImage solution(image.width(), image.height()); + solution.Set(0.0); + solution += image; + image_timer.OK(); + + Timer function_timer("Creating function"); + spii::Function function; + function.hessian_is_enabled = false; + create_functions(foe, image, &function, &solution); + function_timer.OK(); + + cout << "Number of variables : " << function.get_number_of_variables() << endl; + cout << "Number of terms : " << function.get_number_of_terms() << endl; + cout << "Function value : " << function.evaluate() << endl; + + minimize_function(function, &solution); + + cout << "Final function value : " << function.evaluate() << endl; + + Timer save_timer("Saving image"); + check(solution.WriteToFile("output-final.pgm"), "Writing failed."); + save_timer.OK(); + + return 0; +} + +int main(int argc, char** argv) +{ + try { + return main_function(argc, argv); + } + catch (std::exception& e) { + std::cerr << "\nException: " << e.what() << std::endl; + } +} diff --git a/pool/shard011/C++/0122241_GenericSpecializer.cpp b/pool/shard011/C++/0122241_GenericSpecializer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2582deaa3a11d747d711467a24a59e84b67993b0 --- /dev/null +++ b/pool/shard011/C++/0122241_GenericSpecializer.cpp @@ -0,0 +1,142 @@ +//===--- GenericSpecializer.cpp - Specialization of generic functions -----===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// Specialize calls to generic functions by substituting static type +// information. +// +//===----------------------------------------------------------------------===// + +#define DEBUG_TYPE "sil-generic-specializer" + +#include "swift/SIL/OptimizationRemark.h" +#include "swift/SIL/SILFunction.h" +#include "swift/SIL/SILInstruction.h" +#include "swift/SILOptimizer/Utils/Generics.h" +#include "swift/SILOptimizer/Utils/Local.h" +#include "swift/SILOptimizer/PassManager/Transforms.h" +#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" +#include "llvm/ADT/SmallVector.h" + +using namespace swift; + +namespace { + +class GenericSpecializer : public SILFunctionTransform { + + bool specializeAppliesInFunction(SILFunction &F); + + /// The entry point to the transformation. + void run() override { + SILFunction &F = *getFunction(); + + // TODO: We should be able to handle ownership. + if (F.hasOwnership()) + return; + + LLVM_DEBUG(llvm::dbgs() << "***** GenericSpecializer on function:" + << F.getName() << " *****\n"); + + if (specializeAppliesInFunction(F)) + invalidateAnalysis(SILAnalysis::InvalidationKind::Everything); + } + +}; + +} // end anonymous namespace + +bool GenericSpecializer::specializeAppliesInFunction(SILFunction &F) { + SILOptFunctionBuilder FunctionBuilder(*this); + DeadInstructionSet DeadApplies; + llvm::SmallSetVector Applies; + OptRemark::Emitter ORE(DEBUG_TYPE, F.getModule()); + + bool Changed = false; + for (auto &BB : F) { + // Collect the applies for this block in reverse order so that we + // can pop them off the end of our vector and process them in + // forward order. + for (auto It = BB.rbegin(), End = BB.rend(); It != End; ++It) { + auto *I = &*It; + + // Skip non-apply instructions, apply instructions with no + // substitutions, apply instructions where we do not statically + // know the called function, and apply instructions where we do + // not have the body of the called function. + ApplySite Apply = ApplySite::isa(I); + if (!Apply || !Apply.hasSubstitutions()) + continue; + + auto *Callee = Apply.getReferencedFunction(); + if (!Callee) + continue; + if (!Callee->isDefinition()) { + ORE.emit([&]() { + using namespace OptRemark; + return RemarkMissed("NoDef", *I) + << "Unable to specialize generic function " + << NV("Callee", Callee) << " since definition is not visible"; + }); + continue; + } + + Applies.insert(Apply.getInstruction()); + } + + // Attempt to specialize each apply we collected, deleting any + // that we do specialize (along with other instructions we clone + // in the process of doing so). We pop from the end of the list to + // avoid tricky iterator invalidation issues. + while (!Applies.empty()) { + auto *I = Applies.pop_back_val(); + auto Apply = ApplySite::isa(I); + assert(Apply && "Expected an apply!"); + SILFunction *Callee = Apply.getReferencedFunction(); + assert(Callee && "Expected to have a known callee"); + + if (!Apply.canOptimize() || !Callee->shouldOptimize()) + continue; + + // We have a call that can potentially be specialized, so + // attempt to do so. + llvm::SmallVector NewFunctions; + trySpecializeApplyOfGeneric(FunctionBuilder, Apply, DeadApplies, + NewFunctions, ORE); + + // Remove all the now-dead applies. We must do this immediately + // rather than defer it in order to avoid problems with cloning + // dead instructions when doing recursive specialization. + while (!DeadApplies.empty()) { + auto *AI = DeadApplies.pop_back_val(); + + // Remove any applies we are deleting so that we don't attempt + // to specialize them. + Applies.remove(AI); + + recursivelyDeleteTriviallyDeadInstructions(AI, true); + Changed = true; + } + + // If calling the specialization utility resulted in new functions + // (as opposed to returning a previous specialization), we need to notify + // the pass manager so that the new functions get optimized. + for (SILFunction *NewF : reverse(NewFunctions)) { + addFunctionToPassManagerWorklist(NewF, Callee); + } + } + } + + return Changed; +} + +SILTransform *swift::createGenericSpecializer() { + return new GenericSpecializer(); +} diff --git a/pool/shard011/C++/0122242_unittest_eigen.cpp b/pool/shard011/C++/0122242_unittest_eigen.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0c02c77d088c7dc713d5ef7c655413aeb336a2e4 --- /dev/null +++ b/pool/shard011/C++/0122242_unittest_eigen.cpp @@ -0,0 +1,173 @@ +#include +#include "gtest/gtest.h" +#include +#include "shmfw/variable.h" +#include "shmfw/serialization/eigen.h" +#include "shmfw/serialization/io_file.h" + +namespace { + +// The fixture for testing class Foo. +class EigenTest : public ::testing::Test { +protected: + // You can remove any or all of the following functions if its body + // is empty. + + EigenTest() + : shmSegmentName_ ( "ShmTestSegment" ) + , shmSegmentSize_ ( 65536 ) { + srand ( time ( NULL ) ); + // You can do set-up work for each test here. + } + + virtual ~EigenTest() { + // You can do clean-up work that doesn't throw exceptions here. + } + + // If the constructor and destructor are not enough for setting up + // and cleaning up each test, you can define the following methods: + + virtual void SetUp() { + // Code here will be called immediately after the constructor (right + // before each test). + } + + virtual void TearDown() { + // Code here will be called immediately after each test (right + // before the destructor). + } + + std::string shmSegmentName_; + int shmSegmentSize_; + double rand_01() { + return ( double ) rand() / RAND_MAX; + } + double randf ( double fmin, double fmax ) { + return rand_01() * ( fmax - fmin ) + fmin; + } + double randAngle() { + return rand_01() * 2 * M_PI - M_PI; + } + double randf() { + return randf ( -10, 10 ); + } +}; + +TEST_F ( EigenTest, ShmVector3d ) { + + std::string name ( "var0" ); + ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( shmSegmentName_, shmSegmentSize_ ); + ShmFw::Var a ( name,shmHdl ); + ShmFw::Var b ( name,shmHdl ); + *a << rand_01(), rand_01(), rand_01(); + EXPECT_EQ ( *a, *b ); + shmHdl->removeSegment(); +} +TEST_F ( EigenTest, Matrix3d ) { + + std::string name ( "var0" ); + ShmFw::HandlerPtr shmHdl = ShmFw::Handler::create ( shmSegmentName_, shmSegmentSize_ ); + ShmFw::Var a ( name,shmHdl ); + ShmFw::Var b ( name,shmHdl ); + *a = Eigen::Matrix3d::Random(); + EXPECT_EQ ( *a, *b ); + shmHdl->removeSegment(); +} +TEST_F ( EigenTest, serializeVector3dXML ) { + std::string filename ( "/tmp/Vector3d.xml" ); + Eigen::Vector3d a (rand_01(), rand_01(), rand_01()), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrix3dXML ) { + std::string filename ( "/tmp/Matrix3d.xml" ); + Eigen::Matrix3d a = Eigen::Matrix3d::Random(), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeVector3dBin ) { + std::string filename ( "/tmp/Vector3d.bin" ); + Eigen::Vector3d a (rand_01(), rand_01(), rand_01()), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrix3dBin ) { + std::string filename ( "/tmp/Matrix3d.bin" ); + Eigen::Matrix3d a = Eigen::Matrix3d::Random(), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeVector3dTxt ) { + std::string filename ( "/tmp/Vector3d.txt" ); + Eigen::Vector3d a (rand_01(), rand_01(), rand_01()), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrix3dTxt ) { + std::string filename ( "/tmp/Matrix3d.txt" ); + Eigen::Matrix3d a = Eigen::Matrix3d::Random(), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeVectorXdXML ) { + std::string filename ( "/tmp/VectorXd.xml" ); + Eigen::VectorXd a (3), b; + a << rand_01(), rand_01(), rand_01();; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrixXdXML ) { + std::string filename ( "/tmp/MatrixXd.xml" ); + Eigen::MatrixXd a = Eigen::MatrixXd::Random ( 3,3 ), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeVectorXdBin ) { + std::string filename ( "/tmp/VectorXd.bin" ); + Eigen::VectorXd a (3), b; + a << rand_01(), rand_01(), rand_01();; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrixXdBin ) { + std::string filename ( "/tmp/MatrixXd.bin" ); + Eigen::MatrixXd a = Eigen::MatrixXd::Random ( 3,3 ), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeVectorXdTxt ) { + std::string filename ( "/tmp/VectorXd.txt" ); + Eigen::VectorXd a (3), b; + a << rand_01(), rand_01(), rand_01();; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} +TEST_F ( EigenTest, serializeMatrixXdTxt ) { + std::string filename ( "/tmp/MatrixXd.txt" ); + Eigen::MatrixXd a = Eigen::MatrixXd::Random ( 3,3 ), b; + ShmFw::write(filename, a); + ShmFw::read (filename, b); + EXPECT_EQ ( a, b ); +} + + +} // namespace + + + +int main ( int argc, char **argv ) { + ::testing::InitGoogleTest ( &argc, argv ); + return RUN_ALL_TESTS(); +} + diff --git a/pool/shard011/C++/0122244_messageIdTest.cpp b/pool/shard011/C++/0122244_messageIdTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9863ae51e79289445abe874f31721408c89856d5 --- /dev/null +++ b/pool/shard011/C++/0122244_messageIdTest.cpp @@ -0,0 +1,78 @@ +// +// VMime library (http://www.vmime.org) +// Copyright (C) 2002-2013 Vincent Richard +// +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License as +// published by the Free Software Foundation; either version 3 of +// the License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// General Public License for more details. +// +// You should have received a copy of the GNU General Public License along +// with this program; if not, write to the Free Software Foundation, Inc., +// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +// +// Linking this library statically or dynamically with other modules is making +// a combined work based on this library. Thus, the terms and conditions of +// the GNU General Public License cover the whole combination. +// + +#include "tests/testUtils.hpp" + + +VMIME_TEST_SUITE_BEGIN(messageIdTest) + + VMIME_TEST_LIST_BEGIN + VMIME_TEST(testParse) + VMIME_TEST(testParseInvalid) + VMIME_TEST(testGenerate) + VMIME_TEST_LIST_END + + + void testParse() + { + vmime::messageId m1; + m1.parse(""); + + VASSERT_EQ("1.1", "a", m1.getLeft()); + VASSERT_EQ("1.2", "b", m1.getRight()); + } + + void testParseInvalid() + { + vmime::messageId m1; + m1.parse("foo@bar"); + + VASSERT_EQ("1.1", "foo", m1.getLeft()); + VASSERT_EQ("1.2", "bar", m1.getRight()); + } + + void testGenerate() + { + vmime::messageId m1; + + VASSERT_EQ("1", "<>", m1.generate()); + + vmime::messageId m2; + m2.setLeft("a"); + + VASSERT_EQ("2", "", m2.generate()); + + vmime::messageId m3; + m3.setRight("b"); + + VASSERT_EQ("3", "<@b>", m3.generate()); + + vmime::messageId m4; + m4.setLeft("a"); + m4.setRight("b"); + + VASSERT_EQ("4", "", m4.generate()); + } + +VMIME_TEST_SUITE_END + diff --git a/pool/shard011/C++/0122245_XBeeNodeServerHelper.cpp b/pool/shard011/C++/0122245_XBeeNodeServerHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d08a35a31370631974dc3659e0a31b04882a6da4 --- /dev/null +++ b/pool/shard011/C++/0122245_XBeeNodeServerHelper.cpp @@ -0,0 +1,105 @@ +// +// XBeeNodeServerHelper.cpp +// +// Library: IoT/XBee +// Package: Generated +// Module: XBeeNodeServerHelper +// +// This file has been generated. +// Warning: All changes to this will be lost when the file is re-generated. +// +// Copyright (c) 2015, Applied Informatics Software Engineering GmbH. +// All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// + + +#include "IoT/XBee/XBeeNodeServerHelper.h" +#include "IoT/XBee/XBeeNodeEventDispatcher.h" +#include "IoT/XBee/XBeeNodeSkeleton.h" +#include "Poco/RemotingNG/URIUtility.h" +#include "Poco/SingletonHolder.h" + + +namespace IoT { +namespace XBee { + + +namespace +{ + static Poco::SingletonHolder shXBeeNodeServerHelper; +} + + +XBeeNodeServerHelper::XBeeNodeServerHelper(): + _pORB(0) +{ + _pORB = &Poco::RemotingNG::ORB::instance(); + registerSkeleton(); +} + + +XBeeNodeServerHelper::~XBeeNodeServerHelper() +{ +} + + +void XBeeNodeServerHelper::shutdown() +{ + XBeeNodeServerHelper::instance().unregisterSkeleton(); + shXBeeNodeServerHelper.reset(); +} + + +Poco::AutoPtr XBeeNodeServerHelper::createRemoteObjectImpl(Poco::SharedPtr pServiceObject, const Poco::RemotingNG::Identifiable::ObjectId& oid) +{ + return new XBeeNodeRemoteObject(oid, pServiceObject); +} + + +void XBeeNodeServerHelper::enableEventsImpl(const std::string& uri, const std::string& protocol) +{ + Poco::RemotingNG::Identifiable::Ptr pIdentifiable = _pORB->findObject(uri); + Poco::AutoPtr pRemoteObject = pIdentifiable.cast(); + if (pRemoteObject) + { + pRemoteObject->remoting__enableRemoteEvents(protocol); + } + else throw Poco::NotFoundException("remote object", uri); +} + + +XBeeNodeServerHelper& XBeeNodeServerHelper::instance() +{ + return *shXBeeNodeServerHelper.get(); +} + + +std::string XBeeNodeServerHelper::registerObjectImpl(Poco::AutoPtr pRemoteObject, const std::string& listenerId) +{ + return _pORB->registerObject(pRemoteObject, listenerId); +} + + +void XBeeNodeServerHelper::registerSkeleton() +{ + _pORB->registerSkeleton("IoT.XBee.XBeeNode", new XBeeNodeSkeleton); +} + + +void XBeeNodeServerHelper::unregisterObjectImpl(const std::string& uri) +{ + _pORB->unregisterObject(uri); +} + + +void XBeeNodeServerHelper::unregisterSkeleton() +{ + _pORB->unregisterSkeleton("IoT.XBee.XBeeNode", true); +} + + +} // namespace XBee +} // namespace IoT + diff --git a/pool/shard011/C++/0122247_Net.cc b/pool/shard011/C++/0122247_Net.cc new file mode 100644 index 0000000000000000000000000000000000000000..1de12048758640d9d2261828034a0b9373ee47af --- /dev/null +++ b/pool/shard011/C++/0122247_Net.cc @@ -0,0 +1,105 @@ +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with this program. If not, see http://www.gnu.org/licenses/. +// + +#include "Net.h" +#include "basemsg_m.h" + +Net::Net() { + // TODO Auto-generated constructor stub + +} + +Net::~Net() { + for(int i=0;ipar("num_machines"); + qmachines = new cQueue*[num_machines]; + cmachines = new cChannel*[num_machines]; + for(int i=0;igetName()) ){ + BaseMsg *amsg = check_and_cast(msg); + int dest = amsg->getDst(); + if( dest != ID_SCHEDULER ){ + if(!cmachines[dest]) cmachines[dest] = gate("machines$o",dest)->getTransmissionChannel(); + if( !cmachines[dest]->isBusy() ){ + send(amsg,"machines$o",dest); + }else{ + cMessage *fc = new cMessage("freechannel"); + cMsgPar *par = new cMsgPar("dest"); + par->setLongValue(dest); + fc->addPar(par); + if( qmachines[dest]->isEmpty() )scheduleAt(cmachines[dest]->getTransmissionFinishTime(),fc); + qmachines[dest]->insert(msg); + } + }else{ + if(!cscheduler)cscheduler = gate("scheduler$o")->getTransmissionChannel(); + if( !cscheduler->isBusy() ){ + send(amsg,"scheduler$o"); + }else{ + cMessage *fc = new cMessage("freechannel"); + cMsgPar *par = new cMsgPar("dest"); + par->setLongValue(dest); + fc->addPar(par); + if( qscheduler->isEmpty() )scheduleAt(cscheduler->getTransmissionFinishTime(),fc); + qscheduler->insert(msg); + } + } + }else{ + int dest = msg->par(0).longValue(); + cChannel *cdest; + cQueue *qdest; + char *sdest; + if( dest==ID_SCHEDULER ){ + cdest=cscheduler; + sdest="scheduler$o"; + qdest=qscheduler; + }else{ + cdest=cmachines[dest]; + sdest="machines$o"; + qdest=qmachines[dest]; + } + simtime_t t = cdest->getTransmissionFinishTime(); + if( t > simTime() ){ + scheduleAt(t,new cMessage("freechannel",dest)); + }else{ + BaseMsg *p = (BaseMsg*)qdest->pop(); + if( dest==ID_SCHEDULER ) + send(p,sdest); + else + send(p,sdest,dest); + if( !qdest->isEmpty() ){ + simtime_t t = cdest->getTransmissionFinishTime(); + scheduleAt(t,new cMessage("freechannel",dest)); + } + } + delete msg; + } +} diff --git a/pool/shard011/C++/0122248_cl_image_processor.cpp b/pool/shard011/C++/0122248_cl_image_processor.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b2acb7feb57e71f89b731c4794714715478b107 --- /dev/null +++ b/pool/shard011/C++/0122248_cl_image_processor.cpp @@ -0,0 +1,271 @@ +/* + * cl_image_processor.cpp - CL image processor + * + * Copyright (c) 2015 Intel Corporation + * + * 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. + * + * Author: Wind Yuan + */ +#include "cl_image_processor.h" +#include "cl_context.h" +#include "cl_device.h" +#include "cl_image_handler.h" +#include "drm_display.h" +#include "cl_demo_handler.h" +#include "xcam_thread.h" + +namespace XCam { + +class CLHandlerThread + : public Thread +{ +public: + CLHandlerThread (CLImageProcessor *processor) + : Thread ("CLHandlerThread") + , _processor (processor) + {} + ~CLHandlerThread () {} + + virtual bool loop (); + +private: + CLImageProcessor *_processor; +}; + +bool CLHandlerThread::loop () +{ + XCAM_ASSERT (_processor); + XCamReturn ret = _processor->process_cl_buffer_queue (); + if (ret != XCAM_RETURN_NO_ERROR && ret != XCAM_RETURN_BYPASS) + return false; + return true; +} + +CLImageProcessor::CLImageProcessor (const char* name) + : ImageProcessor (name ? name : "CLImageProcessor") + , _seq_num (0) +{ + _context = CLDevice::instance ()->get_context (); + XCAM_ASSERT (_context.ptr()); + + _handler_thread = new CLHandlerThread (this); + XCAM_ASSERT (_handler_thread.ptr ()); + + XCAM_LOG_DEBUG ("CLImageProcessor constructed"); + XCAM_OBJ_PROFILING_INIT; +} + +CLImageProcessor::~CLImageProcessor () +{ + XCAM_LOG_DEBUG ("CLImageProcessor destructed"); +} + +bool +CLImageProcessor::add_handler (SmartPtr &handler) +{ + XCAM_ASSERT (handler.ptr ()); + _handlers.push_back (handler); + return true; +} + +SmartPtr +CLImageProcessor::get_cl_context () +{ + return _context; +} + +bool +CLImageProcessor::can_process_result (SmartPtr &result) +{ + XCAM_UNUSED (result); + return false; +} + +XCamReturn +CLImageProcessor::apply_3a_results (X3aResultList &results) +{ + XCAM_UNUSED (results); + return XCAM_RETURN_NO_ERROR; +} + +XCamReturn +CLImageProcessor::apply_3a_result (SmartPtr &result) +{ + XCAM_UNUSED (result); + return XCAM_RETURN_NO_ERROR; +} + +XCamReturn +CLImageProcessor::process_buffer (SmartPtr &input, SmartPtr &output) +{ + SmartPtr drm_bo_in; + XCamReturn ret = XCAM_RETURN_NO_ERROR; + SmartPtr display = DrmDisplay::instance (); + + drm_bo_in = display->convert_to_drm_bo_buf (display, input); + XCAM_FAIL_RETURN ( + WARNING, + drm_bo_in.ptr (), + XCAM_RETURN_ERROR_MEM, + "CL image processor can't handle this buffer, maybe type error"); + + while (!_done_buffer_queue.is_empty ()) { + SmartPtr done_buf = _done_buffer_queue.pop (50000); //50ms + if (!done_buf.ptr ()) + break; + //notify buffer done + notify_process_buffer_done (done_buf); + } + output = NULL; // consider call back? + + STREAM_LOCK; + + if (_handlers.empty()) { + ret = create_handlers (); + } + + XCAM_FAIL_RETURN ( + WARNING, + !_handlers.empty () && ret == XCAM_RETURN_NO_ERROR, + XCAM_RETURN_ERROR_CL, + "CL image processor create handlers failed"); + + SmartPtr p_buf = new PriorityBuffer; + p_buf->set_seq_num (_seq_num++); + p_buf->data = drm_bo_in; + p_buf->handler = *(_handlers.begin ()); + + XCAM_FAIL_RETURN ( + WARNING, + _process_buffer_queue.push_priority_buf (p_buf), + XCAM_RETURN_ERROR_UNKNOWN, + "CLImageProcessor push priority buffer failed"); + + return XCAM_RETURN_BYPASS; +} + +XCamReturn +CLImageProcessor::process_cl_buffer_queue () +{ + XCamReturn ret = XCAM_RETURN_NO_ERROR; + SmartPtr p_buf = _process_buffer_queue.pop (-1); + if (!p_buf.ptr ()) { + XCAM_LOG_DEBUG ("cl buffer queue stopped"); + return XCAM_RETURN_ERROR_MEM; + } + + SmartPtr data = p_buf->data; + SmartPtr handler = p_buf->handler; + SmartPtr out_data; + + XCAM_ASSERT (data.ptr () && handler.ptr ()); + + XCAM_LOG_DEBUG ("buf:%d, rank:%d\n", p_buf->seq_num, p_buf->rank); + + { + STREAM_LOCK; + ret = handler->execute (data, out_data); + XCAM_FAIL_RETURN ( + WARNING, + ret == XCAM_RETURN_NO_ERROR, + ret, + "CLImageProcessor execute image handler failed"); + XCAM_ASSERT (out_data.ptr ()); + + // for loop in handler, find next handler + ImageHandlerList::iterator i_handler = _handlers.begin (); + for (; i_handler != _handlers.end (); ++i_handler) + { + if (handler.ptr () == (*i_handler).ptr ()) { + ++i_handler; + if (i_handler != _handlers.end ()) + p_buf->handler = *i_handler; + else + p_buf->handler = NULL; + break; + } + } + } + + // buffer processed by all handlers, done + if (!p_buf->handler.ptr ()) { + if (out_data.ptr ()) + out_data->clear_attached_buffers (); + + XCAM_OBJ_PROFILING_START; + CLDevice::instance()->get_context ()->finish (); + XCAM_OBJ_PROFILING_END (get_name (), 30); + + // buffer done, push back + _done_buffer_queue.push (out_data); + return XCAM_RETURN_NO_ERROR; + } + + p_buf->data = out_data; + p_buf->down_rank (); + + XCAM_FAIL_RETURN ( + WARNING, + _process_buffer_queue.push_priority_buf (p_buf), + XCAM_RETURN_ERROR_UNKNOWN, + "CLImageProcessor push priority buffer failed"); + + return ret; +} + +XCamReturn +CLImageProcessor::emit_start () +{ + _done_buffer_queue.resume_pop (); + _process_buffer_queue.resume_pop (); + + if (!_handler_thread->start ()) + return XCAM_RETURN_ERROR_THREAD; + + return XCAM_RETURN_NO_ERROR; +} + +void +CLImageProcessor::emit_stop () +{ + _process_buffer_queue.pause_pop(); + _done_buffer_queue.pause_pop (); + + + for (ImageHandlerList::iterator i_handler = _handlers.begin (); + i_handler != _handlers.end (); ++i_handler) { + (*i_handler)->emit_stop (); + } + + _handler_thread->stop (); + _process_buffer_queue.clear (); + _done_buffer_queue.clear (); +} + +XCamReturn +CLImageProcessor::create_handlers () +{ + SmartPtr demo_handler; + demo_handler = create_cl_demo_image_handler (_context); + XCAM_FAIL_RETURN ( + WARNING, + demo_handler.ptr (), + XCAM_RETURN_ERROR_CL, + "CLImageProcessor create demo handler failed"); + add_handler (demo_handler); + + return XCAM_RETURN_NO_ERROR; +} + +}; diff --git a/pool/shard011/C++/0122249_play_to_termination.cpp b/pool/shard011/C++/0122249_play_to_termination.cpp new file mode 100644 index 0000000000000000000000000000000000000000..638848c30ee80b5c854bc68c35671c0d24d9f02f --- /dev/null +++ b/pool/shard011/C++/0122249_play_to_termination.cpp @@ -0,0 +1,86 @@ +/*************************************************************************** + * Example of the HSFC in action. Simply pick the first joint move and + * play to termination. + ****************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +typedef boost::error_info errinfo; +struct someerror: virtual boost::exception, virtual std::exception { }; + +/*************************************************************************** + * Run the game to termination + **************************************************************************/ + +void run(const std::string& gdlfilename, bool verbose=false) +{ + HSFC::Game game(boost::filesystem::path(gdlfilename.c_str())); + if (verbose) std::cout << "Loaded: " << gdlfilename << std::endl; + HSFC::State state(game); + while (!state.isTerminal()) + { + std::vector jms = state.joints(); + if (jms.empty()) + BOOST_THROW_EXCEPTION(someerror() << errinfo("No joint moves in non-terminal state")); + HSFC::JointMove firstmove = jms[0]; + if (verbose) std::cout << "Playing: " << firstmove << std::endl; + state.play(firstmove); + } + HSFC::JointGoal result = state.goals(); + if (verbose) std::cout << "Result: " << result << std::endl; +} + +/*************************************************************************** + * Main + **************************************************************************/ + +int main(int argc, char* argv[]) +{ + try + { + if (argc < 2 || argc > 3) + { + std::cout << "usage: [--verbose]" << std::endl; + exit(0); + } + std::string gdlfilename(argv[1]); + if (argc == 2) run(gdlfilename); + else run(gdlfilename, true); + return 0; + } + catch(someerror& e) + { + if( std::string const * mi=boost::get_error_info(e) ) + std::cerr << "Error: " << *mi << std::endl; + return 1; + } + catch(HSFC::HSFCException& e) + { + if( std::string const * mi=boost::get_error_info(e) ) + std::cerr << "Error: " << *mi << std::endl; + return 1; + } + catch(boost::exception& e) + { + + return 1; + } + catch(std::exception& e) + { + std::cerr << "std::exception: " << e.what() << std::endl; + return 1; + } + catch(...) + { + std::cerr << "Unknown error" << std::endl; + return 2; + } +} diff --git a/pool/shard011/C++/0122250_lmdbxx_main.cpp b/pool/shard011/C++/0122250_lmdbxx_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc605db20fe1ad39fa1f88c8251c5eed0553aee8 --- /dev/null +++ b/pool/shard011/C++/0122250_lmdbxx_main.cpp @@ -0,0 +1,56 @@ +//#include "stdafx.h" +#if __cplusplus >= 201103L +#include "lmdb++.h" +#endif +#include + + +namespace { +namespace local { + +// REF [file] >> ${LMDBXX_HOME}/example.cc +void example() +{ +#if __cplusplus >= 201103L + // Create and open the LMDB environment. + auto env = lmdb::env::create(); + env.open("./data/database/example.mdb", 0, 0664); + + // Insert some key/value pairs in a write transaction. + auto wtxn = lmdb::txn::begin(env); + auto dbi = lmdb::dbi::open(wtxn, nullptr); + dbi.put(wtxn, "username", "jhacker"); + dbi.put(wtxn, "email", "jhacker@example.org"); + dbi.put(wtxn, "fullname", "J. Random Hacker"); + wtxn.commit(); + + // Fetch key/value pairs in a read-only transaction. + auto rtxn = lmdb::txn::begin(env, nullptr, MDB_RDONLY); + auto cursor = lmdb::cursor::open(rtxn, dbi); + std::string key, value; + while (cursor.get(key, value, MDB_NEXT)) + { + std::printf("key: '%s', value: '%s'\n", key.c_str(), value.c_str()); + } + cursor.close(); + rtxn.abort(); + + // The enviroment is closed automatically. +#else + std::cerr << "A C++11 compiler (CXXFLAGS='-std=c++11') is required" << std::endl; +#endif +} + +} // namespace local +} // unnamed namespace + +namespace my_lmdbxx { + +} // namespace my_lmdbxx + +int lmdbxx_main(int argc, char *argv[]) +{ + local::example(); + + return 0; +} diff --git a/pool/shard011/C++/0122251_QProgressIndicator.cpp b/pool/shard011/C++/0122251_QProgressIndicator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ac67e871a97310185c52878e0ab830bffa1b624a --- /dev/null +++ b/pool/shard011/C++/0122251_QProgressIndicator.cpp @@ -0,0 +1,194 @@ +/* +* +* This file is part of QProgressIndicator, +* an open-source recent files menu widget +* +* Copyright (C) 2009 - 2010 Morgan Leborgne +* +* This program is free software: you can redistribute it and/or modify +* it under the terms of the GNU Lesser General Public License as published by +* the Free Software Foundation, either version 3 of the License, or +* (at your option) any later version. +* +* This program is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU Lesser General Public License for more details. +* +* You should have received a copy of the GNU Lesser General Public License +* along with QProgressIndicator. If not, see . +* +*/ +#include "QProgressIndicator.h" + +#include + +QProgressIndicator::QProgressIndicator(QWidget* parent) + : QWidget(parent), + m_angle(0), + m_timer_identifier(-1), + m_delay(40), + m_always_visible(false), + m_color(Qt::black) +{ + // Set the default size and focus policies. + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFocusPolicy(Qt::NoFocus); +} + +int QProgressIndicator::animationDelay() const +{ + // Return the delay (milliseconds). + return m_delay; +} + +bool QProgressIndicator::isAnimated() const +{ + // Return if the timer is currently active. + return (m_timer_identifier != -1); +} + +bool QProgressIndicator::isDisplayedWhenStopped() const +{ + // Return whether the progress indicator is displayed when stopped. + return m_always_visible; +} + +const QColor & QProgressIndicator::color() const +{ + // Return the color. + return m_color; +} + +QSize QProgressIndicator::sizeHint() const +{ + // Return the recommended size. + return QSize(20, 20); +} + +int QProgressIndicator::heightForWidth(int width) const +{ + // Return the width (as the progress indicator is looks best as a square). + return width; +} + +void QProgressIndicator::startAnimation() +{ + // Check that the timer hasn't already started. + if(m_timer_identifier == -1) + { + // Start the timer with the delay. + m_timer_identifier = QWidget::startTimer(m_delay); + } +} + +void QProgressIndicator::stopAnimation() +{ + // Check if the timer is running. + if(m_timer_identifier != -1) + { + // Kill the timer. + QWidget::killTimer(m_timer_identifier); + + // Reset the timer identifier. + m_timer_identifier = -1; + + // Schedule a repaint. + QWidget::update(); + } +} + +void QProgressIndicator::setAnimationDelay(const int& delay) +{ + // Check if the timer is running. + if(m_timer_identifier != -1) + { + // Kill the timer. + QWidget::killTimer(m_timer_identifier); + } + + // Set the new delay setting. + m_delay = delay; + + // Was the timer previously running. + if(m_timer_identifier != -1) + { + // Restart the timer with the new delay setting. + m_timer_identifier = QWidget::startTimer(m_delay); + } +} + +void QProgressIndicator::setDisplayedWhenStopped(const bool& state) +{ + // Set the new state. + m_always_visible = state; + + // Schedule a repaint. + QWidget::update(); +} + +void QProgressIndicator::setColor(const QColor& color) +{ + // Set the new color. + m_color = color; + + // Schedule a repaint. + QWidget::update(); +} + +void QProgressIndicator::timerEvent(QTimerEvent* /*event*/) +{ + // Update the current rotation angle. + m_angle = (m_angle + 30) % 360; + + // Schedule a repaint. + QWidget::update(); +} + +void QProgressIndicator::paintEvent(QPaintEvent* /*event*/) +{ + // Check if we should alawys display, or we are currently animating. + if(m_always_visible || isAnimated()) + { + // Create a painter for this QWidget. + QPainter painter(this); + + // Ensure antialiasing is enabled. + painter.setRenderHint(QPainter::Antialiasing, true); + + // Calculate the smallest dimension of the QWidget. + const int width = qMin(this->width(), this->height()); + + // Calculate the inner and outer radius'. + const int radius_outer = (width - 1.0) * 0.5; + const int radius_inner = (width - 1.0) * 0.5 * 0.38; + + // Calculate the capsule dimensions. + const int capsule_height = radius_outer - radius_inner; + const int capsule_width = (width > 32 ) ? capsule_height * 0.23 : capsule_height * 0.35; + const int capsule_radius = capsule_width / 2.0; + + // Loop and create the progress capsule indicators. + for(int i = 0; i < 12; ++i) + { + // Set the painter's brush color. + QColor color = m_color; + color.setAlphaF(1.0f - (i/12.0f)); + painter.setPen(Qt::NoPen); + painter.setBrush(color); + + // Save the current painter's state. + painter.save(); + + // Translate and rotate the painter as required. + painter.translate(rect().center()); + painter.rotate(m_angle - i * 30.0f); + + // Draw the progress capsule indicator. + painter.drawRoundedRect(-capsule_width * 0.5, -(radius_inner + capsule_height), capsule_width, capsule_height, capsule_radius, capsule_radius); + + // Restore the painter's previous state. + painter.restore(); + } + } +} diff --git a/pool/shard011/C++/0122252_external_popup_menu_browsertest.cc b/pool/shard011/C++/0122252_external_popup_menu_browsertest.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5e16432dc05fa1d4e07ed8149f70a70c09d859b --- /dev/null +++ b/pool/shard011/C++/0122252_external_popup_menu_browsertest.cc @@ -0,0 +1,208 @@ +// 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 + +#include "base/macros.h" +#include "base/strings/utf_string_conversions.h" +#include "content/common/frame_messages.h" +#include "content/public/test/render_view_test.h" +#include "content/renderer/render_frame_impl.h" +#include "content/renderer/render_view_impl.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/platform/WebSize.h" +#include "third_party/WebKit/public/web/WebView.h" + +// Tests for the external select popup menu (Mac specific). + +namespace content { +namespace { + +const char* const kSelectID = "mySelect"; +const char* const kEmptySelectID = "myEmptySelect"; + +} // namespace + +class ExternalPopupMenuTest : public RenderViewTest { + public: + ExternalPopupMenuTest() {} + + RenderViewImpl* view() { + return static_cast(view_); + } + + RenderFrameImpl* frame() { + return view()->GetMainRenderFrame(); + } + + void SetUp() override { + RenderViewTest::SetUp(); + // We need to set this explictly as RenderMain is not run. + blink::WebView::setUseExternalPopupMenus(true); + + std::string html = "" + ""; + if (ShouldRemoveSelectOnChange()) { + html += ""; + } + + // Load the test page. + LoadHTML(html.c_str()); + + // Set a minimum size and give focus so simulated events work. + view()->GetWidget()->GetWebWidget()->resize(blink::WebSize(500, 500)); + view()->GetWidget()->GetWebWidget()->setFocus(true); + } + + int GetSelectedIndex() { + base::string16 script(base::ASCIIToUTF16(kSelectID)); + script.append(base::ASCIIToUTF16(".selectedIndex")); + int selected_index = -1; + ExecuteJavaScriptAndReturnIntValue(script, &selected_index); + return selected_index; + } + + protected: + virtual bool ShouldRemoveSelectOnChange() const { return false; } + + DISALLOW_COPY_AND_ASSIGN(ExternalPopupMenuTest); +}; + +// Normal case: test showing a select popup, canceling/selecting an item. +TEST_F(ExternalPopupMenuTest, NormalCase) { + IPC::TestSink& sink = render_thread_->sink(); + + // Click the text field once. + EXPECT_TRUE(SimulateElementClick(kSelectID)); + + // We should have sent a message to the browser to show the popup menu. + const IPC::Message* message = + sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); + ASSERT_TRUE(message != NULL); + std::tuple param; + FrameHostMsg_ShowPopup::Read(message, ¶m); + ASSERT_EQ(3U, std::get<0>(param).popup_items.size()); + EXPECT_EQ(1, std::get<0>(param).selected_item); + + // Simulate the user canceling the popup; the index should not have changed. + frame()->OnSelectPopupMenuItem(-1); + EXPECT_EQ(1, GetSelectedIndex()); + + // Show the pop-up again and this time make a selection. + EXPECT_TRUE(SimulateElementClick(kSelectID)); + frame()->OnSelectPopupMenuItem(0); + EXPECT_EQ(0, GetSelectedIndex()); + + // Show the pop-up again and make another selection. + sink.ClearMessages(); + EXPECT_TRUE(SimulateElementClick(kSelectID)); + message = sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); + ASSERT_TRUE(message != NULL); + FrameHostMsg_ShowPopup::Read(message, ¶m); + ASSERT_EQ(3U, std::get<0>(param).popup_items.size()); + EXPECT_EQ(0, std::get<0>(param).selected_item); +} + +// Page shows popup, then navigates away while popup showing, then select. +TEST_F(ExternalPopupMenuTest, ShowPopupThenNavigate) { + // Click the text field once. + EXPECT_TRUE(SimulateElementClick(kSelectID)); + + // Now we navigate to another pager. + LoadHTML("Awesome page!"); + + // Now the user selects something, we should not crash. + frame()->OnSelectPopupMenuItem(-1); +} + +// An empty select should not cause a crash when clicked. +// http://crbug.com/63774 +TEST_F(ExternalPopupMenuTest, EmptySelect) { + EXPECT_TRUE(SimulateElementClick(kEmptySelectID)); +} + +class ExternalPopupMenuRemoveTest : public ExternalPopupMenuTest { + public: + ExternalPopupMenuRemoveTest() {} + + protected: + bool ShouldRemoveSelectOnChange() const override { return true; } +}; + +// Tests that nothing bad happen when the page removes the select when it +// changes. (http://crbug.com/61997) +TEST_F(ExternalPopupMenuRemoveTest, RemoveOnChange) { + // Click the text field once to show the popup. + EXPECT_TRUE(SimulateElementClick(kSelectID)); + + // Select something, it causes the select to be removed from the page. + frame()->OnSelectPopupMenuItem(0); + + // Just to check the soundness of the test, call SimulateElementClick again. + // It should return false as the select has been removed. + EXPECT_FALSE(SimulateElementClick(kSelectID)); +} + +class ExternalPopupMenuDisplayNoneTest : public ExternalPopupMenuTest { + public: + ExternalPopupMenuDisplayNoneTest() {} + + void SetUp() override { + RenderViewTest::SetUp(); + // We need to set this explictly as RenderMain is not run. + blink::WebView::setUseExternalPopupMenus(true); + + std::string html = ""; + // Load the test page. + LoadHTML(html.c_str()); + + // Set a minimum size and give focus so simulated events work. + view()->GetWidget()->GetWebWidget()->resize(blink::WebSize(500, 500)); + view()->GetWidget()->GetWebWidget()->setFocus(true); + } + +}; + +TEST_F(ExternalPopupMenuDisplayNoneTest, SelectItem) { + IPC::TestSink& sink = render_thread_->sink(); + + // Click the text field once to show the popup. + EXPECT_TRUE(SimulateElementClick(kSelectID)); + + // Read the message sent to browser to show the popup menu. + const IPC::Message* message = + sink.GetUniqueMessageMatching(FrameHostMsg_ShowPopup::ID); + ASSERT_TRUE(message != NULL); + std::tuple param; + FrameHostMsg_ShowPopup::Read(message, ¶m); + // Number of items should match item count minus the number + // of "display: none" items. + ASSERT_EQ(5U, std::get<0>(param).popup_items.size()); + + // Select index 1 item. This should select item with index 2, + // skipping the item with 'display: none' + frame()->OnSelectPopupMenuItem(1); + + EXPECT_EQ(2, GetSelectedIndex()); +} + +} // namespace content diff --git a/pool/shard011/C++/0122254_nieg.cpp b/pool/shard011/C++/0122254_nieg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0ee30f3705192145df27e419061631f8acb58173 --- /dev/null +++ b/pool/shard011/C++/0122254_nieg.cpp @@ -0,0 +1,38 @@ +#include "nieg.hpp" + +namespace wat +{ + void nieg_init_directory(const std::string& basename) + { + if (basename == "") + { + LOGTIME("WARNING") << "wat-nieg: basename haven't be set!"; + LOGTIME("WARNING") << "wat-nieg: record and continue will be disabled!"; + return; + } + struct stat fs; + int status = stat(basename.c_str(), &fs); + if (status != 0) + { + if (errno == ENOENT) + { + status = mkdir(basename.c_str(), 0755); + if (status != 0) + { + LOGTIME("ERROR") << "wat-nieg: Create directory " << basename << " failed"; + throw std::runtime_error(strerror(errno)); + } + } + else + { + LOGTIME("ERROR") << "wat-nieg: Get status of " << basename << " failed"; + throw std::runtime_error(strerror(errno)); + } + } + else if (!S_IFDIR & fs.st_mode) + { + LOGTIME("ERROR") << "wat-nieg: " << basename << " is not a directory!"; + throw std::invalid_argument(basename); + } + } +} diff --git a/pool/shard011/C++/0122255_websocket.cpp b/pool/shard011/C++/0122255_websocket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e6095b272a15c94056c589c894db30aff6c886b4 --- /dev/null +++ b/pool/shard011/C++/0122255_websocket.cpp @@ -0,0 +1,60 @@ +#include "../mock_context.hpp" +#include "../parse_rule.hpp" + +#include "core/filter_rule_base.hpp" +#include "core/string_range.hpp" +#include "core/uri.hpp" +#include "rule/filter_rule.hpp" + +#include + +namespace adblock { + +using NormalContext = MockContext; + +struct WebSocketContext : MockContext +{ + bool isWebSocket() const override { return true; } +}; + +TEST(Option_WebSocket, Elementary) +{ + FilterRuleBase rb; + + auto const rule1 = parse_rule("adblock$websocket"_r); + ASSERT_TRUE(rule1); + + rb.put(*rule1); + + { // request via normal channel + auto const& rv = rb.query("http://www.adblock.org"_u, NormalContext()); + EXPECT_FALSE(rv.first); + } + + { // request via WebSocket + auto const& rv = rb.query("http://www.adblock.org"_u, WebSocketContext()); + EXPECT_TRUE(rv.first); + } +} + +TEST(Option_WebSocket, Invert) +{ + FilterRuleBase rb; + + auto const rule1 = parse_rule("adblock$~websocket"_r); + ASSERT_TRUE(rule1); + + rb.put(*rule1); + + { // request via normal channel + auto const& rv = rb.query("http://www.adblock.org"_u, NormalContext()); + EXPECT_TRUE(rv.first); + } + + { // request via WebSocket + auto const& rv = rb.query("http://www.adblock.org"_u, WebSocketContext()); + EXPECT_FALSE(rv.first); + } +} + +} // namespace adblock diff --git a/pool/shard011/C++/0122256_FollowLocationJob.cpp b/pool/shard011/C++/0122256_FollowLocationJob.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cdadbac2546a77e8a4f0b93e20a33b3d1d0642e --- /dev/null +++ b/pool/shard011/C++/0122256_FollowLocationJob.cpp @@ -0,0 +1,108 @@ +/* This file is part of RTags (https://github.com/Andersbakken/rtags). + + RTags 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. + + RTags 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 RTags. If not, see . */ + +#include "FollowLocationJob.h" + +#include "Project.h" +#include "rct/SignalSlot.h" +#include "RTags.h" +#include "Server.h" + +FollowLocationJob::FollowLocationJob(Location loc, + const std::shared_ptr &query, + const std::shared_ptr &project) + : QueryJob(query, project), location(loc) +{ +} + +int FollowLocationJob::execute() +{ + int idx = 0; + Symbol symbol = project()->findSymbol(location, &idx); + if (symbol.isNull()) { + return 1; + } + + // if you invoke a destructor explicitly there's a typeref on the class + // name. This finds the destructor instead. + if ((symbol.kind == CXCursor_TypeRef || symbol.kind == CXCursor_TemplateRef) && idx > 0) { + auto symbols = project()->openSymbols(location.fileId()); + if (!symbols || !symbols->count()) + return 1; + const Symbol prev = symbols->valueAt(idx - 1); + if (prev.kind == CXCursor_MemberRefExpr + && prev.location.column() == symbol.location.column() - 1 + && prev.location.line() == symbol.location.line() + && prev.symbolName.contains("~")) { + symbol = prev; + } + } + + if (queryFlags() & QueryMessage::TargetUsrs) { + const Set usrs = project()->findTargetUsrs(location); + for (const String &usr : usrs) { + write(usr); + } + return 0; + } + + auto targets = RTags::sortTargets(project()->findTargets(symbol)); + + int rank = -1; + Set seen; + auto writeTarget = [&rank, this, &seen](const Symbol &target) { + if (seen.insert(target.location)) { + write(target.location); + rank = RTags::targetRank(target.kind); + } + }; + for (const auto &target : targets) { + if (target.location.isNull()) + continue; + + if (symbol.usr == target.usr) { + writeTarget(target); + if (queryFlags() & QueryMessage::AllTargets) + continue; + break; + } + + if (queryFlags() & QueryMessage::DeclarationOnly ? target.isDefinition() : !target.isDefinition()) { + const auto others = RTags::sortTargets(project()->findTargets(target)); + bool found = false; + for (auto other : others) { + if (!other.isNull() && other.usr == target.usr) { + found = true; + writeTarget(other); + if (!(queryFlags() & QueryMessage::AllTargets)) { + break; + } + } + } + + if (found) { + if (queryFlags() & QueryMessage::AllTargets) { + continue; + } else { + break; + } + } + } + writeTarget(target); + if (!(queryFlags() & QueryMessage::AllTargets)) + break; + } + return 0; +} diff --git a/pool/shard011/C++/0122258_import_dialog_gtk.cc b/pool/shard011/C++/0122258_import_dialog_gtk.cc new file mode 100644 index 0000000000000000000000000000000000000000..443d4538587a951bf0ec5298ab0f671019363810 --- /dev/null +++ b/pool/shard011/C++/0122258_import_dialog_gtk.cc @@ -0,0 +1,146 @@ +// Copyright (c) 2009 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/gtk/import_dialog_gtk.h" + +#include "app/l10n_util.h" +#include "app/resource_bundle.h" +#include "chrome/common/gtk_util.h" +#include "grit/generated_resources.h" +#include "grit/locale_settings.h" + +// static +void ImportDialogGtk::Show(GtkWindow* parent, Profile* profile) { + new ImportDialogGtk(parent, profile); +} + +//////////////////////////////////////////////////////////////////////////////// +// ImportObserver implementation: +void ImportDialogGtk::ImportCanceled() { + ImportComplete(); +} + +void ImportDialogGtk::ImportComplete() { + gtk_widget_destroy(dialog_); + delete this; +} + +ImportDialogGtk::ImportDialogGtk(GtkWindow* parent, Profile* profile) + : parent_(parent), profile_(profile), importer_host_(new ImporterHost()) { + // Build the dialog. + dialog_ = gtk_dialog_new_with_buttons( + l10n_util::GetStringUTF8(IDS_IMPORT_SETTINGS_TITLE).c_str(), + parent, + (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR), + GTK_STOCK_CANCEL, + GTK_RESPONSE_REJECT, + NULL); + gtk_widget_realize(dialog_); + gtk_util::SetWindowWidthFromResources(GTK_WINDOW(dialog_), + IDS_IMPORT_DIALOG_WIDTH_CHARS, + /* resizable */ false); + importer_host_->set_parent_window(GTK_WINDOW(dialog_)); + + // Add import button separately as we might need to disable it, if + // no supported browsers found. + GtkWidget* import_button = gtk_util::AddButtonToDialog(dialog_, + l10n_util::GetStringUTF8(IDS_IMPORT_COMMIT).c_str(), + GTK_STOCK_APPLY, GTK_RESPONSE_ACCEPT); + GTK_WIDGET_SET_FLAGS(import_button, GTK_CAN_DEFAULT); + gtk_dialog_set_default_response(GTK_DIALOG(dialog_), GTK_RESPONSE_ACCEPT); + + GtkWidget* content_area = GTK_DIALOG(dialog_)->vbox; + gtk_box_set_spacing(GTK_BOX(content_area), gtk_util::kContentAreaSpacing); + + GtkWidget* combo_hbox = gtk_hbox_new(FALSE, gtk_util::kLabelSpacing); + GtkWidget* from = gtk_label_new( + l10n_util::GetStringUTF8(IDS_IMPORT_FROM_LABEL).c_str()); + gtk_box_pack_start(GTK_BOX(combo_hbox), from, FALSE, FALSE, 0); + + combo_ = gtk_combo_box_new_text(); + gtk_box_pack_start(GTK_BOX(combo_hbox), combo_, TRUE, TRUE, 0); + + gtk_box_pack_start(GTK_BOX(content_area), combo_hbox, FALSE, FALSE, 0); + + GtkWidget* vbox = gtk_vbox_new(FALSE, gtk_util::kControlSpacing); + + GtkWidget* description = gtk_label_new( + l10n_util::GetStringUTF8(IDS_IMPORT_ITEMS_LABEL).c_str()); + gtk_misc_set_alignment(GTK_MISC(description), 0, 0); + gtk_box_pack_start(GTK_BOX(vbox), description, FALSE, FALSE, 0); + + bookmarks_ = gtk_check_button_new_with_label( + l10n_util::GetStringUTF8(IDS_IMPORT_FAVORITES_CHKBOX).c_str()); + gtk_box_pack_start(GTK_BOX(vbox), bookmarks_, FALSE, FALSE, 0); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(bookmarks_), TRUE); + + search_engines_ = gtk_check_button_new_with_label( + l10n_util::GetStringUTF8(IDS_IMPORT_SEARCH_ENGINES_CHKBOX).c_str()); + gtk_box_pack_start(GTK_BOX(vbox), search_engines_, FALSE, FALSE, 0); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(search_engines_), TRUE); + + passwords_ = gtk_check_button_new_with_label( + l10n_util::GetStringUTF8(IDS_IMPORT_PASSWORDS_CHKBOX).c_str()); + gtk_box_pack_start(GTK_BOX(vbox), passwords_, FALSE, FALSE, 0); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(passwords_), TRUE); + + history_ = gtk_check_button_new_with_label( + l10n_util::GetStringUTF8(IDS_IMPORT_HISTORY_CHKBOX).c_str()); + gtk_box_pack_start(GTK_BOX(vbox), history_, FALSE, FALSE, 0); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(history_), TRUE); + + gtk_box_pack_start(GTK_BOX(content_area), vbox, FALSE, FALSE, 0); + + // Detect any supported browsers that we can import from and fill + // up the combo box. If none found, disable all controls except cancel. + int profiles_count = importer_host_->GetAvailableProfileCount(); + if (profiles_count > 0) { + for (int i = 0; i < profiles_count; i++) { + std::wstring profile = importer_host_->GetSourceProfileNameAt(i); + gtk_combo_box_append_text(GTK_COMBO_BOX(combo_), + WideToUTF8(profile).c_str()); + } + gtk_widget_grab_focus(import_button); + } else { + gtk_combo_box_append_text(GTK_COMBO_BOX(combo_), + l10n_util::GetStringUTF8(IDS_IMPORT_NO_PROFILE_FOUND).c_str()); + gtk_widget_set_sensitive(bookmarks_, FALSE); + gtk_widget_set_sensitive(search_engines_, FALSE); + gtk_widget_set_sensitive(passwords_, FALSE); + gtk_widget_set_sensitive(history_, FALSE); + gtk_widget_set_sensitive(import_button, FALSE); + } + gtk_combo_box_set_active(GTK_COMBO_BOX(combo_), 0); + + g_signal_connect(dialog_, "response", + G_CALLBACK(HandleOnResponseDialog), this); + gtk_widget_show_all(dialog_); +} + +void ImportDialogGtk::OnDialogResponse(GtkWidget* widget, int response) { + gtk_widget_hide_all(dialog_); + if (response == GTK_RESPONSE_ACCEPT) { + uint16 items = NONE; + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(bookmarks_))) + items |= FAVORITES; + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(search_engines_))) + items |= SEARCH_ENGINES; + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(passwords_))) + items |= PASSWORDS; + if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(history_))) + items |= HISTORY; + + if (items == 0) { + ImportComplete(); + } else { + const ProfileInfo& source_profile = + importer_host_->GetSourceProfileInfoAt( + gtk_combo_box_get_active(GTK_COMBO_BOX(combo_))); + StartImportingWithUI(parent_, items, importer_host_.get(), + source_profile, profile_, this, false); + } + } else { + ImportCanceled(); + } +} diff --git a/pool/shard011/C++/0122260_JsonMessage.cpp b/pool/shard011/C++/0122260_JsonMessage.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b4c134278dcef74afd9ec43227fce59ad73d7d8d --- /dev/null +++ b/pool/shard011/C++/0122260_JsonMessage.cpp @@ -0,0 +1,85 @@ +#include "JsonMessage.h" + +using namespace esnlib; + +JsonMessage::JsonMessage(int msgtype) +{ + m_jsonobj = NULL; + m_jsonstr = ""; + m_type = msgtype; +} + +JsonMessage::JsonMessage(int msgtype, const json::Object * obj) +{ + m_jsonobj = (json::Object *) obj; + m_jsonstr = ""; + m_type = msgtype; +} + +JsonMessage::JsonMessage(int msgtype, const std::string& str) +{ + m_jsonobj = NULL; + m_jsonstr = str; + m_type = msgtype; +} + +JsonMessage::JsonMessage(int msgtype, const json::Object * obj, const std::string& str) +{ + m_jsonobj = (json::Object *) obj; + m_jsonstr = str; + m_type = msgtype; +} + +json::Object * JsonMessage::GetJsonObj() +{ + return m_jsonobj; +} + +void JsonMessage::SetJsonObj(json::Object * obj) +{ + m_jsonobj = obj; +} + +const char * JsonMessage::GetJsonStr() const +{ + return m_jsonstr.c_str(); +} + +const std::string& JsonMessage::GetJsonStr() +{ + return m_jsonstr; +} + +void JsonMessage::SetJsonStr(const std::string& str) +{ + m_jsonstr = str; +} + +int JsonMessage::GetMessageType() +{ + return m_type; +} + +int JsonMessage::GetMessageTypeFromBuffer(IoBuffer* data) +{ + data->SetReadPos(JsonMessage::SIGN_SIZE); + return data->GetInt(); +} + +int JsonMessage::GetJsonStrLenFromBuffer(IoBuffer* data) +{ + data->SetReadPos(JsonMessage::LEN_POS); + return data->GetInt(); +} + +void JsonMessage::Send(Session * session, JsonMessage * jsonmsg) +{ + if(session && jsonmsg) session->Write((void*)jsonmsg); +} + +void JsonMessage::SendObject(Session * session, int msgtype, const json::Object & jsonobj) +{ + if(!session) return; + JsonMessage msg(msgtype, &jsonobj); + session->Write((void*)((&msg))); +} diff --git a/pool/shard011/C++/0122261_tokenize.cpp b/pool/shard011/C++/0122261_tokenize.cpp new file mode 100644 index 0000000000000000000000000000000000000000..759ce5f6b0f4da164d1005cc3c6b3497db5c54ab --- /dev/null +++ b/pool/shard011/C++/0122261_tokenize.cpp @@ -0,0 +1,29 @@ +#include "tokenize.hpp" + +using std::string; +using std::vector; + + +vector tokenize(const string& s, const string& delims) +{ + size_t offset = 0; + vector tokens; + + while (true) { + size_t i = s.find_first_not_of(delims, offset); + if (string::npos == i) { + offset = s.length(); + return tokens; + } + + size_t j = s.find_first_of(delims, i); + if (string::npos == j) { + tokens.push_back(s.substr(i)); + offset = s.length(); + continue; + } + + tokens.push_back(s.substr(i, j - i)); + offset = j; + } +} diff --git a/pool/shard011/C++/0122265_SynRigidTerrain.cpp b/pool/shard011/C++/0122265_SynRigidTerrain.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0f1b268a1da4664ec836f5413cae967de52d34f9 --- /dev/null +++ b/pool/shard011/C++/0122265_SynRigidTerrain.cpp @@ -0,0 +1,67 @@ +#include "chrono_synchrono/terrain/SynRigidTerrain.h" + +#include "chrono/assets/ChVisualization.h" + +#include "chrono_vehicle/ChVehicleModelData.h" + +using namespace chrono::vehicle; +using namespace rapidjson; + +namespace chrono { +namespace synchrono { + +SynRigidTerrain::SynRigidTerrain(ChSystem* system, const std::string& filename) { + auto d = SynTerrain::ParseTerrainFileJSON(filename); + + std::string subtype = d["Template"].GetString(); + assert(subtype.compare("RigidTerrain") == 0); + + std::string terrain_file; + if (d.HasMember("Input File")) + terrain_file = d["Input File"].GetString(); + else + terrain_file = filename; + + m_rigid_terrain = chrono_types::make_shared(system, vehicle::GetDataFile(terrain_file)); + + if (d.HasMember("Visualization")) + AddVisualizationAssetsJSON(d["Visualization"]); +} + +void SynRigidTerrain::AddVisualizationAssetsJSON(const Value& a) { + for (auto& patch : m_rigid_terrain->GetPatches()) { + if (a.HasMember("Texture")) { + std::string filename = a["Texture"]["Input File"].GetString(); + double sx = a["Texture"]["Scale"][0u].GetFloat(); + double sy = a["Texture"]["Scale"][1u].GetFloat(); + + patch->SetTexture(GetChronoDataFile(filename), sx, sy); + +#ifdef CHRONO_SENSOR + auto patch_asset = patch->GetGroundBody()->GetAssets()[0]; + if (auto visual_asset = std::dynamic_pointer_cast(patch_asset)) { + std::shared_ptr box_texture = chrono_types::make_shared(); + box_texture->SetKdTexture(GetChronoDataFile(filename)); + + if (a.HasMember("Fresnel")) { + box_texture->SetFresnelMin(a["Fresnel"]["Minimum"].GetFloat()); + box_texture->SetFresnelMax(a["Fresnel"]["Minimum"].GetFloat()); + } + + if (a.HasMember("Specular Color")) { + auto r = a["Specular Color"][0u].GetFloat(); + auto g = a["Specular Color"][1u].GetFloat(); + auto b = a["Specular Color"][2u].GetFloat(); + + box_texture->SetSpecularColor({r, b, g}); + } + + visual_asset->material_list.push_back(box_texture); + } +#endif + } + } +} + +} // namespace synchrono +} // namespace chrono diff --git a/pool/shard011/C++/0122267_jni-helper.cpp b/pool/shard011/C++/0122267_jni-helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6c56cb52e5c4225f2bb36be1e7e91b0c9ab58d94 --- /dev/null +++ b/pool/shard011/C++/0122267_jni-helper.cpp @@ -0,0 +1,153 @@ +#define LOG_TAG "JniHelper" + +#include "jni.h" +#include +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define LOGI(...) do { __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__); } while(0) +#define LOGW(...) do { __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__); } while(0) +#define LOGE(...) do { __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__); } while(0) +#define THROW(env, clazz, msg) do { env->ThrowNew(env->FindClass(clazz), msg); } while (0) + +static jclass ProcessImpl; +static jfieldID ProcessImpl_pid, ProcessImpl_exitValue, ProcessImpl_exitValueMutex; + +static int sdk_version() { + char version[PROP_VALUE_MAX + 1]; + __system_property_get("ro.build.version.sdk", version); + return atoi(version); +} + +extern "C" { +JNIEXPORT jint JNICALL Java_com_github_shadowsocks_JniHelper_sigkill(JNIEnv *env, jobject thiz, jint pid) { + // Suppress "No such process" errors. We just want the process killed. It's fine if it's already killed. + return kill(pid, SIGKILL) == -1 && errno != ESRCH ? errno : 0; +} + +JNIEXPORT jint JNICALL Java_com_github_shadowsocks_JniHelper_sigterm(JNIEnv *env, jobject thiz, jobject process) { + if (!env->IsInstanceOf(process, ProcessImpl)) { + THROW(env, "java/lang/ClassCastException", + "Unsupported process object. Only java.lang.ProcessManager$ProcessImpl is accepted."); + return -1; + } + jint pid = env->GetIntField(process, ProcessImpl_pid); + // Suppress "No such process" errors. We just want the process killed. It's fine if it's already killed. + return kill(pid, SIGTERM) == -1 && errno != ESRCH ? errno : 0; +} + +JNIEXPORT jobject JNICALL + Java_com_github_shadowsocks_JniHelper_getExitValue(JNIEnv *env, jobject thiz, jobject process) { + if (!env->IsInstanceOf(process, ProcessImpl)) { + THROW(env, "java/lang/ClassCastException", + "Unsupported process object. Only java.lang.ProcessManager$ProcessImpl is accepted."); + return NULL; + } + return env->GetObjectField(process, ProcessImpl_exitValue); +} + +JNIEXPORT jobject JNICALL + Java_com_github_shadowsocks_JniHelper_getExitValueMutex(JNIEnv *env, jobject thiz, jobject process) { + if (!env->IsInstanceOf(process, ProcessImpl)) { + THROW(env, "java/lang/ClassCastException", + "Unsupported process object. Only java.lang.ProcessManager$ProcessImpl is accepted."); + return NULL; + } + return env->GetObjectField(process, ProcessImpl_exitValueMutex); +} + +JNIEXPORT void JNICALL Java_com_github_shadowsocks_JniHelper_close(JNIEnv *env, jobject thiz, jint fd) { + close(fd); +} + +JNIEXPORT jint JNICALL + Java_com_github_shadowsocks_JniHelper_sendFd(JNIEnv *env, jobject thiz, jint tun_fd, jstring path) { + int fd; + struct sockaddr_un addr; + const char *sock_str = env->GetStringUTFChars(path, 0); + + if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { + LOGE("socket() failed: %s (socket fd = %d)\n", strerror(errno), fd); + return (jint)-1; + } + + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, sock_str, sizeof(addr.sun_path)-1); + + if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { + LOGE("connect() failed: %s (fd = %d)\n", strerror(errno), fd); + close(fd); + return (jint)-1; + } + + if (ancil_send_fd(fd, tun_fd)) { + LOGE("ancil_send_fd: %s", strerror(errno)); + close(fd); + return (jint)-1; + } + + close(fd); + env->ReleaseStringUTFChars(path, sock_str); + return 0; +} +} + +/* + * This is called by the VM when the shared library is first loaded. + */ + +typedef union { + JNIEnv* env; + void* venv; +} UnionJNIEnvToVoid; + +jint JNI_OnLoad(JavaVM* vm, void* reserved) { + UnionJNIEnvToVoid uenv; + uenv.venv = NULL; + jint result = -1; + JNIEnv* env = NULL; + + if (vm->GetEnv(&uenv.venv, JNI_VERSION_1_6) != JNI_OK) { + THROW(env, "java/lang/RuntimeException", "GetEnv failed"); + goto bail; + } + env = uenv.env; + + if (sdk_version() < 24) { + if (!(ProcessImpl = env->FindClass("java/lang/ProcessManager$ProcessImpl"))) { + THROW(env, "java/lang/RuntimeException", "ProcessManager$ProcessImpl not found"); + goto bail; + } + ProcessImpl = (jclass) env->NewGlobalRef((jobject) ProcessImpl); + if (!(ProcessImpl_pid = env->GetFieldID(ProcessImpl, "pid", "I"))) { + THROW(env, "java/lang/RuntimeException", "ProcessManager$ProcessImpl.pid not found"); + goto bail; + } + if (!(ProcessImpl_exitValue = env->GetFieldID(ProcessImpl, "exitValue", "Ljava/lang/Integer;"))) { + THROW(env, "java/lang/RuntimeException", "ProcessManager$ProcessImpl.exitValue not found"); + goto bail; + } + if (!(ProcessImpl_exitValueMutex = env->GetFieldID(ProcessImpl, "exitValueMutex", "Ljava/lang/Object;"))) { + THROW(env, "java/lang/RuntimeException", "ProcessManager$ProcessImpl.exitValueMutex not found"); + goto bail; + } + } + + result = JNI_VERSION_1_6; + +bail: + return result; +} diff --git a/pool/shard011/C++/0122268_cmd_duplicate_layer.cpp b/pool/shard011/C++/0122268_cmd_duplicate_layer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56344ca195695cd453a8099272dab020f7e27c53 --- /dev/null +++ b/pool/shard011/C++/0122268_cmd_duplicate_layer.cpp @@ -0,0 +1,73 @@ +// Aseprite +// Copyright (C) 2001-2015 David Capello +// +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License version 2 as +// published by the Free Software Foundation. + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "app/app.h" +#include "app/commands/command.h" +#include "app/console.h" +#include "app/context_access.h" +#include "app/document_api.h" +#include "app/document_undo.h" +#include "app/modules/editors.h" +#include "app/modules/gui.h" +#include "app/ui/editor/editor.h" +#include "app/transaction.h" +#include "doc/layer.h" +#include "doc/sprite.h" +#include "ui/ui.h" + +namespace app { + +class DuplicateLayerCommand : public Command { +public: + DuplicateLayerCommand(); + Command* clone() const override { return new DuplicateLayerCommand(*this); } + +protected: + bool onEnabled(Context* context); + void onExecute(Context* context); +}; + +DuplicateLayerCommand::DuplicateLayerCommand() + : Command("DuplicateLayer", + "Duplicate Layer", + CmdRecordableFlag) +{ +} + +bool DuplicateLayerCommand::onEnabled(Context* context) +{ + return context->checkFlags(ContextFlags::ActiveDocumentIsWritable | + ContextFlags::HasActiveLayer | + ContextFlags::ActiveLayerIsImage); +} + +void DuplicateLayerCommand::onExecute(Context* context) +{ + ContextWriter writer(context); + Document* document = writer.document(); + + { + Transaction transaction(writer.context(), "Layer Duplication"); + LayerImage* sourceLayer = static_cast(writer.layer()); + DocumentApi api = document->getApi(transaction); + api.duplicateLayerAfter(sourceLayer, sourceLayer); + transaction.commit(); + } + + update_screen_for_document(document); +} + +Command* CommandFactory::createDuplicateLayerCommand() +{ + return new DuplicateLayerCommand; +} + +} // namespace app diff --git a/pool/shard011/C++/0122269_HistoryID.cpp b/pool/shard011/C++/0122269_HistoryID.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5c2cfdf7b7aa402131292f117d83448ca6c17878 --- /dev/null +++ b/pool/shard011/C++/0122269_HistoryID.cpp @@ -0,0 +1,144 @@ +/* + * Open BEAGLE: A Generic Evolutionary Computation Framework in C++ + * Copyright (C) 2001-2010 by Christian Gagne and Marc Parizeau + * + * 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, version 3 of the License. + * + * 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 and GNU General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public + * License and GNU General Public License along with this library. + * If not, see . + * + * Contact: + * Christian Gagne + * Laboratoire de vision et systemes numeriques + * Departement de genie electrique et de genie informatique + * Universite Laval, Quebec (Quebec), Canada G1V 0A6 + * http://vision.gel.ulaval.ca/~cgagne + * christian.gagne@gel.ulaval.ca + * + */ + +/*! + * \file Beagle/Core/HistoryID.cpp + * \brief Source code of class HistoryID. + * \author Christian Gagne + * $Revision: 1.1 $ + * $Date: 2007/08/27 13:22:06 $ + */ + +#include "Beagle/Core.hpp" + +#include + +using namespace Beagle; + + +/*! + * \brief Construct history ID class, to be used to tag individuals. + * \param inID Initial ID value. + * \param inVar Initial variation number value. + */ +HistoryID::HistoryID(unsigned int inID, unsigned int inVar) : + mID(inID), + mVar(inVar) +{ } + + +/*! + * \brief Make a copy of given HistoryID. + * \param inOriginal HistoryID to copy. + * \param ioSystem Evolutionary system. + */ +void HistoryID::copy(const Member& inOriginal, System& ioSystem) +{ + Beagle_StackTraceBeginM(); + const HistoryID& lOrigHID = castObjectT(inOriginal); + operator=(lOrigHID); + Beagle_StackTraceEndM(); +} + + +/*! + * \return Name of the member, "HistoryID". + */ +const std::string& HistoryID::getName() const +{ + Beagle_StackTraceBeginM(); + const static std::string lName("HistoryID"); + return lName; + Beagle_StackTraceEndM(); +} + + +/*! + * \return Exact type of the HistoryID, "HistoryID". + */ +const std::string& HistoryID::getType() const +{ + Beagle_StackTraceBeginM(); + const static std::string lType("HistoryID"); + return lType; + Beagle_StackTraceEndM(); +} + + +/*! + * \brief Read HistoryID from XML. + * \param inIter Iterator to XML structure to read HistoryID from. + * \param ioContext Evolutionary context. + * \throw Beagle::IOException If XML format is not valid. + */ +void HistoryID::readWithContext(PACC::XML::ConstIterator inIter, Context& ioContext) +{ + Beagle_StackTraceBeginM(); + + // Be sure that root tag is HistoryID + if((inIter->getType()!=PACC::XML::eData) || (inIter->getValue()!="HistoryID")) { + throw Beagle_IOExceptionNodeM(*inIter, "tag expected!"); + } + + // Be sure that the types are corresponding + std::string lType = inIter->getAttribute("type"); + if((lType.empty()==false) && (lType!=getType())) { + std::ostringstream lOSS; + lOSS << "type given '" << lType << "' mismatch type of the history ID '"; + lOSS << getType() << "'!"; + throw Beagle_IOExceptionNodeM(*inIter, lOSS.str()); + } + + // Get ID and variation number + std::string lIDStr = inIter->getAttribute("id"); + if(lIDStr.empty()) { + throw Beagle_IOExceptionNodeM(*inIter, "attribute 'id' should be given in HistoryID!"); + } + mID = str2uint(lIDStr); + std::string lVarStr = inIter->getAttribute("var"); + if(lVarStr.empty()) { + throw Beagle_IOExceptionNodeM(*inIter, "attribute 'var' should be given in HistoryID!"); + } + mVar = str2uint(lVarStr); + + Beagle_StackTraceEndM(); +} + + +/*! + * \brief Write history ID into XML. + * \param ioStreamer XML streamer to write history ID into. + * \param inIndent Whether XML output should be indented. + */ +void HistoryID::writeContent(PACC::XML::Streamer& ioStreamer, bool inIndent) const +{ + Beagle_StackTraceBeginM(); + ioStreamer.insertAttribute("id", mID); + ioStreamer.insertAttribute("var", mVar); + Beagle_StackTraceEndM(); +} diff --git a/pool/shard011/C++/0122270_AcceptConnectionObserver.cpp b/pool/shard011/C++/0122270_AcceptConnectionObserver.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f0b4d0100297572e5c7da42305a7ed08746cd634 --- /dev/null +++ b/pool/shard011/C++/0122270_AcceptConnectionObserver.cpp @@ -0,0 +1,164 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "modules/navigatorconnect/AcceptConnectionObserver.h" + +#include "bindings/core/v8/ExceptionState.h" +#include "bindings/core/v8/ScriptFunction.h" +#include "bindings/core/v8/ScriptPromise.h" +#include "bindings/core/v8/ScriptValue.h" +#include "bindings/core/v8/SerializedScriptValueFactory.h" +#include "core/dom/DOMException.h" +#include "core/dom/ExceptionCode.h" +#include "modules/navigatorconnect/ServicePort.h" +#include "modules/navigatorconnect/ServicePortConnectResponse.h" +#include "modules/serviceworkers/ServiceWorkerGlobalScopeClient.h" + +namespace blink { + +// Function that is called when the promise passed to acceptConnection is either +// rejected or fulfilled. Calls the corresponding method on +// AcceptConnectionObserver. +class AcceptConnectionObserver::ThenFunction final : public ScriptFunction { +public: + enum ResolveType { + Fulfilled, + Rejected, + }; + + static v8::Local createFunction(ScriptState* scriptState, AcceptConnectionObserver* observer, ResolveType type) + { + ThenFunction* self = new ThenFunction(scriptState, observer, type); + return self->bindToV8Function(); + } + + DEFINE_INLINE_VIRTUAL_TRACE() + { + visitor->trace(m_observer); + ScriptFunction::trace(visitor); + } + +private: + ThenFunction(ScriptState* scriptState, AcceptConnectionObserver* observer, ResolveType type) + : ScriptFunction(scriptState) + , m_observer(observer) + , m_resolveType(type) + { + } + + ScriptValue call(ScriptValue value) override + { + ASSERT(m_observer); + ASSERT(m_resolveType == Fulfilled || m_resolveType == Rejected); + if (m_resolveType == Rejected) + m_observer->responseWasRejected(); + else + m_observer->responseWasResolved(value); + m_observer = nullptr; + return value; + } + + Member m_observer; + ResolveType m_resolveType; +}; + +AcceptConnectionObserver* AcceptConnectionObserver::create(ServicePortCollection* collection, PassOwnPtr callbacks, WebServicePortID portID, const KURL& targetURL) +{ + return new AcceptConnectionObserver(collection, callbacks, portID, targetURL); +} + +void AcceptConnectionObserver::contextDestroyed() +{ + ContextLifecycleObserver::contextDestroyed(); + m_state = Done; +} + +void AcceptConnectionObserver::didDispatchEvent() +{ + ASSERT(getExecutionContext()); + if (m_state != Initial) + return; + responseWasRejected(); +} + +ScriptPromise AcceptConnectionObserver::respondWith(ScriptState* scriptState, ScriptPromise value, ExceptionState& exceptionState) +{ + if (m_state != Initial) { + return ScriptPromise::rejectWithDOMException(scriptState, DOMException::create(InvalidStateError, "respondWith was already called.")); + } + + m_state = Pending; + m_resolver = ScriptPromiseResolver::create(scriptState); + ScriptPromise promise = m_resolver->promise(); + value.then( + ThenFunction::createFunction(scriptState, this, ThenFunction::Fulfilled), + ThenFunction::createFunction(scriptState, this, ThenFunction::Rejected)); + return promise; +} + +void AcceptConnectionObserver::responseWasRejected() +{ + ASSERT(getExecutionContext()); + if (m_resolver) + m_resolver->reject(DOMException::create(AbortError)); + m_callbacks->onError(); + m_state = Done; +} + +void AcceptConnectionObserver::responseWasResolved(const ScriptValue& value) +{ + ASSERT(getExecutionContext()); + + ScriptState* scriptState = m_resolver->getScriptState(); + ExceptionState exceptionState(ExceptionState::UnknownContext, nullptr, nullptr, scriptState->context()->Global(), scriptState->isolate()); + ServicePortConnectResponse response = ScriptValue::to(scriptState->isolate(), value, exceptionState); + if (exceptionState.hadException()) { + exceptionState.reject(m_resolver.get()); + m_resolver = nullptr; + responseWasRejected(); + return; + } + if (!response.hasAccept() || !response.accept()) { + responseWasRejected(); + return; + } + WebServicePort webPort; + webPort.targetUrl = m_targetURL; + if (response.hasName()) + webPort.name = response.name(); + if (response.hasData()) { + webPort.data = SerializedScriptValueFactory::instance().create(scriptState->isolate(), response.data(), nullptr, exceptionState)->toWireString(); + if (exceptionState.hadException()) { + exceptionState.reject(m_resolver.get()); + m_resolver = nullptr; + responseWasRejected(); + return; + } + } + webPort.id = m_portID; + ServicePort* port = ServicePort::create(m_collection, webPort); + m_collection->addPort(port); + m_resolver->resolve(port); + m_callbacks->onSuccess(webPort); + m_state = Done; +} + +AcceptConnectionObserver::AcceptConnectionObserver(ServicePortCollection* collection, PassOwnPtr callbacks, WebServicePortID portID, const KURL& targetURL) + : ContextLifecycleObserver(collection->getExecutionContext()) + , m_callbacks(callbacks) + , m_collection(collection) + , m_portID(portID) + , m_targetURL(targetURL) + , m_state(Initial) +{ +} + +DEFINE_TRACE(AcceptConnectionObserver) +{ + visitor->trace(m_collection); + visitor->trace(m_resolver); + ContextLifecycleObserver::trace(visitor); +} + +} // namespace blink diff --git a/pool/shard011/C++/0122271_jni_int.cpp b/pool/shard011/C++/0122271_jni_int.cpp new file mode 100644 index 0000000000000000000000000000000000000000..470a85e8cbd42488f271bf97b75fe74b31f7728b --- /dev/null +++ b/pool/shard011/C++/0122271_jni_int.cpp @@ -0,0 +1,59 @@ +#include "bs/jni/bs_jni.h" +#include + +namespace { + bool _initialized = false; + + jclass _class; + jmethodID _method_ctr; + jmethodID _method_intValue; + + bs::result_t _init(JNIEnv* env) { + if (!_initialized) { + _class = env->FindClass("java/lang/Integer"); + if (_class == NULL) { + return bs::jni::jni_result::ERROR_INIT_FAILED; + } + + _method_ctr = env->GetMethodID(_class, "", "(I)V"); + if (_method_ctr == NULL) { + return bs::jni::jni_result::ERROR_INIT_FAILED; + } + + _method_intValue = env->GetMethodID(_class, "intValue", "()I"); + if (_method_ctr == NULL) { + return bs::jni::jni_result::ERROR_INIT_FAILED; + } + + //TODO for now we need to disable this because otherwise create_int returns some other types except int sometimes + _initialized = false; + } + + return bs::jni::jni_result::SUCCESS; + } +} + +BSEXPORT bs::result_t bs::jni::int_create(JNIEnv* env, int value, jobject* out_instance) { + bs::result_t result = _init(env); + if (result != bs::jni::jni_result::SUCCESS) { + return result; + } + + jobject obj = env->NewObject(_class, _method_ctr, value); + if (obj == NULL) { + return bs::jni::jni_result::ERROR_UNKNOWN; + } + + *out_instance = obj; + return bs::jni::jni_result::SUCCESS; +} +BSEXPORT bs::result_t bs::jni::int_get(JNIEnv* env, jobject boxed, int* out_value) { + bs::result_t result = _init(env); + if (result != bs::jni::jni_result::SUCCESS) { + return result; + } + + int value = env->CallIntMethod(boxed, _method_intValue); + *out_value = value; + return bs::jni::jni_result::SUCCESS; +} \ No newline at end of file diff --git a/pool/shard011/C++/0122275_hook_manager.cpp b/pool/shard011/C++/0122275_hook_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a34f9592fa15615f78e105e17255a91c36280f6b --- /dev/null +++ b/pool/shard011/C++/0122275_hook_manager.cpp @@ -0,0 +1,54 @@ +#include "precompiled.h" + +CHookManager g_hookManager; + +int CHookManager::addHandler(AMX *amx, int func, const char *funcname, int forward, bool post) const +{ + auto hook = m_hooklist.getHookSafe(func); + + if (!hook->post.size() && !hook->pre.size()) + { + // API hookchain + hook->registerHookchain(); + } + + auto& dest = post ? hook->post : hook->pre; + int i = func * MAX_HOOK_FORWARDS + dest.size() + 1; + int index = post ? -i : i; // use unsigned ids for post hooks + + dest.push_back(new CAmxxHookBase(amx, funcname, forward, index)); + return index; +} + +void CHookManager::Clear() const +{ + m_hooklist.clear(); +} + +hook_t *CHookManager::getHook(size_t func) const +{ + return m_hooklist.getHookSafe(func); +} + +CAmxxHookBase *CHookManager::getAmxxHook(cell handle) const +{ + bool post = handle < 0; + + if (post) + handle = ~handle; + else + handle--; + + const size_t func = handle / MAX_HOOK_FORWARDS; + const size_t id = handle & (MAX_HOOK_FORWARDS - 1); + auto hook = m_hooklist.getHookSafe(func); + + if (hook) + { + auto& forwards = post ? hook->post : hook->pre; + if (id < forwards.size()) + return forwards[id]; + } + + return nullptr; +} diff --git a/pool/shard011/C++/0122277_WebKitMediaSource.cpp b/pool/shard011/C++/0122277_WebKitMediaSource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5bdc2ac2d1df6273be4024ddcf797743b30cff78 --- /dev/null +++ b/pool/shard011/C++/0122277_WebKitMediaSource.cpp @@ -0,0 +1,205 @@ +/* + * Copyright (C) 2012 Google Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "config.h" +#include "modules/mediasource/WebKitMediaSource.h" + +#include "bindings/v8/ExceptionState.h" +#include "bindings/v8/ExceptionStatePlaceholder.h" +#include "core/dom/ExceptionCode.h" +#include "core/html/TimeRanges.h" +#include "core/platform/ContentType.h" +#include "core/platform/MIMETypeRegistry.h" +#include "core/platform/graphics/SourceBufferPrivate.h" +#include "modules/mediasource/MediaSourceRegistry.h" +#include "wtf/Uint8Array.h" + +namespace WebCore { + +PassRefPtr WebKitMediaSource::create(ScriptExecutionContext* context) +{ + RefPtr mediaSource(adoptRef(new WebKitMediaSource(context))); + mediaSource->suspendIfNeeded(); + return mediaSource.release(); +} + +WebKitMediaSource::WebKitMediaSource(ScriptExecutionContext* context) + : MediaSourceBase(context) +{ + ScriptWrappable::init(this); + m_sourceBuffers = WebKitSourceBufferList::create(scriptExecutionContext(), asyncEventQueue()); + m_activeSourceBuffers = WebKitSourceBufferList::create(scriptExecutionContext(), asyncEventQueue()); +} + +WebKitSourceBufferList* WebKitMediaSource::sourceBuffers() +{ + return m_sourceBuffers.get(); +} + +WebKitSourceBufferList* WebKitMediaSource::activeSourceBuffers() +{ + // FIXME(91649): support track selection + return m_activeSourceBuffers.get(); +} + +WebKitSourceBuffer* WebKitMediaSource::addSourceBuffer(const String& type, ExceptionState& es) +{ + // 3.1 http://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#dom-addsourcebuffer + // 1. If type is null or an empty then throw an InvalidAccessError exception and + // abort these steps. + if (type.isNull() || type.isEmpty()) { + es.throwDOMException(InvalidAccessError); + return 0; + } + + // 2. If type contains a MIME type that is not supported ..., then throw a + // NotSupportedError exception and abort these steps. + if (!isTypeSupported(type)) { + es.throwDOMException(NotSupportedError); + return 0; + } + + // 4. If the readyState attribute is not in the "open" state then throw an + // InvalidStateError exception and abort these steps. + if (!isOpen()) { + es.throwDOMException(InvalidStateError); + return 0; + } + + // 5. Create a new SourceBuffer object and associated resources. + ContentType contentType(type); + Vector codecs = contentType.codecs(); + OwnPtr sourceBufferPrivate = createSourceBufferPrivate(contentType.type(), codecs, es); + if (!sourceBufferPrivate) + return 0; + + RefPtr buffer = WebKitSourceBuffer::create(sourceBufferPrivate.release(), this); + // 6. Add the new object to sourceBuffers and fire a addsourcebuffer on that object. + m_sourceBuffers->add(buffer); + m_activeSourceBuffers->add(buffer); + // 7. Return the new object to the caller. + return buffer.get(); +} + +void WebKitMediaSource::removeSourceBuffer(WebKitSourceBuffer* buffer, ExceptionState& es) +{ + // 3.1 http://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#dom-removesourcebuffer + // 1. If sourceBuffer is null then throw an InvalidAccessError exception and + // abort these steps. + if (!buffer) { + es.throwDOMException(InvalidAccessError); + return; + } + + // 2. If sourceBuffers is empty then throw an InvalidStateError exception and + // abort these steps. + if (isClosed() || !m_sourceBuffers->length()) { + es.throwDOMException(InvalidStateError); + return; + } + + // 3. If sourceBuffer specifies an object that is not in sourceBuffers then + // throw a NotFoundError exception and abort these steps. + // 6. Remove sourceBuffer from sourceBuffers and fire a removesourcebuffer event + // on that object. + if (!m_sourceBuffers->remove(buffer)) { + es.throwDOMException(NotFoundError); + return; + } + + // 7. Destroy all resources for sourceBuffer. + m_activeSourceBuffers->remove(buffer); + + // 4. Remove track information from audioTracks, videoTracks, and textTracks for all tracks + // associated with sourceBuffer and fire a simple event named change on the modified lists. + // FIXME(91649): support track selection + + // 5. If sourceBuffer is in activeSourceBuffers, then remove it from that list and fire a + // removesourcebuffer event on that object. + // FIXME(91649): support track selection +} + +void WebKitMediaSource::onReadyStateChange(const AtomicString& oldState, const AtomicString& newState) +{ + if (isClosed()) { + m_sourceBuffers->clear(); + m_activeSourceBuffers->clear(); + scheduleEvent(eventNames().webkitsourcecloseEvent); + return; + } + + if (oldState == openKeyword() && newState == endedKeyword()) { + scheduleEvent(eventNames().webkitsourceendedEvent); + return; + } + + if (isOpen()) { + scheduleEvent(eventNames().webkitsourceopenEvent); + return; + } +} + +Vector > WebKitMediaSource::activeRanges() const +{ + Vector > activeRanges(m_activeSourceBuffers->length()); + for (size_t i = 0; i < m_activeSourceBuffers->length(); ++i) + activeRanges[i] = m_activeSourceBuffers->item(i)->buffered(ASSERT_NO_EXCEPTION); + + return activeRanges; +} + +bool WebKitMediaSource::isTypeSupported(const String& type) +{ + // Section 2.1 isTypeSupported() method steps. + // https://dvcs.w3.org/hg/html-media/raw-file/tip/media-source/media-source.html#widl-MediaSource-isTypeSupported-boolean-DOMString-type + // 1. If type is an empty string, then return false. + if (type.isNull() || type.isEmpty()) + return false; + + ContentType contentType(type); + String codecs = contentType.parameter("codecs"); + + // 2. If type does not contain a valid MIME type string, then return false. + if (contentType.type().isEmpty() || codecs.isEmpty()) + return false; + + // 3. If type contains a media type or media subtype that the MediaSource does not support, then return false. + // 4. If type contains at a codec that the MediaSource does not support, then return false. + // 5. If the MediaSource does not support the specified combination of media type, media subtype, and codecs then return false. + // 6. Return true. + return MIMETypeRegistry::isSupportedMediaSourceMIMEType(contentType.type(), codecs); +} + +const AtomicString& WebKitMediaSource::interfaceName() const +{ + return eventNames().interfaceForWebKitMediaSource; +} + +} // namespace WebCore diff --git a/pool/shard011/C++/0122278_EvaluateLinearAlgebraBinary.cc b/pool/shard011/C++/0122278_EvaluateLinearAlgebraBinary.cc new file mode 100644 index 0000000000000000000000000000000000000000..a5f560e1fcd9b2186b820a2fb0d785bafc56427d --- /dev/null +++ b/pool/shard011/C++/0122278_EvaluateLinearAlgebraBinary.cc @@ -0,0 +1,71 @@ +/* + For more information, please see: http://software.sci.utah.edu + + The MIT License + + Copyright (c) 2015 Scientific Computing and Imaging Institute, + University of Utah. + + License for the specific language governing rights and limitations under + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the "Software"), + to deal in the Software without restriction, including without limitation + the rights to use, copy, modify, merge, publish, distribute, sublicense, + and/or sell copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + DEALINGS IN THE SOFTWARE. +*/ +/// @todo Documentation Modules/Math/EvaluateLinearAlgebraBinary.cc + +#include +#include +#include + +using namespace SCIRun::Modules::Math; +using namespace SCIRun::Core::Datatypes; +using namespace SCIRun::Dataflow::Networks; +using namespace SCIRun::Core::Algorithms; + +EvaluateLinearAlgebraBinary::EvaluateLinearAlgebraBinary() : +Module(ModuleLookupInfo("EvaluateLinearAlgebraBinary", "Math", "SCIRun")) +{ + INITIALIZE_PORT(LHS); + INITIALIZE_PORT(RHS); + INITIALIZE_PORT(Result); +} + +void EvaluateLinearAlgebraBinary::setStateDefaults() +{ + auto state = get_state(); + state->setValue(Variables::Operator, 0); + state->setValue(Variables::FunctionString, std::string("x+y")); +} + +void EvaluateLinearAlgebraBinary::execute() +{ + auto lhs = getRequiredInput(LHS); + auto rhs = getRequiredInput(RHS); + + if (needToExecute()) + { + auto state = get_state(); + auto oper = state->getValue(Variables::Operator).toInt(); + auto func = state->getValue(Variables::FunctionString).toString(); + + algo().set(Variables::Operator, oper); + algo().set(Variables::FunctionString, func); + auto output = algo().run(withInputData((LHS, lhs)(RHS, rhs))); + + sendOutputFromAlgorithm(Result, output); + } +} diff --git a/pool/shard011/C++/0122279_complete.cpp b/pool/shard011/C++/0122279_complete.cpp new file mode 100644 index 0000000000000000000000000000000000000000..af308f7388569049832476d2ce5b183cf5bd15cf --- /dev/null +++ b/pool/shard011/C++/0122279_complete.cpp @@ -0,0 +1,47 @@ +//compile g++ complete.cpp -lpthread -lprocessexecutor -std=c++0x -o complete + +#include +#include + + +void run(std::string command, std::list arg){ + + std::string sa; + + ProcessExecutor::Process p(command, arg); + if(p.waitForProcessBegin()){ //if error + p.getLog() >>= sa; + std::cout<<"Log: "<> sa){ + std::cout< arg; + arg.push_back("-a"); + + std::cout<<"====== Running 'ls -a' ======="< +#if K3DPLATFORM_OS_WIN +#include +#include +#elif K3DPLATFORM_OS_MAC || K3DPLATFORM_OS_IOS +#include +#include +#else +#include +#include +#endif +#include "Core/LogUtil.h" + +using namespace k3d; + +namespace render { +const char* TAG_RENDERCONTEXT = "RenderContext"; + +RenderContext::RenderContext() +{ +} + +void +RenderContext::Init(RHIType type, uint32 w, uint32 h) +{ + m_Width = w; + m_Height = h; + m_RhiType = type; +#if !(K3DPLATFORM_OS_MAC || K3DPLATFORM_OS_IOS) + auto pVkRHI = k3d::StaticPointerCast(ACQUIRE_PLUGIN(RHI_Vulkan)); + pVkRHI->Initialize("RenderContext", true); + pVkRHI->Start(); + auto pFactory = pVkRHI->GetFactory(); + DynArray Devices; + pFactory->EnumDevices(Devices); + m_pDevice = Devices[0]; +#else + auto pMtlRHI = k3d::StaticPointerCast(ACQUIRE_PLUGIN(RHI_Metal)); + if (pMtlRHI) { + pMtlRHI->Start(); + m_pDevice = pMtlRHI->GetPrimaryDevice(); + } +#endif +} + +void +RenderContext::Attach(::k3d::IWindow::Ptr hostWindow) +{ +} + +void +RenderContext::PrepareRenderingResource() +{ +} + +void +RenderContext::PreRender() +{ +} + +void +RenderContext::Render() +{ +} + +void +RenderContext::PostRender() +{ +} + +void +RenderContext::Destroy() +{ + m_pDevice->WaitIdle(); + KLOG(Info, "RenderContext", "Destroyed Render Context."); +} + +RenderContext::~RenderContext() +{ +} +} diff --git a/pool/shard011/C++/0122284_main.cpp b/pool/shard011/C++/0122284_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7bdcf7b21c71f6a6a57a582928703c2ef87d0e18 --- /dev/null +++ b/pool/shard011/C++/0122284_main.cpp @@ -0,0 +1,40 @@ +#include +#include +#define LOG_ERROR +#define LOG_DEBUG +#include"pp_socket.h" +using namespace std; +int main() +{ + pp::UDPSocket us; + if(!us.init(true,false)) + { + cout<<"socket init error"<=1) + { + n=10000; + last=now; + } + while(n-->0) + if(!us.sendto(buf,1000)) + { + cout<<"sendto error"<left = str2tree(s.substr(start+1, i-start-1)); + start = i+1; + } else if (cnt == 0) { // ')' + root->right = str2tree(s.substr(start+1, i-start-1)); + } + } + } + + return root; + } +}; + +// Conclusion: +// String to Tree + + + + diff --git a/pool/shard011/C++/0122286_ninjabuilderpreferences.cpp b/pool/shard011/C++/0122286_ninjabuilderpreferences.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3bad70f8acaaf72a1f6b3144e7686734cd501a9d --- /dev/null +++ b/pool/shard011/C++/0122286_ninjabuilderpreferences.cpp @@ -0,0 +1,56 @@ +/* KDevelop CMake Support + * + * Copyright 2006 Matt Rogers + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include "ninjabuilderpreferences.h" + +#include + +#include +#include +#include + +#include "ui_ninjaconfig.h" +#include "ninjabuilderconfig.h" + +K_PLUGIN_FACTORY(NinjaBuilderPreferencesFactory, registerPlugin(); ) +K_EXPORT_PLUGIN(NinjaBuilderPreferencesFactory("kcm_kdev_ninjabuilder")) + +NinjaBuilderPreferences::NinjaBuilderPreferences(QWidget* parent, const QVariantList& args) + : ProjectKCModule( NinjaBuilderPreferencesFactory::componentData(), + parent, args) +{ + QVBoxLayout* l = new QVBoxLayout( this ); + QWidget* w = new QWidget; + m_prefsUi = new Ui::NinjaConfig; + m_prefsUi->setupUi( w ); + l->addWidget( w ); + + m_prefsUi->configureEnvironment->setSelectionWidget( m_prefsUi->kcfg_environmentProfile ); + + addConfig( NinjaBuilderSettings::self(), w ); +} + +NinjaBuilderPreferences::~NinjaBuilderPreferences() +{ + delete m_prefsUi; +} + +#include "ninjabuilderpreferences.moc" + diff --git a/pool/shard011/C++/0122287_Daemon.cpp b/pool/shard011/C++/0122287_Daemon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46ab2eb294e9d2e90c02b10bd37a50ce19ab1a77 --- /dev/null +++ b/pool/shard011/C++/0122287_Daemon.cpp @@ -0,0 +1,146 @@ +#include + +#include "Daemon.h" + +#include "util/Log.h" +#include "version.h" +#include "transport/Transports.h" +#include "transport/NTCPSession.h" +#include "RouterInfo.h" +#include "RouterContext.h" +#include "tunnel/Tunnel.h" +#include "NetDb.h" +#include "Garlic.h" +#include "util/util.h" +#include "Streaming.h" +#include "Destination.h" +#include "HTTPServer.h" +#include "ClientContext.h" + +namespace i2p +{ + namespace util + { + class Daemon_Singleton::Daemon_Singleton_Private + { + public: + Daemon_Singleton_Private() : httpServer(nullptr) + {}; + ~Daemon_Singleton_Private() + { + delete httpServer; + }; + + i2p::util::HTTPServer *httpServer; + }; + + Daemon_Singleton::Daemon_Singleton() : running(1), d(*new Daemon_Singleton_Private()) {}; + Daemon_Singleton::~Daemon_Singleton() { + delete &d; + }; + + bool Daemon_Singleton::IsService () const + { +#ifndef _WIN32 + return i2p::util::config::GetArg("-service", 0); +#else + return false; +#endif + } + + bool Daemon_Singleton::init(int argc, char* argv[]) + { + i2p::util::config::OptionParser(argc, argv); + i2p::context.Init (); + + LogPrint("\n\n\n\ni2pd starting\n"); + LogPrint("Version ", VERSION); + LogPrint("data directory: ", i2p::util::filesystem::GetDataDir().string()); + i2p::util::filesystem::ReadConfigFile(i2p::util::config::mapArgs, i2p::util::config::mapMultiArgs); + + isDaemon = i2p::util::config::GetArg("-daemon", 0); + isLogging = i2p::util::config::GetArg("-log", 1); + + int port = i2p::util::config::GetArg("-port", 0); + if (port) + i2p::context.UpdatePort (port); + const char * host = i2p::util::config::GetCharArg("-host", ""); + if (host && host[0]) + i2p::context.UpdateAddress (boost::asio::ip::address::from_string (host)); + + i2p::context.SetSupportsV6 (i2p::util::config::GetArg("-v6", 0)); + i2p::context.SetFloodfill (i2p::util::config::GetArg("-floodfill", 0)); + auto bandwidth = i2p::util::config::GetArg("-bandwidth", ""); + if (bandwidth.length () > 0) + { + if (bandwidth[0] > 'L') + i2p::context.SetHighBandwidth (); + else + i2p::context.SetLowBandwidth (); + } + + LogPrint("CMD parameters:"); + for (int i = 0; i < argc; ++i) + LogPrint(i, " ", argv[i]); + + return true; + } + + bool Daemon_Singleton::start() + { + // initialize log + if (isLogging) + { + if (isDaemon) + { + std::string logfile_path = IsService () ? "/var/log" : i2p::util::filesystem::GetDataDir().string(); +#ifndef _WIN32 + logfile_path.append("/i2pd.log"); +#else + logfile_path.append("\\i2pd.log"); +#endif + StartLog (logfile_path); + } + else + StartLog (""); // write to stdout + } + + d.httpServer = new i2p::util::HTTPServer( + i2p::util::config::GetArg("-httpaddress", "127.0.0.1"), + i2p::util::config::GetArg("-httpport", 7070) + ); + d.httpServer->Start(); + LogPrint("HTTP Server started"); + i2p::data::netdb.Start(); + LogPrint("NetDB started"); + i2p::transport::transports.Start(); + LogPrint("Transports started"); + i2p::tunnel::tunnels.Start(); + LogPrint("Tunnels started"); + i2p::client::context.Start (); + LogPrint("Client started"); + return true; + } + + bool Daemon_Singleton::stop() + { + LogPrint("Shutdown started."); + i2p::client::context.Stop(); + LogPrint("Client stopped"); + i2p::tunnel::tunnels.Stop(); + LogPrint("Tunnels stopped"); + i2p::transport::transports.Stop(); + LogPrint("Transports stopped"); + i2p::data::netdb.Stop(); + LogPrint("NetDB stopped"); + d.httpServer->Stop(); + LogPrint("HTTP Server stopped"); + + StopLog (); + + delete d.httpServer; d.httpServer = nullptr; + + return true; + } + } +} diff --git a/pool/shard011/C++/0122288_qtluaproperty.cc b/pool/shard011/C++/0122288_qtluaproperty.cc new file mode 100644 index 0000000000000000000000000000000000000000..48a8b58daa49e4310847ca448d4bf5d62cf7a3f4 --- /dev/null +++ b/pool/shard011/C++/0122288_qtluaproperty.cc @@ -0,0 +1,80 @@ +/* + This file is part of LibQtLua. + + LibQtLua is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + LibQtLua 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 Lesser General Public License + along with LibQtLua. If not, see . + + Copyright (C) 2008, Alexandre Becoulet + +*/ + +#include + +#include +#include + +namespace QtLua { + +Property::Property(const QMetaObject *mo, int index) + : Member(mo, index) +{ +} + +void Property::assign(QObjectWrapper &qow, const Value &value) +{ + QMetaProperty mp = _mo->property(_index); + QObject &obj = qow.get_object(); + + // Try to reset property if assign nil + if (value.type() == Value::TNil && mp.isResettable()) + { + if (!mp.reset(&obj)) + QTLUA_THROW(QtLua::Property, "Can't reset QObject property '%'.", .arg(mp.name())); + return; + } + + if (!mp.isWritable()) + QTLUA_THROW(QtLua::Property, "QObject property '%' is read only.", .arg(mp.name())); + + if (!mp.write(&obj, QMetaValue(mp.userType(), value).to_qvariant())) + QTLUA_THROW(QtLua::Property, "Unable to set value of the '%' QObject property.", .arg(mp.name())); +} + +Value Property::access(QObjectWrapper &qow) +{ + QMetaProperty mp = _mo->property(_index); + QObject &obj = qow.get_object(); + + if (!mp.isReadable()) + QTLUA_THROW(QtLua::Property, "QObject property '%' is not readable.", .arg(mp.name())); + + QVariant variant = mp.read(&obj); + + if (!variant.isValid()) + QTLUA_THROW(QtLua::Property, "Unable to read a valid value from the '%' QObject property.", .arg(mp.name())); + + return Value(qow.get_state(), variant); +} + +String Property::get_value_str() const +{ + return String(_mo->className()) + "::" + _mo->property(_index).name(); +} + +String Property::get_type_name() const +{ + QMetaProperty mp = _mo->property(_index); + return Member::get_type_name() + "<" + mp.typeName() + ">"; +} + +} diff --git a/pool/shard011/C++/0122289_CcodeGenTests_Metafunctions.cpp b/pool/shard011/C++/0122289_CcodeGenTests_Metafunctions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9aa0e1826739f911aeda51faf3c5eac2d512447f --- /dev/null +++ b/pool/shard011/C++/0122289_CcodeGenTests_Metafunctions.cpp @@ -0,0 +1,107 @@ +#include "CCodeGenTestsBase.h" + +class CCodeGenTests_Metafunctions : public CCodeGenTestsBase { +}; + +TEST_F(CCodeGenTests_Metafunctions, Sizeof) { + Three::CCodeGenVisitor* visitor = this->visit("def test(Int! x)\n" + " x = sizeof(Int!)\n" + "end\n"); + + EXPECT_EQ("void test(int x);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(int x) {\n" + " x = sizeof(int);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Cardinalityof) { + Three::CCodeGenVisitor* visitor = this->visit("def test([5]Int x)\n" + " Int y = cardinalityof(x)\n" + "end\n"); + + EXPECT_EQ("void test(const int[5] x);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(const int[5] x) {\n" + " const int y = sizeof(x);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Alignof) { + Three::CCodeGenVisitor* visitor = this->visit("def test(Int! x)\n" + " x = alignof(Int!)\n" + "end\n"); + + EXPECT_EQ("void test(int x);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(int x) {\n" + " x = alignof(int);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Typeof) { + Three::CCodeGenVisitor* visitor = this->visit("def test()\n" + " typeof(Int!)\n" + "end\n"); + + EXPECT_EQ("void test(void);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(void) {\n" + " typeof(int);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Containerof) { + Three::CCodeGenVisitor* visitor = this->visit("struct MyStruct\n" + " Int a\n" + " Int b\n" + "end\n" + "def test(*Int ptrB)\n" + " containerof(ptrB, MyStruct, b)\n" + "end\n"); + + EXPECT_EQ("typedef struct MyStruct {\n" + " int a;\n" + " int b;\n" + "} MyStruct;\n\n" + "void test(const int* const ptrB);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(const int* const ptrB) {\n" + " THREE_CONTAINER_OF(ptrB,const MyStruct,b);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Offsetof) { + Three::CCodeGenVisitor* visitor = this->visit("struct MyStruct\n" + " Int a\n" + "end\n" + "def test()\n" + " offsetof(MyStruct, a)\n" + "end\n"); + + EXPECT_EQ("typedef struct MyStruct {\n" + " int a;\n" + "} MyStruct;\n\n" + "void test(void);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(void) {\n" + " offsetof(const MyStruct,a);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Cast) { + Three::CCodeGenVisitor* visitor = this->visit("def test()\n" + " Int! x = cast(Int!, 5)\n" + "end\n"); + + EXPECT_EQ("void test(void);\n", visitor->internalHeaderString()); + EXPECT_EQ("void test(void) {\n" + " int x = (int)(5);\n" + "}\n\n", visitor->bodyString()); +} + +TEST_F(CCodeGenTests_Metafunctions, Varargs) { + Three::CCodeGenVisitor* visitor = this->visit("def test(Vararg ap)\n" + " Int! a = nextarg(Int!, ap)\n" + "end\n"); + + EXPECT_EQ("void test(va_list ap);\n", visitor->internalHeaderString()); + EXPECT_EQ("#include \n\n", visitor->externalHeaderString()); + EXPECT_EQ("void test(va_list ap) {\n" + " int a = va_arg(ap, int);\n" + "}\n\n", visitor->bodyString()); +} diff --git a/pool/shard011/C++/0122291_CWE114_Process_Control__w32_wchar_t_connect_socket_82a.cpp b/pool/shard011/C++/0122291_CWE114_Process_Control__w32_wchar_t_connect_socket_82a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dca3431f7021ce9a739a306870fccfba88610b02 --- /dev/null +++ b/pool/shard011/C++/0122291_CWE114_Process_Control__w32_wchar_t_connect_socket_82a.cpp @@ -0,0 +1,176 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE114_Process_Control__w32_wchar_t_connect_socket_82a.cpp +Label Definition File: CWE114_Process_Control__w32.label.xml +Template File: sources-sink-82a.tmpl.cpp +*/ +/* + * @description + * CWE: 114 Process Control + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Hard code the full pathname to the library + * Sinks: + * BadSink : Load a dynamic link library + * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer + * + * */ + +#include "std_testcase.h" +#include "CWE114_Process_Control__w32_wchar_t_connect_socket_82.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" + +namespace CWE114_Process_Control__w32_wchar_t_connect_socket_82 +{ + +#ifndef OMITBAD + +void bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + wchar_t *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = wcslen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; + /* Eliminate CRLF */ + replace = wcschr(data, L'\r'); + if (replace) + { + *replace = L'\0'; + } + replace = wcschr(data, L'\n'); + if (replace) + { + *replace = L'\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE114_Process_Control__w32_wchar_t_connect_socket_82_base* baseObject = new CWE114_Process_Control__w32_wchar_t_connect_socket_82_bad; + baseObject->action(data); + delete baseObject; +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + /* FIX: Specify the full pathname for the library */ + wcscpy(data, L"C:\\Windows\\System32\\winsrv.dll"); + CWE114_Process_Control__w32_wchar_t_connect_socket_82_base* baseObject = new CWE114_Process_Control__w32_wchar_t_connect_socket_82_goodG2B; + baseObject->action(data); + delete baseObject; +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE114_Process_Control__w32_wchar_t_connect_socket_82; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard011/C++/0122292_AppliedMaterial.cpp b/pool/shard011/C++/0122292_AppliedMaterial.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9aa3241bccf0477870e606de67e929f330736a51 --- /dev/null +++ b/pool/shard011/C++/0122292_AppliedMaterial.cpp @@ -0,0 +1,68 @@ +#include "Material.h" +#include "ResourceManager.h" +#include "Application.h" +#include "AppliedMaterial.h" + +AppliedMaterial::AppliedMaterial(Material * material, const GameObject* const go, bool enabled) : Component(CT_APPLIED_MATERIAL, go, enabled), material(material) +{ + unsigned int buff_size = material->GetNumAllTextures(); + + for (int i = 0; i < buff_size; i++) + uv_channels.push_back(0); +} + +AppliedMaterial::AppliedMaterial(const AppliedMaterial & copy, const GameObject* const go): Component(CT_APPLIED_MATERIAL, go, copy.enabled) +{ + material = App->resource_manager->UseMaterial(copy.material->GetUID(), go); + + for (std::vector::const_iterator it = copy.uv_channels.begin(); it != copy.uv_channels.end(); ++it) + uv_channels.push_back(*it); +} + +AppliedMaterial::~AppliedMaterial() +{ + uv_channels.clear(); +} + +const unsigned int AppliedMaterial::GetUVChannel(const unsigned int num_texture) const +{ + return uv_channels[num_texture]; +} + +const Material * AppliedMaterial::GetMaterial() const +{ + return material; +} + +void AppliedMaterial::Inspector() +{ + //TODO change to pick uv channel + material->Inspector(); +} + +void AppliedMaterial::LoadComponent(char ** iterator, const GameObject* game_object) +{ + //Nothing needed to load +} + +void AppliedMaterial::SaveComponent(char ** iterator) const +{ + COMPONENT_TYPE component_type = CT_APPLIED_MATERIAL; + memcpy(*iterator, &component_type, sizeof(COMPONENT_TYPE)); + *iterator += sizeof(COMPONENT_TYPE); + + memcpy(*iterator, &material->GetUID(), SIZE_OF_UID); + *iterator += SIZE_OF_UID; +} + +const std::string & AppliedMaterial::GetName() const +{ + return material->GetName(); +} + +void AppliedMaterial::AddTexture(Texture * new_texture, unsigned int uv_channel) +{ + material->AddTexture(new_texture, TT_DIFFUSE); + uv_channels.push_back(uv_channel); +} + diff --git a/pool/shard011/JavaScript/0068969_automated-suite.js b/pool/shard011/JavaScript/0068969_automated-suite.js new file mode 100644 index 0000000000000000000000000000000000000000..bb09711821799e5f73cb88f0458bf0c80613cc94 --- /dev/null +++ b/pool/shard011/JavaScript/0068969_automated-suite.js @@ -0,0 +1,116 @@ +/* + Copyright 2016 Google Inc. All Rights Reserved. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +'use strict'; + +/* eslint-disable max-len, no-console, padded-blocks, no-multiple-empty-lines */ +/* eslint-env node,mocha */ + +// These tests make use of selenium-webdriver. You can find the relevant +// documentation here: https://github.com/SeleniumHQ/selenium + +const path = require('path'); +const seleniumAssistant = require('selenium-assistant'); +const mochaUtils = require('sw-testing-helpers').mochaUtils; + +require('geckodriver'); +require('chromedriver'); + +require('chai').should(); + +const testServer = require('./server/index.js'); + +describe('Test SW-Toolbox', function() { + // Browser tests can be slow + this.timeout(100000); + + // Selenium Tests are Flakey + this.retries(3); + + // Driver is initialised to `null` to handle scenarios + // where the desired browser isn't installed / fails to load + // `null` allows afterEach a safe way to skip quiting the driver + let globalDriverReference = null; + let testServerURL; + + before(function() { + return testServer.startServer(path.join(__dirname, '..')) + .then(portNumber => { + testServerURL = `http://localhost:${portNumber}`; + }); + }); + + after(function() { + testServer.killServer(); + }); + + afterEach(function() { + this.timeout(2 * 60 * 1000); + + return seleniumAssistant.killWebDriver(globalDriverReference) + .then(() => { + globalDriverReference = null; + }); + }); + + const queueUnitTest = browserInfo => { + it(`should pass all tests in ${browserInfo.getPrettyName()}`, () => { + return browserInfo.getSeleniumDriver() + .then(driver => { + globalDriverReference = driver; + return mochaUtils.startWebDriverMochaTests( + browserInfo.getPrettyName(), + globalDriverReference, + `${testServerURL}/test/browser-tests/` + ); + }) + .then(testResults => { + mochaUtils.prettyPrintResults(testResults); + if (testResults.failed.length > 0) { + throw new Error('Tests Failed'); + } + }); + }); + }; + + const automatedBrowsers = seleniumAssistant.getLocalBrowsers(); + automatedBrowsers.forEach(browserInfo => { + // Firefox before version 50 have issues that can't be duplicated outside + // of the selenium test runner. + if (browserInfo.getId() === 'firefox' && + browserInfo.getVersionNumber() < 50) { + console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`); + return; + } + + // Opera has bad unregister API and it's driver is far from happy + // with latest builds. + if (browserInfo.getId() === 'opera') { + console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`); + return; + } + + // Block browsers w/o Service Worker support from being included in the + // tests on Travis + if (browserInfo.getId() !== 'firefox' && + browserInfo.getId() !== 'chrome') { + console.log(`Skipping ${browserInfo.getId()}: ${browserInfo.getRawVersionString()}`); + return; + } + + queueUnitTest(browserInfo); + }); +}); diff --git a/pool/shard011/JavaScript/0068970_faq.js b/pool/shard011/JavaScript/0068970_faq.js new file mode 100644 index 0000000000000000000000000000000000000000..e7668e846483d931e7fb7e98f750d9555b6e8b4f --- /dev/null +++ b/pool/shard011/JavaScript/0068970_faq.js @@ -0,0 +1,50 @@ +const html = require('choo/html') +const friendlyUrl = require('friendly-url') +const asElement = require('prismic-element') +const { asText } = require('prismic-richtext') +const { __ } = require('../lib/locale') +const resolve = require('../lib/resolve') +const view = require('../components/view') +const { loader } = require('../components/icons') + +module.exports = view(faq, title) + +function faq (state, emit) { + const doc = state.content.faq + + if (!doc) { + emit('content:fetch', 'faq') + return html` +
+
+ ${loader()} +
+
+ ` + } else if (state.params.anchor) { + emit('scrollto', state.params.anchor) + } + + return html` +
+
+

+ ${asText(doc.data.title)} +

+ ${doc.data.questions.map(question => html` +
+
+

${asText(question.question)}

+
+ ${asElement(question.answer, resolve)} +
+
+ `)} +
+
+ ` +} + +function title () { + return __('How it works') +} diff --git a/pool/shard011/JavaScript/0068974_EventDispatcher.js b/pool/shard011/JavaScript/0068974_EventDispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..474de89226db756dd445acd23752d7df33be1a11 --- /dev/null +++ b/pool/shard011/JavaScript/0068974_EventDispatcher.js @@ -0,0 +1,99 @@ +(function(){ + 'use strict'; + + /** + * @class Global.event.EventDispatcher + * manipulate publish / subscribe interface + * @extends Global.core.BaseClass + * + * var instance = new Global.event.EventDispatcher(), + * callback = Global.core.Functions.bind(console.log); + * + * instance.addEventListener('hoge', callback); + * instance.dispatchEvent('hoge'); // log argumetns + * + */ + Global.define('Global.event.EventDispatcher',{ + + /** + * @method init + * @constructor + */ + init: function(config) { + this.listeners = {}; + this._super(config); + }, + + /** + * @method addEventListener + * Add listener + * @param {String} type Event type + * @param {Function} listener Callback function + * + */ + addEventListener: function(type, listener){ + (this.listeners[type] || (this.listeners[type] = [])).push(listener); + }, + + /** + * @method hasEventListener + * Return true this class listens passed type of event. + * @param {String} type Event type + * @return {Boolean} + */ + hasEventListener: function(type){ + return !!this.listeners[type]; + }, + + /** + * @method removeEventListener + * Remove listener + * @param {String} type Event type + * @param {Function} listener Callback function + */ + removeEventListener: function(type, listener){ + var fncs = this.listeners[type]; + if(fncs){ + for (var i = fncs.length-1; i >= 0; i--){ + if (fncs[i] === listener){ + fncs.splice(i, 1); + } + } + } + }, + + /** + * @method onesEventListener + * Event you passed is only called once. + * @param {String} type Event type + * @param {Function} listener Callback function + */ + onesEventListener: function(type, listener){ + var self = this, + callback = function (event){ + self.removeEventListener(type, callback); + listener.apply(self, [event]); + callback = null; + }; + this.addEventListener(type, callback); + }, + + /** + * @method dispatchEvent + * Dispatch event message. + * @param {String} type Event type + * @param {Object} data Attach data + */ + dispatchEvent: function(type, data){ + var fncs = this.listeners[type], + event = new Global.event.Event({target:this, type: type, data: data}); + + if(fncs){ + fncs = fncs.concat(); + for (var i = 0, n = fncs.length; i < n; i++){ + fncs[i].apply(this, [event]); + } + } + } + }); +})(); diff --git a/pool/shard011/JavaScript/0068975_worker.js b/pool/shard011/JavaScript/0068975_worker.js new file mode 100644 index 0000000000000000000000000000000000000000..7405d0d76e13bf7d99f46cf14c99cb7140e85438 --- /dev/null +++ b/pool/shard011/JavaScript/0068975_worker.js @@ -0,0 +1,70 @@ +'use strict'; + +var buildActions = require('build-actions'); + +/** + * Creates or update a customer. + * + * @public + * @param {Object} data Customer object + * @param {next} Callback + */ +function worker(data, next) { + var email = encodeURIComponent('email="' + data.email + '"') + , client = this.client + , loader = this; + + // + // For the same of simplicity assume that the `email` field is good enough + // to uniquely match a customer. + // @todo This is actually not a good idea because the email can be updated. + // + client.get('/customers?where=' + email, function get(err, res, body) { + if (err || res.statusCode !== 200) { + return next(err || new Error(body.message)); + } + + var customer = body.results[0]; + + if (!customer) { + // + // If a match has not been found, create the customer. + // @todo Pick only the valid properties from `data`. + // + client.post('/customers', data, function post(err, res, body) { + if (err || res.statusCode !== 201) { + return next(err || new Error(body.message)); + } + + loader.created++; + next(); + }); + + return; + } + + var actions = buildActions(customer, data); + + // + // Bail out if there are no changes, otherwise update the customer. + // + if (!actions.length) return next(); + + client.post('/customers/' + customer.id, { + version: customer.version, + actions: actions + }, function post(err, res, body) { + if (err || res.statusCode !== 200) { + return next(err || new Error(body.message)); + } + + loader.updated++; + next(); + }); + }); +} + +// +// Expose the `worker` function. +// +module.exports = worker; diff --git a/pool/shard011/JavaScript/0068977_app.js b/pool/shard011/JavaScript/0068977_app.js new file mode 100644 index 0000000000000000000000000000000000000000..84e3eb517af179b031d4a7ba270acea9a8d9aec6 --- /dev/null +++ b/pool/shard011/JavaScript/0068977_app.js @@ -0,0 +1,33 @@ +var express = require('express'); +var app = express(); +var ENV = require('dotenv').load(); + +app.use(express.static('public')); + +// TODO: Hook up get route. For when querying by current location is implemented. +// app.get('/', function(req, response){ +// response.sendFile(__dirname + 'public/index.html'); +// }); + +var server = app.listen(3000, function () { + var host = server.address().address; + var port = server.address().port; + console.log('Example app listening at http://%s:%s', host, port); +}); + +// ========================================= +// PROXY SERVER-SIDE CODE +// ========================================= + +// var express = require('express'); + +// var portNumber = 3001; +// var app = express(); + +// app.get("/", function (req, res) { +// res.send({ response: "This is data returned from the server, proxy style!" }); +// }) + +// app.listen(portNumber); + +// console.log("Responding server listening on port "+portNumber); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0068978_parse_tag.js b/pool/shard011/JavaScript/0068978_parse_tag.js new file mode 100644 index 0000000000000000000000000000000000000000..074ea44a3d06018ab0d9c4c2ec19d771f953f98c --- /dev/null +++ b/pool/shard011/JavaScript/0068978_parse_tag.js @@ -0,0 +1,50 @@ +'use strict'; + +var classIdSplit = /([\.#]?[a-zA-Z0-9\u007F-\uFFFF_:-]+)/; +var notClassId = /^\.|#/; + +module.exports = function parseTag(tag, props) { + if (!tag) { + return 'DIV'; + } + + var noId = !(props.hasOwnProperty('id')); + + var tagParts = tag.split(classIdSplit) + var tagName = null; + + if (notClassId.test(tagParts[1])) { + tagName = 'DIV'; + } + + var classes, part, type, i; + + for (i = 0; i < tagParts.length; i++) { + part = tagParts[i]; + + if (!part) { + continue; + } + + type = part.charAt(0); + + if (!tagName) { + tagName = part; + } else if (type === '.') { + classes = classes || []; + classes.push(part.substring(1, part.length)); + } else if (type === '#' && noId) { + props.id = part.substring(1, part.length); + } + } + + if (classes) { + if (props.className) { + classes.push(props.className); + } + + props.className = classes.join(' '); + } + + return props.namespace ? tagName : tagName.toUpperCase(); +} diff --git a/pool/shard011/JavaScript/0068986_rtc-text-chat.js b/pool/shard011/JavaScript/0068986_rtc-text-chat.js new file mode 100644 index 0000000000000000000000000000000000000000..c8fe07c98f618e7b7d9d804a4c788a4d5ba72420 --- /dev/null +++ b/pool/shard011/JavaScript/0068986_rtc-text-chat.js @@ -0,0 +1,38 @@ +// Set RTC options. +var rtcOpts = { + room: 'test-data', + signaller: 'https://switchboard.rtc.io', + capture: false +}; + +// call RTC module +var rtc = RTC(rtcOpts); + +// A contenteditable element to show our messages +var messages = document.getElementById('messages'); + +// Bind to events happening on the data channel +function bindDataChannelEvents(id, channel, attributes, connection) { + + // Receive message + channel.onmessage = function (evt) { + messages.innerHTML = evt.data; + }; + + // Send message + messages.onkeyup = function () { + channel.send(this.innerHTML); + }; +} + +// Start working with the established session +function init(session) { + session.createDataChannel('chat', { + ordered: true, + maxRetransmits: 12 + }); + session.on('channel:opened:chat', bindDataChannelEvents); +} + +// Detect when RTC has established a session +rtc.on('ready', init); diff --git a/pool/shard011/JavaScript/0068987_AuScopeQuerierFactory.js b/pool/shard011/JavaScript/0068987_AuScopeQuerierFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..e6e147373b2310ea7f7fead0db6d0129ec027445 --- /dev/null +++ b/pool/shard011/JavaScript/0068987_AuScopeQuerierFactory.js @@ -0,0 +1,96 @@ +/** + * A class for creating instances of portal.layer.querier.Querier + */ +Ext.define('auscope.layer.AuScopeQuerierFactory', { + + extend : 'portal.layer.querier.QuerierFactory', + + + /** + * Creates a new instance of a Querier based on the specified values + * + * knownLayer can be null + */ + _generateQuerier : function(knownLayer, wfsResources, wmsResources, wcsResources, irisResources) { + var cfg = {map : this.map}; + + //Geodesy features don't allow gml:Id lookups + //To workaround this we have a custom feature source that looks up via the gps site id. + if (knownLayer && knownLayer.get('id') === 'geodesy:gnssstation') { + cfg.featureSource = Ext.create('portal.layer.querier.wfs.featuresources.WFSFeatureByPropertySource', { + property : 'GPSSITEID' + }); + } + + if(wfsResources.length > 0 && wmsResources.length > 0){ + cfg.parser = Ext.create('auscope.layer.querier.wfs.AuScopeParser', {}); + cfg.knownLayerParser = Ext.create('auscope.layer.querier.wfs.AuScopeKnownLayerParser', {}); + return Ext.create('portal.layer.querier.wfs.WFSWithMapQuerier', cfg); + } else if (wfsResources.length > 0) { + cfg.parser = Ext.create('auscope.layer.querier.wfs.AuScopeParser', {}); + cfg.knownLayerParser = Ext.create('auscope.layer.querier.wfs.AuScopeKnownLayerParser', {}); + + return Ext.create('portal.layer.querier.wfs.WFSQuerier', cfg); + } else if (wcsResources.length > 0) { + return Ext.create('portal.layer.querier.coverage.WCSQuerier',cfg); + } else if (wmsResources.length > 0) { + //WMS may mean Geotransects + for (var i = 0; i < wmsResources.length; i++) { + if (wmsResources[i].get('name') === 'Onshore_Seismic_Surveys') { + return Ext.create('portal.layer.querier.wms.OnshoreSeismicSurveyQuerier', cfg); + } + } + + for (var i = 0; i < wmsResources.length; i++) { + if (wmsResources[i].get('name') === 'FalseColour123-gamma1.0') { + return Ext.create('portal.layer.querier.wms.WMSXMLFormatQuerier', cfg); + } + } + + if (knownLayer && knownLayer.get('id') === 'remanent-anomalies-EMAGTMI') { + return Ext.create('portal.layer.querier.wms.WMSXMLFormatQuerier', cfg); + } + + if (knownLayer && knownLayer.get('id') === '250K-scanned-geological-maps') { + return Ext.create('portal.layer.querier.wms.ScannedGeologicalMapsQuerier', cfg); + } + + //Or just the plain old WMS querier + return Ext.create('portal.layer.querier.wms.WMSQuerier', cfg); + } else if (irisResources.length > 0) { +// cfg.parser = Ext.create('auscope.layer.querier.wfs.AuScopeParser', {}); +// cfg.knownLayerParser = Ext.create('auscope.layer.querier.wfs.AuScopeKnownLayerParser', {}); + return Ext.create('auscope.layer.querier.iris.IRISQuerier', cfg); + } else { + //Worst case scenario, we render the source CSW record + return Ext.create('portal.layer.querier.csw.CSWQuerier', cfg); + } + }, + + /** + * See parent class for defn + */ + buildFromKnownLayer : function(knownLayer) { + var allOnlineResources = knownLayer.getAllOnlineResources(); + + var wmsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WMS); + var wfsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WFS); + var wcsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WCS); + var irisResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.IRIS); + + return this._generateQuerier(knownLayer, wfsResources, wmsResources, wcsResources, irisResources); + }, + + /** + * See parent class for defn + */ + buildFromCswRecord : function(cswRecord) { + var allOnlineResources = cswRecord.get('onlineResources'); + + var wmsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WMS); + var wfsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WFS); + var wcsResources = portal.csw.OnlineResource.getFilteredFromArray(allOnlineResources, portal.csw.OnlineResource.WCS); + + return this._generateQuerier(null, wfsResources, wmsResources, wcsResources, []); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0068989_ApiConfig.js b/pool/shard011/JavaScript/0068989_ApiConfig.js new file mode 100644 index 0000000000000000000000000000000000000000..a94648d49f3e0095ba051c8b358fc0593de079de --- /dev/null +++ b/pool/shard011/JavaScript/0068989_ApiConfig.js @@ -0,0 +1,43 @@ +/** + Config API routing, URL etc... + */ +'use strict'; + +var config = function config(app, version) { + + console.log("config! " + version); + + var bodyParser = require('body-parser'); + + // configure app to use bodyParser() + // this will let us get the data from a POST + app.use(bodyParser.urlencoded({ + extended: true + })); + app.use(bodyParser.json()); +}; + +/** + * Set web routing to use + * */ +var addRoutes = function addRoutes(app, version) { + var router = require('../routing/routing-' + version); + app.use('/api/v' + version, router); +}; + +/** + Return web server port + */ +var port = function port() { + var portGlobal = process.env.PORT; + console.log("portGlobal = " + portGlobal); + + var port = portGlobal /*|| portParameter*/ || '9090'; + console.log("port = " + port); + + return port; +}; + +module.exports = { + config: config, port: port, addRoutes: addRoutes +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0068991_example.js b/pool/shard011/JavaScript/0068991_example.js new file mode 100644 index 0000000000000000000000000000000000000000..22500cb0e9730c4f5d4d26b19c532c6d971f0f7a --- /dev/null +++ b/pool/shard011/JavaScript/0068991_example.js @@ -0,0 +1,38 @@ +'use strict'; + +var assert = require('assert'); +var BulkMongoDb = require('./'); + +describe('notifications', function() { + var bulkMongoDb; + + before(function(done){ + var notifications = require('./fixtures/notifications'); + var users = require('./fixtures/users'); + + var url = 'mongodb://127.0.0.1:27017/bulkMongoDbtest'; + + var data = [ + { collection : 'notifications', documents : notifications }, + { collection : 'users', documents : users } + ]; + + bulkMongoDb = new BulkMongoDb(url, data); + + bulkMongoDb.insert(function() { + done(); + }); + }); + + after(function(done) { + bulkMongoDb.drop(function(){ + done(); + }); + }); + + describe('when doing something which needs mongodb', function() { + it('should return a valid response', function(){ + assert(true); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069000_chat.js b/pool/shard011/JavaScript/0069000_chat.js new file mode 100644 index 0000000000000000000000000000000000000000..6c62941f2a7da73b52c9e9ef84379d6485107795 --- /dev/null +++ b/pool/shard011/JavaScript/0069000_chat.js @@ -0,0 +1,20 @@ +angular.module('ChattyApp', []) + .controller('ChatController', ['$scope', function ($scope) { + $scope.messages = []; + var socket = io.connect('/'); + socket.on('history', function (oldMessages) { + $scope.$apply(function () { + $scope.messages = oldMessages; + }); + }); + socket.on('newMessage', function (message) { + $scope.$apply(function () { + $scope.messages.unshift(message); + }); + }); + + $scope.sendMsg = function () { + socket.emit('newMessage', { nick: $scope.nick, message: $scope.message }); + }; + }]); + diff --git a/pool/shard011/JavaScript/0069003_ionicons.js b/pool/shard011/JavaScript/0069003_ionicons.js new file mode 100644 index 0000000000000000000000000000000000000000..59734a085608cf47d65f787395201b6acc572ba3 --- /dev/null +++ b/pool/shard011/JavaScript/0069003_ionicons.js @@ -0,0 +1,27 @@ + +(function(doc){ + var scriptElm = doc.scripts[doc.scripts.length - 1]; + var warn = ['[ionicons] Deprecated script, please remove: ' + scriptElm.outerHTML]; + + warn.push('To improve performance it is recommended to set the differential scripts in the head as follows:') + + var parts = scriptElm.src.split('/'); + parts.pop(); + parts.push('ionicons'); + var url = parts.join('/'); + + var scriptElm = doc.createElement('script'); + scriptElm.setAttribute('type', 'module'); + scriptElm.src = url + '/ionicons.esm.js'; + doc.head.appendChild(scriptElm); + warn.push(scriptElm.outerHTML); + + scriptElm = doc.createElement('script'); + scriptElm.setAttribute('nomodule', ''); + scriptElm.src = url + '/ionicons.js'; + doc.head.appendChild(scriptElm); + warn.push(scriptElm.outerHTML); + + console.warn(warn.join('\n')); + +})(document); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069006_AddMovie.spec.js b/pool/shard011/JavaScript/0069006_AddMovie.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c0a3093d5f1a9b298bc81bfd5a979e2a7c76bf5f --- /dev/null +++ b/pool/shard011/JavaScript/0069006_AddMovie.spec.js @@ -0,0 +1,56 @@ +import React from 'react' +import { shallow } from 'enzyme' +import toJson from 'enzyme-to-json' +import { AddMovie } from '../AddMovie' + +describe('components/AddMovie', () => { + let component + let instance + let mutate + let navigation + + beforeEach(() => { + mutate = jest.fn() + navigation = { + navigate: jest.fn() + } + + component = shallow() + + instance = component.instance() + }) + + it('renders AddMovie', () => { + expect(toJson(component)).toMatchSnapshot() + }) + + describe('#insertMovie', () => { + it('should call mutate with correct variables', async () => { + try { + await instance.insertMovie() + + expect(mutate).toHaveBeenCalledWith({ + variables: { + input: { + imdbId: '', + rating: 0, + userId: 2 + } + } + }) + } catch (e) { + throw new Error(e) + } + }) + + it('should navigate back to Feed', async () => { + try { + await instance.insertMovie() + + expect(navigation.navigate).toHaveBeenCalledWith('Feed') + } catch (e) { + throw new Error(e) + } + }) + }) +}) diff --git a/pool/shard011/JavaScript/0069009_purchasercontactnotes.client.controller.test.js b/pool/shard011/JavaScript/0069009_purchasercontactnotes.client.controller.test.js new file mode 100644 index 0000000000000000000000000000000000000000..b54460ffdcec84a47bc2b04f99a16a4e4ee9dc5f --- /dev/null +++ b/pool/shard011/JavaScript/0069009_purchasercontactnotes.client.controller.test.js @@ -0,0 +1,163 @@ +'use strict'; + +(function() { + // Purchasercontactnotes Controller Spec + describe('Purchasercontactnotes Controller Tests', function() { + // Initialize global variables + var PurchasercontactnotesController, + scope, + $httpBackend, + $stateParams, + $location; + + // The $resource service augments the response object with methods for updating and deleting the resource. + // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match + // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. + // When the toEqualData matcher compares two objects, it takes only object properties into + // account and ignores methods. + beforeEach(function() { + jasmine.addMatchers({ + toEqualData: function(util, customEqualityTesters) { + return { + compare: function(actual, expected) { + return { + pass: angular.equals(actual, expected) + }; + } + }; + } + }); + }); + + // Then we can start by loading the main application module + beforeEach(module(ApplicationConfiguration.applicationModuleName)); + + // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). + // This allows us to inject a service but then attach it to a variable + // with the same name as the service. + beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { + // Set a new global scope + scope = $rootScope.$new(); + + // Point global variables to injected services + $stateParams = _$stateParams_; + $httpBackend = _$httpBackend_; + $location = _$location_; + + // Initialize the Purchasercontactnotes controller. + PurchasercontactnotesController = $controller('PurchasercontactnotesController', { + $scope: scope + }); + })); + + it('$scope.find() should create an array with at least one Purchasercontactnote object fetched from XHR', inject(function(Purchasercontactnotes) { + // Create sample Purchasercontactnote using the Purchasercontactnotes service + var samplePurchasercontactnote = new Purchasercontactnotes({ + name: 'New Purchasercontactnote' + }); + + // Create a sample Purchasercontactnotes array that includes the new Purchasercontactnote + var samplePurchasercontactnotes = [samplePurchasercontactnote]; + + // Set GET response + $httpBackend.expectGET('purchasercontactnotes').respond(samplePurchasercontactnotes); + + // Run controller functionality + scope.find(); + $httpBackend.flush(); + + // Test scope value + expect(scope.purchasercontactnotes).toEqualData(samplePurchasercontactnotes); + })); + + it('$scope.findOne() should create an array with one Purchasercontactnote object fetched from XHR using a purchasercontactnoteId URL parameter', inject(function(Purchasercontactnotes) { + // Define a sample Purchasercontactnote object + var samplePurchasercontactnote = new Purchasercontactnotes({ + name: 'New Purchasercontactnote' + }); + + // Set the URL parameter + $stateParams.purchasercontactnoteId = '525a8422f6d0f87f0e407a33'; + + // Set GET response + $httpBackend.expectGET(/purchasercontactnotes\/([0-9a-fA-F]{24})$/).respond(samplePurchasercontactnote); + + // Run controller functionality + scope.findOne(); + $httpBackend.flush(); + + // Test scope value + expect(scope.purchasercontactnote).toEqualData(samplePurchasercontactnote); + })); + + it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Purchasercontactnotes) { + // Create a sample Purchasercontactnote object + var samplePurchasercontactnotePostData = new Purchasercontactnotes({ + name: 'New Purchasercontactnote' + }); + + // Create a sample Purchasercontactnote response + var samplePurchasercontactnoteResponse = new Purchasercontactnotes({ + _id: '525cf20451979dea2c000001', + name: 'New Purchasercontactnote' + }); + + // Fixture mock form input values + scope.name = 'New Purchasercontactnote'; + + // Set POST response + $httpBackend.expectPOST('purchasercontactnotes', samplePurchasercontactnotePostData).respond(samplePurchasercontactnoteResponse); + + // Run controller functionality + scope.create(); + $httpBackend.flush(); + + // Test form inputs are reset + expect(scope.name).toEqual(''); + + // Test URL redirection after the Purchasercontactnote was created + expect($location.path()).toBe('/purchasercontactnotes/' + samplePurchasercontactnoteResponse._id); + })); + + it('$scope.update() should update a valid Purchasercontactnote', inject(function(Purchasercontactnotes) { + // Define a sample Purchasercontactnote put data + var samplePurchasercontactnotePutData = new Purchasercontactnotes({ + _id: '525cf20451979dea2c000001', + name: 'New Purchasercontactnote' + }); + + // Mock Purchasercontactnote in scope + scope.purchasercontactnote = samplePurchasercontactnotePutData; + + // Set PUT response + $httpBackend.expectPUT(/purchasercontactnotes\/([0-9a-fA-F]{24})$/).respond(); + + // Run controller functionality + scope.update(); + $httpBackend.flush(); + + // Test URL location to new object + expect($location.path()).toBe('/purchasercontactnotes/' + samplePurchasercontactnotePutData._id); + })); + + it('$scope.remove() should send a DELETE request with a valid purchasercontactnoteId and remove the Purchasercontactnote from the scope', inject(function(Purchasercontactnotes) { + // Create new Purchasercontactnote object + var samplePurchasercontactnote = new Purchasercontactnotes({ + _id: '525a8422f6d0f87f0e407a33' + }); + + // Create new Purchasercontactnotes array and include the Purchasercontactnote + scope.purchasercontactnotes = [samplePurchasercontactnote]; + + // Set expected DELETE response + $httpBackend.expectDELETE(/purchasercontactnotes\/([0-9a-fA-F]{24})$/).respond(204); + + // Run controller functionality + scope.remove(samplePurchasercontactnote); + $httpBackend.flush(); + + // Test array after successful delete + expect(scope.purchasercontactnotes.length).toBe(0); + })); + }); +}()); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069010_PushDemo.js b/pool/shard011/JavaScript/0069010_PushDemo.js new file mode 100644 index 0000000000000000000000000000000000000000..9d6a0e3274dd5433dbbcae657c1751bc41195015 --- /dev/null +++ b/pool/shard011/JavaScript/0069010_PushDemo.js @@ -0,0 +1,170 @@ +/** + * Created by zachary on 2017/2/24. + */ + +import React, { Component } from 'react'; +import { + StyleSheet, + Text, + View, + TouchableOpacity, + DeviceEventEmitter +} from 'react-native'; +import {Actions} from 'react-native-router-flux'; + +import AV from 'leancloud-storage' +import PushNotification from '@zzzkk2009/react-native-leancloud-sdk' + +const KM_Dev = { + appId: 'K5Rltwmfnxd5pYjMsOFFL0kT-gzGzoHsz', + appKey: 'UseC5jvqLT7TIiQWI8nRPmEl', +} + +const KM_PRO = { + appId: 'K5Rltwmfnxd5pYjMsOFFL0kT-gzGzoHsz', + appKey: 'UseC5jvqLT7TIiQWI8nRPmEl', +} +//AV.setProduction(false) +AV.init( + __DEV__ ? KM_Dev : KM_PRO +) +// var Installation = require('leancloud-installation')(AV); + +export default class PushDemo extends Component { + + constructor(props) { + super(props) + this.state = { + deviceToken: '' + } + } + + componentWillMount() { + const that = this + PushNotification.configure({ + + leancloudAppId: KM_Dev.appId, + leancloudAppKey: KM_Dev.appKey, + + // (optional) Called when Token is generated (iOS and Android) + onRegister: function(data) { + console.log( 'DATA:', data ); + that.setState({ + deviceToken: data.token + }) + }, + + // (required) Called when a remote or local notification is opened or received + onNotification: function(notification) { + console.log( 'NOTIFICATION:', notification ); + console.log('DATA:', notification.data) + if(notification.foreground) {//应用程序在前台 + Actions.PushDemoCallback({ + userInfo: notification.data.userInfo + }) + }else { + if(notification.userInteraction) { + //用户点击通知栏消息 + Actions.PushDemoCallback() + }else { + //程序接收到远程或本地通知 + + } + } + }, + + // IOS ONLY (optional): default: all - Permissions to register. + permissions: { + alert: true, + badge: true, + sound: true + }, + + // Should the initial notification be popped automatically + // default: true + popInitialNotification: true, + + /** + * (optional) default: true + * - Specified if permissions (ios) and token (android and ios) will requested or not, + * - if not, you must call PushNotificationsHandler.requestPermissions() later + */ + requestPermissions: true, + }) + + // PushNotification.subscribe(['private']) //订阅频道, + + //注册本地通知action事件 + // PushNotification.registerNotificationActions(['action1', 'action2']) + // DeviceEventEmitter.addListener('notificationActionReceived', function(action){ + // console.log ('Notification action received: ', action); + // const info = JSON.parse(action.dataJSON); + // if (info.action == 'action1') { + // console.log('action1') + // } else if (info.action == 'action2') { + // console.log('action2') + // } + // // Add all the required actions handlers + // }); + + + } + + componentDidMount() { + + } + + componentWillUnmount() { + + } + + push() { + console.log('this.state.deviceToken===', this.state.deviceToken) + var query = new AV.Query('_Installation'); + query.equalTo('installationId', this.state.deviceToken); + AV.Push.send({ + // channels: ['private'], //注册了频道后,可通过设置频道进行推送 + where: query, + data: { + action: 'com.zachary.leancloud.push.action', //自定义推送,不需要设置频道 + alert: '您有新的订单,请及时处理', + title: '邻家优店发来的通知', + userInfo: { + userId: 1, + userName: 'zachary' + } + } + }); + + + //发送本地通知 + // PushNotification.localNotification({ + // message: 'hello localNotification', + // actions: '["action1", "action2"]' //通知按钮,下拉通知出现 + // }) + } + + render() { + return ( + + {this.push()}}> + 推送 + + + {Actions.PushDemoCallback()}}> + goto PushDemoCallback + + + ); + } +} + +const styles = StyleSheet.create({ + container: { + flex: 1, + justifyContent: 'center', + alignItems: 'center', + backgroundColor: '#F5FCFF', + } +}); + diff --git a/pool/shard011/JavaScript/0069011_Polar.js b/pool/shard011/JavaScript/0069011_Polar.js new file mode 100644 index 0000000000000000000000000000000000000000..b4680298854d80cde06189b921b770ea78e8102e --- /dev/null +++ b/pool/shard011/JavaScript/0069011_Polar.js @@ -0,0 +1,246 @@ +/** + * @module echarts/coord/polar/Polar + */ +define(function(require) { + + 'use strict'; + + var RadiusAxis = require('./RadiusAxis'); + var AngleAxis = require('./AngleAxis'); + + /** + * @alias {module:echarts/coord/polar/Polar} + * @constructor + * @param {string} name + */ + var Polar = function (name) { + + /** + * @type {string} + */ + this.name = name || ''; + + /** + * x of polar center + * @type {number} + */ + this.cx = 0; + + /** + * y of polar center + * @type {number} + */ + this.cy = 0; + + /** + * @type {module:echarts/coord/polar/RadiusAxis} + * @private + */ + this._radiusAxis = new RadiusAxis(); + + /** + * @type {module:echarts/coord/polar/AngleAxis} + * @private + */ + this._angleAxis = new AngleAxis(); + + this._radiusAxis.polar = this._angleAxis.polar = this; + }; + + Polar.prototype = { + + type: 'polar', + + axisPointerEnabled: true, + + constructor: Polar, + + /** + * @param {Array.} + * @readOnly + */ + dimensions: ['radius', 'angle'], + + /** + * @type {module:echarts/coord/PolarModel} + */ + model: null, + + /** + * If contain coord + * @param {Array.} point + * @return {boolean} + */ + containPoint: function (point) { + var coord = this.pointToCoord(point); + return this._radiusAxis.contain(coord[0]) + && this._angleAxis.contain(coord[1]); + }, + + /** + * If contain data + * @param {Array.} data + * @return {boolean} + */ + containData: function (data) { + return this._radiusAxis.containData(data[0]) + && this._angleAxis.containData(data[1]); + }, + + /** + * @param {string} dim + * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis} + */ + getAxis: function (dim) { + return this['_' + dim + 'Axis']; + }, + + /** + * @return {Array.} + */ + getAxes: function () { + return [this._radiusAxis, this._angleAxis]; + }, + + /** + * Get axes by type of scale + * @param {string} scaleType + * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis} + */ + getAxesByScale: function (scaleType) { + var axes = []; + var angleAxis = this._angleAxis; + var radiusAxis = this._radiusAxis; + angleAxis.scale.type === scaleType && axes.push(angleAxis); + radiusAxis.scale.type === scaleType && axes.push(radiusAxis); + + return axes; + }, + + /** + * @return {module:echarts/coord/polar/AngleAxis} + */ + getAngleAxis: function () { + return this._angleAxis; + }, + + /** + * @return {module:echarts/coord/polar/RadiusAxis} + */ + getRadiusAxis: function () { + return this._radiusAxis; + }, + + /** + * @param {module:echarts/coord/polar/Axis} + * @return {module:echarts/coord/polar/Axis} + */ + getOtherAxis: function (axis) { + var angleAxis = this._angleAxis; + return axis === angleAxis ? this._radiusAxis : angleAxis; + }, + + /** + * Base axis will be used on stacking. + * + * @return {module:echarts/coord/polar/Axis} + */ + getBaseAxis: function () { + return this.getAxesByScale('ordinal')[0] + || this.getAxesByScale('time')[0] + || this.getAngleAxis(); + }, + + /** + * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined + * @return {Object} {baseAxes: [], otherAxes: []} + */ + getTooltipAxes: function (dim) { + var baseAxis = (dim != null && dim !== 'auto') + ? this.getAxis(dim) : this.getBaseAxis(); + return { + baseAxes: [baseAxis], + otherAxes: [this.getOtherAxis(baseAxis)] + }; + }, + + /** + * Convert a single data item to (x, y) point. + * Parameter data is an array which the first element is radius and the second is angle + * @param {Array.} data + * @param {boolean} [clamp=false] + * @return {Array.} + */ + dataToPoint: function (data, clamp) { + return this.coordToPoint([ + this._radiusAxis.dataToRadius(data[0], clamp), + this._angleAxis.dataToAngle(data[1], clamp) + ]); + }, + + /** + * Convert a (x, y) point to data + * @param {Array.} point + * @param {boolean} [clamp=false] + * @return {Array.} + */ + pointToData: function (point, clamp) { + var coord = this.pointToCoord(point); + return [ + this._radiusAxis.radiusToData(coord[0], clamp), + this._angleAxis.angleToData(coord[1], clamp) + ]; + }, + + /** + * Convert a (x, y) point to (radius, angle) coord + * @param {Array.} point + * @return {Array.} + */ + pointToCoord: function (point) { + var dx = point[0] - this.cx; + var dy = point[1] - this.cy; + var angleAxis = this.getAngleAxis(); + var extent = angleAxis.getExtent(); + var minAngle = Math.min(extent[0], extent[1]); + var maxAngle = Math.max(extent[0], extent[1]); + // Fix fixed extent in polarCreator + // FIXME + angleAxis.inverse + ? (minAngle = maxAngle - 360) + : (maxAngle = minAngle + 360); + + var radius = Math.sqrt(dx * dx + dy * dy); + dx /= radius; + dy /= radius; + + var radian = Math.atan2(-dy, dx) / Math.PI * 180; + + // move to angleExtent + var dir = radian < minAngle ? 1 : -1; + while (radian < minAngle || radian > maxAngle) { + radian += dir * 360; + } + + return [radius, radian]; + }, + + /** + * Convert a (radius, angle) coord to (x, y) point + * @param {Array.} coord + * @return {Array.} + */ + coordToPoint: function (coord) { + var radius = coord[0]; + var radian = coord[1] / 180 * Math.PI; + var x = Math.cos(radian) * radius + this.cx; + // Inverse the y + var y = -Math.sin(radian) * radius + this.cy; + + return [x, y]; + } + + }; + + return Polar; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069013_MslSignatureEnvelope.js b/pool/shard011/JavaScript/0069013_MslSignatureEnvelope.js new file mode 100644 index 0000000000000000000000000000000000000000..3d0dadf0340305b13d802e015db87855ce76a527 --- /dev/null +++ b/pool/shard011/JavaScript/0069013_MslSignatureEnvelope.js @@ -0,0 +1,304 @@ +/** + * Copyright (c) 2013-2015 Netflix, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + *

MSL signature envelopes contain all of the information necessary for + * verifying data using a known key.

+ * + * @author Wesley Miaw + */ +var MslSignatureEnvelope; +var MslSignatureEnvelope$create; +var MslSignatureEnvelope$parse; +var MslSignatureEnvelope$Version; + +(function() { + /** + * JSON key version. + * @const + * @type {string} + */ + var KEY_VERSION = "version"; + /** + * JSON key algorithm. + * @const + * @type {string} + */ + var KEY_ALGORITHM = "algorithm"; + /** + * JSON key signature. + * @const + * @type {string} + */ + var KEY_SIGNATURE = "signature"; + + /** Versions. */ + var Version = MslSignatureEnvelope$Version = { + /** + *

Version 1.

+ * + * {@code signature} + * + *

The signature is represented as raw bytes.

+ */ + V1 : 1, + /** + *

Version 2.

+ * + * {@code { + * "#mandatory" : [ "version", "algorithm", "signature" ], + * "version" : "number", + * "algorithm" : "string", + * "signature" : "base64" + * }} where: + *
    + *
  • {@code version} is the number '2'
  • + *
  • {@code algorithm} is one of the recognized signature algorithms
  • + *
  • {@code signature} is the Base64-encoded signature
  • + *
+ * + *

Supported algorithms: + * + * + * + * + * + *
AlgorithmDescription
HmacSHA256HMAC w/SHA-256
SHA256withRSARSA signature w/SHA-256
AESCmacAES CMAC

+ */ + V2 : 2, + }; + + MslSignatureEnvelope = util.Class.create({ + /** + * Create a new signature envelope with the provided data. + * + * @param {Version} version the envelope version. + * @param {?MslConstants$SignatureAlgo} algorithm the signature algorithm. May be null. + * @param {Uint8Array} signature the signature. + */ + init: function init(version, algorithm, signature) { + // Create the byte representation. + var bytes; + switch (version) { + case Version.V1: + bytes = signature; + break; + case Version.V2: + var jsonObj = {}; + jsonObj[KEY_VERSION] = version; + jsonObj[KEY_ALGORITHM] = algorithm; + jsonObj[KEY_SIGNATURE] = base64$encode(signature); + bytes = textEncoding$getBytes(JSON.stringify(jsonObj), MslConstants$DEFAULT_CHARSET); + break; + default: + throw new MslInternalException("Signature envelope version " + version + " encoding unsupported."); + } + + // The properties. + var props = { + version: { value: version, writable: false, enumerable: false, configurable: false }, + algorithm: { value: algorithm, writable: false, configurable: false }, + signature: { value: signature, writable: false, configurable: false }, + bytes: { value: bytes, writable: false, configurable: false }, + }; + Object.defineProperties(this, props); + } + }); + + /** + *

This method has two acceptable parameter lists.

+ * + *

The first form creates a version 1 signature envelope.

+ * + * @param {Uint8Array} signature the signature. + * @param {{result: function(MslSignatureEnvelope), error: function(Error)}} + * callback the callback functions that will receive the envelope + * or any thrown exceptions. + * + *

The second form creates a version 2 signature envelope.

+ * + * @param {MslConstants$SignatureAlgo} algorithm the signature algorithm. + * @param {Uint8Array} signature the signature. + * @param {{result: function(MslSignatureEnvelope), error: function(Error)}} + * callback the callback functions that will receive the envelope + * or any thrown exceptions. + */ + MslSignatureEnvelope$create = function MslSignatureEnvelope$create(/* variable arguments */) { + var version, + signature, + algorithm, + callback; + + // Handle the first form. + if (arguments.length == 2) { + version = Version.V1; + signature = arguments[0]; + algorithm = null; + callback = arguments[1]; + } + + // Handle the second form. + else if (arguments.length == 3) { + version = Version.V2; + algorithm = arguments[0]; + signature = arguments[1]; + callback = arguments[2]; + } + + // Malformed arguments are not explicitly handled, just as with any + // other function. + + AsyncExecutor(callback, function() { + return new MslSignatureEnvelope(version, algorithm, signature); + }); + }; + + /** + * Create a new signature envelope from the provided envelope bytes. If a + * signature version is provided then the JSON object is parsed accordingly. + * + * @param {Uint8Array} envelope the raw envelope bytes. + * @param {?MslSignatureEnvelope$Version} version the envelope version. + * May be null. + * @param {{result: function(MslSignatureEnvelope), error: function(Error)}} + * callback the callback functions that will receive the envelope + * or any thrown exceptions. + * @throws MslCryptoException if there is an error processing the signature + * envelope. + * @throws MslEncodingException if there is an error parsing the JSON. + * @see #getBytes() + */ + MslSignatureEnvelope$parse = function MslSignatureEnvelope$parse(envelope, version, callback) { + AsyncExecutor(callback, function() { + if (version) { + switch (version) { + case Version.V1: + return new MslSignatureEnvelope(Version.V1, null, envelope); + case Version.V2: + try { + // We expect the byte representation to be a JSON string. + var json = textEncoding$getString(envelope, MslConstants$DEFAULT_CHARSET); + var envelopeJo = JSON.parse(json); + + // Extract values. + var v = parseInt(envelopeJo[KEY_VERSION]), + algorithmName = envelopeJo[KEY_ALGORITHM], + signatureB64 = envelopeJo[KEY_SIGNATURE]; + if (typeof v !== 'number' || v != v || + typeof algorithmName !== 'string' || + typeof signatureB64 !== 'string') + { + throw new MslEncodingException(MslError.JSON_PARSE_ERROR, "signature envelope " + base64$encode(envelope)); + } + + // Verify version. + if (Version.V2 != v) + throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + base64$encode(envelope)); + + // Grab algorithm. + var algorithm = MslConstants$SignatureAlgo$fromString(algorithmName); + if (!algorithm) + throw new MslCryptoException(MslError.UNIDENTIFIED_ALGORITHM, "signature envelope " + base64$encode(envelope)); + + // Grab signature. + var signature = base64$decode(signatureB64); + if (!signature) + throw new MslCryptoException(MslError.INVALID_SIGNATURE, "signature envelope " + base64$encode(envelope)); + + // Return the envelope. + return new MslSignatureEnvelope(Version.V2, algorithm, signature); + } catch (e) { + if (e instanceof SyntaxError) + throw new MslEncodingException(MslError.JSON_PARSE_ERROR, "signature envelope " + base64$encode(envelope), e); + throw e; + } + default: + throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + base64$encode(envelope)); + } + } + + // Attempt to convert this to a JSON object. + var envelopeJo; + try { + // If this is a JSON object, we expect the byte representation to + // be a Base64-encoding of the JSON string. + var json = textEncoding$getString(envelope, MslConstants$DEFAULT_CHARSET); + envelopeJo = JSON.parse(json); + } catch (e) { + envelopeJo = null; + } + + // Determine the envelope version. + // + // If there is no JSON object, or there is no version field (as the + // binary signature may coincidentally parse into JSON), then this is a + // version 1 envelope. + var envelopeVersion; + if (!envelopeJo || !envelopeJo[KEY_VERSION]) { + envelopeVersion = Version.V1; + } else { + envelopeVersion = envelopeJo[KEY_VERSION]; + if (typeof envelopeVersion !== 'number' || envelopeVersion !== envelopeVersion) { + // There is a possibility that this is a version 1 envelope. + envelopeVersion = Version.V1; + } + } + + // Parse envelope. + switch (envelopeVersion) { + case Version.V1: + return new MslSignatureEnvelope(envelopeVersion, null, envelope); + case Version.V2: + // Extract envelope data. + var algorithm = envelopeJo[KEY_ALGORITHM]; + var signatureB64 = envelopeJo[KEY_SIGNATURE]; + + // Verify data. + if (typeof algorithm !== 'string' || + typeof signatureB64 !== 'string') + { + // It is extremely unlikely but possible that this is a + // version 1 envelope. + return new MslSignatureEnvelope(Version.V1, null, envelope); + } + + // Verify algorithm. + algorithm = MslConstants$SignatureAlgo$fromString(algorithm); + if (!algorithm) { + // It is extremely unlikely but possible that this is a + // version 1 envelope. + return new MslSignatureEnvelope(Version.V1, null, envelope); + } + + // If the signature fails to decode then it is extremely + // unlikely but possible that this is a version 1 envelope. + // + // A zero-length signature is OK and does not indicate an + // error. + try { + signature = base64$decode(signatureB64); + } catch (e) { + return new MslSignatureEnvelope(Version.V1, null, envelope); + } + + // Return the version 2 envelope. + return new MslSignatureEnvelope(envelopeVersion, algorithm, signature); + default: + throw new MslCryptoException(MslError.UNSUPPORTED_SIGNATURE_ENVELOPE, "signature envelope " + envelope); + } + }); + }; +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069014_HintUtils.js b/pool/shard011/JavaScript/0069014_HintUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..c8d181ff746e611e21112e47d847b594abdb386a --- /dev/null +++ b/pool/shard011/JavaScript/0069014_HintUtils.js @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2013 Adobe Systems Incorporated. All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + */ + +/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */ +/*global define */ + +define(function (require, exports, module) { + "use strict"; + + var acorn = require("thirdparty/acorn/acorn"); + + var LANGUAGE_ID = "javascript", + HTML_LANGUAGE_ID = "html", + SUPPORTED_LANGUAGES = [LANGUAGE_ID, HTML_LANGUAGE_ID], + SINGLE_QUOTE = "'", + DOUBLE_QUOTE = "\""; + + /** + * Create a hint token with name value that occurs at the given list of + * positions. + * + * @param {string} value - name of the new hint token + * @param {?Array.=} positions - optional list of positions at which + * the token occurs + * @return {Object} - a new hint token + */ + function makeToken(value, positions) { + positions = positions || []; + + return { + value: value, + positions: positions + }; + } + + /** + * Is the string key perhaps a valid JavaScript identifier? + * + * @param {string} key - string to test. + * @return {boolean} - could key be a valid identifier? + */ + function maybeIdentifier(key) { + var result = false, + i; + + for (i = 0; i < key.length; i++) { + result = acorn.isIdentifierChar(key.charCodeAt(i)); + if (!result) { + break; + } + } + + return result; + } + + /** + * Is the token's class hintable? (A very conservative test.) + * + * @param {Object} token - the token to test for hintability + * @return {boolean} - could the token be hintable? + */ + function hintable(token) { + switch (token.type) { + case "comment": + case "number": + case "regexp": + // exclude variable & param decls + case "def": + return false; + default: + return true; + } + } + + /** + * Determine if hints should be displayed for the given key. + * + * @param {string} key - key entered by the user + * @return {boolean} true if the hints should be shown for the key, + * false otherwise. + */ + function hintableKey(key) { + return (key === null || key === "." || maybeIdentifier(key)); + } + + /** + * Divide a path into directory and filename parts + * + * @param {string} path - a URI with directories separated by / + * @return {{dir: string, file: string}} - a pair of strings that + * correspond to the directory and filename of the given path. + */ + function splitPath(path) { + var index = path.lastIndexOf("/"), + dir = (index === -1) ? "" : path.substring(0, index), + file = path.substring(index + 1, path.length); + + return {dir: dir, file: file }; + } + + /* + * Get a JS-hints-specific event name. Used to prevent event namespace + * pollution. + * + * @param {string} name - the unqualified event name + * @return {string} - the qualified event name + */ + function eventName(name) { + var EVENT_TAG = "brackets-js-hints"; + return name + "." + EVENT_TAG; + } + + /* + * Annotate a list of tokens as literals of a particular kind; + * if string literals, annotate with an appropriate delimiter. + * + * @param {Array.} literals - list of hint tokens + * @param {string} kind - the kind of literals in the list (e.g., "string") + * @return {Array.} - the input array; to each object in the array a + * new literal {boolean} property has been added to indicate that it + * is a literal hint, and also a new kind {string} property to indicate + * the literal kind. For string literals, a delimiter property is also + * added to indicate what the default delimiter should be (viz. a + * single or double quotation mark). + */ + function annotateLiterals(literals, kind) { + return literals.map(function (t) { + t.literal = true; + t.kind = kind; + t.origin = "ecma5"; + if (kind === "string") { + if (/[\\\\]*[^\\]"/.test(t.value)) { + t.delimiter = SINGLE_QUOTE; + } else { + t.delimiter = DOUBLE_QUOTE; + } + } + return t; + }); + } + + /* + * Annotate a list of tokens as keywords + * + * @param {Array.} keyword - list of keyword tokens + * @return {Array.} - the input array; to each object in the array a + * new keyword {boolean} property has been added to indicate that the + * hint is a keyword. + */ + function annotateKeywords(keywords) { + return keywords.map(function (t) { + t.keyword = true; + t.origin = "ecma5"; + return t; + }); + } + + function isSupportedLanguage(languageId) { + return SUPPORTED_LANGUAGES.indexOf(languageId) !== -1; + } + + var KEYWORD_NAMES = [ + "break", "case", "catch", "continue", "debugger", "default", "delete", + "do", "else", "finally", "for", "function", "if", "in", "instanceof", + "new", "return", "switch", "this", "throw", "try", "typeof", "var", + "void", "while", "with" + ], + KEYWORD_TOKENS = KEYWORD_NAMES.map(function (t) { + return makeToken(t, []); + }), + KEYWORDS = annotateKeywords(KEYWORD_TOKENS); + + var LITERAL_NAMES = [ + "true", "false", "null" + ], + LITERAL_TOKENS = LITERAL_NAMES.map(function (t) { + return makeToken(t, []); + }), + LITERALS = annotateLiterals(LITERAL_TOKENS); + + exports.makeToken = makeToken; + exports.hintable = hintable; + exports.hintableKey = hintableKey; + exports.maybeIdentifier = maybeIdentifier; + exports.splitPath = splitPath; + exports.eventName = eventName; + exports.annotateLiterals = annotateLiterals; + exports.isSupportedLanguage = isSupportedLanguage; + exports.KEYWORDS = KEYWORDS; + exports.LITERALS = LITERALS; + exports.LANGUAGE_ID = LANGUAGE_ID; + exports.SINGLE_QUOTE = SINGLE_QUOTE; + exports.DOUBLE_QUOTE = DOUBLE_QUOTE; + exports.SUPPORTED_LANGUAGES = SUPPORTED_LANGUAGES; +}); diff --git a/pool/shard011/JavaScript/0069017_produto.js b/pool/shard011/JavaScript/0069017_produto.js new file mode 100644 index 0000000000000000000000000000000000000000..73c30bbe9346f4ed1f83cd4bdaa551b0ba0ede8e --- /dev/null +++ b/pool/shard011/JavaScript/0069017_produto.js @@ -0,0 +1,81 @@ +'use strict' +const Model = require('../../database/db.js').model +const Valor = Model.Valor +const Estabelecimento = Model.Estabelecimento +const Produto = Model.Produto +const Marca = Model.Marca +const express = require('express') +const produto = express.Router() +const error = require('../error-handling.js') + +/** + * + * + * + */ +produto.get('/', (req, res)=>{ + // recebe par de coordenadas por query + // retorna valores dos produtos nos estabelecimentos próximos +}) + +/** + * + * + * + */ +produto.get('/id/:id', (req, res)=>{ + //recebe id + //retorna detalhes de produto +}) + +/** + * + * + * + */ +produto.get('/:estabelecimento', (req, res)=>{ + // recebe estabelecimento + // retorna este produto de várias marcas com seus valores +}) + +/** + * + * + * + */ +produto.get('/:marca', (req, res)=>{ + // recebe marca e par de coordenadas + // retorna valor médio para este produto nos estabelecimentos próximos +}) + +/** + * + * + * + */ +produto.post('/', (req, res)=>{ + // recebe dados do produto e registra no banco + // retorna id e createdAt +}) + +/** + * + * + * + */ +produto.put('/:id', (req, res)=>{ + // recebe id de produto e corpo com dados a substituir + // retorna id e updatedAt +}) + +/** + * + * + * + */ +produto.delete('/:id', (req, res)=>{ + // recebe id e destrói registro de produto + // retorna id e destroyedAt +}) + +module.exports = produto diff --git a/pool/shard011/JavaScript/0069020_Pagination.js b/pool/shard011/JavaScript/0069020_Pagination.js new file mode 100644 index 0000000000000000000000000000000000000000..c1fabe661922aaef8a652292920034fc61d781ab --- /dev/null +++ b/pool/shard011/JavaScript/0069020_Pagination.js @@ -0,0 +1,28 @@ +const objectAssign = require('object-assign') + +function Pagination(paging, options, fetcher) { + this.currentPage = paging.currentPage + this.pageSize = paging.pageSize + this.totalPages = paging.totalPages + this.totalResults = paging.totalResults + this.hasNext = paging.currentPage < this.totalPages + this.hasPrevious = paging.currentPage > 0 + this.sort = paging.sort + + this.fetcher = fetcher + this.options = options +} + +Pagination.prototype.next = function () { + return this.fetcher( + objectAssign({}, this.options, {page: this.options.page + 1}) + ) +} + +Pagination.prototype.previous = function () { + return this.fetcher( + objectAssign({}, this.options, {page: Math.max(0, this.options.page - 1)}) + ) +} + +module.exports = Pagination diff --git a/pool/shard011/JavaScript/0069021_associationsmanager.js b/pool/shard011/JavaScript/0069021_associationsmanager.js new file mode 100644 index 0000000000000000000000000000000000000000..4b50b9c1863d6468d246d57d768ee17dc08f7542 --- /dev/null +++ b/pool/shard011/JavaScript/0069021_associationsmanager.js @@ -0,0 +1,188 @@ +/** + * Copyright reelyActive 2015-2022 + * We believe in an open Internet of Things + */ + + +const HTTP_STATUS_OK = 200; +const HTTP_STATUS_CREATED = 201; +const HTTP_STATUS_BAD_REQUEST = 400; +const HTTP_STATUS_NOT_FOUND = 404; + + +/** + * AssociationsManager Class + * Manages the association of wireless identifiers with metadata. + */ +class AssociationsManager { + + /** + * AssociationsManager constructor + * @param {Object} options The options as a JSON object. + * @param {DatabaseManager} database The database manager. + * @constructor + */ + constructor(options, database) { + options = options || {}; + + this.database = database; + } + + /** + * Retrieve an existing association. + * @param {String} id The id of the device association. + * @param {String} type The type of id of the device association. + * @param {String} property A specific association property to get. + * @param {callback} callback Function to call on completion. + */ + retrieve(id, type, property, callback) { + let isSpecificAssociation = (id && type); + + if(isSpecificAssociation) { + let key = id + '/' + type; + + this.database.get(key, function(err, association) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else if(association === undefined) { + return callback(HTTP_STATUS_NOT_FOUND); + } + else if(property) { + let data = { associations: {} }; + data.associations[key] = {}; + data.associations[key][property] = association[property]; + return callback(HTTP_STATUS_OK, data); + } + else { + let data = { associations: {} }; + data.associations[key] = association; + return callback(HTTP_STATUS_OK, data); + } + }); + } + else { + let query = {}; + + this.database.find(query, function(err, result) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else { + let associations = {}; + for(let key of result.keys()) { + associations[key] = {}; + } + return callback(HTTP_STATUS_OK, { associations: associations }); + } + }); + } + } + + /** + * Create/replace an association. + * @param {String} id The id of the device association. + * @param {String} type The type of id of the device association. + * @param {String} url The URL associated with the device. + * @param {String} directory The directory associated with the device. + * @param {Array} tags The tags associated with the device. + * @param {Array} position The position associated with the device. + * @param {callback} callback Function to call on completion. + */ + replace(id, type, url, directory, tags, position, callback) { + let self = this; + let key = id + '/' + type; + + this.database.get(key, function(err, association) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + + let isPresent = (association !== undefined); + association = association || {}; + + if(url && (typeof url === 'string')) { + association.url = url; + } + if(directory && (typeof directory === 'string')) { + association.directory = directory; + } + if(tags && Array.isArray(tags)) { + association.tags = tags; + } + if(position && Array.isArray(position)) { + association.position = position; + } + + self.database.set(key, association, function(err) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else { + let status = (isPresent ? HTTP_STATUS_OK : HTTP_STATUS_CREATED); + let data = { associations: {} }; + data.associations[key] = association; + + return callback(status, data); + } + }); + }); + } + + /** + * Remove an existing association. + * @param {String} id The id of the device association. + * @param {String} type The type of id of the device association. + * @param {String} property A specific association property to remove. + * @param {callback} callback Function to call on completion. + */ + remove(id, type, property, callback) { + let self = this; + let key = id + '/' + type; + + // Delete only a single property + if(property) { + this.database.get(key, function(err, association) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else if((association === undefined) || + !association.hasOwnProperty(property)) { + return callback(HTTP_STATUS_NOT_FOUND); + } + + delete association[property]; + + self.database.set(key, association, function(err) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else { + let data = { associations: {} }; + data.associations[key] = association; + return callback(HTTP_STATUS_OK, { associations: association }); + } + }); + }); + } + + // Delete the entire association + else { + this.database.delete(key, function(err, isRemoved) { + if(err) { + return callback(HTTP_STATUS_BAD_REQUEST); + } + else if(!isRemoved) { + return callback(HTTP_STATUS_NOT_FOUND); + } + else { + return callback(HTTP_STATUS_OK); + } + }); + } + } + +} + + +module.exports = AssociationsManager; diff --git a/pool/shard011/JavaScript/0069025_binding.js b/pool/shard011/JavaScript/0069025_binding.js new file mode 100644 index 0000000000000000000000000000000000000000..2935794ec9d2960d4ed16506f157f2a7a59da17a --- /dev/null +++ b/pool/shard011/JavaScript/0069025_binding.js @@ -0,0 +1,109 @@ +$.fn.binding = function(dfg){ + this.dfg = $.extend({ + data:{} + },dfg); + var _binding = function(_self){ + this.ele = $(_self[0]); + this.self = _self; + this.data = _self.dfg.data; + this.init(); + }; + /*插件初始化*/ + _binding.prototype.init = function(){ + this.resolveHtml(); + this.resolveEle(); + this.bindTextAndEvent(); + this.modelInit(); + } + /*解析HTML模版*/ + _binding.prototype.resolveHtml = function(){ + let html = $(this.ele).html(), + reg = new RegExp('{{(.*?)}}','gim'), + m = html.match(reg); + if(m&&m.length>0){ + m.forEach(function(item,i){ + html = html.replace(item,''); + }) + $(this.ele).html(html); + } + } + /*处理绑定的元素*/ + _binding.prototype.resolveEle = function(){ + let map = {}, + that = this, + eles = Array.from($(this.ele).find('[b-text],[b-html],[b-model]')); + eles.forEach(function(item,i){ + let key = $(item).attr('b-text')||$(item).attr('b-html')||$(item).attr('b-model'); + if(!map[key]){ + map[key] = { + value:that['data'][key], + ele:[item] + } + }else{ + map[key].ele.push(item); + } + }) + this.map = map; + } + /*text文本类型的绑定*/ + _binding.prototype.bindTextAndEvent = function(){ + for(let i in this.map){ + this.set(i,this.map[i]); + } + } + /*model的双向绑定*/ + _binding.prototype.modelInit = function(){ + let eles = Array.from($(this.ele).find('[b-model]')), + that = this; + eles.forEach(function(item,i){ + if($(item).attr('type')=='radio'||$(item).attr('type')=='checkbox'){ + $(item).on('change',function(){ + that.changeEvent($(item),$(item).attr('b-model')) + }) + }else{ + $(item).on('keyup',function(){ + that.keyupEvent($(item),$(item).attr('b-model')) + }) + } + }) + } + /*input的keyup事件*/ + _binding.prototype.keyupEvent=function(input,key){ + this[key]=input.val() + } + /*input radio checkbox的change事件*/ + _binding.prototype.changeEvent=function(input,key){ + this[key]=input.prop('checked'); + } + /*利用defineProperty这个属性设计set和get*/ + _binding.prototype.set = function(key,val){ + let that = this; + Object.defineProperty(this, key, { + get:function(){ + return val.value + }, + set:function(newValue){ + val.value = newValue; + val.ele.forEach(function(item,i){ + that.setText(item,val.value) + }) + } + }) + this[key] = val.value; + } + /*改变页面上的值*/ + _binding.prototype.setText = function(ele,value){ + ele = $(ele); + if(ele[0].tagName=='INPUT'){ + if(ele.attr('type')=='radio'||ele.attr('type')=='checkbox'){ + ele.prop('checked',value); + }else{ + ele.val(value) + } + }else{ + ele[ele.attr('b-text')?'text':'html'](value); + } + + } + return new _binding(this); +} diff --git a/pool/shard011/JavaScript/0069026_globalSourceConfigUtil-spec.js b/pool/shard011/JavaScript/0069026_globalSourceConfigUtil-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..d8f9722d40819b4c6cf4a3c2e9e2af6e05a06b2e --- /dev/null +++ b/pool/shard011/JavaScript/0069026_globalSourceConfigUtil-spec.js @@ -0,0 +1,103 @@ +/* + * Copyright (C) 2017-2019 Dremio Corporation + * + * 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. + */ + +import { cloneDeep } from 'lodash'; +import addAlwaysPresent, { + crossSourceSelectionUiConfig, + getAlwaysPresentFunctionalConfig, + inlineMetadataRefreshConfig +} from './globalSourceConfigUtil'; + +describe('globalSourceConfigUtil', () => { + + const defaultFunctionalConfig = { + elements: [] + }; + + const defaultUiConfig = { + form: { + tabs: [ + { + name: 'General' + }, + { + name: 'Advanced', + sections: [{ + elements: [{ + propName: 'config.allowCreateDrop' + }] + }] + } + ] + } + }; + + it('adds always present config to functional config and ui config', () => { + const functionalConfig = cloneDeep(defaultFunctionalConfig); + const uiConfig = cloneDeep(defaultUiConfig); + + const expectedFunctionalConfig = { + ...functionalConfig, + elements: [ + ...functionalConfig.elements, + ...getAlwaysPresentFunctionalConfig() + ] + }; + + const expectedUiConfig = cloneDeep(uiConfig); + expectedUiConfig.form.tabs[1].sections[0].elements.push(crossSourceSelectionUiConfig, inlineMetadataRefreshConfig); + addAlwaysPresent(functionalConfig, uiConfig); + expect(functionalConfig).to.deep.equal(expectedFunctionalConfig); + expect(uiConfig).to.deep.equal(expectedUiConfig); + }); + + it('handles case where there are no elements in advanced tab', () => { + const functionalConfig = cloneDeep(defaultFunctionalConfig); + const uiConfig = { + form: { + tabs: [ + { + name: 'General' + }, + { + name: 'Advanced' + } + ] + } + }; + + const expectedFunctionalConfig = { + ...functionalConfig, + elements: [ + ...functionalConfig.elements, + ...getAlwaysPresentFunctionalConfig() + ] + }; + + const expectedUiConfig = cloneDeep(uiConfig); + expectedUiConfig.form.tabs[1].sections = [ + { + elements: [ + crossSourceSelectionUiConfig, + inlineMetadataRefreshConfig + ] + } + ]; + addAlwaysPresent(functionalConfig, uiConfig); + expect(functionalConfig).to.deep.equal(expectedFunctionalConfig); + expect(uiConfig).to.deep.equal(expectedUiConfig); + }); +}); diff --git a/pool/shard011/JavaScript/0069027_copy.js b/pool/shard011/JavaScript/0069027_copy.js new file mode 100644 index 0000000000000000000000000000000000000000..dc52f42616a3f19de5e47237a7c11bf6f3e2f7d3 --- /dev/null +++ b/pool/shard011/JavaScript/0069027_copy.js @@ -0,0 +1,14 @@ +'use strict'; + +const path = require('path'); +const gulp = require('gulp'); +const $ = require('gulp-load-plugins')(); +const cfg = require('config'); + +const copy = cfg.copy.map(folder => path.join(cfg.root.src, folder, '/**/*')); + +gulp.task('copy', () => ( + gulp.src(copy) + .pipe($.changed(cfg.root.dest)) + .pipe(gulp.dest(cfg.root.dest)) +)); diff --git a/pool/shard011/JavaScript/0069028_menus.js b/pool/shard011/JavaScript/0069028_menus.js new file mode 100644 index 0000000000000000000000000000000000000000..5c1d67ba8141a5a5c4518c2d73048a31bab1ecec --- /dev/null +++ b/pool/shard011/JavaScript/0069028_menus.js @@ -0,0 +1,156 @@ +import { Menu, MenuItem, clipboard } from 'electron'; + +export function createAppMenu(app, mainWindow, appSettings) { + const appMenu = new Menu(); + + // add MacOS app menu + if (process.platform === 'darwin') { + const quitMenuItem = new MenuItem({ + role: 'quit', + }); + + appMenu.append( + new MenuItem({ + label: app.getName(), + submenu: [quitMenuItem], + }), + ); + + appMenu.append( + new MenuItem({ + label: 'Edit', + submenu: [ + { + role: 'undo', + }, + { + role: 'redo', + }, + { + type: 'separator', + }, + { + role: 'cut', + }, + { + role: 'copy', + }, + { + role: 'paste', + }, + { + role: 'delete', + }, + { + role: 'selectall', + }, + ], + }), + ); + } + + appMenu.append( + new MenuItem({ + label: 'Share', + submenu: [ + new MenuItem({ + label: 'Copy location', + accelerator: 'Ctrl + Alt + C', + click: () => clipboard.writeText(mainWindow.webContents.getURL()), + }), + ], + }), + ); + + const groupMessagesPlaySoundMenuItem = new MenuItem({ + type: 'checkbox', + label: 'Play sound', + checked: appSettings.isGroupNotificationSoundEnabled(), + enabled: appSettings.isGroupNotificationsEnabled(), + click: () => appSettings.toggleGroupNotificationSoundEnabled(), + }); + const groupMessagesFlashTrayMenuItem = new MenuItem({ + type: 'checkbox', + label: 'Taskbar notice', + checked: appSettings.isGroupFlashTaskbarEnabled(), + enabled: appSettings.isGroupNotificationsEnabled(), + click: () => appSettings.toggleGroupFlashTaskbarEnabled(), + }); + const groupMessagesShowNotificationMenuItem = new MenuItem({ + type: 'checkbox', + label: 'Show notification', + checked: appSettings.isGroupNotificationsEnabled(), + click: () => { + appSettings.toggleGroupNotificationsEnabled(); + groupMessagesPlaySoundMenuItem.enabled = appSettings.isGroupNotificationsEnabled(); + groupMessagesFlashTrayMenuItem.enabled = appSettings.isGroupNotificationsEnabled(); + }, + }); + const groupMessagesMenuItem = new MenuItem({ + label: 'Group messages', + submenu: [ + groupMessagesShowNotificationMenuItem, + groupMessagesFlashTrayMenuItem, + groupMessagesPlaySoundMenuItem, + ], + }); + + const directMessagesPlaySoundMenuItem = new MenuItem({ + type: 'checkbox', + label: 'Play sound', + checked: appSettings.isDirectNotificationSoundEnabled(), + enabled: appSettings.isDirectNotificationsEnabled(), + click: () => appSettings.toggleDirectNotificationSoundEnabled(), + }); + const directMessagesFlashTrayItem = new MenuItem({ + type: 'checkbox', + label: 'Taskbar notice', + checked: appSettings.isDirectFlashTaskbarEnabled(), + enabled: appSettings.isDirectNotificationsEnabled(), + click: () => appSettings.toggleDirectFlashTaskbarEnabled(), + }); + const directMessagesShowNotificationMenuItem = new MenuItem({ + type: 'checkbox', + label: 'Show notification', + checked: appSettings.isDirectNotificationsEnabled(), + click: () => { + appSettings.toggleDirectNotificationsEnabled(); + directMessagesPlaySoundMenuItem.enabled = appSettings.isDirectNotificationsEnabled(); + directMessagesFlashTrayItem.enabled = appSettings.isDirectNotificationsEnabled(); + }, + }); + const directMessagesMenuItem = new MenuItem({ + label: 'Direct messages', + submenu: [ + directMessagesShowNotificationMenuItem, + directMessagesFlashTrayItem, + directMessagesPlaySoundMenuItem, + ], + }); + + appMenu.append( + new MenuItem({ + label: 'Settings', + submenu: [groupMessagesMenuItem, directMessagesMenuItem], + }), + ); + + return appMenu; +} + +export const selectionMenu = Menu.buildFromTemplate([ + { role: 'copy' }, + { type: 'separator' }, + { role: 'selectall' }, +]); + +export const inputMenu = Menu.buildFromTemplate([ + { role: 'undo' }, + { role: 'redo' }, + { type: 'separator' }, + { role: 'cut' }, + { role: 'copy' }, + { role: 'paste' }, + { type: 'separator' }, + { role: 'selectall' }, +]); diff --git a/pool/shard011/JavaScript/0069032_sshpair.js b/pool/shard011/JavaScript/0069032_sshpair.js new file mode 100644 index 0000000000000000000000000000000000000000..51a535f4ac079a687dc0c0923364c3c8cca51ea4 --- /dev/null +++ b/pool/shard011/JavaScript/0069032_sshpair.js @@ -0,0 +1,44 @@ +#!/usr/bin/env node + +(function() { + 'use strict'; + + require('terminal-colors'); + + var cp = require('child_process'), + ssh = require('ssh-client'), + host = process.argv[2]; + + function help() { + var pkg = require('./package'); + console.log('# sshpair (sshync', pkg.version + ')'); + console.log('# by', pkg.author, '\n'); + console.log('sshpair '); + process.exit(); + } + + if(!host || host.indexOf('@') === -1) + help(); + + host = host.split('@'); + var host_ip = host.pop(), + host_user = host.pop(); + + cp.exec('echo -e "y\n" | ssh-keygen -q -N "" -f ~/.ssh/id_rsa', () => {}); + console.log('generated ssh key to', '~/.ssh/id_rsa.pub'.blue); + + var client = ssh(host_user, host_ip, () => { + client.exec('mkdir -p ~/.ssh', (error, stdout, stderr) => { + if (error) + throw error; + + client.putFile('~/.ssh/id_rsa.pub', '~/.ssh/authorized_keys', (error, stdout, stderr) => { + if (error) + throw error; + + console.log('~/.ssh/id_rsa.pub'.blue, '=>', '~/.ssh/authorized_keys'.green); + process.exit(); + }); + }); + }); +}()); diff --git a/pool/shard011/JavaScript/0069033_edit-image.controller.spec.js b/pool/shard011/JavaScript/0069033_edit-image.controller.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..38ab9e16dd5135255bc3707f9744836eb906ab58 --- /dev/null +++ b/pool/shard011/JavaScript/0069033_edit-image.controller.spec.js @@ -0,0 +1,169 @@ +/** + * (c) Copyright 2016 Hewlett-Packard Development Company, L.P. + * + * 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. + */ + +(function() { + 'use strict'; + + describe('horizon.app.core.images edit image controller', function() { + + var controller, $scope, events, $q, settingsCall, $timeout; + + /////////////////////// + + beforeEach(module('horizon.framework')); + + beforeEach(module('horizon.app.core')); + beforeEach(module('horizon.app.core.images')); + + beforeEach(inject(function ($injector, _$rootScope_, _$q_, _$timeout_) { + $scope = _$rootScope_.$new(); + $q = _$q_; + $timeout = _$timeout_; + + events = $injector.get('horizon.app.core.images.events'); + controller = $injector.get('$controller'); + })); + + function createController() { + var settings = { + getSettings: function() { + settingsCall = $q.defer(); + return settingsCall.promise; + } + }; + return controller('horizon.app.core.images.steps.EditImageController as ctrl', { + $scope: $scope, + events: events, + 'horizon.app.core.openstack-service-api.settings': settings + }); + } + + function setImagePromise(image) { + var deferred = $q.defer(); + deferred.resolve({data: image}); + $scope.imagePromise = deferred.promise; + } + + it('should have options for visibility and protected', function() { + setImagePromise({id: '1', container_format: 'bare', is_public: false, properties: []}); + var ctrl = createController(); + + expect(ctrl.imageVisibilityOptions.length).toEqual(2); + expect(ctrl.imageProtectedOptions.length).toEqual(2); + }); + + it('should map is_public', function() { + setImagePromise({id: '1', container_format: 'bare', is_public: false, properties: []}); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image.visibility).toEqual('private'); + }); + + it('reads the data format settings', function() { + setImagePromise({id: '1', container_format: 'bare', is_public: false, properties: []}); + var ctrl = createController(); + settingsCall.resolve({OPENSTACK_IMAGE_FORMATS: ['aki', 'ami']}); + $timeout.flush(); + expect(ctrl.imageFormats.aki).toBeDefined(); + expect(ctrl.imageFormats.ami).toBeDefined(); + expect(Object.keys(ctrl.imageFormats).length).toBe(2); + }); + + it('should initialize image values correctly', function() { + setImagePromise({ + id: '1', + container_format: 'bare', + disk_format: 'ova', + is_public: true, + properties: [] + }); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image.disk_format).toEqual('ova'); + expect(ctrl.image.visibility).toEqual('public'); + }); + + it('should set local image_format to docker when container is docker', function() { + setImagePromise({id: '1', disk_format: 'raw', container_format: 'docker', + is_public: false, properties: []}); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image_format).toEqual('docker'); + }); + + it('should set container to aki when disk format is same', function() { + setImagePromise({id: '1', disk_format: 'aki', container_format: '', + is_public: false, properties: []}); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image.container_format).toEqual('aki'); + }); + + it('should set container to ami when disk format is same', function() { + setImagePromise({id: '1', disk_format: 'ami', container_format: '', + is_public: false, properties: []}); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image.container_format).toEqual('ami'); + }); + + it('should set container to ari when disk format is same', function() { + setImagePromise({id: '1', disk_format: 'ari', container_format: '', + is_public: false, properties: []}); + var ctrl = createController(); + $timeout.flush(); + + expect(ctrl.image.container_format).toEqual('ari'); + }); + + it('should emit events on image change', function() { + spyOn($scope, '$emit').and.callThrough(); + + setImagePromise({id: '1', container_format: 'bare', properties: []}); + var ctrl = createController(); + ctrl.image = 1; + $scope.$apply(); + + ctrl.image = 2; + $scope.$apply(); + + expect($scope.$emit).toHaveBeenCalledWith('horizon.app.core.images.IMAGE_CHANGED', 2); + }); + + it("should destroy the image changed watcher when the controller is destroyed", function() { + setImagePromise({id: '1', container_format: 'bare', properties: []}); + spyOn($scope, '$emit').and.callThrough(); + + var ctrl = createController(); + ctrl.image = 1; + $scope.$apply(); + + $scope.$emit("$destroy"); + $scope.$emit.calls.reset(); + + ctrl.image = 2; + $scope.$apply(); + + expect($scope.$emit).not.toHaveBeenCalled(); + }); + + }); +})(); diff --git a/pool/shard011/JavaScript/0069036_toggle.js b/pool/shard011/JavaScript/0069036_toggle.js new file mode 100644 index 0000000000000000000000000000000000000000..8c4dbd766a9ced8c16a48248ef4bd5e7cad7c0eb --- /dev/null +++ b/pool/shard011/JavaScript/0069036_toggle.js @@ -0,0 +1,52 @@ + +(function(global, $, UI){ + + var Toggle = function(element, options) { + + var $this = this, $element = $(element); + + if($element.data("toggle")) return; + + this.options = $.extend({}, Toggle.defaults, options); + this.totoggle = this.options.target ? $(this.options.target):[]; + this.element = $element.on("click", function(e) { + e.preventDefault(); + $this.toggle(); + }); + + this.element.data("toggle", this); + }; + + $.extend(Toggle.prototype, { + + toggle: function() { + + if(!this.totoggle.length) return; + + this.totoggle.toggleClass(this.options.cls); + + if(this.options.cls == 'uk-hidden') { + $(document).trigger("uk-check-display"); + } + } + }); + + Toggle.defaults = { + target: false, + cls: 'uk-hidden' + }; + + UI["toggle"] = Toggle; + + $(document).on("uk-domready", function(e) { + + $("[data-uk-toggle]").each(function() { + var ele = $(this); + + if (!ele.data("toggle")) { + var obj = new Toggle(ele, UI.Utils.options(ele.attr("data-uk-toggle"))); + } + }); + }); + +})(this, jQuery, jQuery.UIkit); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069038_TabBarController.js b/pool/shard011/JavaScript/0069038_TabBarController.js new file mode 100644 index 0000000000000000000000000000000000000000..04ee4aa0ed416186eaacb8e907320f3c5ce2b8cb --- /dev/null +++ b/pool/shard011/JavaScript/0069038_TabBarController.js @@ -0,0 +1,243 @@ +/** + * This Source Code is licensed under the MIT license. If a copy of the + * MIT-license was not distributed with this file, You can obtain one at: + * http://opensource.org/licenses/mit-license.html. + * + * @author: Hein Rutjes (IjzerenHein) + * @license MIT + * @copyright Gloey Apps, 2015 + */ + +/** + * TabBarController. + * + * @module + */ +define(function(require, exports, module) { + + // import dependencies + var View = require('famous/core/View'); + var AnimationController = require('../AnimationController'); + var TabBar = require('./TabBar'); + var LayoutDockHelper = require('../helpers/LayoutDockHelper'); + var LayoutController = require('../LayoutController'); + var Easing = require('famous/transitions/Easing'); + + /** + * @class + * @param {Object} options Configurable options. + * @param {TabBarController.Position} [options.tabBarPosition] Position (default: BOTTOM). + * @param {Number} [options.tabBarSize] Size of the tabBar (default: 50). + * @param {Number} [options.tabBarZIndex] Z-index the tabBar is put above the content (AnimationController) (default: 10). + * @param {Object} [options.tabBar] Options that are passed to the TabBar. + * @param {Object} [options.animationController] Options that are passed to the AnimationController. + * @alias module:TabBarController + */ + function TabBarController(options) { + View.apply(this, arguments); + + _createRenderables.call(this); + _createLayout.call(this); + _setListeners.call(this); + + this.tabBar.setOptions({ + layoutController: { + direction: ((this.options.tabBarPosition === TabBarController.Position.TOP) || (this.options.tabBarPosition === TabBarController.Position.BOTTOM)) ? 0 : 1 + } + }); + } + TabBarController.prototype = Object.create(View.prototype); + TabBarController.prototype.constructor = TabBarController; + + TabBarController.Position = { + TOP: 0, + BOTTOM: 1, + LEFT: 2, + RIGHT: 3 + }; + + /** + * Default layout-function for the TabBarController. Supports simple + * docking to any of the four edges. + */ + TabBarController.DEFAULT_LAYOUT = function(context, options) { + var dock = new LayoutDockHelper(context, options); + switch (this.options.tabBarPosition) { + case TabBarController.Position.TOP: + dock.top('tabBar', this.options.tabBarSize, this.options.tabBarZIndex); + break; + case TabBarController.Position.BOTTOM: + dock.bottom('tabBar', this.options.tabBarSize, this.options.tabBarZIndex); + break; + case TabBarController.Position.LEFT: + dock.left('tabBar', this.options.tabBarSize, this.options.tabBarZIndex); + break; + case TabBarController.Position.RIGHT: + dock.right('tabBar', this.options.tabBarSize, this.options.tabBarZIndex); + break; + } + dock.fill('content'); + }; + + TabBarController.DEFAULT_OPTIONS = { + tabBarPosition: TabBarController.Position.BOTTOM, + tabBarSize: 50, + tabBarZIndex: 10, + tabBar: { + createRenderables: { + background: true + } + }, + animationController: { + transition: {duration: 300, curve: Easing.inOutQuad}, + animation: AnimationController.Animation.FadedZoom + } + }; + + /** + * Creates the renderables (tabBar, animationController). + */ + function _createRenderables() { + this.tabBar = new TabBar(this.options.tabBar); + this.animationController = new AnimationController(this.options.animationController); + this._renderables = { + tabBar: this.tabBar, + content: this.animationController + }; + } + + /** + * Creates the outer (header-footer) layout. + */ + function _createLayout() { + this.layout = new LayoutController(this.options.layoutController); + this.layout.setLayout(TabBarController.DEFAULT_LAYOUT.bind(this)); + this.layout.setDataSource(this._renderables); + this.add(this.layout); + } + + /** + * Sets the listeners. + */ + function _setListeners() { + this.tabBar.on('tabchange', function(event) { + _updateView.call(this, event); + this._eventOutput.emit('tabchange', { + target: this, + index: event.index, + oldIndex: event.oldIndex, + item: this._items[event.index], + oldItem: ((event.oldIndex >= 0) && (event.oldIndex < this._items.length)) ? this._items[event.oldIndex] : undefined + }); + }.bind(this)); + } + + /** + * Updates the view-container with the selected view. + */ + function _updateView(event) { + var index = this.tabBar.getSelectedItemIndex(); + this.animationController.halt(); + if (index >= 0) { + this.animationController.show(this._items[index].view); + } + else { + this.animationController.hide(); + } + } + + /** + * Patches the TabBarController instance's options with the passed-in ones. + * + * @param {Object} options Configurable options. + * @param {TabBarController.Position} [options.tabBarPosition] Position (default: BOTTOM). + * @param {Number} [options.tabBarSize] Size of the tabBar (default: 50). + * @param {Number} [options.tabBarZIndex] Z-index the tabBar is put above the content (AnimationController) (default: 10). + * @param {Object} [options.tabBar] Options that are passed to the TabBar. + * @param {Object} [options.animationController] Options that are passed to the AnimationController. + * @return {TabBarController} this + */ + TabBarController.prototype.setOptions = function(options) { + View.prototype.setOptions.call(this, options); + if (this.layout && options.layoutController) { + this.layout.setOptions(options.layoutController); + } + if (this.tabBar && options.tabBar) { + this.tabBar.setOptions(options.tabBar); + } + if (this.animationController && options.animationController) { + this.animationController(options.animationController); + } + if (this.layout && (options.tabBarPosition !== undefined)) { + this.tabBar.setOptions({ + layoutController: { + direction: ((options.tabBarPosition === TabBarController.Position.TOP) || (options.tabBarPosition === TabBarController.Position.BOTTOM)) ? 0 : 1 + } + }); + } + if (this.layout) { + this.layout.reflowLayout(); + } + return this; + }; + + /** + * Sets the items for the tab-bar controller. + * + * Example 1: + * + * ```javascript + * var tabBarController = new TabBarController(); + * tabBarController.setItems([ + * {tabItem: 'Profile', view: new ProfileView()}, + * {tabItem: 'Map', view: new MapView()}, + * {tabItem: 'Login', view: new LoginView()} + * {tabItem: 'Settings', view: new SettingsView()} + * ]); + *``` + * + * @param {Array} items Array of tab-bar controller items. + * @return {TabBarController} this + */ + TabBarController.prototype.setItems = function(items) { + this._items = items; + var tabItems = []; + for (var i = 0; i < items.length; i++) { + tabItems.push(items[i].tabItem); + } + this.tabBar.setItems(tabItems); + _updateView.call(this); + return this; + }; + + /** + * Get the tab-items (also see `setItems`). + * + * @return {Array} tab-items + */ + TabBarController.prototype.getItems = function() { + return this._items; + }; + + /** + * Sets the index of the selected tab. + * + * @param {Number} index selected index. + * @return {TabBar} this + */ + TabBarController.prototype.setSelectedItemIndex = function(index) { + this.tabBar.setSelectedItemIndex(index); + return this; + }; + + /** + * Get the index of the selected tab-item. + * + * @return {Number} selected index + */ + TabBarController.prototype.getSelectedItemIndex = function() { + return this.tabBar.getSelectedItemIndex(); + }; + + module.exports = TabBarController; +}); diff --git a/pool/shard011/JavaScript/0069039_diagnosisLetter.js b/pool/shard011/JavaScript/0069039_diagnosisLetter.js new file mode 100644 index 0000000000000000000000000000000000000000..3d7b81032b9902e79cd12ed892856af42d64448b --- /dev/null +++ b/pool/shard011/JavaScript/0069039_diagnosisLetter.js @@ -0,0 +1,115 @@ +define(function(require) { + var system = require('durandal/system'); + var Backend = require('modules/diagnosis'); + var Structures = require('modules/patientStructures'); + var backend = new Backend(); + var self; + + var DiagnosisLetter = function(title,patientId,practiceId,date,options) { + self = this; + this.title = title || DiagnosisLetter.defaultTitle; + this.patientId = patientId || DiagnosisLetter.patientId; + this.practiceId = practiceId || DiagnosisLetter.practiceId; + this.date = date || DiagnosisLetter.date; + this.options = options || DiagnosisLetter.defaultOptions; + this.text = ko.observable(); + this.letter = ko.observable(); + this.getPhysician(); + + }; + + // /********************************************************************************************** + // * Retrieve data for physician + // *********************************************************************************************/ + + DiagnosisLetter.prototype.getPhysician = function(data) { + var isEmpty = false; + backend.getLetter(self.patientId,self.practiceId,self.date).success(function(data) { + if(data.length > 0) { + var d = $.map(data, function(item) { + self.text(item.diagnosis_letter); + if(self.text() == '') { + var letter = ''; + backend.getReferringPhysician(self.patientId,self.practiceId).success(function(data) { + if(data.length > 0) { + var d = $.map(data, function(item) { + letter += item.first_name + ' ' + item.last_name + ',' + item.degree + '\n\n'; + }); + backend.getPatient(self.patientId).success(function(data) { + if(data.length > 0) { + var d = $.map(data, function(item) { + letter += 'RE :' + item.first_name + ' ' + item.last_name + ', DOB: ' + + item.date_of_birth + '\n'; + }); + + backend.getServiceRecord(self.date,self.patientId,self.practiceId).success(function(data) { + if(data.length > 0) { + var d = $.map(data, function(item) { + letter+= 'Dear Dr. \n\n I saw the above patient in the office on ' + self.date + + ' for ' + item.systems_comment + ' evaluation of - \n'; + }); + + backend.getDiagnosis(self.patientId,self.practiceId,self.date).success(function(data) { + var diagnosis = ''; + if(data.length > 0) { + var d = $.map(data, function(item) { + diagnosis+= item.diagnosis + '\n'; + }); + letter += diagnosis + '\n'; + letter+= 'My Recommendations are as follows: \n\n\n'; + letter+= 'I appreciate your trust in our service. If you have any questions, do not hesitate to call me \n\n'; + letter+= 'Thank You \n\n'; + letter+= 'Sincerely \n'; + backend.getPhysician(self.patientId,self.practiceId,self.date).success(function(data) { + var m = ''; + if(data.length > 0) { + var d = $.map(data, function(item) { + letter += item.first_name + ' ' + item.last_name + ',' + item.degree + '\n\n'; + self.text(letter); + }); + } + }); + + + } + }); + + } + }); + } + }); + } + }); + } + }); + } + }); + } + DiagnosisLetter.prototype.printLetter = function(data) { + backend.saveLetter(self.patientId, self.practiceId,self.date,self.text); + var height = $('.flowHolder').height(); + var settings = 'directories=no, height=' + height + ', width=800, location=yes, ' + + 'menubar=no, status=no, titlebar=no, toolbar=no'; + var win = window.open( + 'php/printLetter.php/?patientId=' + self.patientId + '&practiceId=' + + self.practiceId + '&date=' + self.date + , + '', + settings + ); + }; + + + DiagnosisLetter.prototype.selectOption = function(dialogResult) { + this.modal.close(dialogResult); + }; + + DiagnosisLetter.prototype.closeWindow = function(data) { + this.modal.close('close'); + }; + + DiagnosisLetter.defaultTitle = ''; + DiagnosisLetter.defaultOptions = ['Save','Cancel']; + + return DiagnosisLetter; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069042_base.js b/pool/shard011/JavaScript/0069042_base.js new file mode 100644 index 0000000000000000000000000000000000000000..04c3fbeda287b55199603d71af784fbdeb2ed46d --- /dev/null +++ b/pool/shard011/JavaScript/0069042_base.js @@ -0,0 +1,226 @@ +// Underscore.js 1.8.3 +// http://underscorejs.org +// (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors +// Underscore may be freely distributed under the MIT license. + +(function() { + + // Baseline setup + // -------------- + + // Establish the root object, `window` in the browser, or `exports` on the server. + var root = this; + + // Save the previous value of the `_` variable. + var previousUnderscore = root._; + + // Save bytes in the minified (but not gzipped) version: + var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; + + // Create quick reference variables for speed access to core prototypes. + var + push = ArrayProto.push, + slice = ArrayProto.slice, + toString = ObjProto.toString, + hasOwnProperty = ObjProto.hasOwnProperty; + + // All **ECMAScript 5** native function implementations that we hope to use + // are declared here. + var + nativeIsArray = Array.isArray, + nativeKeys = Object.keys, + nativeBind = FuncProto.bind, + nativeCreate = Object.create; + + // Naked function reference for surrogate-prototype-swapping. + var Ctor = function(){}; + + // Create a safe reference to the Underscore object for use below. + var _ = function(obj) { + if (obj instanceof _) return obj; + if (!(this instanceof _)) return new _(obj); + this._wrapped = obj; + }; + + // Export the Underscore object for **Node.js**, with + // backwards-compatibility for the old `require()` API. If we're in + // the browser, add `_` as a global object. + if (typeof exports !== 'undefined') { + if (typeof module !== 'undefined' && module.exports) { + exports = module.exports = _; + } + exports._ = _; + } else { + root._ = _; + } + + // Current version. + _.VERSION = '1.8.3'; + + // Internal function that returns an efficient (for current engines) version + // of the passed-in callback, to be repeatedly applied in other Underscore + // functions. + var optimizeCb = function(func, context, argCount) { + if (context === void 0) return func; + switch (argCount == null ? 3 : argCount) { + case 1: return function(value) { + return func.call(context, value); + }; + case 2: return function(value, other) { + return func.call(context, value, other); + }; + case 3: return function(value, index, collection) { + return func.call(context, value, index, collection); + }; + case 4: return function(accumulator, value, index, collection) { + return func.call(context, accumulator, value, index, collection); + }; + } + return function() { + return func.apply(context, arguments); + }; + }; + + // A mostly-internal function to generate callbacks that can be applied + // to each element in a collection, returning the desired result — either + // identity, an arbitrary callback, a property matcher, or a property accessor. + var cb = function(value, context, argCount) { + if (value == null) return _.identity; + if (_.isFunction(value)) return optimizeCb(value, context, argCount); + if (_.isObject(value)) return _.matcher(value); + return _.property(value); + }; + _.iteratee = function(value, context) { + return cb(value, context, Infinity); + }; + + // An internal function for creating assigner functions. + var createAssigner = function(keysFunc, undefinedOnly) { + return function(obj) { + var length = arguments.length; + if (length < 2 || obj == null) return obj; + for (var index = 1; index < length; index++) { + var source = arguments[index], + keys = keysFunc(source), + l = keys.length; + for (var i = 0; i < l; i++) { + var key = keys[i]; + if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; + } + } + return obj; + }; + }; + + // An internal function for creating a new object that inherits from another. + var baseCreate = function(prototype) { + if (!_.isObject(prototype)) return {}; + if (nativeCreate) return nativeCreate(prototype); + Ctor.prototype = prototype; + var result = new Ctor; + Ctor.prototype = null; + return result; + }; + + var property = function(key) { + return function(obj) { + return obj == null ? void 0 : obj[key]; + }; + }; + + // Helper for collection methods to determine whether a collection + // should be iterated as an array or as an object + // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength + // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 + var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; + var getLength = property('length'); + var isArrayLike = function(collection) { + var length = getLength(collection); + return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; + }; + + + // Collection Functions + // Array Functions + // Function (ahem) Functions + // Object Functions + // Utility Functions + + // Add a "chain" function. Start chaining a wrapped Underscore object. + _.chain = function(obj) { + var instance = _(obj); + instance._chain = true; + return instance; + }; + + // OOP + // --------------- + // If Underscore is called as a function, it returns a wrapped object that + // can be used OO-style. This wrapper holds altered versions of all the + // underscore functions. Wrapped objects may be chained. + + // Helper function to continue chaining intermediate results. + var result = function(instance, obj) { + return instance._chain ? _(obj).chain() : obj; + }; + + // Add your own custom functions to the Underscore object. + _.mixin = function(obj) { + _.each(_.functions(obj), function(name) { + var func = _[name] = obj[name]; + _.prototype[name] = function() { + var args = [this._wrapped]; + push.apply(args, arguments); + return result(this, func.apply(_, args)); + }; + }); + }; + + // Add all of the Underscore functions to the wrapper object. + _.mixin(_); + + // Add all mutator Array functions to the wrapper. + _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + var obj = this._wrapped; + method.apply(obj, arguments); + if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; + return result(this, obj); + }; + }); + + // Add all accessor Array functions to the wrapper. + _.each(['concat', 'join', 'slice'], function(name) { + var method = ArrayProto[name]; + _.prototype[name] = function() { + return result(this, method.apply(this._wrapped, arguments)); + }; + }); + + // Extracts the result from a wrapped and chained object. + _.prototype.value = function() { + return this._wrapped; + }; + + // Provide unwrapping proxy for some methods used in engine operations + // such as arithmetic and JSON stringification. + _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; + + _.prototype.toString = function() { + return '' + this._wrapped; + }; + + // AMD registration happens at the end for compatibility with AMD loaders + // that may not enforce next-turn semantics on modules. Even though general + // practice for AMD registration is to be anonymous, underscore registers + // as a named module because, like jQuery, it is a base library that is + // popular enough to be bundled in a third party lib, but not be part of + // an AMD load request. Those cases could generate an error when an + // anonymous define() is called outside of a loader request. + if (typeof define === 'function' && define.amd) { + define('underscore', [], function() { + return _; + }); + } +}.call(this)); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069046_form-new.client.controller.js b/pool/shard011/JavaScript/0069046_form-new.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..9073bdcd32da1de7b4c4bdbd9227a48f002c4183 --- /dev/null +++ b/pool/shard011/JavaScript/0069046_form-new.client.controller.js @@ -0,0 +1,46 @@ +(function(){ + 'use strict'; + angular.module('survey') + .controller('FormNewController', FormNewController); + FormNewController.$inject = [ 'SurveyFactory', 'Logger' ]; + + function FormNewController(SurveyFactory, Logger){ + var vm = this; + vm.surveyList = []; + vm.survey = new Survey(); + vm.newSurvey = newSurvey; + vm.deleteSurvey = deleteSurvey; + + //Placing start-up logic in a consistent place + activate(); + + function activate(){ + SurveyFactory.showAllSurveys().then(function(data){ + vm.surveyList = data; + console.log(data); + }); + } + function Survey(){ + this.name = '' + } + function newSurvey(){ + SurveyFactory.newSurvey(vm.survey).then(function(data){ + if(data.errors){ + Logger.warning(data.errors.name.message); + } else { + vm.surveyList.push(data); + } + }); + } + function deleteSurvey(surveyId){ + SurveyFactory.deleteSurvey( surveyId ).then(function(data){ + if(data.success){ + Logger.success(data.message); + activate(); + } else { + + } + }); + } + } +}()); diff --git a/pool/shard011/JavaScript/0069049_tdd.js b/pool/shard011/JavaScript/0069049_tdd.js new file mode 100644 index 0000000000000000000000000000000000000000..123048fcba6d750abe02c536bb3c51b98ba8bb9c --- /dev/null +++ b/pool/shard011/JavaScript/0069049_tdd.js @@ -0,0 +1,55 @@ +define([ + 'dojo/aspect', + '../../main', + '../Suite', + '../Test' +], function (aspect, main, Suite, Test) { + var currentSuite, + suites = []; + + function registerSuite(name, factory) { + var parentSuite = currentSuite; + + currentSuite = new Suite({ name: name, parent: parentSuite }); + parentSuite.tests.push(currentSuite); + + suites.push(parentSuite); + factory(); + currentSuite = suites.pop(); + } + + return { + suite: function (name, factory) { + if (/* is a root suite */ !currentSuite) { + main.suites.forEach(function (suite) { + currentSuite = suite; + registerSuite(name, factory); + currentSuite = null; + }); + } + else { + registerSuite(name, factory); + } + }, + + test: function (name, test) { + currentSuite.tests.push(new Test({ name: name, test: test, parent: currentSuite })); + }, + + before: function (fn) { + aspect.after(currentSuite, 'setup', fn); + }, + + after: function (fn) { + aspect.after(currentSuite, 'teardown', fn); + }, + + beforeEach: function (fn) { + aspect.after(currentSuite, 'beforeEach', fn); + }, + + afterEach: function (fn) { + aspect.after(currentSuite, 'afterEach', fn); + } + }; +}); diff --git a/pool/shard011/JavaScript/0069052_appAlert.js b/pool/shard011/JavaScript/0069052_appAlert.js new file mode 100644 index 0000000000000000000000000000000000000000..9af754f5495bab9cb95a2f7aaea22da64b2764b7 --- /dev/null +++ b/pool/shard011/JavaScript/0069052_appAlert.js @@ -0,0 +1,42 @@ +'use strict' + +/* eslint-disable no-unused-vars */ +const React = require('react') + +const ReactBootrap = require('react-bootstrap') +const Modal = ReactBootrap.Modal +const Button = ReactBootrap.Button +/* eslint-enable no-unused-vars */ + +const PropTypes = require('prop-types') + +const createReactClass = require('create-react-class') + +const AppAlert = createReactClass({ + displayName: 'AppAlert', + + propTypes: { + showAlert: PropTypes.bool.isRequired, + alertType: PropTypes.string.isRequired, + alertDetail: PropTypes.string.isRequired, + handleHide: PropTypes.func.isRequired + }, + + render: function render () { + return ( + + + {this.props.alertType} + + +

{this.props.alertDetail}

+
+ + + +
+ ) + } +}) + +module.exports = AppAlert diff --git a/pool/shard011/JavaScript/0069053_stylus.js b/pool/shard011/JavaScript/0069053_stylus.js new file mode 100644 index 0000000000000000000000000000000000000000..d84d46ded3d25a9f2d0668285cbfb7c0858efef4 --- /dev/null +++ b/pool/shard011/JavaScript/0069053_stylus.js @@ -0,0 +1,30 @@ +var gulp = require( "gulp" ); +var plumber = require( "gulp-plumber" ); +var browserSync = require( "browser-sync" ); + +var stylus = require( "gulp-stylus" ); +var nib = require( "nib" ); + +var paths = require( "./config" ).paths; + +gulp.task( "styles", function() { + create( false ); +} ); + +gulp.task( "styles-build", function() { + create( true ); +} ); + +function create( isBuild ) { + var opts = {} + opts.use = [ nib() ]; + opts.compress = isBuild; + opts.sourcemap = isBuild ? false : { inline: true }; + opts.url = { name: "url64" }; + return gulp.src( paths.styles + "main.styl" ) + .pipe( plumber() ) + .pipe( stylus( opts) ) + .pipe( plumber.stop() ) + .pipe( gulp.dest( ( isBuild ? paths.build : paths.dist ) + "/css" ) ) + .pipe( browserSync.stream() ); +} diff --git a/pool/shard011/JavaScript/0069054_gulpfile.js b/pool/shard011/JavaScript/0069054_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..3691adc7cba392b6a780e96885ae3138192ca644 --- /dev/null +++ b/pool/shard011/JavaScript/0069054_gulpfile.js @@ -0,0 +1,135 @@ +var gulp = require('gulp'); +var path = require('path'); +var fs = require('fs'); +var del = require('del'); +var gutil = require('gulp-util'); +var webpack = require('webpack'); +var gulpWebpack = require('gulp-webpack'); +var karma = require('karma').server; +var WebpackDevServer = require('webpack-dev-server'); + +var appPaths = require("./root.js").paths; +var generateWebpackConfig = require('./conf/webpack.config.js'); +var argv = require('yargs').argv; + +var target = argv.target || 'development'; +var configTarget = argv.configTarget || target || 'development'; +var sourceMaps = argv.maps || (target === 'development'); +var watch = argv.watch || (target === 'development'); +var uglify = argv.uglify || (target === 'production'); +var port = argv.port || 8085; +var singleRun = argv.singleRun || false; + +var targetDir = target; +// May change to this later: +//var targetDir = (target === configTarget) ? target : target + '-' + configTarget; +var webpackBuildPath = path.join(appPaths.buildDir, targetDir); + +gutil.log('Build Target: ' + target); +gutil.log('Config Target: ' + configTarget); + +/** + * Build webpack bundle + */ +gulp.task('build', ['clean'], function() { + var webpackConfig = generateWebpackConfig(configTarget, watch, sourceMaps, uglify); + return gulp.src(path.join(appPaths.srcDir, 'index.js')) + .pipe(gulpWebpack( webpackConfig )) + .pipe(gulp.dest(webpackBuildPath)); +}); + +/** + * Clean bundle + */ +gulp.task('clean', function (cb) { + del([ + 'build/**' + ]).then(function() { + cb(); + }); +}); + +/** + * Build webpack bundle + */ +gulp.task('analyze', function(cb) { + var webpackConfig = generateWebpackConfig(configTarget, false, sourceMaps, true); + + gulp.src(path.join(appPaths.srcDir, 'index.js')) + .pipe(gulpWebpack( webpackConfig, null, function(err, stats) { + fs.writeFileSync(path.join(webpackBuildPath, 'profile.json'), JSON.stringify(stats.toJson(), null, ' ')); + })); +}); + + +/** + * test + * + * Run karma test server + */ +gulp.task('test', function(done) { + karma.start({ + configFile: __dirname + '/conf/karma.conf.js', + singleRun: singleRun, + webpack: generateWebpackConfig(configTarget, watch, sourceMaps, uglify) + }, done); +}); + +/** + * dev-server + * + * Webpack development server + */ +gulp.task("dev-server", function(callback) { + var webpackConfig = generateWebpackConfig(configTarget, watch, sourceMaps); + webpackConfig.output.publicPath = "/"; + webpackConfig.output.path = path.join(appPaths.buildDir, target), + + webpackConfig.debug = true; + // Start a webpack-dev-server + + new WebpackDevServer( webpack(webpackConfig), { + filename: "[name].js", + publicPath: webpackConfig.output.publicPath, + stats: { + colors: true + } + }).listen(port, function(err) { + if(err) throw new gutil.PluginError("webpack-dev-server", err); + // Server listening + gutil.log("[webpack-dev-server]", "http://localhost:"+port+"/"); + + // keep the server alive or continue? + // callback(); + }); +}); + +try { + var stagingDeployTools = require('ots-deploy-tools')( + require('./deploy-config.js'), + 'staging', + require('./package.json'), + argv + ); + + + /** + * deploy-staging + * + * Deploys the entire application root to the staging server, excluding + * the server environment.json file and a few unimportant files. + */ + gulp.task('deploy-staging', function() { + return stagingDeployTools.templates.deployApp({ + src: './build/staging/', + npmInstall: false, + restartUpstart: false, + symlinkConfigFile: false + }); + }); +} +catch (e) { + gutil.log('deploy-config.js not present or some other error. Deployment tasks unavailable.'); +} + + diff --git a/pool/shard011/JavaScript/0069058_dfg-put-setter-by-val.js b/pool/shard011/JavaScript/0069058_dfg-put-setter-by-val.js new file mode 100644 index 0000000000000000000000000000000000000000..2a3546b62f065795cc18f581e0b667fc265f40de --- /dev/null +++ b/pool/shard011/JavaScript/0069058_dfg-put-setter-by-val.js @@ -0,0 +1,41 @@ +function shouldBe(actual, expected) { + if (actual !== expected) + throw new Error('bad value: ' + actual); +} + +function testAttribute(object, name, type) { + shouldBe(Reflect.has(object, name), true); + let desc = Reflect.getOwnPropertyDescriptor(object, name); + shouldBe(desc.configurable, true); + shouldBe(desc.enumerable, true); + if (type === 'get') { + shouldBe(typeof desc.get, 'function'); + shouldBe(typeof desc.set, 'undefined'); + } else if (type === 'set') { + shouldBe(typeof desc.get, 'undefined'); + shouldBe(typeof desc.set, 'function'); + } else { + shouldBe(typeof desc.get, 'function'); + shouldBe(typeof desc.set, 'function'); + } +} +noInline(testAttribute); + +function setter(name) +{ + var object = { + ok: 0, + set [name](value) { + this.ok = value; + } + }; + + testAttribute(object, 'hello', 'set'); + object.hello = 42; + return object.ok; + +} +noInline(setter); + +for (var i = 0; i < 10000; ++i) + shouldBe(setter('hello'), 42); diff --git a/pool/shard011/JavaScript/0069059_CorpusCard.js b/pool/shard011/JavaScript/0069059_CorpusCard.js new file mode 100644 index 0000000000000000000000000000000000000000..d92da7a5565c77c8e7a16719ef85d80b09710dd5 --- /dev/null +++ b/pool/shard011/JavaScript/0069059_CorpusCard.js @@ -0,0 +1,57 @@ +import React from 'react' +import PropTypes from 'prop-types' +import { FormattedMessage as T, FormattedRelativeTime as D, useIntl } from 'react-intl' +import { selectUnit } from '@formatjs/intl-utils' + +const CorpusCard = ({ + server, + corpus, + selectCorpus, + routerPush +}) => { + const { formatMessage } = useIntl() + const { password, name, status, webentities_in, total_webentities, created_at, last_activity } = corpus + const handleSelectCorpus = () => { + const path = corpus.password ? '/login/corpus-login-form' : 'browser' + selectCorpus(server, corpus) + routerPush(path) + } + + return ( +
  • +

    + { name } + { password && } + { status === 'ready' && } +

    +
    + +
    +
    + + } } + /> + + - + } } /> +
    +
  • + ) +} + +CorpusCard.propTypes = { + corpus: PropTypes.object.isRequired, + server: PropTypes.object.isRequired, + history: PropTypes.shape({ + push: PropTypes.func + }), + + // actions + selectCorpus: PropTypes.func, +} + + + +export default CorpusCard \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069063_barometer.js b/pool/shard011/JavaScript/0069063_barometer.js new file mode 100644 index 0000000000000000000000000000000000000000..f926dac29cdca32b18701c1b7ebd0798f2d934e5 --- /dev/null +++ b/pool/shard011/JavaScript/0069063_barometer.js @@ -0,0 +1,207 @@ +var Emitter = require("events").EventEmitter; +var util = require("util"); + +var Board = require("./board"); +var Fn = require("./fn"); + +var toFixed = Fn.toFixed; + + +var Controllers = { + MPL115A2: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "MPL115A2", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + // http://cache.freescale.com/files/sensors/doc/data_sheet/MPL115A2.pdf + // P. 6, Eqn. 2 + return ((65 / 1023) * raw) + 50; + } + } + }, + MPL3115A2: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "MPL3115A2", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + // formulas extracted from code example: + // https://github.com/adafruit/Adafruit_MPL3115A2_Library + var inches = (raw / 4) / 3377; + return inches * 3.39; + } + } + }, + BMP180: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "BMP180", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + return raw / 1000; + } + } + }, + BMP280: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "BMP280", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + return raw / 1000; + } + } + }, + BME280: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "BME280", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + return raw / 1000; + } + } + }, + MS5611: { + initialize: { + value: function(opts, dataHandler) { + var Multi = require("./imu"); + var driver = Multi.Drivers.get(this.board, "MS5611", opts); + driver.on("data", function(data) { + dataHandler.call(this, data.pressure); + }.bind(this)); + } + }, + // kPa (Kilopascals) + toPressure: { + value: function(raw) { + return raw / 1000; + } + } + }, +}; + +Controllers["BMP085"] = Controllers["BMP-085"] = Controllers.BMP180; + +/** + * Barometer + * @constructor + * + * five.Barometer(opts); + * + * five.Barometer({ + * controller: "CONTROLLER" + * address: 0x00 + * }); + * + * + * @param {Object} opts [description] + * + */ + +function Barometer(opts) { + if (!(this instanceof Barometer)) { + return new Barometer(opts); + } + + var controller = null; + var last = null; + var raw = null; + + Board.Component.call( + this, opts = Board.Options(opts) + ); + + var freq = opts.freq || 25; + + if (opts.controller && typeof opts.controller === "string") { + controller = Controllers[opts.controller.toUpperCase()]; + } else { + controller = opts.controller; + } + + if (controller == null) { + // controller = Controllers["ANALOG"]; + throw new Error("Missing Barometer controller"); + } + + Board.Controller.call(this, controller, opts); + + if (!this.toPressure) { + this.toPressure = opts.toPressure || function(raw) { + return raw; + }; + } + + if (typeof this.initialize === "function") { + this.initialize(opts, function(data) { + raw = data; + }); + } + + Object.defineProperties(this, { + pressure: { + get: function() { + return toFixed(this.toPressure(raw), 4); + } + } + }); + + setInterval(function() { + if (raw === null) { + return; + } + + var data = { + pressure: this.pressure + }; + + this.emit("data", data); + + if (this.pressure !== last) { + last = this.pressure; + this.emit("change", data); + } + }.bind(this), freq); +} + + +util.inherits(Barometer, Emitter); + +module.exports = Barometer; diff --git a/pool/shard011/JavaScript/0069066_test-cli.js b/pool/shard011/JavaScript/0069066_test-cli.js new file mode 100644 index 0000000000000000000000000000000000000000..59faea2e8bb6926175284ea993f681c17f54bffc --- /dev/null +++ b/pool/shard011/JavaScript/0069066_test-cli.js @@ -0,0 +1,35 @@ +/* + * Command line interface to test Fuzzee + * + * Two ways to use: + * Pipe mode: + * cat tests/validation/junit_tipper.fcl | node test-cli + * + * File mode: + * node test-cli tests/validation/junit_tipper.fcl + */ + +var fs = require('fs') + +var Fuzzee = require('./index') + +// String mode +if(process.argv[2]) { + var stream = fs.createReadStream(process.argv[2]) + var string = '' + stream.on('data',function(data) { + string += data.toString() + }) + + stream.on('end',function() { + var fuzzee = new Fuzzee(string) + fuzzee.on('end', function() { + console.log(fuzzee.js) + }) + }) +} +// Pipe mode +else { + fuzzee = new Fuzzee() + process.stdin.pipe(fuzzee).pipe(process.stdout) +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069067_nativestorage.js b/pool/shard011/JavaScript/0069067_nativestorage.js new file mode 100644 index 0000000000000000000000000000000000000000..0d200776ac03d42b1c72001db6c8949a0a64e338 --- /dev/null +++ b/pool/shard011/JavaScript/0069067_nativestorage.js @@ -0,0 +1,75 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var plugin_1 = require('./plugin'); +/** + * @name NativeStorage + * @description Native storage of variables in Android and iOS + * + * @usage + * ```typescript + * import { NativeStorage } from 'ionic-native'; + * + * NativeStorage.setItem('myitem', {property: 'value', anotherProperty: 'anotherValue'}) + * .then( + * () => console.log('Stored item!'), + * error => console.error('Error storing item', error) + * ); + * + * NativeStorage.getItem('myitem') + * .then( + * data => console.log(data), + * error => console.error(error) + * ); + * ``` + */ +var NativeStorage = (function () { + function NativeStorage() { + } + /** + * Stores a value + * @param reference {string} + * @param value + */ + NativeStorage.setItem = function (reference, value) { return; }; + /** + * Gets a stored item + * @param reference {string} + */ + NativeStorage.getItem = function (reference) { return; }; + /** + * Removes a single stored item + * @param reference {string} + */ + NativeStorage.remove = function (reference) { return; }; + /** + * Removes all stored values. + */ + NativeStorage.clear = function () { return; }; + __decorate([ + plugin_1.Cordova() + ], NativeStorage, "setItem", null); + __decorate([ + plugin_1.Cordova() + ], NativeStorage, "getItem", null); + __decorate([ + plugin_1.Cordova() + ], NativeStorage, "remove", null); + __decorate([ + plugin_1.Cordova() + ], NativeStorage, "clear", null); + NativeStorage = __decorate([ + plugin_1.Plugin({ + plugin: 'cordova-plugin-nativestorage', + pluginRef: 'NativeStorage', + repo: 'https://github.com/TheCocoaProject/cordova-plugin-nativestorage' + }) + ], NativeStorage); + return NativeStorage; +}()); +exports.NativeStorage = NativeStorage; +//# sourceMappingURL=nativestorage.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069069_options.js b/pool/shard011/JavaScript/0069069_options.js new file mode 100644 index 0000000000000000000000000000000000000000..291be2dcad16ebb0631c4766c3130ceabe8b6d9e --- /dev/null +++ b/pool/shard011/JavaScript/0069069_options.js @@ -0,0 +1,197 @@ +/** + * Notificator Options + * @namespace + */ + +var NotificatorOptions = { + /** + * Init options + */ + init: function(_notificator) { + this.notificator = _notificator; + + this.elems = { + updateInterval: document.getElementById('interval'), + openListe: document.getElementById('openListe'), + openInNewTab: document.getElementById("newTab"), + showAllNotifButton: document.getElementById("allNotifs"), + showDesktopNotif: document.getElementById("notifNative"), + useDetailedNotifs: document.getElementById("detailedNotifs"), + notifPriority: document.getElementById("priorityNotif"), + mpPriority: document.getElementById("priorityMP"), + playSon: document.getElementById("playSon"), + tweet: document.getElementById("tweet"), + SdZLink: document.getElementById("SdZLink"), + autoclosePopup: document.getElementById("autoclosePopup"), + archiveAllLink: document.getElementById("archiveAllLink") + }; + + document.getElementById("enregistrer").addEventListener("click", this.save.bind(this)); + document.getElementById("reset").addEventListener("click", this.reset.bind(this)); + this.elems["updateInterval"].addEventListener("keyup", this.checkInput.bind(this)); + this.elems["openListe"].addEventListener("click", this.toggle.bind(this)); + this.elems["showDesktopNotif"].addEventListener("click", this.toggle.bind(this)); + + this.load(); + }, + + oldValue: 5, + + /** + * Check inputs + * @param {Object} [evt] JS Event + */ + checkInput: function(evt) { + var val = this.elems["updateInterval"].value; + if(val == '') + this.elems["updateInterval"].value = this.oldValue; + else { + if(parseInt(val) > 60) { + this.elems["updateInterval"].value = 60; + this.oldValue = 60; + } else { + this.oldValue = val; + } + } + }, + + /** + * Reset options + */ + reset: function() { + var c = confirm("Voulez vous r\u00E9ellement remettre \u00E0 z\u00E9ro les options ?"); + if(c) { + this.notificator.resetOptions(); + window.location.reload(); + } + }, + + /** + * Save options + */ + save: function() { + this.notificator.setOptions(this.getValues(), function() { + //console.log("Options Saved"); + window.close(); + }); + }, + + /** + * Load options + */ + load: function() { + this.options = this.notificator.getOptions(); + + for(var key in this.elems) { + if(this.options[key] !== undefined) { + if(this.elems[key].type == "checkbox") { + this.elems[key].checked = this.options[key]; + } + else { + this.elems[key].value = this.options[key]; + } + } + } + this.toggle(); + this.oldValue = this.elems['updateInterval'].value; + this.checkAvatar(); + }, + + /** + * Get inputs value + * @returns {Object} The input values + */ + getValues: function() { + var obj = {}; + for(var key in this.elems) { + var val = this.elems[key].type == "checkbox" ? this.elems[key].checked : parseInt(this.elems[key].value); + obj[key] = val; + } + return obj; + }, + + /** + * Toggle inputs + */ + toggle: function() { + if(this.elems['showDesktopNotif'].checked) { + $(".subNotifFields").removeClass("disabled"); + $(".subNotifFields input").attr("disabled", false); + } + else { + $(".subNotifFields").addClass("disabled"); + $(".subNotifFields input").attr("disabled", true); + } + + if(this.elems['openListe'].checked) { + $(".subPopupFields").removeClass("disabled"); + $(".subPopupFields input").attr("disabled", false); + } + else { + $(".subPopupFields").addClass("disabled"); + $(".subPopupFields input").attr("disabled", true); + } + + $(".priority input").on("change", function(e) { + var value = "Erreur"; + switch(parseInt(e.target.value)) { + case -2: + value = "Pas important"; + break; + case -1: + value = "Peu important"; + break; + case 0: + value = "Normale"; + break; + case 1: + value = "Important"; + break; + case 2: + value = "Très important"; + break; + } + $(e.currentTarget).parent().find(".value").text(value); + }).trigger("change"); + }, + + /** + * Check avatar + */ + checkAvatar: function() { + $.get("http://www.fr.openclassrooms.com", this.loadCallback.bind(this), "text"); + }, + + /** + * Callback when page loaded + */ + loadCallback: function(data) { + var self = this, + xmlDoc = new DOMParser().parseFromString(data, "text/xml"), + $data = $(xmlDoc); + + var leDiv = $("div#connecteComme"); + + //on est pas connecté ! + if(!this.notificator.logged) { + leDiv.find("a").attr("href","http://www.fr.openclassrooms.com/login"); + leDiv.find("strong").text("Non connecté !"); + } else { + var avatarImgSrc = donnees.find("img").attr('src'), + profil = $data.find("div#memberLinks a.nickname"), + profilName = profil.text(), + profilLink = profil.attr('href'); + + leDiv.find("a").attr("href","http://www.fr.openclassrooms.com" + profilLink); + leDiv.find("strong").text(profilName); + leDiv.find("img").attr("src",avatarImgSrc); + } + } +}; + +document.addEventListener('DOMContentLoaded', function () { + chrome.runtime.getBackgroundPage(function(bgWindow) { + var notificator = bgWindow.theNotificator; + NotificatorOptions.init.call(NotificatorOptions, notificator); + }); +}); diff --git a/pool/shard011/JavaScript/0069071_context.js b/pool/shard011/JavaScript/0069071_context.js new file mode 100644 index 0000000000000000000000000000000000000000..d92d6f9c9c1dcae73c1b7c42ffcdac2af013d2b8 --- /dev/null +++ b/pool/shard011/JavaScript/0069071_context.js @@ -0,0 +1,92 @@ +/* + * Copyright (c) 2017 Martin Donath + * + * 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. + */ + +import inspect from "../util/inspect" + +/* ---------------------------------------------------------------------------- + * Class + * ------------------------------------------------------------------------- */ + +export class Context { + + /** + * Create a context stack + * + * This is necessary for easy querying of iframes. + * + * @constructor + * + * @property {string} context_ - Context stack + */ + constructor() { + this.stack_ = [] + } + + /** + * Push a context onto the stack + * + * @param {HTMLIFrameElement} context - Context + * + * @return {number} Size of stack + */ + push(context) { + if (!(context instanceof this.window.Element)) + throw new TypeError(`Invalid element: ${inspect(context)}`) + if (!(context instanceof this.window.HTMLIFrameElement)) + throw new TypeError(`Invalid element type: ${inspect(context.tagName)}`) + + /* Push context onto stack */ + return this.stack_.push(context) + } + + /** + * Pop a context from the stack + * + * @return {HTMLIFrameElement} Context + */ + pop() { + return this.stack_.pop() + } + + /** + * Retrieve window object for current context + * + * @return {Window} Window object + */ + get window() { + return this.stack_.length + ? this.stack_[this.stack_.length - 1].contentWindow + : window + } + + /** + * Retrieve document object for current context + * + * @return {Document} Document object + */ + get document() { + return this.stack_.length + ? this.stack_[this.stack_.length - 1].contentDocument + : document + } +} + +/* ---------------------------------------------------------------------------- + * Export default context + * ------------------------------------------------------------------------- */ + +const _ = new Context() +export { _ as default } diff --git a/pool/shard011/JavaScript/0069072_connector.js b/pool/shard011/JavaScript/0069072_connector.js new file mode 100644 index 0000000000000000000000000000000000000000..ae3695b5f945366b2fe7f76b36f06fe0157bc6cf --- /dev/null +++ b/pool/shard011/JavaScript/0069072_connector.js @@ -0,0 +1,179 @@ +'use strict'; +var BBPromise = require('bluebird'); +var OAuth = require('@hoist/oauth').OAuth; +var _ = require('lodash'); +var logger = require('@hoist/logger'); +var config = require('config'); + +function QBOConnector(settings) { + logger.info({ + settings: settings + }, 'constructed qbo-connector'); + this.settings = settings; + + this.auth = BBPromise.promisifyAll(new OAuth( + 'https://oauth.intuit.com/oauth/v1/get_request_token', + 'https://oauth.intuit.com/oauth/v1/get_access_token', + settings.consumerKey, + settings.consumerSecret, + '1.0', + 'https://' + config.get('Hoist.domains.bouncer') + '/bounce', + 'HMAC-SHA1' + ), { + multiArgs: true + }); + this.auth._originalCreateClient = this.auth._createClient; + this.auth._createClient = function (port, hostname, method, path, headers, sslEnabled) { + headers['user-agent'] = 'Hoist'; + headers.Accept = 'application/json'; + return this._originalCreateClient(port, hostname, method, path, headers, sslEnabled); + }; + this.auth._performSecureRequestAsync = BBPromise.promisify(this.auth._performSecureRequest, this.auth, { + multiArgs: true + }); + _.bindAll(this); +} + + +/* istanbul ignore next */ +QBOConnector.prototype.authorize = function (authorization) { + this.authorization = authorization; + this.settings.accessKey = authorization.get('AccessToken'); + this.settings.accessSecret = authorization.get('AccessTokenSecret'); +}; + +QBOConnector.prototype.swapRequestToken = function (requestToken, requestTokenSecret, verifier) { + return this.auth.getOAuthAccessTokenAsync(requestToken, requestTokenSecret, verifier); +}; + +QBOConnector.prototype.generateRequestToken = function () { + logger.info('requesting auth token'); + return this.auth.getOAuthRequestTokenAsync(); +}; + + +QBOConnector.prototype.receiveBounce = function (bounce) { + logger.info(this.settings); + if (bounce.get('RequestToken')) { + /*jshint camelcase: false */ + return this.swapRequestToken(bounce.get('RequestToken'), bounce.get('RequestTokenSecret'), bounce.query.oauth_verifier) + .spread(function (accessToken, accessTokenSecret, auth_headers) { + logger.info(auth_headers); + logger.info('got request token'); + return bounce.delete('RequestToken') + .then(function () { + return bounce.delete('RequestTokenSecret'); + }).then(function () { + return bounce.set('AccessToken', accessToken); + }).then(function () { + return bounce.set('AccessTokenSecret', accessTokenSecret); + }).then(function () { + return bounce.set('CompanyId', bounce.query.realmId); + }).then(function () { + bounce.done(); + }); + }); + } else if (bounce.get('IntuitSetup')) { + return this.generateRequestToken() + .bind(this) + .spread(function (requestToken, requestTokenSecret) { + logger.info('got request token'); + return bounce.set('RequestToken', requestToken) + .bind(this) + .then(function () { + return bounce.set('RequestTokenSecret', requestTokenSecret); + }) + .bind(this) + .then(function () { + bounce.redirect('https://appcenter.intuit.com/Connect/Begin?oauth_token=' + requestToken); + }); + }); + } else { + return this.generateSetupUrl(bounce) + .bind(this) + .then(function (qboSetupUrl) { + return bounce.set('IntuitSetup', true) + .then(function () { + bounce.redirect(qboSetupUrl); + }); + }); + } + bounce.done(); +}; + +QBOConnector.prototype.generateSetupUrl = function (bounce) { + var datasources = []; + return BBPromise.try(function () { + /* istanbul ignore else */ + if (bounce.query.quickbooks || (!(bounce.query.quickbooks) && !(bounce.query.payments))) { + datasources.push('quckbooks'); + } + /* istanbul ignore else */ + if (bounce.query.payments) { + datasources.push('payments'); + } + return 'https://appcenter.intuit.com/Connect/SessionStart?grantUrl=' + encodeURIComponent('https://' + config.get('Hoist.domains.bouncer') + '/bounce') + '&datasources=' + encodeURIComponent(datasources.join()); + }); +}; + +QBOConnector.prototype.get = function get(url, extraHeader) { + logger.info('inside hoist-connector-qbo.get'); + return this.request('GET', url, null, extraHeader); +}; + +QBOConnector.prototype.update = function put(url, data) { + logger.info('inside hoist-connector-qbo.put'); + var uri = require('url').parse(url, true); + uri.query.operation = 'update'; + delete uri.search; + delete uri.path; + return this.request('POST', require('url').format(uri), data); +}; +QBOConnector.prototype.delete = function put(url, data) { + logger.info('inside hoist-connector-qbo.put'); + var uri = require('url').parse(url, true); + uri.query.operation = 'delete'; + delete uri.search; + delete uri.path; + return this.request('POST', require('url').format(uri), data); +}; + +QBOConnector.prototype.create = function post(url, data) { + logger.info('inside hoist-connector-qbo.post'); + return this.request('POST', url, data); +}; + +QBOConnector.prototype.authorize = function (authorization) { + this.authorization = authorization; + this.settings.accessKey = authorization.get('AccessToken'); + this.settings.accessSecret = authorization.get('AccessTokenSecret'); + this.settings.companyId = authorization.get('CompanyId'); + +}; +QBOConnector.prototype.getRootUrl = function () { + var domain = 'quickbooks.api.intuit.com'; + if (this.settings.isSandbox) { + domain = 'sandbox--quickbooks-api-intuit-com-s404txkcwglf.runscope.net'; + var originalDomain = 'sandbox-quickbooks.api.intuit.com'; + this.auth._createSignatureBaseOriginal = this.auth._createSignatureBase; + this.auth._createSignatureBase = function (method, u, parameters) { + return this._createSignatureBaseOriginal(method, u.replace(domain, originalDomain), parameters); + }; + } + return 'https://' + domain + '/v3/company/' + this.settings.companyId; +}; +QBOConnector.prototype.request = function request(method, path, data) { + var contentType = 'application/json'; + data = data ? data : null; + + logger.info({ + method: method, + path: path + }, 'inside hoist-connector-qbo.request'); + return this.auth._performSecureRequestAsync(this.settings.accessKey, this.settings.accessSecret, method, this.getRootUrl() + path, null, data, contentType).spread(function (data) { + return JSON.parse(data); + }); +}; + + +module.exports = QBOConnector; diff --git a/pool/shard011/JavaScript/0069074_slick.js b/pool/shard011/JavaScript/0069074_slick.js new file mode 100644 index 0000000000000000000000000000000000000000..9d591348f2883c28bd3a9060b2e7b3d66370b988 --- /dev/null +++ b/pool/shard011/JavaScript/0069074_slick.js @@ -0,0 +1,58 @@ +// Generated by CoffeeScript 1.7.1 +(function() { + var __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; + + angular.module('bardo.directives', []); + + angular.module('bardo.directives').directive('slick', function($timeout) { + var SLICK_FUNCTION_WHITELIST, SLICK_OPTION_WHITELIST, isEmpty; + SLICK_OPTION_WHITELIST = ['accessiblity', 'autoplay', 'autoplaySpeed', 'arrows', 'cssEase', 'dots', 'draggable', 'fade', 'easing', 'infinite', 'onBeforeChange', 'onAfterChange', 'pauseOnHover', 'responsive', 'slide', 'slidesToShow', 'slidesToScroll', 'speed', 'swipe', 'touchMove', 'touchThreshold', 'vertical']; + SLICK_FUNCTION_WHITELIST = ['slickGoTo', 'slickNext', 'slickPrev', 'slickPause', 'slickPlay', 'slickAdd', 'slickRemove', 'slickFilter', 'slickUnfilter', 'unslick']; + isEmpty = function(value) { + var key; + if (angular.isArray(value)) { + return value.length === 0; + } else if (angular.isObject(value)) { + for (key in value) { + if (value.hasOwnProperty(key)) { + return false; + } + } + } + return true; + }; + return { + scope: { + settings: '=', + control: '=', + onDirectiveInit: '&' + }, + restrict: 'AE', + transclude: true, + terminal: true, + link: function(scope, element, attr, ngModel) { + $timeout((function() { + var options, slick; + element.addClass('bardo-slick'); + options = scope.settings || {}; + angular.forEach(attr, function(value, key) { + if (__indexOf.call(SLICK_OPTION_WHITELIST, key) >= 0) { + return options[key] = scope.$eval(value); + } + }); + slick = element.slick(options); + scope.internalControl = scope.control || {}; + SLICK_FUNCTION_WHITELIST.forEach(function(value) { + scope.internalControl[value] = function() { + slick[value].apply(slick, arguments); + }; + }); + scope.onDirectiveInit(); + }), 500); + } + }; + }); + +}).call(this); + +//# sourceMappingURL=slick.map diff --git a/pool/shard011/JavaScript/0069080_Server.js b/pool/shard011/JavaScript/0069080_Server.js new file mode 100644 index 0000000000000000000000000000000000000000..0b1f17337e1d2105b794e93c1beecb8932aa955c --- /dev/null +++ b/pool/shard011/JavaScript/0069080_Server.js @@ -0,0 +1,55 @@ +/* eslint-env mocha */ +const { Client } = require('irc-upd') +const ircs = require('../src') +const Message = require('../src/Message') +const assert = require('assert') + +const PORT = 30667 + +describe('ircs', () => { + let server + let client + beforeEach(done => { + client = null + server = ircs().listen(PORT, done) + .on('error', assert.fail) + }) + afterEach(done => { + if (client) client.disconnect() + server.close(done) + }) + + const connect = (nick = 'test', opts = { port: PORT }) => { + client = new Client('localhost', nick, { port: PORT }) + return client + } + + it('receives connections on a port', done => { + connect() + .on('error', assert.fail) + .on('connect', done) + }) + + it('passes messages through the appropriate middleware', done => { + let called = false + server.use(() => { called = true }) + server.use('OTHER', () => { + assert.fail('Middleware for other commands should not be called') + }) + server.use('TEST', () => { + assert.ok(called, 'Middleware without a command should always be called') + done() + }) + server.execute(new Message(null, 'TEST', [])) + }) + + it('executes middleware in order', done => { + let stage = 0 + server.use(() => { assert.strictEqual(stage++, 0) }) + server.use(() => { assert.strictEqual(stage++, 1) }) + server.use(() => { assert.strictEqual(stage++, 2) }) + server.use(() => { assert.strictEqual(stage++, 3) }) + server.use(() => { done() }) + server.execute(new Message(null, 'TEST', [])) + }) +}) diff --git a/pool/shard011/JavaScript/0069081_PosAnimation.js b/pool/shard011/JavaScript/0069081_PosAnimation.js new file mode 100644 index 0000000000000000000000000000000000000000..2630c978fcb534ca7fbd6fea5a3b1b189a701961 --- /dev/null +++ b/pool/shard011/JavaScript/0069081_PosAnimation.js @@ -0,0 +1,93 @@ +/* + * L.PosAnimation is used by Leaflet internally for pan animations. + */ + +L.PosAnimation = L.Evented.extend({ + + run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number]) + this.stop(); + + this._el = el; + this._inProgress = true; + this._newPos = newPos; + + this.fire('start'); + + el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + + 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)'; + + L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); + L.DomUtil.setPosition(el, newPos); + + // toggle reflow, Chrome flickers for some reason if you don't do this + L.Util.falseFn(el.offsetWidth); + + // there's no native way to track value updates of transitioned properties, so we imitate this + this._stepTimer = setInterval(L.bind(this._onStep, this), 50); + }, + + stop: function () { + if (!this._inProgress) { return; } + + // if we just removed the transition property, the element would jump to its final position, + // so we need to make it stay at the current position + + L.DomUtil.setPosition(this._el, this._getPos()); + this._onTransitionEnd(); + L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation + }, + + _onStep: function () { + var stepPos = this._getPos(); + if (!stepPos) { + this._onTransitionEnd(); + return; + } + // jshint camelcase: false + // make L.DomUtil.getPosition return intermediate position value during animation + this._el._leaflet_pos = stepPos; + + this.fire('step'); + }, + + // you can't easily get intermediate values of properties animated with CSS3 Transitions, + // we need to parse computed style (in case of transform it returns matrix string) + + _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/, + + _getPos: function () { + var left, top, matches, + el = this._el, + style = window.getComputedStyle(el); + + if (L.Browser.any3d) { + matches = style[L.DomUtil.TRANSFORM].match(this._transformRe); + if (!matches) { return; } + left = parseFloat(matches[1]); + top = parseFloat(matches[2]); + } else { + left = parseFloat(style.left); + top = parseFloat(style.top); + } + + return new L.Point(left, top, true); + }, + + _onTransitionEnd: function () { + L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); + + if (!this._inProgress) { return; } + this._inProgress = false; + + this._el.style[L.DomUtil.TRANSITION] = ''; + + // jshint camelcase: false + // make sure L.DomUtil.getPosition returns the final position value after animation + this._el._leaflet_pos = this._newPos; + + clearInterval(this._stepTimer); + + this.fire('step').fire('end'); + } + +}); diff --git a/pool/shard011/JavaScript/0069083_Note.js b/pool/shard011/JavaScript/0069083_Note.js new file mode 100644 index 0000000000000000000000000000000000000000..1d5f9ea58a64495ef35297b5c66825e9de9f54c5 --- /dev/null +++ b/pool/shard011/JavaScript/0069083_Note.js @@ -0,0 +1,119 @@ +import React, { Component, PropTypes } from 'react'; + +class Note extends Component { + + constructor(props){ + super(props); + this.state = { + noteIsOn: false + }; + } + + handleNoteOn(){ + this.setState({ + noteIsOn: true + }); + + this.props.onNoteOn(); + } + + handleNoteOff(){ + this.setState({ + noteIsOn: false + }); + + this.props.onNoteOff(); + } + + onMouseEnter(){ + const { + mouseIsDown + } = this.props; + + if(!mouseIsDown){ + return; + } + + this.handleNoteOn(); + } + + onMouseLeave(){ + const { + mouseIsDown + } = this.props; + + if(!mouseIsDown){ + return; + } + + this.handleNoteOff(); + } + + onMouseDown(){ + this.handleNoteOn(); + } + + onMouseUp(){ + this.handleNoteOff(); + } + + componentWillReceiveProps(nextProps){ + if(!this.props.noteIsDown && nextProps.noteIsDown){ + this.handleNoteOn(); + } + + if(this.props.noteIsDown && !nextProps.noteIsDown){ + this.handleNoteOff(); + } + } + + render(){ + const { + type, + isWhiteKey, + x, + height, + width + } = this.props; + + const { + noteIsOn + } = this.state; + + return ( + this.onMouseUp() } + onMouseDown={ e => this.onMouseDown() } + onMouseEnter={ e => this.onMouseEnter() } + onMouseLeave={ e => this.onMouseLeave() } + stroke={ isWhiteKey ? '#555555' : '979797' } + fill={ noteIsOn ? '#e19758' : isWhiteKey ? '#FFFFF7' : '4B4B4B' } + x={x} + y="0" + width={ isWhiteKey ? width : Math.floor(width / 2) } + height={ isWhiteKey ? height : Math.floor(height * 0.7 )} + /> + ); + } +} + +Note.propTypes = { + mouseIsDown: PropTypes.bool, + onNoteOn: PropTypes.func, + onNoteOff: PropTypes.func, + isWhiteKey: PropTypes.bool, + width: PropTypes.number, + height: PropTypes.number, + x: PropTypes.number, + noteIsDown: PropTypes.bool, +}; + +Note.defaultProps = { + x: 0, + width: 80, + height: 400, + onNoteOn: () => {}, + onNoteOff: () => {} +}; + +export default Note; diff --git a/pool/shard011/JavaScript/0069084_Radio.js b/pool/shard011/JavaScript/0069084_Radio.js new file mode 100644 index 0000000000000000000000000000000000000000..2cf126f5596ef2fb15deafc8d760e1d742ee0a6c --- /dev/null +++ b/pool/shard011/JavaScript/0069084_Radio.js @@ -0,0 +1,213 @@ +import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose"; +import _extends from "@babel/runtime/helpers/esm/extends"; +import * as React from 'react'; +import PropTypes from 'prop-types'; +import { deepmerge, refType } from '@material-ui/utils'; +import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled'; +import SwitchBase from '../internal/SwitchBase'; +import useThemeProps from '../styles/useThemeProps'; +import RadioButtonIcon from './RadioButtonIcon'; +import { alpha } from '../styles/colorManipulator'; +import capitalize from '../utils/capitalize'; +import createChainedFunction from '../utils/createChainedFunction'; +import useRadioGroup from '../RadioGroup/useRadioGroup'; +import { getRadioUtilityClass } from './radioClasses'; +import experimentalStyled, { shouldForwardProp } from '../styles/experimentalStyled'; + +const overridesResolver = (props, styles) => { + const { + styleProps + } = props; + return deepmerge(styles.root || {}, styles[`color${capitalize(styleProps.color)}`]); +}; + +const useUtilityClasses = styleProps => { + const { + classes, + color + } = styleProps; + const slots = { + root: ['root', `color${capitalize(color)}`] + }; + return _extends({}, classes, composeClasses(slots, getRadioUtilityClass, classes)); +}; + +const RadioRoot = experimentalStyled(SwitchBase, { + shouldForwardProp: prop => shouldForwardProp(prop) || prop === 'classes' +}, { + name: 'MuiRadio', + slot: 'Root', + overridesResolver +})(({ + theme, + styleProps +}) => _extends({ + /* Styles applied to the root element. */ + color: theme.palette.text.secondary +}, styleProps.color !== 'default' && { + '&.Mui-checked': { + color: theme.palette[styleProps.color].main, + '&:hover': { + backgroundColor: alpha(theme.palette[styleProps.color].main, theme.palette.action.hoverOpacity), + // Reset on touch devices, it doesn't add specificity + '@media (hover: none)': { + backgroundColor: 'transparent' + } + } + } +}, { + '&.Mui-disabled': { + color: theme.palette.action.disabled + } +})); +const defaultCheckedIcon = /*#__PURE__*/React.createElement(RadioButtonIcon, { + checked: true +}); +const defaultIcon = /*#__PURE__*/React.createElement(RadioButtonIcon, null); +const Radio = /*#__PURE__*/React.forwardRef(function Radio(inProps, ref) { + const props = useThemeProps({ + props: inProps, + name: 'MuiRadio' + }); + + const { + checked: checkedProp, + color = 'secondary', + name: nameProp, + onChange: onChangeProp, + size = 'medium' + } = props, + other = _objectWithoutPropertiesLoose(props, ["checked", "color", "name", "onChange", "size"]); + + const styleProps = _extends({}, props, { + color, + size + }); + + const classes = useUtilityClasses(styleProps); + const radioGroup = useRadioGroup(); + let checked = checkedProp; + const onChange = createChainedFunction(onChangeProp, radioGroup && radioGroup.onChange); + let name = nameProp; + + if (radioGroup) { + if (typeof checked === 'undefined') { + checked = radioGroup.value === props.value; + } + + if (typeof name === 'undefined') { + name = radioGroup.name; + } + } + + return /*#__PURE__*/React.createElement(RadioRoot, _extends({ + color: color, + type: "radio", + icon: /*#__PURE__*/React.cloneElement(defaultIcon, { + fontSize: size === 'small' ? 'small' : 'medium' + }), + checkedIcon: /*#__PURE__*/React.cloneElement(defaultCheckedIcon, { + fontSize: size === 'small' ? 'small' : 'medium' + }), + styleProps: styleProps, + classes: classes, + name: name, + checked: checked, + onChange: onChange, + ref: ref + }, other)); +}); +process.env.NODE_ENV !== "production" ? Radio.propTypes = { + // ----------------------------- Warning -------------------------------- + // | These PropTypes are generated from the TypeScript type definitions | + // | To update them edit the d.ts file and run "yarn proptypes" | + // ---------------------------------------------------------------------- + + /** + * If `true`, the component is checked. + */ + checked: PropTypes.bool, + + /** + * The icon to display when the component is checked. + */ + checkedIcon: PropTypes.node, + + /** + * Override or extend the styles applied to the component. + */ + classes: PropTypes.object, + + /** + * The color of the component. It supports those theme colors that make sense for this component. + * @default 'secondary' + */ + color: PropTypes.oneOf(['default', 'primary', 'secondary']), + + /** + * If `true`, the component is disabled. + */ + disabled: PropTypes.bool, + + /** + * If `true`, the ripple effect is disabled. + */ + disableRipple: PropTypes.bool, + + /** + * The icon to display when the component is unchecked. + */ + icon: PropTypes.node, + + /** + * The id of the `input` element. + */ + id: PropTypes.string, + + /** + * [Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#Attributes) applied to the `input` element. + */ + inputProps: PropTypes.object, + + /** + * Pass a ref to the `input` element. + */ + inputRef: refType, + + /** + * Name attribute of the `input` element. + */ + name: PropTypes.string, + + /** + * Callback fired when the state is changed. + * + * @param {object} event The event source of the callback. + * You can pull out the new value by accessing `event.target.value` (string). + * You can pull out the new checked state by accessing `event.target.checked` (boolean). + */ + onChange: PropTypes.func, + + /** + * If `true`, the `input` element is required. + */ + required: PropTypes.bool, + + /** + * The size of the component. + * `small` is equivalent to the dense radio styling. + * @default 'medium' + */ + size: PropTypes.oneOf(['medium', 'small']), + + /** + * The system prop that allows defining system overrides as well as additional CSS styles. + */ + sx: PropTypes.object, + + /** + * The value of the component. The DOM API casts this to a string. + */ + value: PropTypes.any +} : void 0; +export default Radio; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069086_InsteonDataCellRenderer.js b/pool/shard011/JavaScript/0069086_InsteonDataCellRenderer.js new file mode 100644 index 0000000000000000000000000000000000000000..6578bf12a4407d4c5d9acf35fd18221d4f75ca19 --- /dev/null +++ b/pool/shard011/JavaScript/0069086_InsteonDataCellRenderer.js @@ -0,0 +1,43 @@ + + + +/** + * This cell renderer adds a dialog for annotating events to table cells. + */ +define(function(require, exports, module) { + + // Load dependencies + var _ = require('underscore'); + var mvc = require('splunkjs/mvc'); + var $ = require('jquery'); + var AnnotateEventView = require('annotate_event_view'); + + var BaseCellRenderer = require('views/shared/results_table/renderers/BaseCellRenderer'); + + var InsteonDataCellRenderer = BaseCellRenderer.extend({ + + canRender: function(cell) { + return $.inArray(cell.field, ["status"]) >= 0; + }, + + render: function($td, cell) { + + // Handle ack + if(cell.field === "ack" && cell.value === "1" || cell.value === 1 || cell.value === "ack"){ + $td.html('ack'); + } + + //Handle nack + else if(cell.field === "ack" && cell.value === "-1" || cell.value === -1 || cell.value === "nack"){ + $td.html('nack'); + } + + // Handle other cases + else{ + $td.html(""); + } + } + }); + + return InsteonDataCellRenderer; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069087_MonitorController.js b/pool/shard011/JavaScript/0069087_MonitorController.js new file mode 100644 index 0000000000000000000000000000000000000000..f3bb39dd9a9d7b80fe9c4718b6ce85f72037c9cc --- /dev/null +++ b/pool/shard011/JavaScript/0069087_MonitorController.js @@ -0,0 +1,79 @@ +var path = require('path'), + mongoose = require('mongoose'), + passport = require('passport'), + chalk = require('chalk'); +var config = require(path.resolve('./config/env/default.js')), + errors = require(path.resolve('./config/lib/errors.js')), + is = require('is_js'), + logger = require(path.resolve('./config/lib/logger.js')), + _ = require('lodash'); + +const Farm = mongoose.model('Farm'); +const User = mongoose.model('User'); +const System = mongoose.model('System'); +const Device = mongoose.model('Device'); +const Vegetable = mongoose.model('Vegetable'); +const Growing = mongoose.model('Growing'); + +const errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); + +const nodemailer = require('nodemailer'); +const smtpTransport = nodemailer.createTransport(config.mailer.options); +// 统一参数错误信息 +const paramError = { error: '参数错误' }; + +const monitor = { + /** + * 获取order列表 + * @param ({farm_id, user}) param + * @return (Promise<[growing]>) return + */ + browseOrder(option) { + + validateOption(option) + .then(validateUserRole) + .then(getGrowings) + .then(sanitize) + .then(option => { + const { data } = option; + let growings = data; + return Promise.resolve(growings); + }) + .catch(err => { + return Promise.reject(err); + }); + + function validateOption(option) { + return Promise.resolve(option); + } + + /** + * 检测用户权限 + * @param (option) param + * @return (option) return + */ + function validateUserRole(option) { + return Promise.resolve(option); + } + + /** + * 获取growing + * @param (option) option + * @return (option) option + */ + function getGrowings(option) { + return Promise.resolve(option); + } + + /** + * 格式化数据 + * @param (option) option + * @return (option) option + */ + function sanitize(option) { + return Promise.resolve(option); + } + } +}; + +module.exports = monitor; diff --git a/pool/shard011/JavaScript/0069088_qDecorator.js b/pool/shard011/JavaScript/0069088_qDecorator.js new file mode 100644 index 0000000000000000000000000000000000000000..b6d219c9d4e2cac64a330fc3e1c4f00a385a63b0 --- /dev/null +++ b/pool/shard011/JavaScript/0069088_qDecorator.js @@ -0,0 +1,31 @@ +/** + * $q decorator. + * @file qDecorator.js. + * @copyright Copyright © Lunch-Time 2013 + */ +define([], function() { + 'use strict'; + + var qDecorator = ['$delegate', function ($delegate) { + + $delegate.rejectAsync = function(reason) { + var promise = $delegate.reject(reason); + + return { + then: promise.then, + 'catch': function(callback) { + promise.then(null, callback); + return promise; + }, + 'finally': function (callback) { + promise.then(null, callback); + return promise; + } + }; + }; + + return $delegate; + }]; + + return qDecorator; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069091_studentAssessmentExam.js b/pool/shard011/JavaScript/0069091_studentAssessmentExam.js new file mode 100644 index 0000000000000000000000000000000000000000..7385ed642a864670b7753d4bf47a58a79789f354 --- /dev/null +++ b/pool/shard011/JavaScript/0069091_studentAssessmentExam.js @@ -0,0 +1,45 @@ +var ERR = require('async-stacktrace'); +var express = require('express'); +var router = express.Router(); + +var error = require('@prairielearn/prairielib/error'); +var assessment = require('../../lib/assessment'); +var sqldb = require('@prairielearn/prairielib/sql-db'); +var sqlLoader = require('@prairielearn/prairielib/sql-loader'); + +var sql = sqlLoader.loadSqlEquiv(__filename); + +router.get('/', function(req, res, next) { + if (res.locals.assessment.type !== 'Exam') return next(); + if (res.locals.assessment.multiple_instance) { + res.render(__filename.replace(/\.js$/, '.ejs'), res.locals); + } else { + var params = { + assessment_id: res.locals.assessment.id, + user_id: res.locals.user.user_id, + }; + sqldb.query(sql.select_single_assessment_instance, params, function(err, result) { + if (ERR(err, next)) return; + if (result.rowCount == 0) { + res.render(__filename.replace(/\.js$/, '.ejs'), res.locals); + } else { + res.redirect(res.locals.urlPrefix + '/assessment_instance/' + result.rows[0].id); + } + }); + } +}); + +router.post('/', function(req, res, next) { + if (res.locals.assessment.type !== 'Exam') return next(); + if (!res.locals.authz_result.authorized_edit) return next(error.make(403, 'Not authorized', res.locals)); + if (req.body.__action == 'newInstance') { + assessment.makeAssessmentInstance(res.locals.assessment.id, res.locals.user.user_id, res.locals.authn_user.user_id, res.locals.authz_data.mode, res.locals.authz_result.time_limit_min, res.locals.req_date, (err, assessment_instance_id) => { + if (ERR(err, next)) return; + res.redirect(res.locals.urlPrefix + '/assessment_instance/' + assessment_instance_id); + }); + } else { + return next(error.make(400, 'unknown __action', {locals: res.locals, body: req.body})); + } +}); + +module.exports = router; diff --git a/pool/shard011/JavaScript/0069092_main.js b/pool/shard011/JavaScript/0069092_main.js new file mode 100644 index 0000000000000000000000000000000000000000..5e0af9eea9eee22852306a02c7fb4809fa748743 --- /dev/null +++ b/pool/shard011/JavaScript/0069092_main.js @@ -0,0 +1,40 @@ +"use strict"; + +const electron = require("electron"); +const path = require("path"); +const reload = require("electron-reload"); +const isDev = require("electron-is-dev"); +const { app, BrowserWindow, ipcMain, dialog } = electron; +let mainWindow = null; + +if (isDev) { + const electronPath = path.join(__dirname, "node_modules", ".bin", "electron"); + reload(__dirname, { electron: electronPath }); +} + +app.on("window-all-closed", () => { + if (process.platform !== "darwin") { + app.quit(); + } +}); + +app.on("ready", () => { + mainWindow = new BrowserWindow({ width: 800, height: 600 }); + mainWindow.loadURL(`file://${__dirname}/index.html`); + if (isDev) { + mainWindow.webContents.openDevTools({ mode: "detach" }); + } + + mainWindow.on("close", () => { + mainWindow = null; + }); +}); + +ipcMain.on("show-dialog", (e, arg) => { + const msgInfo = { + title: "My App Alert", + message: arg.message, + buttons: ["OK"] + }; + dialog.showMessageBox(msgInfo); +}); diff --git a/pool/shard011/JavaScript/0069094_expiry-date.js b/pool/shard011/JavaScript/0069094_expiry-date.js new file mode 100644 index 0000000000000000000000000000000000000000..334914f8f3bac26a2012ecf1bf6381d8a2b0af3a --- /dev/null +++ b/pool/shard011/JavaScript/0069094_expiry-date.js @@ -0,0 +1,46 @@ +define(function(require, exports, module) { + var Validator = require('bootstrap.validator'); + require('common/validator-rules').inject(Validator); + var Notify = require('common/bootstrap-notify'); + + require('jquery.bootstrap-datetimepicker'); + + exports.run = function() { + + var validator = new Validator({ + element: '#expiryday-set-form', + autoSubmit: false, + failSilently: true, + triggerType: 'change', + onFormValidated: function(error, results, $form){ + if (error) { + return false; + } + $('#student-save').button('loading').addClass('disabled'); + + $.post($form.attr('action'), $form.serialize(), function(response) { + if (response == true) { + Notify.success(Translator.trans('修改学员成功')); + } else { + Notify.danger(Translator.trans('修改学员失败')); + } + window.location.reload(); + }); + } + }); + + validator.addItem({ + element: '[name=deadline]', + required: true, + display: '有效期' + }); + + $("#student_deadline").datetimepicker({ + language: 'zh-CN', + autoclose: true, + format: 'yyyy-mm-dd', + minView: 'month' + }); + $("#student_deadline").datetimepicker('setStartDate', new Date); + }; +}); diff --git a/pool/shard011/JavaScript/0069095_useManualEventHandlers.spec.js b/pool/shard011/JavaScript/0069095_useManualEventHandlers.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..1c5c8c2c89d25c72861480bf64674bb1b298388e --- /dev/null +++ b/pool/shard011/JavaScript/0069095_useManualEventHandlers.spec.js @@ -0,0 +1,124 @@ +import * as React from 'react'; +import { render } from '@testing-library/react'; + +import useManualEventHandlers from '../../../src/components/UseManualEventHandlers'; + +import { Highcharts } from '../../test-utils'; +import HighchartContext from '../../../src/components/HighchartsContext'; + +describe('useManualEventHandlers', () => { + let ProvidedComponent; + let target; + + beforeEach(() => { + target = new Object(); + const Component = props => { + useManualEventHandlers(props, target); + return
    ; + }; + ProvidedComponent = props => ( + + + + ); + }); + + afterEach(() => { + Highcharts.removeEvent.mockClear(); + Highcharts.addEvent.mockClear(); + }); + + describe('when mounted', () => { + it('should call the Highcharts.addEvent', () => { + const onEventHandler = jest.fn(); + const onOtherEventHandler = jest.fn(); + + const props = { + enabled: true, + onEventHandler, + onOtherEventHandler, + onNotAFunction: 'trip', + something: 'stringy', + count: 14 + }; + + render(); + + expect(Highcharts.removeEvent).not.toHaveBeenCalled(); + expect(Highcharts.addEvent).toHaveBeenCalledWith( + target, + 'eventHandler', + onEventHandler + ); + expect(Highcharts.addEvent).toHaveBeenCalledWith( + target, + 'otherEventHandler', + onOtherEventHandler + ); + expect(Highcharts.addEvent).not.toHaveBeenCalledWith( + target, + 'onNotAFunction', + 'trip' + ); + }); + + it('should not call the Highcharts.addEvent when props is undefined', () => { + render(); + + expect(Highcharts.addEvent).not.toHaveBeenCalled(); + }); + }); + + describe('when updated', () => { + it('should call the Highcharts.removeEvent and addEvent with changed handlers', () => { + const onEventHandler = jest.fn(); + const onOtherEventHandler = jest.fn(); + const onThirdEventHandler = jest.fn(); + const props = { + onEventHandler, + onOtherEventHandler, + onThirdEventHandler + }; + + const wrapper = render(); + Highcharts.addEvent.mockClear(); + Highcharts.removeEvent.mockClear(); + const onNewOtherEventHandler = jest.fn(); + + const updatedProps = { + onEventHandler, + onOtherEventHandler: onNewOtherEventHandler + }; + wrapper.rerender(); + + expect(Highcharts.removeEvent).not.toHaveBeenCalledWith( + target, + 'eventHandler', + onEventHandler + ); + expect(Highcharts.addEvent).not.toHaveBeenCalledWith( + target, + 'eventHandler', + onEventHandler + ); + + expect(Highcharts.removeEvent).toHaveBeenCalledWith( + target, + 'otherEventHandler', + onOtherEventHandler + ); + expect(Highcharts.addEvent).toHaveBeenCalledWith( + target, + 'otherEventHandler', + onNewOtherEventHandler + ); + /* TODO removing eventhandlers completely fails. + expect(Highcharts.removeEvent).toHaveBeenCalledWith( + target, + 'thirdEventHandler', + onThirdEventHandler + ); + */ + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069096_address_and_contact.js b/pool/shard011/JavaScript/0069096_address_and_contact.js new file mode 100644 index 0000000000000000000000000000000000000000..4bdc9bb9e677672d6b4760f2710e78d0cb112a82 --- /dev/null +++ b/pool/shard011/JavaScript/0069096_address_and_contact.js @@ -0,0 +1,47 @@ +frappe.provide('frappe.contacts') + +$.extend(frappe.contacts, { + clear_address_and_contact: function(frm) { + $(frm.fields_dict['address_html'].wrapper).html(""); + frm.fields_dict['contact_html'] && $(frm.fields_dict['contact_html'].wrapper).html(""); + }, + + render_address_and_contact: function(frm) { + // render address + if(frm.fields_dict['address_html'] && "addr_list" in frm.doc.__onload) { + $(frm.fields_dict['address_html'].wrapper) + .html(frappe.render_template("address_list", + cur_frm.doc.__onload)) + .find(".btn-address").on("click", function() { + frappe.new_doc("Address"); + }); + } + + // render contact + if(frm.fields_dict['contact_html'] && "contact_list" in frm.doc.__onload) { + $(frm.fields_dict['contact_html'].wrapper) + .html(frappe.render_template("contact_list", + cur_frm.doc.__onload)) + .find(".btn-contact").on("click", function() { + frappe.new_doc("Contact"); + } + ); + } + }, + get_last_doc: function(frm) { + const reverse_routes = frappe.route_history.reverse(); + const last_route = reverse_routes.find(route => { + return route[0] === 'Form' && route[1] !== frm.doctype + }) + let doctype = last_route && last_route[1]; + let docname = last_route && last_route[2]; + + if (last_route && last_route.length > 3) + docname = last_route.slice(2).join("/"); + + return { + doctype, + docname + } + } +}) \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069097_uxrocket.accordion.js b/pool/shard011/JavaScript/0069097_uxrocket.accordion.js new file mode 100644 index 0000000000000000000000000000000000000000..1e708d2f1f265b8e2ee88acff7e87b947c09c1c4 --- /dev/null +++ b/pool/shard011/JavaScript/0069097_uxrocket.accordion.js @@ -0,0 +1,283 @@ +/** + * UX Rocket + * jQuery based accordion + * @author Bilal Cinarli + * @author Kursad Yildirmak + */ + +(function(factory) { + 'use strict'; + if(typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['jquery'], factory); + } else if(typeof exports === 'object' && typeof require === 'function') { + // Browserify + factory(jQuery); + } else { + // Browser globals + factory(jQuery); + } +}(function($) { + var ux, + rocketName = 'uxrCollapsible', + i = 1, + + defaults = { + header: '.collapsible-header', + content: '.collapsible-content', + current: '', + closeSiblings: false, + animateWith: 'css', // css or js + duration: 200, + + onReady: false, + onOpen: false, + onClose: false, + waitOnOpen: false + }, + events = { + click: 'click.' + rocketName, + ready: 'uxrready.' + rocketName, + collapsed: 'uxrcollapsed.' + rocketName, + expanded: 'uxrexpanded.' + rocketName + }, + ns = { + prefix: 'uxr-', + rocket: 'uxRocket', + data: rocketName, + name: 'collapsible', + classes: { + node: 'node', + header: 'header', + content: 'content', + ready: 'ready', + current: 'current', + animate: 'animate' + } + }, + + utils = new uxrPluginUtils({ns: ns}); + + // Constructor + var Collapsible = function(el, options, selector) { + this._instance = i; + this._name = rocketName; + this._defaults = defaults; + + this.el = el; + this.$el = $(el); + this.options = $.extend(true, {}, defaults, options, this.$el.data()); + this.selector = selector; + this.siblings = this.$el.siblings(this.selector); + this.isActive = this.options.active || false; + this.currentClass = utils.getClassname('current') + ' ' + this.options.current; + + i++; + + this.init(); + }; + + Collapsible.prototype.init = function() { + if(this.el.id === '') { + this.el.id = ns.data + '-' + this._instance; + } + + this.registry(); + + this.getChildren(); + + // add ready class + this.decorateUI(); + + this.bindUI(); + + this.emitEvent('ready'); + }; + + Collapsible.prototype.handleClasses = function() { + this.$el.addClass(utils.getClassname('node') + ' ' + utils.getClassname('ready') + ' ' + utils.getClassname('animate') + this.options.animateWith.toUpperCase()); + + if(this.isActive || this.$el.hasClass(this.options.current)) { + this.$el.addClass(this.currentClass); + this.isActive = true; + } + }; + + Collapsible.prototype.handleChildClasses = function() { + this.$header.addClass(utils.getClassname('header')); + this.$content.addClass(utils.getClassname('content')); + }; + + Collapsible.prototype.getChildren = function() { + this.$header = this.$el.find('> ' + this.options.header); + this.$content = this.$el.find('> ' + this.options.content); + }; + + Collapsible.prototype.decorateUI = function() { + this.handleClasses(); + this.handleChildClasses(); + }; + + Collapsible.prototype.bindUI = function() { + var _this = this; + + this.$header.on(events.click, function() { + _this.toggle(); + }); + + this.$el + .on(events.ready, function() { + utils.callback(_this.options.onReady); + }) + .on(events.collapsed, function(e) { + _this.onCollapse(e); + }) + .on(events.expanded, function(e) { + _this.onExpand(e); + }); + }; + + Collapsible.prototype.unbindUI = function() { + this.$el.off('.' + rocketName); + this.$header.off('.' + rocketName); + }; + + Collapsible.prototype.onCollapse = function(e) { + if(this.el.id === e.target.id) { + // close children + ux.closeAll(this.$el); + + utils.callback(this.options.onClose); + } + }; + + Collapsible.prototype.onExpand = function(e) { + if(this.el.id === e.target.id) { + utils.callback(this.options.onOpen); + } + }; + + Collapsible.prototype.toggle = function() { + if(this.isActive) { + this.close(); + } + else { + this.open(); + } + }; + + Collapsible.prototype.closeSiblings = function() { + this.siblings.each(function() { + var $this = $(this), + collapsible = $this.data(rocketName); + + if(!$this.hasClass(utils.getClassname('current'))) { + return; + } + + if($this.hasClass(utils.getClassname('animate') + 'JS')) { + collapsible.$content.slideUp(); + } + + collapsible.isActive = false; + collapsible.emitEvent('collapsed'); + $this.removeClass(utils.getClassname('current') + ' ' + collapsible.options.current); + }); + }; + + Collapsible.prototype.open = function(force) { + if(this.options.animateWith === 'js') { + this.$content.slideDown(this.options.duration); + } + + if(this.options.closeSiblings && !force) { + this.closeSiblings(); + } + + if(!this.options.waitOnOpen) { + this.$el.addClass(this.currentClass); + this.isActive = true; + this.emitEvent('expanded'); + }else{ + if(this.options.waitOnOpen(this.$el)){ + this.$el.addClass(this.currentClass); + this.isActive = true; + this.emitEvent('expanded'); + } + } + }; + + Collapsible.prototype.close = function() { + if(this.options.animateWith === 'js') { + this.$content.slideUp(this.options.duration); + } + + this.$el.removeClass(this.currentClass); + this.isActive = false; + + this.emitEvent('collapsed'); + }; + + Collapsible.prototype.registry = function() { + var uxrocket = this.$el.data(ns.rocket) || {}; + + // register plugin data to rocket + uxrocket[ns.data] = { + hasWrapper: false, + ready: utils.getClassname('ready'), + selector: this.selector, + options: this.options + }; + + this.$el.data(ns.rocket, uxrocket); + }; + + Collapsible.prototype.emitEvent = function(which) { + this.$el.trigger(events[which]); + }; + + ux = $.fn.collapsible = $.fn.uxrcollapsible = $.uxrcollapsible = function(options) { + var selector = this.selector; + + return this.each(function() { + if($.data(this, ns.data)) { + return; + } + + // Bind the plugin and attach the instance to data + $.data(this, ns.data, new Collapsible(this, options, selector)); + }); + }; + + ux.openAll = function(parent) { + var $parent = $(parent); + + $parent + .find('.' + utils.getClassname('ready')) + .not('.' + utils.getClassname('current')) + .each(function() { + var collapsible = $(this).data(rocketName); + + collapsible.open(true); + }); + }; + + ux.closeAll = function(parent) { + var $parent = $(parent); + + $parent + .find('.' + utils.getClassname('ready')) + .filter('.' + utils.getClassname('current')) + .each(function() { + var collapsible = $(this).data(rocketName); + + collapsible.close(); + }); + }; + + // Version + ux.version = '1.3.3'; + + // settings + ux.settings = defaults; +})); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069100_SettingsWindow.js b/pool/shard011/JavaScript/0069100_SettingsWindow.js new file mode 100644 index 0000000000000000000000000000000000000000..bc4894133e905db4c2bcb355e1da445c791ee525 --- /dev/null +++ b/pool/shard011/JavaScript/0069100_SettingsWindow.js @@ -0,0 +1,43 @@ +function SettingsWindow() { + + var self = Ti.UI.createWindow({ + title:'Settings', + backgroundColor:'#fff' + }); + + + + var generalDataSet = [ + //{ title: 'Maps', hasChild:true, link:'ui/common/MapWindow'}, + { title: 'Preset Contacts', hasChild:true, link:'ui/common/PresetWindow'}, + { title: 'Message Default', hasChild:true, link:'/ui/common/MessageWindow'}, + ]; + + var tableView = Ti.UI.createTableView({ + + data: generalDataSet, + + }); + + + self.add(tableView); + + tableView.addEventListener('click', function(e){ + + if (e.rowData.link) { + newWindow = require(e.rowData.link); + Ti.API.info('link: ' + e.rowData.link); + + win = new newWindow({title:e.rowData.title,containingTab:self.containingTab,tabGroup:self.tabGroup}); + + } + self.containingTab.open(win,{animated:true}); + + }); + + return self; + + +} + +module.exports = SettingsWindow; diff --git a/pool/shard011/JavaScript/0069104_List.js b/pool/shard011/JavaScript/0069104_List.js new file mode 100644 index 0000000000000000000000000000000000000000..33b4809c861bc3cdd2c0d3cecb726597bd43ead0 --- /dev/null +++ b/pool/shard011/JavaScript/0069104_List.js @@ -0,0 +1,47 @@ +import { connect } from 'dva'; +import React from 'react'; +import Add from '../components/Add'; + +import List from '../components/List'; + +const Lists = ({ dispatch, lists, inputs }) => { + function handleDelete(id) { + dispatch({ + type: 'lists/delete', + payload: id + }); + } + + function handleAdd() { + dispatch({ + type: 'lists/add', + payload: inputs.input + }); + } + + function handelChange(e) { + dispatch({ + type: 'inputs/change', + payload: e.target.value + }); + } + + return ( +
    + +
    +
    +

    List of Products

    +
    + +
    + ); +}; + +const mapStateToProps = ({ inputs, lists }) => { + // 属性解析赋值处理 + return { inputs, lists }; +}; + +// export default Lists; +export default connect(mapStateToProps)(Lists); diff --git a/pool/shard011/JavaScript/0069105_app.js b/pool/shard011/JavaScript/0069105_app.js new file mode 100644 index 0000000000000000000000000000000000000000..3f7c694aadd65b8b1de68b8c4fb0aea445b49e27 --- /dev/null +++ b/pool/shard011/JavaScript/0069105_app.js @@ -0,0 +1,36 @@ +const md5 = require('blueimp-md5') +const core = require('./config/core') +const { md5Key } = core() +const manager = require('./config/manager') +const managerConfig = { ...manager, password: md5(manager.password, md5Key) } + +module.exports = app => { + app.beforeStart(async () => { + const ctx = app.createAnonymousContext() + try { + let initManager = await ctx.model.User.findOne(managerConfig) + if (initManager) { + console.log('super manager has existed') + } else { + await ctx.model.User.create(managerConfig) + console.log(`super manager user create success!`) + } + } catch (err) { + console.warn(`super manager user create fail! \n`, err) + } + }) + // 数字校验-允许提交字符串格式的数字 + app.validator.addRule('unstrict_number', (rule, value) => { + if (value && !isNaN(value)) { + value = Number(value) + } + if (typeof value !== 'number') { + return 'should be a number' + } + }) + app.validator.addRule('unstrict_boolean', (rule, value) => { + if (typeof value === 'boolean') return + if (value === 'false' || value === 'true') return + return 'should be a boolean' + }) +} diff --git a/pool/shard011/JavaScript/0069106_users.service.js b/pool/shard011/JavaScript/0069106_users.service.js new file mode 100644 index 0000000000000000000000000000000000000000..4863a6bc262f5f826a12940a9e53613b1b2ca332 --- /dev/null +++ b/pool/shard011/JavaScript/0069106_users.service.js @@ -0,0 +1,29 @@ +// Initializes the `users` service on path `/users` +const createService = require('feathers-rethinkdb'); +const hooks = require('./users.hooks'); +const filters = require('./users.filters'); + +module.exports = function () { + const app = this; + const Model = app.get('rethinkdbClient'); + const paginate = app.get('paginate'); + + const options = { + name: 'users', + Model, + paginate + }; + + // Initialize our service with any options it requires + app.use('/users', createService(options)); + + // Get our initialized service so that we can register hooks and filters + const service = app.service('users'); + + service.hooks(hooks); + + if (service.filter) { + service.filter(filters); + } + +}; diff --git a/pool/shard011/JavaScript/0069110_index.js b/pool/shard011/JavaScript/0069110_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4e6102d080931615711e1153235672c51ab1cdd4 --- /dev/null +++ b/pool/shard011/JavaScript/0069110_index.js @@ -0,0 +1,46 @@ +import Vue from 'vue' +import Router from 'vue-router' +import menuModule from 'vuex-store/modules/menu' +Vue.use(Router) + +export default new Router({ + mode: 'hash', // Demo is living in GitHub.io, so required! + linkActiveClass: 'is-active', + scrollBehavior: () => ({ y: 0 }), + routes: [ + { + name: 'Home', + path: '/', + component: require('../views/Home') + }, + { + name: 'Login', + path: '/login', + component: require('../views/auth/Login') + }, + { + name: 'Login Firebase', + path: '/login-firebase', + component: require('../views/auth/LoginFirebase') + }, + ...generateRoutesFromMenu(menuModule.state.items), + { + path: '*', + redirect: '/' + } + ] +}) + +// Menu should have 2 levels. +function generateRoutesFromMenu (menu = [], routes = []) { + for (let i = 0, l = menu.length; i < l; i++) { + let item = menu[i] + if (item.path) { + routes.push(item) + } + if (!item.component) { + generateRoutesFromMenu(item.children, routes) + } + } + return routes +} diff --git a/pool/shard011/JavaScript/0069116_gulpfile.js b/pool/shard011/JavaScript/0069116_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..722dda7a6bc01c4a55163e0ee1ea3594344a9bad --- /dev/null +++ b/pool/shard011/JavaScript/0069116_gulpfile.js @@ -0,0 +1,28 @@ +/* jshint node:true */ +var gulp = require('gulp'), + uglify = require('gulp-uglify'), + concat = require('gulp-concat'), + jshint = require("gulp-jshint"), + del = require('del'); + +gulp.task('clear', function(){ + del(['dist/future.js']); +}); + +gulp.task('default', ['clear'], function() { + gulp.src(['utils/regenerator-runtime.js']) + .pipe(concat('regenerator-runtime.js')) + .pipe(uglify()) + .pipe(gulp.dest('dist')); + gulp.src(['src/wx.js']) + .pipe(concat('wx.js')) + .pipe(uglify()) + .pipe(gulp.dest('dist')); + return gulp.src(['src/TimeoutError.js', + 'src/Future.js']) + .pipe(concat('future.js')) + .pipe(jshint()) + .pipe(jshint.reporter()) + .pipe(uglify()) + .pipe(gulp.dest('dist')); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069120_app.js b/pool/shard011/JavaScript/0069120_app.js new file mode 100644 index 0000000000000000000000000000000000000000..812dfc5b4f971e5607f816980912e511e9dd1496 --- /dev/null +++ b/pool/shard011/JavaScript/0069120_app.js @@ -0,0 +1,67 @@ +/* + * App startup code + * + * At this point, Quasar is configured and ready to use. (see main.js) + */ + +import Vue from 'vue' + +import '@/base/style/app.styl' +import 'quasar/dist/quasar.ie.polyfills' +import '@quasar/extras/roboto-font/roboto-font.css' +import '@quasar/extras/material-icons/material-icons.css' +import '@quasar/extras/fontawesome-v5/fontawesome-v5.css' + +import { sync } from 'vuex-router-sync' +import router from './router' +import datastore from './datastore' +import './socket' +import i18n from './i18n' +import log from '@/utils/log' +import './sentry' +import polyfill from '@/utils/polyfill' +import { DetectMobileKeyboardPlugin } from '@/utils/detectMobileKeyboard' +import { IconPlugin } from './icons' +import loadInitialData from './loadInitialData' + +import Root from '@/base/pages/Root' +import '@/utils/datastore/presenceReporter' +import '@/utils/performance' + +export default async function initApp () { + Vue.use(DetectMobileKeyboardPlugin) + Vue.use(IconPlugin) + + if (__ENV.DEV) { + log.setLevel('debug') + } + + sync(datastore, router) + + if (__ENV.CORDOVA) { + require('@/utils/cordova/setBaseURL') + } + + await Promise.all([ + loadInitialData(), + polyfill.init(), + ]) + + if (__ENV.CORDOVA) { + require('@/utils/cordova') + } + + /* eslint-disable no-new */ + const vueRoot = new Vue({ + el: '#q-app', + router, + store: datastore, + i18n, + render: h => h(Root), + }) + + // makes it easier to remote debug vue in cordova + // for example to access vuex, type this into the console + // window.vueRoot.$store.state + window.vueRoot = vueRoot +} diff --git a/pool/shard011/JavaScript/0069125_error-guard.js b/pool/shard011/JavaScript/0069125_error-guard.js new file mode 100644 index 0000000000000000000000000000000000000000..feb3e7610c463993b6ffa5f3ca835dc941db1492 --- /dev/null +++ b/pool/shard011/JavaScript/0069125_error-guard.js @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2015-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @polyfill + */ + +/* eslint-disable strict */ + +let _inGuard = 0; + +/** + * This is the error handler that is called when we encounter an exception + * when loading a module. This will report any errors encountered before + * ExceptionsManager is configured. + */ +let _globalHandler = function onError(e) { + throw e; +}; + +/** + * The particular require runtime that we are using looks for a global + * `ErrorUtils` object and if it exists, then it requires modules with the + * error handler specified via ErrorUtils.setGlobalHandler by calling the + * require function with applyWithGuard. Since the require module is loaded + * before any of the modules, this ErrorUtils must be defined (and the handler + * set) globally before requiring anything. + */ +const ErrorUtils = { + setGlobalHandler: function(fun) { + _globalHandler = fun; + }, + getGlobalHandler: function() { + return _globalHandler; + }, + reportError: function(error) { + _globalHandler && _globalHandler(error); + }, + reportFatalError: function(error) { + _globalHandler && _globalHandler(error, true); + }, + applyWithGuard: function(fun, context, args) { + try { + _inGuard++; + return fun.apply(context, args); + } catch (e) { + ErrorUtils.reportError(e); + } finally { + _inGuard--; + } + }, + applyWithGuardIfNeeded: function(fun, context, args) { + if (ErrorUtils.inGuard()) { + return fun.apply(context, args); + } else { + ErrorUtils.applyWithGuard(fun, context, args); + } + }, + inGuard: function() { + return _inGuard; + }, + guard: function(fun, name, context) { + if (typeof fun !== 'function') { + console.warn('A function must be passed to ErrorUtils.guard, got ', fun); + return null; + } + name = name || fun.name || ''; + function guarded() { + return ( + ErrorUtils.applyWithGuard( + fun, + context || this, + arguments, + null, + name + ) + ); + } + + return guarded; + } +}; + +global.ErrorUtils = ErrorUtils; diff --git a/pool/shard011/JavaScript/0069133_logger-utils.js b/pool/shard011/JavaScript/0069133_logger-utils.js new file mode 100644 index 0000000000000000000000000000000000000000..934adaee013f70ffe0bfe7b1635bba15b9f0ce76 --- /dev/null +++ b/pool/shard011/JavaScript/0069133_logger-utils.js @@ -0,0 +1,106 @@ +'use strict'; + +/** + * @ngdoc service + * @name ui.logger.logUtils + * @description + * # loggerUtils + * Service in the ui.logger. + */ +/** + * @ngdoc method + * @name $defaultLogger + * @methodOf ui.logger.logUtils + * @description + * Used to assign an instance of $log to service object, which can be used for console logging . + * @param {object} logger instance of logging service + * @returns {Object} returns logger instance + */ +/** + * @ngdoc method + * @name isEnabled + * @methodOf ui.logger.logUtils + * @description + * Checks if a particular logger level is enabled or not. + * @param {object} logger instance of logger. + * @param {string} type the logger level which is to checked + * @returns {Boolean} returns true if logger level is enabled + */ +/** + * @ngdoc method + * @name getLogData + * @methodOf ui.logger.logUtils + * @description + * Used to generate the log data corresponding to error or exceptions. + * @param {object} logger instance of logger. + * @param {object} exception the exception object corresponding to which log are to be generated + * @returns {Object} returns log information object containing name,time,url,message and stackframe corresponding to exception. + */ +angular.module('ui.logger') + .service('logUtils', function (StackTrace, $window,loggerLevels,$injector,sourceMapUtil) { + var $defaultLogger; + function errback(err) { + $defaultLogger.warn("Error server-side logging failed"); + $defaultLogger.log(err.message); + } + function log(logger,exception) { + var errorMessage = exception.toString(); + var eventLogDateTime = moment().format('LLL'); + var $q; + if(!(exception instanceof Error)){ + $q=$injector.get('$q'); + return $q.resolve({ + name:logger.name, + time:eventLogDateTime, + url: $window.location.href, + message: errorMessage + }); + }else{ + $q=$injector.get('$q'); + + return StackTrace.fromError(exception,StackTrace.$options).then(function(stackframes){ + var _promises=[]; + for(var a=0;a { + compile(, {req, res}).then((context) => { + const bundle = environment.bundle + res.send(` + + + + Frontful TodoMVC + + + + + ${context.style} + + + +
    ${context.view}
    + ${context.state} + + + + + `) + }).catch((error) => { + if (error instanceof Exceptions.Cancel) + next() + else + next(error) + }) +}) + +export default app diff --git a/pool/shard011/JavaScript/0069136_application.js b/pool/shard011/JavaScript/0069136_application.js new file mode 100644 index 0000000000000000000000000000000000000000..0848e01a4812bdab3138a41764c1ac90349e8536 --- /dev/null +++ b/pool/shard011/JavaScript/0069136_application.js @@ -0,0 +1,23 @@ +// Invoke 'strict' JavaScript mode +'use strict'; + +// Set the main application name +var mainApplicationModuleName = 'mean'; + +// Create the main application +var mainApplicationModule = angular.module(mainApplicationModuleName, ['ngRoute', 'users', 'example']); + +// Configure the hashbang URLs using the $locationProvider services +mainApplicationModule.config(['$locationProvider', + function($locationProvider) { + $locationProvider.hashPrefix('!'); + } +]); + +// Fix Facebook's OAuth bug +if (window.location.hash === '#_=_') window.location.hash = '#!'; + +// Manually bootstrap the AngularJS application +angular.element(document).ready(function() { + angular.bootstrap(document, [mainApplicationModuleName]); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069138_list-categorised.js b/pool/shard011/JavaScript/0069138_list-categorised.js new file mode 100644 index 0000000000000000000000000000000000000000..d6db4b77cca18e24a49a83959340046c1e77a2bd --- /dev/null +++ b/pool/shard011/JavaScript/0069138_list-categorised.js @@ -0,0 +1,58 @@ +/** @jsx React.DOM */ + +var React = require('react'), + SetClass = require('classnames'), + Tappable = require('react-tappable'), + Navigation = require('touchstonejs').Navigation, + Link = require('touchstonejs').Link, + UI = require('touchstonejs').UI; + +var Months = require('../../../data/months'); + +var HeaderList = React.createClass({ + render: function() { + + var months = []; + var lastSeason = ''; + + this.props.months.forEach(function(month, i) { + + var season = month.season; + + if (lastSeason !== season) { + lastSeason = season; + + months.push( +
    {season}
    + ); + } + + month.key = 'month-' + i; + months.push(
    {month.name}
    ); + }); + + return ( +
    + {months} +
    + ); + } +}); + +module.exports = React.createClass({ + mixins: [Navigation], + + render: function() { + + return ( + + + + + + + + + ); + } +}); diff --git a/pool/shard011/JavaScript/0069150_blood.js b/pool/shard011/JavaScript/0069150_blood.js new file mode 100644 index 0000000000000000000000000000000000000000..6ab1982f6c199ec7ad2b818e8a0639522fbf71f8 --- /dev/null +++ b/pool/shard011/JavaScript/0069150_blood.js @@ -0,0 +1,13 @@ +game.Blood = me.AnimationSheet.extend({ + init: function(x, y) { + var w = 32, h = 32; + this.parent(x, y, me.loader.getImage('trap'), w, h); + this.addAnimation('splat', [5,5,5,5,10,11,12,13,14], 30); + var _this = this; + this.setCurrentAnimation('splat', function() { + me.game.world.removeChild(_this); + return false; + }); + this.z = 220; + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069151_index.js b/pool/shard011/JavaScript/0069151_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d54f63c1e22771e1c98e9ce7e9068622955f79a4 --- /dev/null +++ b/pool/shard011/JavaScript/0069151_index.js @@ -0,0 +1,78 @@ +/* + The Conflict of Interest (COI) module of Kuali Research + Copyright © 2005-2016 Kuali, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see +*/ + +import styles from './style'; +import classNames from 'classnames'; +import React from 'react'; +import Sidebar from '../../sidebar'; +import ActionPanel from '../../action-panel'; +import InstructionEditor from '../../instruction-editor'; +import QuestionnaireConfig from '../../questionnaire-config'; +import {INSTRUCTION_STEP} from '../../../../../../coi-constants'; +import {AppHeader} from '../../../app-header'; + +export default function Questionnaire(props, {configState}) { + const {applicationState, config, editorStates, dirty} = configState; + + let instructionText = ''; + if (config.general.instructions && config.general.instructions[INSTRUCTION_STEP.FINANCIAL_ENTITIES]) { + instructionText = config.general.instructions[INSTRUCTION_STEP.FINANCIAL_ENTITIES]; + } + + let configSection; + if (applicationState) { + configSection = ( + + + + + ); + } + + return ( +
    + + + + +
    + Financial Entities Questionnaire +
    +
    + {configSection} + +
    +
    +
    +
    + ); +} + +Questionnaire.contextTypes = { + configState: React.PropTypes.object +}; diff --git a/pool/shard011/JavaScript/0069152_pg.js b/pool/shard011/JavaScript/0069152_pg.js new file mode 100644 index 0000000000000000000000000000000000000000..68b52a4e69143cffd1164f67cb195285e0eb7e37 --- /dev/null +++ b/pool/shard011/JavaScript/0069152_pg.js @@ -0,0 +1,33 @@ +'use strict'; + +var path = require('path') + , NAMES = require(path.join(__dirname, '..', 'names')) + , DB = NAMES.DB + , POSTGRES = NAMES.POSTGRES + ; + +function record(segment, scope) { + var duration = segment.getDurationInMillis() + , exclusive = segment.getExclusiveDurationInMillis() + , transaction = segment.trace.transaction + , type = transaction.isWeb() ? DB.WEB : DB.OTHER + , operation = segment.name + ; + + if (scope) transaction.measure(operation, scope, duration, exclusive); + + transaction.measure(operation, null, duration, exclusive); + transaction.measure(type, null, duration, exclusive); + transaction.measure(DB.ALL, null, duration, exclusive); + + if (segment.port > 0) { + var hostname = segment.host || 'localhost' + , location = hostname + ':' + segment.port + , instance = DB.INSTANCE + '/' + POSTGRES.PREFIX + '/' + location + ; + + transaction.measure(instance, null, duration, exclusive); + } +} + +module.exports = record; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069153_deck.js b/pool/shard011/JavaScript/0069153_deck.js new file mode 100644 index 0000000000000000000000000000000000000000..3315019d346328570e84d73cea8041fccb6c34a6 --- /dev/null +++ b/pool/shard011/JavaScript/0069153_deck.js @@ -0,0 +1,24 @@ +import React, {PropTypes} from 'react'; +import {Slide} from './slide'; + +const slides = [ + 'title', + 'mirage', + 'routes', + 'handler', + 'handler+redux', + 'server-hapi', + 'server-express' +]; + +export function Deck (props) { + return ( +
    + {slides.map(slide => )} +
    + ); +} + +Deck.propTypes = { + id: PropTypes.string.isRequired +}; diff --git a/pool/shard011/JavaScript/0069154_spinner.js b/pool/shard011/JavaScript/0069154_spinner.js new file mode 100644 index 0000000000000000000000000000000000000000..6d47a1627db9350ae453fbc058fe5c29ab52eb76 --- /dev/null +++ b/pool/shard011/JavaScript/0069154_spinner.js @@ -0,0 +1,41 @@ +var showSpinner = function() { + if ($("#nav-cover").length > 0) { + return; + } + var opts = { + lines: 13, // The number of lines to draw + length: 0, // The length of each line + width: 5, // The line thickness + radius: 10, // The radius of the inner circle + corners: 1, // Corner roundness (0..1) + rotate: 0, // The rotation offset + direction: 1, // 1: clockwise, -1: counterclockwise + color: '#fff', // #rgb or #rrggbb or array of colors + speed: 1, // Rounds per second + trail: 100, // Afterglow percentage + shadow: true, // Whether to render a shadow + hwaccel: true, // Whether to use hardware acceleration + className: 'spinner', // The CSS class to assign to the spinner + zIndex: 2e9, // The z-index (defaults to 2000000000) + top: 'auto', // Top position relative to parent in px + left: 'auto' // Left position relative to parent in px + }; + $("
    ").css({ + position: "absolute", + width: "100%", + height: "100%", + left: 0, + top: 0, + zIndex: 1000000, // to be on the safe side + backgroundColor: "rgba(0, 0, 0, 0.5)" + }).appendTo($("#navigation").css("position", "relative")); + $("#navigation").spin(opts); +}; + +var hideSpinner = function() { + if ($("#nav-cover").length == 0) { + return; + } + $("#nav-cover").remove(); + $("#navigation").spin(false); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069155_discovery_route.js b/pool/shard011/JavaScript/0069155_discovery_route.js new file mode 100644 index 0000000000000000000000000000000000000000..a8e78972980d51dbaee0425106c8fcc6c7481f74 --- /dev/null +++ b/pool/shard011/JavaScript/0069155_discovery_route.js @@ -0,0 +1,67 @@ +/** + The parent route for all discovery routes. Handles the logic for showing + the loading spinners. + + @class DiscoveryRoute + @extends Discourse.Route + @namespace Discourse + @module Discourse +**/ +Discourse.DiscoveryRoute = Discourse.Route.extend(Discourse.ScrollTop, Discourse.OpenComposer, { + + beforeModel: function(transition) { + if (transition.targetName.indexOf("discovery.top") === -1 && + Discourse.User.currentProp("should_be_redirected_to_top")) { + this.transitionTo("discovery.top"); + } + }, + + actions: { + loading: function() { + var controller = this.controllerFor('discovery'); + + // If we're already loading don't do anything + if (controller.get('loading')) { return; } + + controller.set('loading', true); + controller.set('scheduledSpinner', Ember.run.later(controller, function() { + this.set('loadingSpinner', true); + },500)); + }, + + loadingComplete: function() { + var controller = this.controllerFor('discovery'); + Ember.run.cancel(controller.get('scheduledSpinner')); + controller.setProperties({ loading: false, loadingSpinner: false }); + this._scrollTop(); + }, + + didTransition: function() { + this.send('loadingComplete'); + }, + + // clear a pinned topic + clearPin: function(topic) { + topic.clearPin(); + }, + + createTopic: function() { + this.openComposer(this.controllerFor('discovery/topics')); + }, + + changeBulkTemplate: function(w) { + var controllerName = w.replace('modal/', ''), + factory = this.container.lookupFactory('controller:' + controllerName); + + this.render(w, {into: 'topicBulkActions', outlet: 'bulkOutlet', controller: factory ? controllerName : 'topicBulkActions'}); + }, + + showBulkActions: function() { + var selected = this.controllerFor('discovery/topics').get('selected'); + Discourse.Route.showModal(this, 'topicBulkActions', selected); + this.send('changeBulkTemplate', 'modal/bulk_actions_buttons'); + } + } + +}); + diff --git a/pool/shard011/JavaScript/0069160_binary-search.js b/pool/shard011/JavaScript/0069160_binary-search.js new file mode 100644 index 0000000000000000000000000000000000000000..ec780954f3fe19455379390ec80a3097a85bc76f --- /dev/null +++ b/pool/shard011/JavaScript/0069160_binary-search.js @@ -0,0 +1,31 @@ +function solve(args) { + var input = args[0].split('\n').map(function(x) { + return +x; + }), + n = input[0], + numbers = input.slice(1, input.length - 2), + target = input[input.length - 1], + left = 0, + right = numbers.length - 1, + middle = (numbers.length / 2) | 0; + + numbers.sort(function(x, y) { + return x - y; + }); + + while (left <= right) { + if (target > numbers[middle]) { + left = middle + 1; + } else if (target < numbers[middle]) { + right = middle - 1; + } else { + return middle; + } + + middle = ((right + left) / 2) | 0; + } + + return -1; +} + +console.log(solve(['10\n1\n2\n4\n8\n16\n31\n32\n64\n77\n99\n32'])); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069161_fullscreen_test.js b/pool/shard011/JavaScript/0069161_fullscreen_test.js new file mode 100644 index 0000000000000000000000000000000000000000..ef4ce93d01b18d7abad1437420f3915cb1609449 --- /dev/null +++ b/pool/shard011/JavaScript/0069161_fullscreen_test.js @@ -0,0 +1,45 @@ +// Copyright 2015 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +goog.module('goog.dom.fullscreen_test'); +goog.setTestOnly(); + +const DomHelper = goog.require('goog.dom.DomHelper'); +const PropertyReplacer = goog.require('goog.testing.PropertyReplacer'); +const asserts = goog.require('goog.testing.asserts'); +const fullscreen = goog.require('goog.dom.fullscreen'); +const testSuite = goog.require('goog.testing.testSuite'); + +let domHelper; +let mockDoc; +let stubs; + +testSuite({ + setUp() { + mockDoc = {}; + domHelper = new DomHelper(); + stubs = new PropertyReplacer(); + stubs.replace(domHelper, 'getDocument', () => mockDoc); + }, + + testGetFullScreenElement() { + const element = document.createElement('div'); + mockDoc.fullscreenElement = element; + assertEquals(element, fullscreen.getFullScreenElement(domHelper)); + }, + + testGetFullScreenElementNotFullScreen() { + assertNull(fullscreen.getFullScreenElement(domHelper)); + }, +}); diff --git a/pool/shard011/JavaScript/0069163_scripts.js b/pool/shard011/JavaScript/0069163_scripts.js new file mode 100644 index 0000000000000000000000000000000000000000..8b6884aa94145390011b9a9e51ae6b480fe043b5 --- /dev/null +++ b/pool/shard011/JavaScript/0069163_scripts.js @@ -0,0 +1,79 @@ +/******************************************************************************* + * Copyright (c) 2015-2017 Red Hat, Inc. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: + * Red Hat, Inc. - initial API and implementation + *******************************************************************************/ + +'use strict'; + +var path = require('path'); +var gulp = require('gulp'); +var conf = require('./conf'); + +var browserSync = require('browser-sync'); +var webpack = require('webpack-stream'); + +var $ = require('gulp-load-plugins')(); + +function webpackWrapper(watch, test, callback) { + var webpackOptions = { + resolve: { extensions: ['', '.ts'] }, + watch: watch, + module: { + preLoaders: [{ test: /\.ts$/, exclude: /node_modules/, loader: 'tslint-loader'}], + loaders: [{ test: /\.ts$/, exclude: /node_modules/, loaders: ['ng-annotate', 'babel-loader', 'awesome-typescript-loader']}] + }, + output: { filename: 'index.module.js' } + }; + + if(watch) { + webpackOptions.devtool = 'inline-source-map'; + } + + var webpackChangeHandler = function(err, stats) { + if(err) { + conf.errorHandler('Webpack')(err); + } + $.util.log(stats.toString({ + colors: $.util.colors.supportsColor, + chunks: false, + hash: false, + version: false + })); + browserSync.reload(); + if(watch) { + watch = false; + callback(); + } + }; + + var sources = [ path.join(conf.paths.src, '/app/index.module.ts') ]; + if (test) { + sources.push(path.join(conf.paths.src, '/{app,components}/**/*.spec.ts')); + } + + return gulp.src(sources) + .pipe(webpack(webpackOptions, null, webpackChangeHandler)) + .pipe(gulp.dest(path.join(conf.paths.tmp, '/serve/app'))); +} + +gulp.task('scripts', ['colors', 'proxySettings'], function () { + return webpackWrapper(false, false); +}); + +gulp.task('scripts:watch', ['scripts'], function (callback) { + return webpackWrapper(true, false, callback); +}); + +gulp.task('scripts:test', ['colors', 'outputcolors', 'proxySettings'], function () { + return webpackWrapper(false, true); +}); + +gulp.task('scripts:test-watch', ['scripts'], function (callback) { + return webpackWrapper(true, true, callback); +}); diff --git a/pool/shard011/JavaScript/0069167_query1.js b/pool/shard011/JavaScript/0069167_query1.js new file mode 100644 index 0000000000000000000000000000000000000000..2005928b366bc442ae21e50441c9235ab29bdc19 --- /dev/null +++ b/pool/shard011/JavaScript/0069167_query1.js @@ -0,0 +1,31 @@ +var r = require('rethinkDB'); + +var log = log; //eslint-disable-line + +r.connect({ + host: 'localhost', + port: 28015 +}).then(function (conn){ + r.table('authors').run(conn).then(function (cursor){ + cursor.toArray(function (err, result) { + if (err) throw new err; + log(JSON.stringify(result, null, 2)); + }); + }); +}).catch(function (err){ + throw err; +}); + +r.connect({ + host: 'localhost', + port: 28015 +}).then(function (conn){ + r.table('authors').run(conn).then(function (cursor){ + cursor.toArray(function (err, result) { + if (err) throw new err; + log(JSON.stringify(result, null, 2)); + }); + }); +}).catch(function (err){ + throw err; +}); diff --git a/pool/shard011/JavaScript/0069168_tag.server.model.tests.js b/pool/shard011/JavaScript/0069168_tag.server.model.tests.js new file mode 100644 index 0000000000000000000000000000000000000000..2fa8eeb379f9f79171afa7a95de28c10a87e14d1 --- /dev/null +++ b/pool/shard011/JavaScript/0069168_tag.server.model.tests.js @@ -0,0 +1,65 @@ +'use strict'; + +/** + * Module dependencies. + */ +var should = require('should'), + mongoose = require('mongoose'), + User = mongoose.model('User'), + Tag = mongoose.model('Tag'); + +/** + * Globals + */ +var user, tag; + +/** + * Unit tests + */ +describe('Tag Model Unit Tests:', function() { + beforeEach(function(done) { + user = new User({ + firstName: 'Full', + lastName: 'Name', + displayName: 'Full Name', + email: 'test@test.com', + username: 'username', + password: 'password' + }); + + user.save(function() { + tag = new Tag({ + tag: 'Tag Name', + user: user + }); + + done(); + }); + }); + + describe('Method Save', function() { + it('should be able to save without problems', function(done) { + return tag.save(function(err) { + should.not.exist(err); + done(); + }); + }); + + it('should be able to show an error when try to save without tag', function(done) { + tag.tag = ''; + + return tag.save(function(err) { + should.exist(err); + done(); + }); + }); + }); + + afterEach(function(done) { + Tag.remove().exec(function(){ + User.remove().exec(function(){ + done(); + }); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069169_graph.js b/pool/shard011/JavaScript/0069169_graph.js new file mode 100644 index 0000000000000000000000000000000000000000..087c5d5188a1c9041c6c2014181aeda70cf5117f --- /dev/null +++ b/pool/shard011/JavaScript/0069169_graph.js @@ -0,0 +1,152 @@ +//based loosely on bostock's example and +//http://bl.ocks.org/d3noob/5141278 + +var nodes = data.nodes +var links = data.links +var count = 0 +for (i in links) { + if (count setState({ ...state, width: "half" })} + tooltip="Make This Card Smaller" + > + + call_received + + + ); + } else { + iconarray.push( + setState({ ...state, width: "full" })} + tooltip="Expand to Full Width" + > + + call_made + + + ); + } + } + + return ( +
    + + setState({ + ...state, + expanded: val + })} + expanded={state.expanded} + > + +
    + {iconarray} +
    +
    + {hasDropdown + ? + {this.props.dropdown} + + : null} + + + {this.props.children} + +
    +
    + ); + } +} + +export default ExpandableCard; diff --git a/pool/shard011/JavaScript/0069174_set.js b/pool/shard011/JavaScript/0069174_set.js new file mode 100644 index 0000000000000000000000000000000000000000..dcdc3528395f26eb6375c028246e047dced0ea35 --- /dev/null +++ b/pool/shard011/JavaScript/0069174_set.js @@ -0,0 +1,106 @@ +var cdlre = (function(cdlre) { + var extend = cdlre.extend, + assert = cdlre.assert; + + // Set(a, b, c, ...) makes a set keyed on |toString| values. + function Set(items) { + // Should be used like a constructor. + assert(this instanceof Set); + + this._map = {}; + for (var i = 0; i < items.length; ++i) + this._map[items[i]] = null; + this._length = items.length; + } + + Set.prototype.length = function Set__length() { + return this._length; + }; + + Set.prototype.pop = function() { + var self = this; + if (self.length() === 0) + throw new Error("Empty set"); + var result; + for (var key in self._map) { + if (!self._map.hasOwnProperty(key)) + continue; + result = key; + delete self._map[key]; + break; + } + self._length -= 1; + return result; + }; + + Set.prototype.getOnly = function Set__getOnly() { + assert(this.length() === 1); + return Object.keys(this._map)[0]; + }; + + Set.prototype.has = function(item) { + return item in this._map; + }; + + // Apply |mapFun| to both the elements of the set and the target, and then + // test for membership. + Set.prototype.hasWithMap = function(target, mapFun) { + var mappedTarget = mapFun(target); + + for (var item in this._map) { + if (!this._map.hasOwnProperty(item)) + continue; + + var mappedItem = mapFun(item); + if (mappedItem === mappedTarget) + return true; + } + + return false; + } + + Set.prototype.each = function(callback) { + for (var key in this._map) { + if (!this._map.hasOwnProperty(key)) + continue; + var result = callback(key); + if (result) // Truthy value indicates early return, like "break". + return; + } + }; + + Set.prototype.toString = function() { + var pieces = ['Set(']; + var saw = false; + for (var key in this._map) { + if (!this._map.hasOwnProperty(key)) + continue; + saw = true; + pieces.push(uneval(key), ', '); + } + if (saw) + pieces.pop(); + pieces.push(')') + return pieces.join(''); + }; + + function SetUnion(set1, set2) { + return { + has: function(val) { return set1.has(val) || set2.has(val); }, + toString: function() { return 'SetUnion(' + set1 + ', ' + set2 + ')'; } + }; + }; + + function SetDifference(set1, set2) { + return { + has: function(val) { return set1.has(val) && !set2.has(val); }, + toString: function() { return 'SetDifference(' + set1 + ', ' + set2 + ')'; } + }; + }; + + return extend(cdlre, { + Set: Set, + SetUnion: SetUnion, + SetDifference: SetDifference, + }); +})(cdlre); diff --git a/pool/shard011/JavaScript/0069176_app.module.js b/pool/shard011/JavaScript/0069176_app.module.js new file mode 100644 index 0000000000000000000000000000000000000000..2f9a8f52b063b6e296356e737bdee994f463f19d --- /dev/null +++ b/pool/shard011/JavaScript/0069176_app.module.js @@ -0,0 +1,32 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var core_1 = require('@angular/core'); +var platform_browser_1 = require('@angular/platform-browser'); +var dive_log_component_1 = require('./dive-log.component'); +var dive_data_pipe_1 = require('./dive-data.pipe'); +var AppModule = (function () { + function AppModule() { + } + AppModule = __decorate([ + core_1.NgModule({ + imports: [platform_browser_1.BrowserModule], + declarations: [ + dive_log_component_1.DiveLogComponent, + dive_data_pipe_1.DiveDataPipe + ], + bootstrap: [dive_log_component_1.DiveLogComponent] + }), + __metadata('design:paramtypes', []) + ], AppModule); + return AppModule; +}()); +exports.AppModule = AppModule; +//# sourceMappingURL=app.module.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069180_index.js b/pool/shard011/JavaScript/0069180_index.js new file mode 100644 index 0000000000000000000000000000000000000000..8a300bf7bad783ad3d2cb2423bf1915e60f3a4c9 --- /dev/null +++ b/pool/shard011/JavaScript/0069180_index.js @@ -0,0 +1,135 @@ +import styled from 'styled-components'; +import _ from 'lodash'; +import React from 'react'; +import { fadein2 } from 'styles/animations'; +import GithubIcon from 'react-icons/lib/fa/github'; +import LinkedInIcon from 'react-icons/lib/fa/linkedin'; +import PhoneIcon from 'react-icons/lib/fa/phone'; +import EmailIcon from 'react-icons/lib/fa/envelope-o'; +import ResumeIcon from 'react-icons/lib/fa/file-text-o'; + +import ClipboardButton from 'react-clipboard.js'; +import ReactTooltip from 'react-tooltip' + +const ShelfContainer = styled.div` + position: fixed; + right: 0; + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; + z-index: 5; + + padding: 0px 15px; + border-bottom-left-radius: 10px; + background-color: rgba(255, 255, 255, 0.8); + + color: white; + + animation: ${fadein2} 0.5s; + + @media (max-device-width: 700px) { + width: 100%; + border-bottom-left-radius: 0px; + } +` + +const ShelfButton = styled.a` + margin: 5px 10px 0px 10px; + margin-top: 0; + font-size: 20px; + text-decoration: none; + color: #333; + transition: all 0.5s; + + &:focus { + outline:0 !important; + } + + &:hover { + color: orange; + transform: scale(1.2); + transition: all 0.5s; + } +` + +const ShelfButton2 = styled(ClipboardButton)` + margin: 0px 3px 0px 3px; + font-size: 20px; + text-decoration: none; + color: #333; + transition: all 0.5s; + + &:focus { + outline:0 !important; + } + + &:hover { + color: orange; + transform: scale(1.1); + transition: all 0.5s; + } +` +// +// const ShelfText = styled.div` +// font-size: 12px; +// color: black; +// cursor: pointer; +// transition: all 0.5s; +// +// &:hover { +// color: #555; +// transform: scale(1.1); +// transition: all 0.5s; +// } +// ` +// +// const VL = styled.div` +// width: 2px; +// height: 12px; +// background-color: #555; +// margin: 2px 15px 0 15px; +// +// @media (max-device-width: 480px) { +// margin: 2px 3px 0 3px; +// width: 1px; +// } +// ) +// ` + +const items = [ + { url: 'https://github.com/ZhengRaymond', name: 'GitHub', button: , text: null }, + { url: 'https://www.linkedin.com/in/ZhengRaymond/', name: 'LinkedIn', button: , text: null }, + { value: 'raymond.zheng@uwaterloo.ca', name: 'Email', button: , text: 'raymond.zheng@edu.uwaterloo.ca' }, + { value: '2266001234', name: 'Phone', button: , text: '(226) 600-1234' }, + { url: "https://github.com/ZhengRaymond/resume/blob/master/Raymond Zheng's Resume.pdf?raw=true", name: 'Resume', button: , text: null }, +] + +export default class Shelf extends React.Component { + render() { + return ( + + setTimeout(() => ReactTooltip.hide(), 1500)}/> + { + _.map(items, (item) => { + if (item.url) { + return ( + {item.button} + ) + } + else { + return ( +
    + + {item.button} + +
    + ) + } + }) + } +
    + ) + } + +} diff --git a/pool/shard011/JavaScript/0069181_Form.js b/pool/shard011/JavaScript/0069181_Form.js new file mode 100644 index 0000000000000000000000000000000000000000..522ba178d7e5608cad658a4c227f9d1623507190 --- /dev/null +++ b/pool/shard011/JavaScript/0069181_Form.js @@ -0,0 +1,144 @@ +/* This software is licensed under a BSD license; see the LICENSE file for details. */ + +$.widget("ui.Form", { + _init: function () { + this.cssPrefix = this.options._cssPrefix; + this.finishedCallback = this.options._finishedCallback; + this.utils = this.options._utils; + + this.html = dget(this.options, "html"); + this.continueMessage = dget(this.options, "continueMessage", "Click here to continue"); + this.checkedValue = dget(this.options, "checkedValue", "yes"); + this.uncheckedValue = dget(this.options, "uncheckedValue", "no"); + this.validators = dget(this.options, "validators", { }); + this.errorCSSClass = dget(this.options, "errorCSSClass", "error"); + this.obligatoryErrorGenerator = + dget(this.options, "obligatoryErrorGenerator", + function (field) { return "The \u2018" + field + "\u2019 field is obligatory."; }); + this.obligatoryCheckboxErrorGenerator = + dget(this.options, "obligatoryCheckboxErrorGenerator", + function (field) { return "You must check the " + field + " checkbox to continue."; }); + this.obligatoryRadioErrorGenerator = + dget(this.options, "obligatoryRadioErrorGenerator", + function (field) { return "You must select an option for \u2018" + field + "\u2019."; }); + + var t = this; + + function alertOrAddError(name, error) { + var ae = $("label." + escape(t.errorCSSClass) + "[for=__ALL_FIELDS__]"); + if (ae.length > 0) { + ae.addClass(t.cssPrefix + "error-text").text(error); + return; + } + + var e = $("label." + escape(t.errorCSSClass) + "[for=" + escape(name) + "]"); + if (e.length > 0) + e.addClass(t.cssPrefix + "error-text").text(error); + else + alert(error); + } + + var HAS_LOADED = false; + + function handleClick(dom) { + return function (e) { + e.preventDefault(); + if (! HAS_LOADED) return; + + // Get rid of any previous errors. + $("." + t.cssPrefix + "error-text").empty(); + + var rlines = []; + + var inps = $(dom).find("input[type=text]"); + var tas = $(dom).find("textarea"); + for (var i = 0; i < tas.length; ++i) { inps.push(tas[i]); } + + for (var i = 0; i < inps.length; ++i) { + var inp = $(inps[i]); + + if (inp.hasClass("obligatory") && ((! inp.attr('value')) || inp.attr('value').match(/^\s*$/))) { + alertOrAddError(inp.attr('name'), t.obligatoryErrorGenerator(inp.attr('name'))); + return; + } + + if (t.validators[inp.attr('name')]) { + var er = t.validators[inp.attr('name')](inp.attr('value')); + if (typeof(er) == "string") { + alertOrAddError(inp.attr('name'), er); + return; + } + } + + rlines.push([["Field name", custom_url_encode(inp.attr('name'))], + ["Field value", custom_url_encode(inp.attr('value'))]]); + } + + var checks = $(dom).find("input[type=checkbox]"); + for (var i = 0; i < checks.length; ++i) { + var check = $(checks[i]); + + // Checkboxes with the 'obligatory' class must be checked. + if (! check.attr('checked') && check.hasClass('obligatory')) { + alertOrAddError(check.attr('name'), t.obligatoryCheckboxErrorGenerator(check.attr('name'))); + return; + } + + rlines.push([["Field name", check.attr('name')], + ["Field value", check.attr('checked') ? t.checkedValue : t.uncheckedValue]]); + } + + var rads = $(dom).find("input[type=radio]"); + // Sort by name. + var rgs = { }; + for (var i = 0; i < rads.length; ++i) { + var rad = $(rads[i]); + if (rad.attr('name')) { + if (! rgs[rad.attr('name')]) + rgs[rad.attr('name')] = []; + rgs[rad.attr('name')].push(rad); + } + } + for (k in rgs) { + // Check if it's oblig. + var oblig = false; + var oneIsSelected = false; + var oneThatWasSelected; + var val; + for (var i = 0; i < rgs[k].length; ++i) { + if (rgs[k][i].hasClass('obligatory')) oblig = true; + if (rgs[k][i].attr('checked')) { + oneIsSelected = true; + oneThatWasSelected = i; + val = rgs[k][i].attr('value'); + } + } + if (oblig && (! oneIsSelected)) { + alertOrAddError(rgs[k][0].attr('name'), t.obligatoryRadioErrorGenerator(rgs[k][0].attr('name'))); + return; + } + if (oneIsSelected) { + rlines.push([["Field name", rgs[k][0].attr('name')], + ["Field value", rgs[k][oneThatWasSelected].attr('value')]]); + } + } + + t.finishedCallback(rlines); + } + } + + var dom = htmlCodeToDOM(this.html, function (dom) { HAS_LOADED = true; }); + t.element.append(dom); + t.element.append($("

    ").append($("").attr('href', '').text("\u2192 " + t.continueMessage) + .addClass(ibex_controller_name_to_css_prefix("Message") + "continue-link") + .click(handleClick(dom)))); + } +}); + +ibex_controller_set_properties("Form", { + obligatory: ["html"], + countsForProgressBar: false, + htmlDescription: function (opts) { + return htmlCodeToDOM(opts.html); + } +}); diff --git a/pool/shard011/JavaScript/0069182_supports-cache.js b/pool/shard011/JavaScript/0069182_supports-cache.js new file mode 100644 index 0000000000000000000000000000000000000000..5aca1a45e5c86df757dc5a1d0117bc7c5a270328 --- /dev/null +++ b/pool/shard011/JavaScript/0069182_supports-cache.js @@ -0,0 +1,70 @@ +/*jshint unused:vars */ +define(function defineSupportsCache(require) { + 'use strict'; + + /* + Facility to cache test results in localStorage. + + USAGE: + cache.get('key'); + cache.set('key', 'value'); + */ + + function readLocalStorage(key) { + if (!document.hasFocus()) { + // if the document does not have focus when tests are executed, focus() may + // not be handled properly and eventy may not be dispatched immediately. + // This can happen when a document is reloaded while Developer Tools have focus. + window.console && window.console.warn && console.warn('document requires focus for a11y support tests'); + return {}; + } + + var data; + try { + data = window.localStorage && window.localStorage.getItem(key); + data = data ? JSON.parse(data) : {}; + } catch (e) { + data = {}; + } + + return data; + } + + function writeLocalStorage(key, value) { + if (!document.hasFocus()) { + // if the document does not have focus when tests are executed, focus() may + // not be handled properly and eventy may not be dispatched immediately. + // This can happen when a document is reloaded while Developer Tools have focus. + try { + window.localStorage && window.localStorage.removeItem(key); + } catch(e) {} + + return; + } + + try { + window.localStorage && window.localStorage.setItem(key, JSON.stringify(value)); + } catch (e) {} + } + + var userAgent = window.navigator.userAgent; + var cacheKey = 'ally-supports-cache'; + var cache = readLocalStorage(cacheKey); + + // update the cache if the user agent changes (newer version, etc) + if (cache.userAgent !== userAgent) { + cache = {}; + } + + cache.userAgent = userAgent; + + return { + get: function getCacheValue(key) { + return cache[key]; + }, + set: function setCacheValue(key, value) { + cache[key] = value; + writeLocalStorage(cacheKey, cache); + } + }; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069184_test.js b/pool/shard011/JavaScript/0069184_test.js new file mode 100644 index 0000000000000000000000000000000000000000..9f166600b4995fbc71c5e5ae362f5166cb7ecbc4 --- /dev/null +++ b/pool/shard011/JavaScript/0069184_test.js @@ -0,0 +1,148 @@ +var assert = require('assert'), + Re = require('../lib/re'), + // WARNING: CHANGING ANY OF THE FOLLOWING THREE PARAMATER WILL AFFECT TEST DURATION + RETRIES = 4, + INTERVAL = 15, + options = {retries: RETRIES, strategy: {type: Re.STRATEGIES.CONSTANT, initial: INTERVAL}}, + re; + +describe("re.try", function(){ + beforeEach(function(){ + re = new Re(options); + }); + + it("should retry when done is called with an error", function(complete){ + var TEST_TRIES = 2, + testTryCount = 0; + + re.try(function(retryCount, done){ + var err = (testTryCount < TEST_TRIES) ? new Error("sux0r") : null; + testTryCount++; + + done(err, retryCount); + }, + function(err, retryCount){ + assert.ok(testTryCount > 1, "Didn't try more than once."); + complete(); + }); + }); + + it("should run at least 'retries' + 1 times, if done called with error", function(complete){ + var testTryCount = 0; + + re.try(function(retryCount, done){ + testTryCount++; + done(new Error("sux0r")); + }, + function(err, retryCount){ + assert.ok(testTryCount >= (RETRIES + 1), "Didn't try hard enough."); + complete(); + }); + }); + + it("should run at most 'retries' + 1 times, if done called with error", function(complete){ + var testTryCount = 0; + + re.try(function(retryCount, done){ + testTryCount++; + done(new Error("sux0r")); + }, + function(err, retryCount){ + assert.ok(testTryCount <= (RETRIES + 1), "Tried too hard."); + complete(); + }); + }); + + it("should callback with a falsy err, if success happens within retries", function(complete){ + + re.try(function(retryCount, done){ + + var err = (retryCount < RETRIES) ? new Error("sux0r") : null; + + done(err, retryCount); + }, + function(err, retryCount){ + if(err) throw err; + complete(); + }); + }); + + it("should callback with a truthy err, if no success happens", function(complete){ + + re.try(function(retryCount, done){ + done(new Error("sux0r")); + }, + function(err, retryCount){ + assert.ok(err, "There should have been an error, but wasn't.") + complete(); + }); + }); + + it("should retry when an exception is thrown", function(complete){ + var TEST_TRIES = 2, + testTryCount = 0; + + re.try(function(retryCount, done){ + testTryCount++; + + if(testTryCount < TEST_TRIES) throw new Error("sux0r"); + + done(null, retryCount); + }, + function(err, retryCount){ + assert.ok(testTryCount > 1, "Didn't try more than once."); + complete(); + }); + }); + + it("should run at least 'retries' + 1 times, if exception always thrown", function(complete){ + var testTryCount = 0; + + re.try(function(retryCount, done){ + testTryCount++; + throw new Error("sux0r"); + }, + function(err, retryCount){ + assert.ok(testTryCount >= (RETRIES + 1), "Didn't try hard enough."); + complete(); + }); + }); + + it("should run at most 'retries' + 1 times, if exception always thrown", function(complete){ + var testTryCount = 0; + + re.try(function(retryCount, done){ + testTryCount++; + throw new Error("sux0r"); + }, + function(err, retryCount){ + assert.ok(testTryCount <= (RETRIES + 1), "Tried too hard."); + complete(); + }); + }); + + it("should callback with a falsy err, if success happens within retries", function(complete){ + + re.try(function(retryCount, done){ + + if(retryCount < RETRIES) throw new Error("sux0r"); + + done(null, retryCount); + }, + function(err, retryCount){ + if(err) throw err; + complete(); + }); + }); + + it("should callback with a truthy err, if no success happens", function(complete){ + + re.try(function(retryCount, done){ + throw new Error("sux0r"); + }, + function(err, retryCount){ + assert.ok(err, "There should have been an error, but wasn't.") + complete(); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069186_router.js b/pool/shard011/JavaScript/0069186_router.js new file mode 100644 index 0000000000000000000000000000000000000000..29f07a75d1d2708e05cce813c1d99b1141c7714b --- /dev/null +++ b/pool/shard011/JavaScript/0069186_router.js @@ -0,0 +1,191 @@ +"use strict"; + +var $ = require('jquery'), + _ = require('underscore'), + Backbone = require('backbone'), + models = require('./models'), + views = require('./views'), + logger = require('./logger'), + querystring = require('querystring'); + +module.exports = Backbone.Router.extend({ + + initialize: function(options) { + this.app = options.app; + logger.debug("Init router"); + + this.on("route", this.everyRoute); + }, + + routes: { + "": "listProjects", + "blueprints": "listBlueprints", + "blueprints/new": "newBlueprint", + "blueprints/:slug": "editBlueprint", + "blueprints/:slug/new_project": "newProject", + "blueprints/:slug/edit": "editBlueprint", + "projects": "listProjects", + "projects/new": "chooseBlueprint", + "projects/:slug": "editProject", + "projects/:slug/edit": "editProject" + }, + + // This is called for every route + everyRoute: function(route, params) { + this.app.trigger( 'loadingStart' ); + this.app.analyticsEvent( 'pageview' ); + this.app.listener.start(); + if ( params ) { + logger.debug(route, params); + } else { + logger.debug(route); + } + }, + + listBlueprints: function(params) { + var blueprints = this.app.blueprints, + app = this.app, query = {}, view; + if(params) { query = querystring.parse(params); } + + Promise.resolve( blueprints.fetch() ).then(function() { + view = new views.ListBlueprints({ collection: blueprints, query: query, app: app }); + view.render(); + app.view + .display( view ) + .setTab('blueprints'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + }, + + newBlueprint: function() { + var blueprint = new models.Blueprint(), + view = new views.EditBlueprint({ model: blueprint, app: this.app }); + this.app.view + .display( view ) + .setTab('blueprints'); + + view.render(); + }, + + editBlueprint: function(slug) { + var blueprint = this.app.blueprints.findWhere({ slug: slug }), + maybeFetch = Promise.resolve(), + app = this.app, view; + + if ( !blueprint ) { + blueprint = new models.Blueprint({ id: slug }); + this.app.blueprints.add(blueprint); + maybeFetch = Promise.resolve( blueprint.fetch() ); + } + + maybeFetch.then(function() { + var view = new views.EditBlueprint({ model: blueprint, app: app }); + view.render(); + app.view + .display( view ) + .setTab('blueprints'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + }, + + chooseBlueprint: function(params) { + var blueprints = this.app.blueprints, + app = this.app, query = {}, view; + + if(params) { query = querystring.parse(params); } + query['status'] = 'ready'; + + Promise.resolve( blueprints.fetch() ).then(function() { + view = new views.ChooseBlueprint({ collection: blueprints, query: query, app: app }); + view.render(); + app.view + .display( view ) + .setTab('projects'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + }, + + listProjects: function(params) { + var projects = this.app.projects, + app = this.app, query = {}, view, jqxhr; + + if(params) { query = querystring.parse(params); } + + if (query.page) { + jqxhr = projects.getPage(parseInt(query.page)); + } else { + jqxhr = projects.getFirstPage(); + } + + Promise.resolve( jqxhr ).then(function() { + view = new views.ListProjects({ + collection: projects, + query: _.pick(query, 'status', 'blueprint_type', 'theme', 'search'), + app: app + }); + view.render(); + app.view + .display( view ) + .setTab('projects'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + }, + + newProject: function(slug) { + var blueprint = this.app.blueprints.findWhere({ slug: slug }), + maybeFetch = Promise.resolve(), + app = this.app, view, project; + + if ( !blueprint ) { + blueprint = new models.Blueprint({ id: slug }); + this.app.blueprints.add(blueprint); + maybeFetch = Promise.resolve( blueprint.fetch() ); + } + + maybeFetch.then(function() { + project = new models.Project({ blueprint: blueprint }); + view = new views.EditProject({ model: project, app: app }); + view.render(); + app.view + .display( view ) + .setTab('projects'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + }, + + editProject: function(slug) { + var project = this.app.projects.findWhere({ slug: slug }), + maybeFetch = Promise.resolve('some value'), + app = this.app, view, blueprint; + + if ( !project ) { + project = new models.Project({ id: slug }); + this.app.projects.add(project); + maybeFetch = Promise.resolve( project.fetch() ); + } + + maybeFetch.then(function() { + blueprint = app.blueprints.findWhere({ id: project.get('blueprint_id') }); + + if ( !blueprint ) { + blueprint = new models.Blueprint({ id: project.get('blueprint_id') }); + app.blueprints.add(blueprint); + return blueprint.fetch(); + } + }).then(function() { + project.blueprint = blueprint; + view = new views.EditProject({ model: project, app: app }); + view.render(); + app.view + .display( view ) + .setTab('projects'); + }).catch(function(jqXHR) { + app.view.displayError(jqXHR.status, jqXHR.statusText, jqXHR.responseText); + }); + } +}); diff --git a/pool/shard011/JavaScript/0069190_SiteLoader.js b/pool/shard011/JavaScript/0069190_SiteLoader.js new file mode 100644 index 0000000000000000000000000000000000000000..dc99715db6472a7196735afecb1bcc41c3613734 --- /dev/null +++ b/pool/shard011/JavaScript/0069190_SiteLoader.js @@ -0,0 +1,54 @@ +// import + +import React, {Component, PropTypes} from 'react'; +import styles from './SiteLoader.css'; +import {connect} from 'react-redux'; +import cn from 'classnames'; +import _ from 'lodash'; + +// vars + +const sizes = ['small', 'medium', 'large', 'jumbo']; + +// export + +@connect((state) => { + return { + siteLoader: state.siteLoader, + }; +}) +export default class SiteLoader extends Component { + static propTypes = { + className: PropTypes.string, + siteLoader: PropTypes.object.isRequired, + size: PropTypes.oneOf(sizes).isRequired, + }; + + static defaultProps = { + size: _.last(sizes), + }; + + className() { + return cn( + styles.SiteLoader, + this.props.className, { + [styles.active]: this.props.siteLoader.active, + }); + } + + render() { + const {size} = this.props; + + return ( +

    +
    +
    +
    +
    +
    +
    +
    +
    + ); + } +} diff --git a/pool/shard011/JavaScript/0069193_models.js b/pool/shard011/JavaScript/0069193_models.js new file mode 100644 index 0000000000000000000000000000000000000000..4f3c3be1ee544c3b98b3709f2be86765224b89d6 --- /dev/null +++ b/pool/shard011/JavaScript/0069193_models.js @@ -0,0 +1,207 @@ +var mongoose = require('mongoose'); +var ObjectId = mongoose.Schema.Types.ObjectId; +var Mixed = mongoose.Schema.Types.Mixed; +var bcrypt = require('bcrypt-nodejs'); +var CmsModels = require('../../../currentcms/lib/models'); +var utils = require('../../../currentcms/lib/utils'); + +exports = module.exports = { + + InventoryItem: { + meta: { + plural: 'Inventory', + name: '<%= name %>', + dashboard: true + }, + schema: { + list: [], + }, + pre_remove: function (i, next) { + utils.removeEach(i.list, next); + } + }, + + Customer: { + meta: { + plural: 'Customers', + name: '<%= google.email %>', + dashboard: true, + workflow: false + }, + schema: { + local: { + email: String, + password: String + }, + facebook: { + id: String, + token: String, + email: String, + name: String + }, + twitter: { + id: String, + token: String, + displayName: String, + username: String + }, + google: { + id: String, + token: String, + email: String, + name: String + } + }, + methods: { + generateHash: function (password) { + return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); + }, + validPassword: function (password) { + return bcrypt.compareSync(password, this.local.password); + }, + identifier: function () { + if (this.local.email) + return this.local.email; + else if (this.facebook.name) + return this.facebook.name; + else if (this.twitter.username) + return this.twitter.username; + else if (this.google.name) + return this.google.name; + } + } + }, + + CustomerAddress: { + meta: { + plural: 'Customer Address', + name: '<%= name %>', + dashboard: true, + workflow: false + }, + schema: { + user: {type: ObjectId, ref: 'Customer'}, + name: String, + address: String + } + }, + + Invoice: { + meta: { + plural: 'Invoices', + name: '<%= title %>', + dashboard: true, + workflow: false + }, + schema: { + user: {type: ObjectId, ref: 'Customer'}, + title: String, + description: String, + items: Mixed, + total: Number, + stripeReference: String + } + }, + + Page: { + meta: { + plural: 'Pages', + name: '<%= title %>', + dashboard: true, + workflow: false + }, + schema: { + title: String, + subtitle: String, + body: mongoose.Schema.Types.Mixed, + pages: [ + {type: ObjectId, ref: 'Page'} + ], + url: String, + template: String, + description: String, + resources: [ + {type: ObjectId, ref: 'Resource'} + ] + }, + browse: [ + {name: 'title', cell: 'char', filters: ['$regex', '='], order: 'asc,desc'}, + {name: 'url', cell: 'char', filters: ['$regex', '='], order: 'asc,desc,default'}, + {name: 'resources', cell: 'image' }, + {name: 'modified', cell: 'int', filters: ['$gt', '$lt', '$gte', '$lte'], order: 'asc,desc'}, + {name: 'state', cell: 'int', filters: ['='], order: 'asc,desc'} + ], + form: [ + {name: 'title', widget: 'input', options: {className: 'large'}}, + {name: 'url', widget: 'input'}, + {name: 'template', widget: 'select', options: {options: [ 'Portfolio', 'LandingPage', 'InformationPage', 'Contact' ]}}, + {name: 'resources', label: 'images', widget: 'upload', options: {type: 'Resource', array: true}}, + {name: 'body', widget: 'rich_text_cee', options: {collapsable: true, collapsed: false}}, + {name: 'pages', widget: 'choose_create', options: {type: 'Page', array: true}} + ] + + }, + + News: { + meta: { + plural: 'News', + name: '<%= title %>', + dashboard: true, + workflow: false + }, + schema: { + title: String, + subtitle: String, + body: String, + release_date: Date + }, + browse: [ + {name: 'title', cell: 'char', filters: ['$regex', '='], order: 'asc,desc,default'}, + {name: 'release_date', cell: 'date', filters: ['$gt', '$lt', '$gte', '$lte'], order: 'asc,desc'}, + {name: 'modified', cell: 'int', filters: ['$gt', '$lt', '$gte', '$lte'], order: 'asc,desc'} + ], + form: [ + {name: 'title', widget: 'input'}, + {name: 'subtitle', widget: 'input'}, + {name: 'body', widget: 'rich_text', options: {collapsable: true, collapsed: true}}, + {name: 'release_date', widget: 'date'} + ] + }, + + BlogEntry: { + meta: { + plural: 'Blog Entries', + name: '<%= title %>', + dashboard: true + }, + schema: { + title: String, + subtitle: String, + body: String, + release_date: Date + }, + browse: [ + {name: 'title', cell: 'char', filters: ['$regex', '='], order: 'asc,desc,default'}, + {name: 'release_date', cell: 'date', filters: ['$gt', '$lt', '$gte', '$lte'], order: 'asc,desc'}, + {name: 'modified', cell: 'int', filters: ['$gt', '$lt', '$gte', '$lte'], order: 'asc,desc'} + ], + form: [ + {name: 'title', widget: 'input'}, + {name: 'subtitle', widget: 'input'}, + {name: 'body', widget: 'rich_text', options: {collapsable: true, collapsed: true}}, + {name: 'release_date', widget: 'date'} + ] + }, + + Resource: CmsModels.ResourceInfo(), + User: CmsModels.UserInfo() + +} + + + +exports.Resource.jobs = { + image: ['thumb', 'medium', 'large'], + audio: ['mp3'], + video: [] +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069195_browserrange.js b/pool/shard011/JavaScript/0069195_browserrange.js new file mode 100644 index 0000000000000000000000000000000000000000..2c85777f50bd6a8385ad1348219702628ff7c698 --- /dev/null +++ b/pool/shard011/JavaScript/0069195_browserrange.js @@ -0,0 +1,149 @@ +// Copyright 2007 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Definition of the browser range namespace and interface, as + * well as several useful utility functions. + * + * DO NOT USE THIS FILE DIRECTLY. Use goog.dom.Range instead. + * + * @author robbyw@google.com (Robby Walker) + * @author ojan@google.com (Ojan Vafai) + * @author jparent@google.com (Julie Parent) + * + * @supported IE6, IE7, FF1.5+, Safari. + */ + + +goog.provide('goog.dom.browserrange'); +goog.provide('goog.dom.browserrange.Error'); + +goog.require('goog.dom'); +goog.require('goog.dom.browserrange.GeckoRange'); +goog.require('goog.dom.browserrange.IeRange'); +goog.require('goog.dom.browserrange.OperaRange'); +goog.require('goog.dom.browserrange.W3cRange'); +goog.require('goog.dom.browserrange.WebKitRange'); +goog.require('goog.userAgent'); + + +/** + * Common error constants. + * @enum {string} + */ +goog.dom.browserrange.Error = { + NOT_IMPLEMENTED: 'Not Implemented' +}; + + +// NOTE(robbyw): While it would be nice to eliminate the duplicate switches +// below, doing so uncovers bugs in the JsCompiler in which +// necessary code is stripped out. + + +/** + * Static method that returns the proper type of browser range. + * @param {Range|TextRange} range A browser range object. + * @return {goog.dom.browserrange.AbstractRange} A wrapper object. + */ +goog.dom.browserrange.createRange = function(range) { + if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) { + return new goog.dom.browserrange.IeRange( + /** @type {TextRange} */ (range), + goog.dom.getOwnerDocument(range.parentElement())); + } else if (goog.userAgent.WEBKIT) { + return new goog.dom.browserrange.WebKitRange( + /** @type {Range} */ (range)); + } else if (goog.userAgent.GECKO) { + return new goog.dom.browserrange.GeckoRange( + /** @type {Range} */ (range)); + } else if (goog.userAgent.OPERA) { + return new goog.dom.browserrange.OperaRange( + /** @type {Range} */ (range)); + } else { + // Default other browsers, including Opera, to W3c ranges. + return new goog.dom.browserrange.W3cRange( + /** @type {Range} */ (range)); + } +}; + + +/** + * Static method that returns the proper type of browser range. + * @param {Node} node The node to select. + * @return {goog.dom.browserrange.AbstractRange} A wrapper object. + */ +goog.dom.browserrange.createRangeFromNodeContents = function(node) { + if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) { + return goog.dom.browserrange.IeRange.createFromNodeContents(node); + } else if (goog.userAgent.WEBKIT) { + return goog.dom.browserrange.WebKitRange.createFromNodeContents(node); + } else if (goog.userAgent.GECKO) { + return goog.dom.browserrange.GeckoRange.createFromNodeContents(node); + } else if (goog.userAgent.OPERA) { + return goog.dom.browserrange.OperaRange.createFromNodeContents(node); + } else { + // Default other browsers to W3c ranges. + return goog.dom.browserrange.W3cRange.createFromNodeContents(node); + } +}; + + +/** + * Static method that returns the proper type of browser range. + * @param {Node} startNode The node to start with. + * @param {number} startOffset The offset within the node to start. This is + * either the index into the childNodes array for element startNodes or + * the index into the character array for text startNodes. + * @param {Node} endNode The node to end with. + * @param {number} endOffset The offset within the node to end. This is + * either the index into the childNodes array for element endNodes or + * the index into the character array for text endNodes. + * @return {goog.dom.browserrange.AbstractRange} A wrapper object. + */ +goog.dom.browserrange.createRangeFromNodes = function(startNode, startOffset, + endNode, endOffset) { + if (goog.userAgent.IE && !goog.userAgent.isDocumentMode(9)) { + return goog.dom.browserrange.IeRange.createFromNodes(startNode, startOffset, + endNode, endOffset); + } else if (goog.userAgent.WEBKIT) { + return goog.dom.browserrange.WebKitRange.createFromNodes(startNode, + startOffset, endNode, endOffset); + } else if (goog.userAgent.GECKO) { + return goog.dom.browserrange.GeckoRange.createFromNodes(startNode, + startOffset, endNode, endOffset); + } else if (goog.userAgent.OPERA) { + return goog.dom.browserrange.OperaRange.createFromNodes(startNode, + startOffset, endNode, endOffset); + } else { + // Default other browsers to W3c ranges. + return goog.dom.browserrange.W3cRange.createFromNodes(startNode, + startOffset, endNode, endOffset); + } +}; + + +/** + * Tests whether the given node can contain a range end point. + * @param {Node} node The node to check. + * @return {boolean} Whether the given node can contain a range end point. + */ +goog.dom.browserrange.canContainRangeEndpoint = function(node) { + // NOTE(user, bloom): This is not complete, as divs with style - + // 'display:inline-block' or 'position:absolute' can also not contain range + // endpoints. A more complete check is to see if that element can be partially + // selected (can be container) or not. + return goog.dom.canHaveChildren(node) || + node.nodeType == goog.dom.NodeType.TEXT; +}; diff --git a/pool/shard011/JavaScript/0069196_Color.js b/pool/shard011/JavaScript/0069196_Color.js new file mode 100644 index 0000000000000000000000000000000000000000..31ddcdc54cbea595289585c2efce03e203bb775b --- /dev/null +++ b/pool/shard011/JavaScript/0069196_Color.js @@ -0,0 +1,93 @@ +/* + * Reseplaneraren + * Provides access to Västtrafik journey planner + * + * OpenAPI spec version: 1.10.1 + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * + * Swagger Codegen version: 2.4.12 + * + * Do not edit the class manually. + * + */ + +(function(root, factory) { + if (typeof define === 'function' && define.amd) { + // AMD. Register as an anonymous module. + define(['ApiClient'], factory); + } else if (typeof module === 'object' && module.exports) { + // CommonJS-like environments that support module.exports, like Node. + module.exports = factory(require('../ApiClient')); + } else { + // Browser globals (root is window) + if (!root.Reseplaneraren) { + root.Reseplaneraren = {}; + } + root.Reseplaneraren.Color = factory(root.Reseplaneraren.ApiClient); + } +}(this, function(ApiClient) { + 'use strict'; + + /** + * The Color model module. + * @module model/Color + * @version 1.10.1 + */ + + /** + * Constructs a new Color. + * @alias module:model/Color + * @class + * @param bgColor {String} Backgroundcolor of this line + * @param fgColor {String} Foregroundcolor of this line + * @param stroke {String} Stroke style of this line + */ + var exports = function(bgColor, fgColor, stroke) { + this.bgColor = bgColor; + this.fgColor = fgColor; + this.stroke = stroke; + }; + + /** + * Constructs a Color from a plain JavaScript object, optionally creating a new instance. + * Copies all relevant properties from data to obj if supplied or a new instance if not. + * @param {Object} data The plain JavaScript object bearing properties of interest. + * @param {module:model/Color} obj Optional instance to populate. + * @return {module:model/Color} The populated Color instance. + */ + exports.constructFromObject = function(data, obj) { + if (data) { + obj = obj || new exports(); + if (data.hasOwnProperty('bgColor')) + obj.bgColor = ApiClient.convertToType(data['bgColor'], 'String'); + if (data.hasOwnProperty('fgColor')) + obj.fgColor = ApiClient.convertToType(data['fgColor'], 'String'); + if (data.hasOwnProperty('stroke')) + obj.stroke = ApiClient.convertToType(data['stroke'], 'String'); + } + return obj; + } + + /** + * Backgroundcolor of this line + * @member {String} bgColor + */ + exports.prototype.bgColor = undefined; + + /** + * Foregroundcolor of this line + * @member {String} fgColor + */ + exports.prototype.fgColor = undefined; + + /** + * Stroke style of this line + * @member {String} stroke + */ + exports.prototype.stroke = undefined; + + return exports; + +})); diff --git a/pool/shard011/JavaScript/0069197_batch.js b/pool/shard011/JavaScript/0069197_batch.js new file mode 100644 index 0000000000000000000000000000000000000000..402cdfa7b34f6d6c5147e5c368a5c5936e1000b1 --- /dev/null +++ b/pool/shard011/JavaScript/0069197_batch.js @@ -0,0 +1,110 @@ + +var Batch = Batch || { }; + + +// called when the gui params change and we need to update mesh +Batch.particleSystemChangeCallback = function ( InputSettings ) { + + // Get rid of an old system + ParticleEngine.stop(); + for ( var i = 0 ; i < ParticleEngine._emitters.length ; ++i ) { + Scene.removeObject( ParticleEngine.getDrawableParticles( i ) ); + } + ParticleEngine.removeEmitters(); + ParticleEngine.removeAnimations(); + + // Get rid of old models + Scene.removeObjects(); + + // If we specified animated model, then lets load it first + if ( InputSettings.animatedModelName ) { + var loader = new THREE.JSONLoader( true ); + loader.load( InputSettings.animatedModelName, InputSettings.animationLoadFunction ); + } + + // Create new system + var initializer = new InputSettings.initializerFunction ( InputSettings.initializerSettings ); + + var updater = new InputSettings.updaterFunction ( InputSettings.updaterSettings ); + + var emitter = new Emitter( { + maxParticles: InputSettings.maxParticles, // how many particles can be generated by this emitter? + particlesFreq: InputSettings.particlesFreq, // how many particle per second will we emit? + initialize: initializer, // initializer object + update: updater, // updater object + material: InputSettings.particleMaterial, + cloth: InputSettings.cloth, + width: InputSettings.width, + height: InputSettings.height, + } ); + + // If we are not dealing with cloth, lets sort particles + if ( !InputSettings.cloth ) { + emitter.enableSorting( Batch.cmds.sorting ); + } + + ParticleEngine.addEmitter ( emitter ); + + // Add new particle system + ParticleEngine.start(); + + // Add the particle system + for ( var i = 0 ; i < ParticleEngine._emitters.length ; ++i ) { + Scene.addObject( ParticleEngine.getDrawableParticles( i ) ); + } + + // Create the scene + InputSettings.createScene(); +}; + +Batch.parseUrl = function() { + var url = document.URL; + var cmds = Parser.getCommands(url); + + Batch.selectedSystem = cmds[0].system; + Batch.cmds = cmds[0]; +} + + +// when HTML is finished loading, do this +window.onload = function() { + Student.updateHTML(); + + // Setup renderer, scene and gui + Scene.create(); + + Batch.parseUrl(); + + // Add particle system + Batch.particleSystemChangeCallback( SystemSettings[Batch.selectedSystem] ); + + if( Batch.selectedSystem != 'cloth' ) { + var emitters = ParticleEngine.getEmitters(); + for ( var i = 0 ; i < emitters.length ; i++ ) { + emitters[i]._material.uniforms.texture.value = new THREE.ImageUtils.loadTexture( 'images/' + Batch.cmds.texture + '.png' ); + emitters[i]._material.depthTest = (Batch.cmds.depthTest === 'true'); + emitters[i]._material.transparent = (Batch.cmds.transparent === 'true'); + emitters[i]._sorting = (Batch.cmds.sorting === 'true'); + + var blendType; + if ( Batch.cmds.blending == "Normal" ) { + var blendType = THREE.NormalBlending; + } else if ( Batch.cmds.blending == "Additive" ) { + var blendType = THREE.AdditiveBlending; + } else { + console.log( "Blend type unknown!" ); + return; + } + emitters[i]._material.blending = blendType; + emitters[i]._material.needsUpdate = true; + } + } + + Gui.values.windowSize = Batch.cmds.size; + + Renderer.create( Scene, document.getElementById("canvas") ); + Renderer.onWindowResize(); + Renderer.update(); +}; + + diff --git a/pool/shard011/JavaScript/0069199_prefixUtils.js b/pool/shard011/JavaScript/0069199_prefixUtils.js new file mode 100644 index 0000000000000000000000000000000000000000..a3f42c841a63929f96183f818ae2682b5bd93932 --- /dev/null +++ b/pool/shard011/JavaScript/0069199_prefixUtils.js @@ -0,0 +1,137 @@ +'use strict'; +/** + * Append prefix declaration to list of prefixes in query window. + * + * @param yasqe + * @param prefix + */ +var addPrefixes = function(yasqe, prefixes) { + var existingPrefixes = yasqe.getPrefixesFromQuery(); + //for backwards compatability, we stil support prefixes value as string (e.g. 'rdf: ' + if (typeof prefixes == "string") { + addPrefixAsString(yasqe, prefixes); + } else { + for (var pref in prefixes) { + if (!(pref in existingPrefixes)) + addPrefixAsString(yasqe, pref + ": <" + prefixes[pref] + ">"); + } + } + yasqe.collapsePrefixes(false); +}; + +var addPrefixAsString = function(yasqe, prefixString) { + var lastPrefix = null; + var lastPrefixLine = 0; + var numLines = yasqe.lineCount(); + for (var i = 0; i < numLines; i++) { + var firstToken = yasqe.getNextNonWsToken(i); + if (firstToken != null && (firstToken.string == "PREFIX" || firstToken.string == "BASE")) { + lastPrefix = firstToken; + lastPrefixLine = i; + } + } + + if (lastPrefix == null) { + yasqe.replaceRange("PREFIX " + prefixString + "\n", { + line: 0, + ch: 0 + }); + } else { + var previousIndent = getIndentFromLine(yasqe, lastPrefixLine); + yasqe.replaceRange("\n" + previousIndent + "PREFIX " + prefixString, { + line: lastPrefixLine + }); + } + yasqe.collapsePrefixes(false); +}; +var removePrefixes = function(yasqe, prefixes) { + var escapeRegex = function(string) { + //taken from http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711 + return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + for (var pref in prefixes) { + yasqe.setValue(yasqe.getValue().replace(new RegExp("PREFIX\\s*" + pref + ":\\s*" + escapeRegex("<" + prefixes[pref] + ">") + "\\s*", "ig"), '')); + } + yasqe.collapsePrefixes(false); + +}; + +/** + * Get defined prefixes from query as array, in format {"prefix:" "uri"} + * + * @param cm + * @returns {Array} + */ +var getPrefixesFromQuery = function(yasqe) { + var queryPrefixes = {}; + var shouldContinue = true; + var getPrefixesFromLine = function(lineOffset, colOffset) { + if (!shouldContinue) return; + if (!colOffset) colOffset = 1; + var token = yasqe.getNextNonWsToken(i, colOffset); + if (token) { + if (token.state.possibleCurrent.indexOf("PREFIX") == -1 && token.state.possibleNext.indexOf("PREFIX") == -1) shouldContinue = false; //we are beyond the place in the query where we can enter prefixes + if (token.string.toUpperCase() == "PREFIX") { + var prefix = yasqe.getNextNonWsToken(i, token.end + 1); + if (prefix) { + var uri = yasqe.getNextNonWsToken(i, prefix.end + 1); + if (uri) { + var uriString = uri.string; + if (uriString.indexOf("<") == 0) + uriString = uriString.substring(1); + if (uriString.slice(-1) == ">") + uriString = uriString + .substring(0, uriString.length - 1); + queryPrefixes[prefix.string.slice(0, -1)] = uriString; + + getPrefixesFromLine(lineOffset, uri.end + 1); + } else { + getPrefixesFromLine(lineOffset, prefix.end + 1); + } + + } else { + getPrefixesFromLine(lineOffset, token.end + 1); + } + } else { + getPrefixesFromLine(lineOffset, token.end + 1); + } + } + }; + + + var numLines = yasqe.lineCount(); + for (var i = 0; i < numLines; i++) { + if (!shouldContinue) break; + getPrefixesFromLine(i); + + } + return queryPrefixes; +}; + +/** + * Get the used indentation for a certain line + * + * @param yasqe + * @param line + * @param charNumber + * @returns + */ +var getIndentFromLine = function(yasqe, line, charNumber) { + if (charNumber == undefined) + charNumber = 1; + var token = yasqe.getTokenAt({ + line: line, + ch: charNumber + }); + if (token == null || token == undefined || token.type != "ws") { + return ""; + } else { + return token.string + getIndentFromLine(yasqe, line, token.end + 1); + }; +}; + +module.exports = { + addPrefixes: addPrefixes, + getPrefixesFromQuery: getPrefixesFromQuery, + removePrefixes: removePrefixes +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069201_CertificateModel.js b/pool/shard011/JavaScript/0069201_CertificateModel.js new file mode 100644 index 0000000000000000000000000000000000000000..39e4a1ccff92c6f15f9a9b4fd5807f9c7d8ac615 --- /dev/null +++ b/pool/shard011/JavaScript/0069201_CertificateModel.js @@ -0,0 +1,241 @@ +CertificateService = new Backbone.Service({ url: '/', + sync: { + 'create': { + 'path': path.api.certificates, + 'data': { + action: 'ADD', + courseId: Utils.getCourseId(), + companyID: jQuery('#curriculumCompanyID').val() + }, + 'method': 'post' + }, + 'update': { + 'path':function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + parameters = { + action: 'UPDATE', + courseId: Utils.getCourseId() + } + _.extend(parameters, model.toJSON()) + return parameters + }, + 'method': 'post' + }, + 'read': { + 'path': function (model) { + return path.api.certificates + model.id; + }, + 'data': function (model) { + return { + action: 'GETBYID', + courseId: Utils.getCourseId() + } + }, + 'method': 'get' + }, + 'delete': { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action:'DELETE', + courseId: Utils.getCourseId() + } + }, + 'method': 'post' + } + }, + + targets: { + 'clone': { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action: 'CLONE', + courseId: Utils.getCourseId() + + } + }, + method: 'post' + }, + 'publish': { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action:'PUBLISH', + courseId: Utils.getCourseId() + } + }, + method: 'post' + }, + 'unpublish': { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action: 'UNPUBLISH', + courseId: Utils.getCourseId() + } + }, + method: 'post' + }, + 'join' : { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action: 'ADDUSER', + userID: jQuery('#curriculumStudentID').val(), + courseId: Utils.getCourseId() + } + }, + method: 'post' + }, + 'leave' : { + 'path': function (model) { + return path.api.certificates + model.id + }, + 'data': function (model) { + return { + action: 'DELETEUSER', + userID: jQuery('#curriculumStudentID').val(), + courseId: Utils.getCourseId() + } + }, + method: 'post' + } + } +}); + +var CertificateModel = Backbone.Model.extend({ + defaults: { + title: '', + description: '', + sitesCount: 0, + usersCount: 0, + isPublished: false, + isPermanent: true, + validPeriod: {value: 0, valueType: 'UNLIMITED'}, + isOpenBadgesIntegration: false + } +}).extend(CertificateService); + + +CertificateCollectionService = new Backbone.Service({ url: path.root, + sync: { + 'read': { + 'path': path.api.certificates, + 'data': function (e, options) { + var order = options.order; + var sortBy = order.split(':')[0]; + var asc = order.split(':')[1]; + return { + action: 'GETALL', + companyID: jQuery('#curriculumCompanyID').val(), + page: options.currentPage, + count: options.itemsOnPage, + filter: options.filter, + scope: options.scope, + sortBy: sortBy, + sortAscDirection: asc, + resultAs: "short", + courseId: Utils.getCourseId() + } + }, + method: 'get' + } + } +}); + +var CertificateCollection = Backbone.Collection.extend({ + model: CertificateModel, + parse: function (response) { + this.trigger('certificateCollection:updated', { total: response.total, currentPage: response.currentPage }); + return response.records; + } +}).extend(CertificateCollectionService); + +// my collection +MyCertificateCollectionService = new Backbone.Service({ url: path.root, + sync: { + 'read': { + 'path': function (e, options) { + return path.api.users + jQuery('#curriculumStudentID').val() + '/certificates' + }, + 'data': function (e, options) { + var order = options.order; + var sortBy = order.split(':')[0]; + var asc = order.split(':')[1]; + + return { + companyID: jQuery('#curriculumUserCompanyID').val(), + page: options.currentPage, + count: options.itemsOnPage, + filter: options.filter, + scope: options.scope, + sortBy: sortBy, + sortAscDirection: asc, + resultAs: "short", + isOnlyPublished: true, + courseId: Utils.getCourseId() + } + }, + method: 'get' + } +}}); + +var MyCertificateCollection = Backbone.Collection.extend({ + model: CertificateModel, + parse: function (response) { + this.trigger('certificateCollection:updated', { total: response.total, currentPage: response.currentPage }); + return response.records; + } +}).extend(MyCertificateCollectionService); + +// available certificates + +AvailableCertificateCollectionService = new Backbone.Service({ url: path.root, + sync: { + 'read': { + 'path': function (e, options) { + return path.api.users + jQuery('#curriculumStudentID').val() + '/certificates' + + '' + }, + 'data': function (e, options) { + var order = options.order; + var sortBy = order.split(':')[0]; + var asc = order.split(':')[1]; + return { + companyID: jQuery('#curriculumUserCompanyID').val(), + page: options.currentPage, + count: options.itemsOnPage, + filter: options.filter, + sortBy: sortBy, + sortAscDirection: asc, + resultAs: "short", + available:true, + isOnlyPublished: true, + scope: options.scope, + courseId: Utils.getCourseId() + } + }, + method: 'get' + }} +}); + +var AvailableCertificateCollection = Backbone.Collection.extend({ + model: CertificateModel, + parse: function (response) { + this.trigger('certificateCollection:updated', { total: response.total, currentPage: response.currentPage }); + return response.records; + } +}).extend(AvailableCertificateCollectionService); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069202_withPropsOnChange.js b/pool/shard011/JavaScript/0069202_withPropsOnChange.js new file mode 100644 index 0000000000000000000000000000000000000000..8a66f7e76ee3eaa8aa5db86c4f4881f1370caf48 --- /dev/null +++ b/pool/shard011/JavaScript/0069202_withPropsOnChange.js @@ -0,0 +1,53 @@ +/* + * Copied from recompose to move the first call to `propsMapper`. + * Prevents setState warning. + */ + +import { createFactory, Component } from 'react'; +import pick from 'recompose/utils/pick'; +import shallowEqual from 'recompose/shallowEqual'; +import setDisplayName from 'recompose/setDisplayName'; +import wrapDisplayName from 'recompose/wrapDisplayName'; + +const withPropsOnChange = (shouldMapOrKeys, propsMapper) => BaseComponent => { + const factory = createFactory(BaseComponent); + const shouldMap = + typeof shouldMapOrKeys === 'function' + ? shouldMapOrKeys + : (props, nextProps) => + !shallowEqual( + pick(props, shouldMapOrKeys), + pick(nextProps, shouldMapOrKeys), + ); + + class WithPropsOnChange extends Component { + computedProps = {}; + + componentWillMount() { + // move first `propsMapper` call into componentWillMount incase there is a setState in it + this.computedProps = propsMapper(this.props); + } + + componentWillReceiveProps(nextProps) { + if (shouldMap(this.props, nextProps)) { + this.computedProps = propsMapper(nextProps); + } + } + + render() { + return factory({ + ...this.props, + ...this.computedProps, + }); + } + } + + if (process.env.NODE_ENV !== 'production') { + return setDisplayName(wrapDisplayName(BaseComponent, 'withPropsOnChange'))( + WithPropsOnChange, + ); + } + return WithPropsOnChange; +}; + +export default withPropsOnChange; diff --git a/pool/shard011/JavaScript/0069205_columns.js b/pool/shard011/JavaScript/0069205_columns.js new file mode 100644 index 0000000000000000000000000000000000000000..20ec94646a659b52eebbb8bfebf79d8592e11562 --- /dev/null +++ b/pool/shard011/JavaScript/0069205_columns.js @@ -0,0 +1,162 @@ +/** + * Copyright (c) UNA, Inc - https://una.io + * MIT License - https://opensource.org/licenses/MIT + * + * @defgroup Messenger Messenger + * @ingroup UnaModules + * @{ + */ + +/** + * Builder class + * Adapt messenger main page for different devises + */ + +var oJotWindowBuilder = (function(){ + var _oPrivate = { + sLeftAreaName: '.bx-messanger-items-list', + sLotSelector: '.bx-messenger-jots-snip', + sRightAreaName: '.bx-messenger-main-block', //left column of the body without header + sLeftTopBlockArea: '#bx-messangger-block-head', + sBothColumnsParent: '.bx-layout-row', + sInfoUsersArea: '.bx-messenger-top-user-info', + sBlockHeaderArea: '.bx-messenger-block > .bx-db-header', + sToolbar: '#bx-toolbar', + oLeftCol: null, + oRightCol: null, + iLeftSize: '30%', + iRightSize: '70%', + sActiveType:'both', + iMainAreaHeight:null, //area of the body without header with both columns + iLeftAreaHeight:null, //left column header height + iRightAreaHeight:null, //right column header height + iResizeTimeout:null, + + updateLeftHeight:function(){ + this.iLeftAreaHeight = $(this.sLeftTopBlockArea).outerHeight(); + $(this.sLeftAreaName).height(this.iMainAreaHeight - this.iLeftAreaHeight); + }, + + updateRightHeight:function(){ + this.iRightAreaHeight = $(this.sInfoUsersArea).length ? $(this.sInfoUsersArea).outerHeight() : $(this.sBlockHeaderArea).outerHeight(); + + if (this.iRightAreaHeight == null) + return; + + $(this.sRightAreaName).height(this.iMainAreaHeight - this.iRightAreaHeight); + }, + init:function(){ + var iParent = $(this.sBothColumnsParent).outerWidth(); + + if (!iParent || this.oLeftCol != null || this.oRightCol != null) return ; + + this.oLeftCol = $(this.sBothColumnsParent + ' > div').first(); + this.oRightCol = $(this.sBothColumnsParent + ' > div').last(); + + var iLeftW = (this.oLeftCol.outerWidth()*100/iParent).toFixed(2); + if (!iLeftW) + return; + + this.iRightSize = (100 - iLeftW) + '%'; + this.iLeftSize = iLeftW + '%'; + }, + isMobile:function(){ + return $(window).width() <= 720; + }, + + changeColumn:function(sSide){ + this.init(); + + if (this.isMobile()) + { + if (sSide) + this.sActiveType = sSide; + else + this.sActiveType = this.sActiveType == 'left' ? 'right' : 'left'; + } + else + this.sActiveType = 'both'; + + this.resizeColumns(); + }, + activateLeft:function(){ + this.oRightCol.hide().width('0%'); + this.iRightSize = '0%'; + this.oLeftCol.width('100%').fadeIn(); + this.updateLeftHeight(); + }, + activateRight:function(){ + this.oLeftCol.hide().width('0%'); + this.iLeftSize = '0%'; + this.oRightCol.width('100%').fadeIn(); + this.updateRightHeight(); + }, + + activateBoth:function(){ + if (parseInt(this.iRightSize) == 0 || parseInt(this.iRightSize) == 100) + { + this.iLeftSize = '30%'; + this.iRightSize = '70%'; + if (!parseInt(this.iRightAreaHeight)) + oJotWindowBuilder.loadRightColumn(); + } + + this.oLeftCol.width(this.iLeftSize).fadeIn('slow'); + this.oRightCol.width(this.iRightSize).fadeIn('slow'); + + this.updateLeftHeight(); + this.updateRightHeight(); + }, + onResizeWindow:function(){ + this.init(); + + if (this.isMobile()) + this.sActiveType = this.sActiveType == 'both' ? 'left' : this.sActiveType; + else + this.sActiveType = 'both'; + + this.iMainAreaHeight = $(window).height() - $(this.sToolbar).outerHeight(); + this.resizeColumns(); + }, + resizeColumns:function(){ + switch(this.sActiveType){ + case 'left' : this.activateLeft(); break; + case 'right' : this.activateRight(); break; + default: + this.activateBoth(); + } + } + }; + + return { + resizeWindow:function() + { + clearTimeout(_oPrivate.iResizeTimeout); + _oPrivate.iResizeTimeout = setTimeout(function(){ + _oPrivate.onResizeWindow() + }, 300); + }, + updateColumnSize:function() + { + _oPrivate.resizeColumns(); + }, + changeColumn:function(sSide) + { + _oPrivate.changeColumn(sSide); + }, + isHistoryColActive:function() + { + return _oPrivate.sActiveType == 'both' || _oPrivate.sActiveType == 'right'; + }, + loadRightColumn:function() + { + console.log('Occurs when resizing window and right column is empty. Overwrite it in class owner.'); + }, + isMobile:function() + { + return _oPrivate.isMobile(); + } + } +})(); + +/** @} */ diff --git a/pool/shard011/JavaScript/0069206_postcss-plugin.js b/pool/shard011/JavaScript/0069206_postcss-plugin.js new file mode 100644 index 0000000000000000000000000000000000000000..0f224846fafed4741ff87cd6f2f6d39ead32ba23 --- /dev/null +++ b/pool/shard011/JavaScript/0069206_postcss-plugin.js @@ -0,0 +1,167 @@ +var fs = require('fs') +var test = require('tape') +var postcss = require('postcss') +var doiuse = require('../') +var atImport = require('postcss-import') +var hasKeys = require('./has-keys') +var mock = require('mock-fs') + +test('leaves css alone by default', function (t) { + var css, out + css = fs.readFileSync(require.resolve('./cases/gradient.css')).toString() + out = postcss(doiuse({ + browsers: [ + 'ie >= 7', + 'safari >= 6', + 'opera >= 10.1' + ] + })).process(css).css + t.equal(out, css) + t.end() +}) + +test('calls back for unsupported feature usages', function (t) { + var count, css + css = fs.readFileSync(require.resolve('./cases/gradient.css')) + count = 0 + postcss(doiuse({ + browsers: ['ie 8'], + onFeatureUsage: function (usageInfo) { + count++ + hasKeys(t, usageInfo, ['feature', 'featureData', 'usage', 'message']) + hasKeys(t, usageInfo.featureData, ['title', 'missing', 'missingData', 'caniuseData']) + } + })) + .process(css).then(function () { + t.equal(count, 4) + t.end() + }) +}) + +test('ignores specified features and calls back for the others', function (t) { + var count, css + css = fs.readFileSync(require.resolve('./cases/gradient.css')) + count = 0 + postcss(doiuse({ + browsers: ['ie 8'], + ignore: [ + 'css-gradients' + ], + onFeatureUsage: function (usageInfo) { + count++ + hasKeys(t, usageInfo, ['feature', 'featureData', 'usage', 'message']) + hasKeys(t, usageInfo.featureData, ['title', 'missing', 'missingData', 'caniuseData']) + } + })) + .process(css).then(function () { + t.equal(count, 2) + t.end() + }) +}) + +test('ignores specified files and calls back for others', function (t) { + var run, ignoreCss, processCss, pcss + ignoreCss = fs.readFileSync(require.resolve('./cases/ignore-file.css')) + processCss = fs.readFileSync(require.resolve('./cases/gradient.css')) + run = false + + pcss = function () { + return postcss(doiuse({ + browsers: ['ie 6'], + ignoreFiles: ['**/ignore-file.css'], + onFeatureUsage: function (usageInfo) { + run = true + } + })) + } + + pcss().process(ignoreCss, {from: './cases/ignore-file.css'}) + .then(function () { + t.false(run, 'should be false') + }) + .then(function () { + return pcss().process(processCss, {from: './cases/gradient.css'}) + }) + .then(function () { + t.true(run, 'should be true') + t.end() + }) +}) + +test('ignores rules from some imported files, and not others', function (t) { + var count, css, cssPath + cssPath = require.resolve('./cases/ignore-import.css') + css = fs.readFileSync(cssPath) + count = 0 + + postcss([atImport(), + doiuse({ + browsers: ['ie 6'], + ignoreFiles: ['**/ignore-file.css'], + onFeatureUsage: function (usageInfo) { + count++ + } + })]) + .process(css, {from: cssPath}) + .then(function () { + t.equal(count, 2) + t.end() + }) +}) + +test('ignores rules specified in comments', function (t) { + var count, ignoreCss, ignoreCssPath, processCss, processCssPath + ignoreCssPath = require.resolve('./cases/ignore-comment.css') + ignoreCss = fs.readFileSync(ignoreCssPath) + + processCssPath = require.resolve('./cases/ignore-file.css') + processCss = fs.readFileSync(processCssPath) + + count = 0 + + var processor = postcss([atImport(), + doiuse({ + browsers: ['ie 6'], + onFeatureUsage: function (usageInfo) { + count++ + } + })]) + + processor.process(ignoreCss, {from: ignoreCssPath}) + .then(function () { + t.equal(count, 2) + }).then(function () { + processor.process(processCss, {from: processCssPath}) + .then(function () { + t.equal(count, 3, 'inline css disabing rules must apply only to current file') + t.end() + }) + }) +}) + +test('info with browserslist file', function (t) { + mock({ + 'browserslist': 'Safari 8\nIE >= 11' + }) + + var actual = doiuse({}).info().browsers + var expected = [['ie', '11'], ['safari', '8']] + + t.deepEqual(actual, expected) + + mock.restore() + + t.end() +}) + +test('info with no browserslist file or browsers config', function (t) { + var actual = doiuse({}).info().browsers + + var expected = doiuse({ + browsers: doiuse['default'] + }).info().browsers + + t.deepEqual(actual, expected) + + t.end() +}) diff --git a/pool/shard011/JavaScript/0069208_log.js b/pool/shard011/JavaScript/0069208_log.js new file mode 100644 index 0000000000000000000000000000000000000000..07c8c7807b15082615cebf9dade9cbffdbae9628 --- /dev/null +++ b/pool/shard011/JavaScript/0069208_log.js @@ -0,0 +1,30 @@ +'use strict'; + +/** + * database layout for 'users' + * @type {Object} + */ +module.exports = { + + views: { + + byId: { + map: function(doc) { + if (doc.resource === 'log') { + doc.params.id = doc._id; + emit(doc._id, doc); + } + } + }, + + byTimestamp: { + map: function(doc) { + if (doc.resource === 'log') { + emit(doc.params.timestamp, doc); + } + } + } + + } + +}; diff --git a/pool/shard011/JavaScript/0069209_cms_collection.js b/pool/shard011/JavaScript/0069209_cms_collection.js new file mode 100644 index 0000000000000000000000000000000000000000..c8be72ef5c8647d5af1444fe62dae2741279893e --- /dev/null +++ b/pool/shard011/JavaScript/0069209_cms_collection.js @@ -0,0 +1,139 @@ +(function() { + 'use strict'; + angular.module('cms.collection', [ + 'ngResource', + 'cms.core' + ]) + .factory('CollectionServer', ['CollectionApi', function(CollectionApi) { + var CollectionServer = function(ctrl) { + this.ctrl = ctrl; + }; + + CollectionServer.prototype.create = function(projectId, collection) { + var promise, callback, failurecallback; + promise = createCollection(projectId, collection).$promise; + callback = createCollectionCallback(this.ctrl); + failurecallback = createCollectionFailureCallback(this.ctrl); + promise.then(callback, failurecallback); + }; + + function createCollection (projectId, collection) { + return CollectionApi.create({projectId: projectId}, collection); + } + + function createCollectionCallback(ctrl) { + return function (response) { + ctrl.onCollectionCreated(response); + }; + }; + + function createCollectionFailureCallback(ctrl) { + return function (response) { + ctrl.onCollectionCreateFailed(); + }; + }; + + CollectionServer.prototype.update = function(projectId, collectionId, collection) { + var promise, callback, failurecallback; + promise = updateCollection(projectId, collectionId, collection).$promise; + callback = updateCollectionCallback(this.ctrl); + failurecallback = updateCollectionFailureCallback(this.ctrl); + promise.then(callback, failurecallback); + }; + + function updateCollection (projectId, collectionId, collection) { + return CollectionApi.update({projectId: projectId, collectionId: collectionId}, collection); + } + + function updateCollectionCallback(ctrl) { + return function (response) { + console.log(response); + }; + }; + + function updateCollectionFailureCallback(ctrl) { + return function (response) { + console.log(response); + }; + }; + + CollectionServer.prototype.get = function(projectId, collectionId) { + var promise, callback, failurecallback; + promise = getCollection(projectId, collectionId).$promise; + callback = getCollectionCallback(this.ctrl); + failurecallback = getCollectionFailureCallback(this.ctrl); + promise.then(callback, failurecallback); + }; + + function getCollection (projectId, collectionId) { + return CollectionApi.get({'projectId': projectId, 'collectionId': collectionId}); + } + + function getCollectionCallback(ctrl) { + return function (response) { + ctrl.onCollectionFetched(response); + }; + }; + + function getCollectionFailureCallback(ctrl) { + return function (response) { + ctrl.onCollectionFetchError(); + }; + }; + + CollectionServer.prototype.getAll = function(projectId) { + var promise, callback, failurecallback; + promise = getCollections(projectId).$promise; + callback = getCollectionsCallback(this.ctrl); + failurecallback = getCollectionsFailureCallback(this.ctrl); + promise.then(callback, failurecallback); + }; + + function getCollections (projectId) { + return CollectionApi.getAll({'projectId': projectId}); + } + + function getCollectionsCallback(ctrl) { + return function (response) { + ctrl.onCollectionFetched(response); + }; + }; + + function getCollectionsFailureCallback(ctrl) { + return function (response) { + ctrl.onCollectionFetchError(); + }; + }; + + return CollectionServer; + }]) + .factory('CollectionApi', [ + '$resource', 'urls','getHeaders', + function ($resource, urls, getHeaders) { + return $resource( + [urls.baseApiUrl, 'project/:projectId/collection/:collectionId'].join(''), + { projectId: "@projectId", collectionId: "@collectionId" }, + { + create: { + method: 'POST', + headers: getHeaders() + }, + update: { + method: 'PUT', + headers: getHeaders() + }, + get: { + method: 'GET', + headers: getHeaders() + }, + getAll: { + method: 'GET', + headers: getHeaders(), + isArray: true + } + }, + {stripTrailingSlashes: false} + ); + } + ]); +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069211_index.js b/pool/shard011/JavaScript/0069211_index.js new file mode 100644 index 0000000000000000000000000000000000000000..759ff174e9669ea72fa1c67ee619b44716a40928 --- /dev/null +++ b/pool/shard011/JavaScript/0069211_index.js @@ -0,0 +1,57 @@ +import Jurisdiction from '../../router/app' + +/** + * 通过meta.role判断是否与当前用户权限匹配 + * @param roles + * @param route + */ +function hasPermission(roles, route) { + if (route.meta && route.meta.roles) { + return roles.some(role => route.meta.roles.indexOf(role) >= 0) + } + return true +} + +/** + * 递归过滤异步路由表,返回符合用户角色权限的路由表 + * @param asyncRouterMap + * @param roles + */ +function filterAsyncRouter(asyncRouterMap, roles) { + return asyncRouterMap.filter(route => { + if (hasPermission(roles, route)) { + if (route.children && route.children.length) { + route.children = filterAsyncRouter(route.children, roles) + } + return true + } + return false + }) +} + +const permission = { + state: { + addRouters: [] + }, + mutations: { + SET_ROUTERS: (state, routers) => { + state.addRouters = routers; + } + }, + actions: { + GetRouters({commit}, roles) { + return new Promise(resolve => { + let accessedRouters; + if (roles.indexOf('admin') >= 0) { + accessedRouters = Jurisdiction + } else { + accessedRouters = filterAsyncRouter(Jurisdiction, roles) + } + commit('SET_ROUTERS', accessedRouters); + resolve() + }) + } + } +}; + +export default permission diff --git a/pool/shard011/JavaScript/0069212_hook.spec.js b/pool/shard011/JavaScript/0069212_hook.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..07a0130407308f6c407b42fd19899504778b67d2 --- /dev/null +++ b/pool/shard011/JavaScript/0069212_hook.spec.js @@ -0,0 +1,36 @@ +const { assert } = require('chai'); +const RediBox = require('redibox').default; + +const Hook = require('./../../src/hook'); + +describe('core', () => { + it('Should extend redibox hook class and provide an emitter', (done) => { + const hook = new Hook(); + const protoName = Object.getPrototypeOf(Hook).name; + assert.equal(protoName, 'BaseHook', `Hook should extend 'Hook' but it extends '${protoName}'`); + assert.isDefined(hook.on); + assert.isDefined(hook.emit); + done(); + }); + + it('Should extend redibox BaseHook class and provide a name property', (done) => { + const hook = new Hook(); + assert.isDefined(hook.name); + assert.equal(global.HOOK_NAME, hook.name); + done(); + }); + + // IOREDIS issue - with tests only + // it(`Should mount to core.${global.HOOK_NAME}`, (done) => { + // const config = { hooks: {} }; + // config.hooks[global.HOOK_NAME] = Hook; + // const redibox = new RediBox(config, () => { + // assert.isTrue(redibox.hooks.hasOwnProperty(global.HOOK_NAME)); + // redibox.disconnect(); + // done(); + // }); + // redibox.on('error', (e) => { + // console.error(e); + // }); + // }); +}); diff --git a/pool/shard011/JavaScript/0069214_shell.js b/pool/shard011/JavaScript/0069214_shell.js new file mode 100644 index 0000000000000000000000000000000000000000..c8532e4f98403121d434ca426f6ad71eaef502ea --- /dev/null +++ b/pool/shard011/JavaScript/0069214_shell.js @@ -0,0 +1,59 @@ +define(['plugins/router', 'durandal/app', 'durandal/system', 'models/history', 'models/user', 'services/account'], function (router, app, system, history, user, accountService) { + return { + user: user, + router: router, + activate: function () { + + var def = new $.Deferred(); + + accountService.loggedIn() + .done(function (data, status, xhr) { + history.prime() + .done(function () { + configureRouter() + .done(function () { + def.resolve(); + }); + }); + }) + .fail(function (xhr) { + location.hash = '#login'; + configureRouter() + .done(function () { + def.resolve(); + }); + }); + + return def; + }, + compositionComplete: function () { + $(function () { + $('.navbar-nav').on('click', function () { + if ($('.navbar-header .navbar-toggle').css('display') != 'none') { + $(".navbar-header .navbar-toggle").trigger("click"); + } + }); + }); + }, + logOff: function () { + accountService.logOff + .done(function () { + router.navigate('#login'); + }); + } + }; + + function configureRouter() { + router.map([ + { route: ['Books', ''], title: 'Books', moduleId: 'viewmodels/books', nav: true }, + { route: 'Chapters/:name', title: 'Chapters', moduleId: 'viewmodels/chapters', nav: true }, + { route: 'login', moduleId: 'viewmodels/login', nav: true }, + { route: 'register', moduleId: 'viewmodels/register', nav: true }, + { route: 'readingLog', moduleId: 'viewmodels/readingLog', nav: true } + ]).buildNavigationModel(); + + router.mapUnknownRoutes('viewmodels/books', "#books"); + + return router.activate(); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069215_tooltip.js b/pool/shard011/JavaScript/0069215_tooltip.js new file mode 100644 index 0000000000000000000000000000000000000000..17be62d19788769c4a800d4d6023c430df433c43 --- /dev/null +++ b/pool/shard011/JavaScript/0069215_tooltip.js @@ -0,0 +1,158 @@ +// Copyright (c) 2007-2011 gocept gmbh & co. kg +// See also LICENSE.txt + +zeit.cms.showToolTip = function(context, text, where) { + var body = jQuery('body')[0]; + var div = $('tooltip'); + if (!isNull(div)) { + zeit.cms.hideToolTip(div.signals); + } + div = DIV({'id': 'tooltip'}); + div.innerHTML = text; + where.x += 20; + where.y += 10; + MochiKit.Style.setElementPosition(div, where); + body.appendChild(div); + + div.signals = []; + div.signals.push( + MochiKit.Signal.connect( + context, 'onmouseout', function(event) { + zeit.cms.hideToolTip(div.signals); + })); + div.signals.push( + MochiKit.Signal.connect( + 'tooltip', 'onmousemove', function(event) { + zeit.cms.hideToolTip(div.signals); + })); +}; + + +zeit.cms.hideToolTip = function(signals) { + while (signals.length) { + MochiKit.Signal.disconnect(signals.pop()); + } + $('tooltip').parentNode.removeChild($('tooltip')); +}; + + +zeit.cms.ToolTip = gocept.Class.extend({ + + construct: function(context, url_getter) { + var self = this; + self.context = $(context); + self.url_getter = url_getter; + self.events = []; + + self.mouse_over_deferred = null; + + self.events.push(MochiKit.Signal.connect( + context, 'onmouseover', + self, self.handleMouseOver)); + self.events.push(MochiKit.Signal.connect( + context, 'onmouseout', self, self.handleMouseOut)); + }, + + destruct: function() { + var self = this; + while (self.events.length) { + MochiKit.Signal.disconnect(self.events.pop()); + } + }, + + handleMouseOver: function(event) { + var othis = this; + if (this.mouse_over_deferred !== null) { + return; + } + if (!isUndefinedOrNull( + MochiKit.DragAndDrop.Draggables.activeDraggable)) { + return; + } + this.mouse_over_deferred = MochiKit.Async.callLater( + 0.4, function(result) { + othis.mouse_over_deferred = null; + var url = othis.url_getter(event); + if (url === null) { + return; + } + if (url.indexOf('tooltip:') == 0) { + zeit.cms.showToolTip( + othis.context, + url.substring('tooltip:'.length), + event.mouse().client); + } else { + var d = MochiKit.Async.doSimpleXMLHttpRequest(url); + d.addCallback(function(result) { + zeit.cms.showToolTip( + othis.context, + result.responseText, event.mouse().client); + return result; + }); + } + }); + }, + + handleMouseOut: function(event) { + if (this.mouse_over_deferred === null) { + return; + } + this.mouse_over_deferred.cancel(); + this.mouse_over_deferred = null; + } +}); + + +zeit.cms.LinkToolTip = zeit.cms.ToolTip.extend({ + + construct: function(context) { + var othis = this; + var url_getter = function() { + return othis.getURLFromLink(); + }; + arguments.callee.$.construct.call(othis, context, url_getter); + }, + + getURLFromLink: function() { + var othis = this; + var url = othis.context.href; + if (!url) { + return null; + } + return url + '/@@drag-pane.html'; + } +}); + + +zeit.cms.TextToolTip = zeit.cms.ToolTip.extend({ + + construct: function(context) { + } + +}); + + +zeit.cms.ToolTipManager = zeit.cms.ToolTip.extend({ + + construct: function(context) { + var self = this; + self.context = context; + var url_getter = function(event) { + return self.getURL(event); + }; + arguments.callee.$.construct.call(self, context, url_getter); + }, + + getURL: function(event) { + var self = this; + var target = event.target(); + while (!target.hasAttribute('cms:tooltip') && target != self.context) { + target = target.parentNode; + } + var tooltip = target.getAttribute('cms:tooltip'); + if (!tooltip) { + return null; + } + return 'tooltip:' + tooltip; + } +}); diff --git a/pool/shard011/JavaScript/0069219_TileUtils.test.js b/pool/shard011/JavaScript/0069219_TileUtils.test.js new file mode 100644 index 0000000000000000000000000000000000000000..fcd20d761eb40250a588dffdcbcec1fd336f1adf --- /dev/null +++ b/pool/shard011/JavaScript/0069219_TileUtils.test.js @@ -0,0 +1,20 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this file, + * You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* jshint node:true, esnext:true */ +"use strict"; + +const TileUtils = require("lib/TileUtils"); +const assert = require("chai").assert; + +describe("TileUtils", function() { + var firstLink = {url: "http://example0.com/", title: "site#0", frecency: 1, lastVisitDate: 1}; + var secondLink = {url: "http://example1.com/", title: "site#1", frecency: 3, lastVisitDate: 1}; + var thirdLink = {url: "http://example2.com/", title: "site#2", frecency: 3, lastVisitDate: 1}; + + it("should merge links", () => { + var merged = JSON.stringify(TileUtils.getMergedLinks([[firstLink, thirdLink], [secondLink]])); + assert.equal(merged, JSON.stringify([secondLink, thirdLink, firstLink])); + }); + +}); diff --git a/pool/shard011/JavaScript/0069220_index.js b/pool/shard011/JavaScript/0069220_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1dc95181d6f76b69a5c452e6743951013a780280 --- /dev/null +++ b/pool/shard011/JavaScript/0069220_index.js @@ -0,0 +1,53 @@ +var test = require('tap').test, + q = require('q'), + createGraph = require('ngraph.graph'), + createGraphBuilder = require('../'); + +test('Passes default data', function (t) { + t.plan(3); + + var builder = createGraphBuilder(function (url) { + t.ok(url, 'Has default registry url'); + t.ok(url.indexOf('browserify') >= 0, 'Has package'); + return q.all([]); + }); + + var graph = createGraph(); + builder.createNpmDependenciesGraph('browserify', graph).fail(function (err) { + t.ok(err, 'Fired error, since we did not provide valid response'); + }); +}); + +test('Checks dependencies', function (t) { + // TODO: implement me. + t.end(); + return; + t.plan(2); + var builder = createGraphBuilder(function (url, data) { + return q.fcall(createFakeResponse); + }); + + var graph = createGraph(); + builder.createNpmDependenciesGraph('browserify', graph) + .then(function () { + t.equals(graph.getNodesCount(), 2, 'Graph has two links'); + t.ok(graph.hasLink('browserify', 'util'), 'Graph has two links'); + }); +}); + +function createFakeResponse() { + return { + data: { + rows: [{ + id: 'browserify', + value: { + _id: 'browserify@3.30.2', + dependencies: { + "util": "~0.10.1" + } + } + } + ] + } + }; +} diff --git a/pool/shard011/JavaScript/0069223_Island.js b/pool/shard011/JavaScript/0069223_Island.js new file mode 100644 index 0000000000000000000000000000000000000000..fb2505143cc3156dbb12ab911ee1f7876e773137 --- /dev/null +++ b/pool/shard011/JavaScript/0069223_Island.js @@ -0,0 +1,217 @@ +import React, { Component } from 'react'; +import { connect } from 'react-redux'; +import arrayContains from 'array-contains'; + +import { MESSAGE } from '../constants/AppConstants'; + +import mediator from '../mediator'; + +import config from '../config/index'; + +import { moveOnIsland } from '../actions/heroActions'; + +export default class Island extends Component { + state = { + moveTime: 0, + }; + + onMove(x, y) { + const { dispatch } = this.props; + const island = this.getIsland(); + if (arrayContains(island.disabledCoordinates, [x, y])) { + mediator.emit(MESSAGE, 'You can\'t move there'); + return; + } + + let counter = config.islandMoveTime; + + this.setState({ moveTime: counter }); + + this.moveInterval = window.setInterval(() => { + counter--; + + this.setState({ moveTime: counter }); + + if (counter === 0) { + window.clearInterval(this.moveInterval); + dispatch(moveOnIsland(x, y)); + } + }, 1000); + } + onCancelMove() { + window.clearInterval(this.moveInterval); + this.setState({ moveTime: 0 }); + } + + getIsland() { + const { islands } = mediator.storage; + const { hero } = this.props; + return islands.find(item => item.id === hero.location.island); + } + renderInfo() { + const { hero } = this.props; + const { location } = hero; + const { moveTime } = this.state; + + return ( + + ); + } + render() { + const { hero } = this.props; + const island = this.getIsland(); + const { location } = hero; + const squareWidth = 20; + + // TODO: maybe should be in db + const islandDimensions = { + width: 1980, + height: 1280, + }; + + const mapDimensions = { + width: 960, + height: 480, + }; + + const heroPosition = { + left: location.coordinateX * squareWidth, + top: location.coordinateY * squareWidth, + }; + const mapMargin = { + left: heroPosition.left - mapDimensions.width / 2, + top: heroPosition.top - mapDimensions.height / 2, + }; + + if (mapMargin.left < 0) { + mapMargin.left = 0; + } else if (islandDimensions.width - mapMargin.left < mapDimensions.width) { + mapMargin.left -= mapDimensions.width - (islandDimensions.width - mapMargin.left); + } + + if (mapMargin.top < 0) { + mapMargin.top = 0; + } else if (islandDimensions.height - mapMargin.top < mapDimensions.height) { + mapMargin.top -= mapDimensions.height - (islandDimensions.height - mapMargin.top); + } + + const mapOffset = { + top: mapMargin.top / squareWidth, + left: mapMargin.left / squareWidth, + }; + + // TODO: temporary + function markSquareRed(e) { + const targetStyle = e.target.style; + targetStyle.background = (targetStyle.background === 'red') ? '' : 'red'; + } + + const squares = []; + + for (let i = 0; i < mapDimensions.width / squareWidth; i++) { + for (let j = 0; j < mapDimensions.height / squareWidth; j++) { + const x = (i + mapOffset.left); + const y = (j + mapOffset.top); + const coordX = location.coordinateX; + const coordY = location.coordinateY; + + const handled = ( + coordX - x === -1 && coordY - y === -1 || + coordX - x === 0 && coordY - y === -1 || + coordX - x === 1 && coordY - y === -1 || + + coordX - x === -1 && coordY - y === 1 || + coordX - x === 0 && coordY - y === 1 || + coordX - x === 1 && coordY - y === 1 || + + coordX - x === -1 && coordY - y === 0 || + coordX - x === 1 && coordY - y === 0); + + let background = ''; + if (handled) { + background = 'white'; + } else if (arrayContains(island.disabledCoordinates, [x, y])) { + background = 'red'; + } + + squares.push( +
    + ); + } + } + + /* eslint-disable max-len */ + // Getting disabled squares + // window.coords = []; Array.prototype.forEach.call(document.querySelectorAll("*[style]"), function(elm) {if (elm.style.background === 'red') coords.push([ parseInt(elm.title.split(' ')[1]), parseInt(elm.title.split(' ')[3]) ]); }); JSON.stringify(window.coords); + /* eslint-enable max-len */ + + return ( +
    + {this.renderInfo()} +
    +
    + + {squares} +
    + +
    +
    + ); + } +} + +function select(state) { + return { hero: state.hero }; +} + +export default connect(select)(Island); diff --git a/pool/shard011/JavaScript/0069225_test-child-process-spawnsync-timeout.js b/pool/shard011/JavaScript/0069225_test-child-process-spawnsync-timeout.js new file mode 100644 index 0000000000000000000000000000000000000000..2923d8c21cb01776fbaf7f0abeae9173d3ec9199 --- /dev/null +++ b/pool/shard011/JavaScript/0069225_test-child-process-spawnsync-timeout.js @@ -0,0 +1,50 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; +const common = require('../common'); +const assert = require('assert'); + +const spawnSync = require('child_process').spawnSync; +const { debuglog, getSystemErrorName } = require('util'); +const debug = debuglog('test'); + +const TIMER = 200; +const SLEEP = common.platformTimeout(5000); + +switch (process.argv[2]) { + case 'child': + setTimeout(() => { + debug('child fired'); + process.exit(1); + }, SLEEP); + break; + default: + const start = Date.now(); + const ret = spawnSync(process.execPath, [__filename, 'child'], + { timeout: TIMER }); + assert.strictEqual(ret.error.code, 'ETIMEDOUT'); + assert.strictEqual(getSystemErrorName(ret.error.errno), 'ETIMEDOUT'); + const end = Date.now() - start; + assert(end < SLEEP); + assert(ret.status > 128 || ret.signal); + break; +} diff --git a/pool/shard011/JavaScript/0069228_gulpfile.js b/pool/shard011/JavaScript/0069228_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..3d314882c0cd13d6a1a56d5d64c1768f1fc0315f --- /dev/null +++ b/pool/shard011/JavaScript/0069228_gulpfile.js @@ -0,0 +1,86 @@ +var gulp = require('gulp') +var g_if = require('gulp-if') +var react = require('gulp-react') +var less = require('gulp-less') +var cssmin = require('gulp-cssmin') +var concat = require('gulp-concat') +var uglify = require('gulp-uglify') +var imagemin = require('gulp-imagemin') +var sourcemaps = require('gulp-sourcemaps') +var connect = require('gulp-connect') +var source = require('vinyl-source-stream') +var browserify = require('browserify') +var reactify = require('reactify') +var del = require('del') + +var paths = { + build: 'build/', + main: ['./js/main.js'], + js: ['js/**/*.js', 'js/**/*.jsx'], + js_lib: ['abalone-js/abalone.js', 'abalone-js/bower_components/d3/d3.js'], + img: ['static/**/*.png'], + css: ['less/**/*.less', 'abalone-js/abalone.css'], + html: ['html/**/*.html'], +} + +gulp.task('clean', function(cb) { + del([paths.build], cb) +}) + +gulp.task('js-main', function() { + return browserify(paths.main) + .transform(reactify) + .bundle() + .pipe(source('bundle.min.js')) + .pipe(gulp.dest('build/static')) +}) + +gulp.task('js-libs', function() { + return gulp.src(paths.js_lib) + .pipe(concat('lib.js')) + .pipe(gulp.dest('build/static')) +}) + +gulp.task('css', function() { + return gulp.src(paths.css) + .pipe(sourcemaps.init()) + .pipe(less()) + .pipe(cssmin()) + .pipe(concat('bundle.min.css')) + .pipe(sourcemaps.write()) + .pipe(gulp.dest('build/static')) +}) + +gulp.task('img', function() { + return gulp.src(paths.img) + .pipe(imagemin({ + optimizationLevel: 5 + })) + .pipe(gulp.dest('build/static')) + .pipe(connect.reload()) +}) + +gulp.task('html', function() { + return gulp.src(paths.html) + .pipe(gulp.dest('build/')) +}) + +gulp.task('watch', function() { + gulp.watch(paths.js, ['js-main']) + gulp.watch(paths.js_lib, ['js-libs']) + gulp.watch(paths.css, ['css']) + gulp.watch(paths.img, ['img']) + gulp.watch(paths.html, ['html']) +}) + +gulp.task('server', function() { + connect.server({ + root: 'build', + fallback: 'build/index.html', + port: 8000, + livereload: true + }) +}) + +gulp.task('default', ['watch', 'js-main', 'js-libs', 'css', 'img', 'html', 'server']) +gulp.task('compile', ['js-main', 'js-libs', 'css', 'img', 'html']) diff --git a/pool/shard011/JavaScript/0069229_substantial.js b/pool/shard011/JavaScript/0069229_substantial.js new file mode 100644 index 0000000000000000000000000000000000000000..a35a21a400697d6d27157a3e4bd217296c9fbb63 --- /dev/null +++ b/pool/shard011/JavaScript/0069229_substantial.js @@ -0,0 +1,140 @@ +'use strict'; + +/* + +Substantial is a tile generator wrapper. Given a tile source, it will retrieve requested tile from it, +and check if the tile has enough useful information in it to save it, rather than skip it and +let kartotherian use overzooming later. + */ + +let Promise = require('bluebird'), + zlib = require('zlib'), + qidx = require('quadtile-index'), + Err = require('@kartotherian/err'), + checkType = require('@kartotherian/input-validator'), + _ = require('underscore'), + core; + + +function Substantial(uri, callback) { + let self = this; + return Promise.try(() => { + let params = checkType.normalizeUrl(uri).query; + if (!params.source) { + throw new Err("Uri must include 'source' query parameter: %j", uri); + } + checkType(params, 'minzoom', 'integer', 0, 0, 22); + checkType(params, 'maxzoom', 'integer', 22, params.minzoom + 1, 22); + checkType(params, 'maxsize', 'integer', undefined, 0); + checkType(params, 'layers', 'string-array', true, 1); + checkType(params, 'debug', 'boolean', false); + self.params = params; + return core.loadSource(params.source); + }).then(handler => { + self.source = handler; + if (handler.query) { + self.query = query; + } + if (self.params.debug) { + // in debug mode, return a predefined tile instead + return self.source.getTileAsync(9, 156, 190).then(dh => { + self.params.debug = dh; + }); + } + }).return(self).nodeify(callback); +} + +Substantial.prototype.getTile = function(z, x, y, callback) { + let self = this; + return self.source.getTileAsync(z, x, y).then(dh => { + if (z < self.params.minzoom || z > self.params.maxzoom) { + return dh; + } + let p = self._testTile(z, x, y, dh[0]).return(dh); + if (self.params.debug) { + // For debug mode, return predefined tile when no tile error would be thrown otherwise + p = p.catch(err => { + if (Err.isNoTileError(err)) { + return self.params.debug; + } else { + throw err; + } + }); + } + return p; + }).nodeify(callback, {spread: true}); +}; + +Substantial.prototype.getInfo = function(callback) { + return this.source.getInfo(callback); +}; + +/** + * Checks if data satisfies filtering requirements, and succeeds if it should be passed, + * or errors out with the missing tile error + * @returns {Promise} + * @private + */ +Substantial.prototype._testTile = function _testTile(zoom, x, y, data) { + // this must be set to the source + let self = this; + if (!data) { + Err.throwNoTile(); + } + if (data.length >= self.params.maxsize) { + return Promise.resolve(undefined); // generated tile is too big, save + } + let vt = new core.mapnik.VectorTile(zoom, x, y); + return core.uncompressAsync(data).then(uncompressed => vt.setDataAsync(uncompressed)).then(() => { + if (vt.empty()) { + Err.throwNoTile(); + } else { + let layers = vt.names(); + if (layers.length === 0 || + (layers.length === 1 && _.contains(self.params.layers, layers[0])) + ) { + // TODO: BUG?: should we use query() to check if there are any features? + // either no layers, or only contains one whitelisted layer + Err.throwNoTile(); + } + } + }); +}; + +function query(options) { + let self = this, + applyFilter = options.zoom >= self.params.minzoom && options.zoom <= self.params.maxzoom, + iterator = this.source.query(applyFilter ? _.extend(options, {getTiles: true}) : options), + isDone = false; + + if (!applyFilter) { + return iterator; + } + let getNextValAsync = () => { + if (isDone) { + return Promise.resolve(undefined); + } + return iterator().then(iterValue => { + if (iterValue !== undefined) { + let xy = qidx.indexToXY(iterValue.idx); + return self._testTile(iterValue.zoom, xy[0], xy[1], iterValue.tile).return(iterValue); + } + isDone = true; + }).catch(err => { + if (Err.isNoTileError(err)) { + return getNextValAsync(); + } else { + throw err; + } + }); + }; + return getNextValAsync; +} + + +Substantial.initKartotherian = function(cor) { + core = cor; + core.tilelive.protocols['substantial:'] = Substantial; +}; + +module.exports = Substantial; diff --git a/pool/shard011/JavaScript/0069232_events-list.client.controller.js b/pool/shard011/JavaScript/0069232_events-list.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..97fc840d3dac9f60f2c99fa982eefe27ed8d3a09 --- /dev/null +++ b/pool/shard011/JavaScript/0069232_events-list.client.controller.js @@ -0,0 +1,153 @@ +'use strict'; + +var eventsApp = angular.module('events'); + +eventsApp.controller('EventsController', ['$scope', '$googleCalendar', '$uibModal', '$log', '$mdSidenav', + function ($scope, $googleCalendar, $uibModal, $log, $mdSidenav) { + + + //================================================================================ + // Variables + //================================================================================ + + $scope.events = []; + $scope.calEvents = []; + $scope.eventSources = []; + $scope.isCalendarView = true; + $scope.isTableView = false; + $scope.isSidenavOpen = false; + + /* config object */ + $scope.uiConfig = { + calendar: { + schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source', + editable: false, + + aspectRatio: 1.5, + + header: { + left: 'month,agendaWeek,agendaDay,verticalResourceView', + center: 'title', + right: 'today prev,next' + }, + eventLimit: true, + navLinks: true, + views: { + verticalResourceView: { + type: 'timeline', + duration: { days: 1 }, + buttonText: 'day by doctor', + + }, + agendaDay: { + resources: false + } + }, + minTime: '8:00', + maxTime: '21:00', + + resourceAreaWidth: '20%', + resourceLabelText: 'Doctors', + + resources: [ + { id: 'Dr. Rajendra Kurady', title: 'Dr Rajendra Kurady', eventColor: 'maroon' }, + { id: 'Dr. Saphal Shetty', title: 'Dr. Saphal Shetty', eventColor: 'green' }, + { id: 'Dr. Satish K', title: 'Dr. Satish K', eventColor: '#FF00FF' }, + { id: 'Dr. Siddharth K', title: 'Dr. Siddharth K', eventColor: 'orange' }, + { id: 'Prof. Dr. Shiva Shankar', title: 'Prof. Dr. Shiva Shankar', eventColor: 'red' }, + { id: 'Prof. Dr. Ponnanna A A', title: 'Prof. Dr. Ponnanna A A', eventColor: 'lime' }, + { id: 'Prof. Dr. Anjan Shah', title: 'Prof. Dr. Anjan Shah', eventColor: 'purple' }, + { id: 'Dr. Sudarshan Pujari', title: 'Dr. Sudarshan Pujari', eventColor: '#9ACD32' }, + { id: 'Dr. Sudarshan A', title: 'Dr. Sudarshan A', eventColor: 'maroon' }, + { id: 'Dr. Manjunath Hegde', title: 'Dr. Manjunath Hegde', eventColor: 'black' }, + { id: 'Dr. Pallavi Urs', title: 'Dr. Pallavi Urs', eventColor: '#FF00FF' }, + { id: 'Dr. Veena Aralli', title: 'Dr. Veena Aralli', eventColor: '#0000FF' }, + { id: 'Prof. Dr. Dharma M Hinduja', title: 'Prof. Dr. Dharma M Hinduja', eventColor: '#00FFFF' }, + { id: 'Prof. Dr. Nanda Kishor', title: 'Prof. Dr. Nanda Kishor', eventColor: '#FFC0CB' }, + { id: 'Prof. Dr. Sunil Rao', title: 'Prof. Dr. Sunil Rao', eventColor: '#BDB76B' }, + { id: 'Dr. Aparna Srinivas', title: 'Dr. Aparna Srinivas', eventColor: '#00BFFF' }, + { id: 'Dr. Harish Sampath', title: 'Dr. Harish Sampath', eventColor: '#9ACD32' }, + { id: 'Dr. Ranjitha Shetty', title: 'Dr. Ranjitha Shetty', eventColor: '#FFFFE0' }, + { id: 'Dr. Syed Mutheei Ulla', title: 'Dr. Syed Mutheei Ulla', eventColor: '#B8860B' }, + ], + + eventRender: function (event, element) { + + var view = $('#calendar').fullCalendar('getView'); + + if (view.name === 'verticalResourceView') { + element.find('.fc-title').empty(); + element.find('.fc-title').append(event.description.split('\n')[0]); + } + else { + element.find('.fc-title').empty(); + + if (event.description === 'On Vacation') { + element.find('.fc-title').append('On Vacation - ' + event.title); + } else { + element.find('.fc-title').append(event.title); + } + + } + + }, + eventClick: $scope.alertOnEventClick + } + }; + + this.toggleview = function () { + if ($scope.isCalendarView === true) { + $scope.isCalendarView = false; + $scope.isTableView = true; + } + else { + $scope.isCalendarView = true; + $scope.isTableView = false; + } + }; + + /* alert on eventClick calendar*/ + $scope.alertOnEventClick = function (date, jsEvent, view) { + $scope.currentEvent = date; + $mdSidenav('right').toggle(); + }; + + //================================================================================ + // Scope Functions + //================================================================================ + + $scope.getEvents = function () { + $googleCalendar.getEvents().then(function (events, eventRender) { + + $scope.events = events; + + for (var index = 0; index < events.length; index++) { + var event = events[index]; + + $scope.calEvents[index] = { + 'title': event.summary, + 'start': event.start.dateTime, + 'end': event.end.dateTime, + 'description': event.description, + 'resourceId': event.summary, + 'stick': 'true', + }; + console.log(event.summary); + } + + }); + }; + + $scope.eventSources = [$scope.calEvents]; + + $scope.setCurrentEvent = function (event) { + $scope.currentEvent = event; + }; + + $scope.myFilter = function (event) { + return event.description !== 'On Vacation'; + }; + + + }]); + diff --git a/pool/shard011/JavaScript/0069234_parallel-lint.js b/pool/shard011/JavaScript/0069234_parallel-lint.js new file mode 100644 index 0000000000000000000000000000000000000000..a9aec06c2dfa0a103056f763d5df5aaf64a2f1c7 --- /dev/null +++ b/pool/shard011/JavaScript/0069234_parallel-lint.js @@ -0,0 +1,45 @@ +var Linter = require("tslint"); +var fs = require("fs"); + +function getLinterOptions() { + return { + configuration: require("../tslint.json"), + formatter: "prose", + formattersDirectory: undefined, + rulesDirectory: "built/local/tslint" + }; +} + +function lintFileContents(options, path, contents) { + var ll = new Linter(path, contents, options); + return ll.lint(); +} + +function lintFileAsync(options, path, cb) { + fs.readFile(path, "utf8", function (err, contents) { + if (err) { + return cb(err); + } + var result = lintFileContents(options, path, contents); + cb(undefined, result); + }); +} + +process.on("message", function (data) { + switch (data.kind) { + case "file": + var target = data.name; + var lintOptions = getLinterOptions(); + lintFileAsync(lintOptions, target, function (err, result) { + if (err) { + process.send({ kind: "error", error: err.toString() }); + return; + } + process.send({ kind: "result", failures: result.failureCount, output: result.output }); + }); + break; + case "close": + process.exit(0); + break; + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069236_TargetSet.js b/pool/shard011/JavaScript/0069236_TargetSet.js new file mode 100644 index 0000000000000000000000000000000000000000..bb736508d5e8168b32beb7fcbcf4b5298a597e7f --- /dev/null +++ b/pool/shard011/JavaScript/0069236_TargetSet.js @@ -0,0 +1,60 @@ +import React from 'react'; +import PropTypes from 'prop-types'; + +import _ from 'lodash'; + +import { LoadingScreen } from './ui/LoadingScreen'; +import { AddToSetButton } from './ui/AddToSetButton'; + +import { extractThemeName } from '../lib/helpers'; + +export const TargetSet = (props) => { + let themeName = ''; + const currentSet = props.getCurrentSet(props.match.params.set_number); + + if (!_.isEmpty(currentSet)) { + themeName = extractThemeName(currentSet.details.theme_id, props.popularThemes); + } + + return ( +
    +

    Set Details

    + {(_.isEmpty(currentSet)) && + + } + + {(!_.isEmpty(currentSet)) && +
    +
    +

    {currentSet.details.name}

    +

    {currentSet.details.set_num}

    + {currentSet.details.name} +
    +
    +
    +
      +
    • Theme:{themeName}
    • +
    • Year:{currentSet.details.year}
    • +
    • Pieces:{currentSet.details.num_parts}
    • +
    • Owned:{currentSet.quantity}
    • +
    + + {(currentSet.quantity === 0) && + + } +
    +
    +
    + } +
    + ); +}; + +TargetSet.propTypes = { + handleAddSet: PropTypes.func.isRequired, + userSets: PropTypes.array.isRequired, + cachedThemes: PropTypes.array.isRequired, + popularThemes: PropTypes.array.isRequired +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069237_game-template.js b/pool/shard011/JavaScript/0069237_game-template.js new file mode 100644 index 0000000000000000000000000000000000000000..a9af39988149ff9fe7dba7234dd32b8a7ee7460f --- /dev/null +++ b/pool/shard011/JavaScript/0069237_game-template.js @@ -0,0 +1,26 @@ + +Game.Template = (function () { + /** + * @param {String} templateName template, period-separated + * @returns {Handlebars} template + */ + const getTemplate = function (templateName) { + let template = window.spa_templates + templateName.split(/\./g).forEach(name => { + template = template ? (template[name] || null) : null + }) + return template + } + + /** + * @param {String} templateName Template name + * @param {Object} data Data to parse with + * @returns {String} + */ + const parseTemplate = function (templateName, data) { + const template = getTemplate(templateName) + return (template && typeof template === 'function') ? template(data) : null + } + + return { getTemplate, parseTemplate } +})() diff --git a/pool/shard011/JavaScript/0069241_translate_delete_glossary_beta.js b/pool/shard011/JavaScript/0069241_translate_delete_glossary_beta.js new file mode 100644 index 0000000000000000000000000000000000000000..9eef42fac86d477facf610711ec2adad628696c4 --- /dev/null +++ b/pool/shard011/JavaScript/0069241_translate_delete_glossary_beta.js @@ -0,0 +1,61 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +'use strict'; + +function main( + projectId = 'YOUR_PROJECT_ID', + location = 'us-central1', + glossaryId = 'glossary-id' +) { + // [START translate_delete_glossary_beta] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'YOUR_PROJECT_ID'; + // const location = 'global'; + + // Imports the Google Cloud Translation library + const {TranslationServiceClient} = require('@google-cloud/translate').v3beta1; + + // Instantiates a client + const translationClient = new TranslationServiceClient(); + + async function deleteGlossary() { + // Construct request + const name = translationClient.glossaryPath( + projectId, + location, + glossaryId + ); + const request = { + parent: translationClient.locationPath(projectId, location), + name: name, + }; + + // Delete glossary using a long-running operation. + // You can wait for now, or get results later. + const [operation] = await translationClient.deleteGlossary(request); + + // Wait for operation to complete. + const [response] = await operation.promise(); + + console.log(`Deleted glossary: ${response.name}`); + } + + deleteGlossary(); + // [END translate_delete_glossary_beta] +} + +main(...process.argv.slice(2)); diff --git a/pool/shard011/JavaScript/0069243_groupAddController.js b/pool/shard011/JavaScript/0069243_groupAddController.js new file mode 100644 index 0000000000000000000000000000000000000000..14bafc829867a576dea06e07877cda84044b7cd2 --- /dev/null +++ b/pool/shard011/JavaScript/0069243_groupAddController.js @@ -0,0 +1,158 @@ +(function () { + + var controller = function ($mdDialog,$location,arrayToUrlParams,mixedContentToArray,$scope,orgResources) { + + var c = this; + c.data = { + name : '', + description :'', + users : [] + }; + var selectMemberListener = function(){ + jQuery(document).on('touchend click','.lapalaa li', function(){ + var elem = jQuery(this); + var checkmark = elem.find('md-icon'); + var id = elem.attr('id'); + var index = -1; + for(var i=0; i< c.selectedMembers.length; i++){ + if(c.selectedMembers[i].id === id+''){ + index = i; + break; + } + } + var name = elem.find('p').text(); + if(index !== -1){ + checkmark.removeAttr('style'); + c.selectedMembers.splice(index,1); + console.log(c.selectedMembers) + } + else{ + checkmark.css('display','block'); + c.selectedMembers.push({id : id, name : name}); + } + }) + }; + c.removeMember = function(index){ + c.showMembers.splice(index,1); + }; + c.makePlunner = function(index, id){ + c.addGroup.planner.index = index; + c.addGroup.planner.id = id + + }; + c.moveItems = function(){ + c.showMembers = c.selectedMembers; + jQuery('.lapalaa li').find('md-icon').removeAttr('style'); + c.selectedMembers = []; + }; + c.showMembers = []; + c.selectedMembers = []; + var elaborateUsers = function(urs){ + var targetArray=[]; + var tmpArray = []; + for(var i=0; i
    ' + this.message + '
    ', + parent: angular.element(document.body), + clickOutsideToClose: false + } + ); + }, + hide: function () { + $mdDialog.cancel(); + } + }; + c.addGroup = { + planner: {index:undefined, id:undefined}, + members: [], + name: '', + desc: '', + errors: [], + invalidFields: { + nameReq: false, + plannerReq: false, + descReq: false, + membersReq: false + }, + submit: function () { + var validationStatus; + var validMembers=[]; + + //Checks tha validity status of input fields + this.invalidFields.nameReq = (c.data.name === ''); + this.invalidFields.membersReq = (c.showMembers.length === 0); + this.invalidFields.plannerReq = (this.planner.index == null || angular.isUndefined(this.planner.index)); + this.invalidFields.descReq = (c.data.description === ''); + + validationStatus = this.invalidFields.descriptionReq || this.invalidFields.nameReq || this.invalidFields.membersReq || this.invalidFields.plannerReq; + //Submits everything to the server if data is valid + if (!validationStatus) { + for(var i=0; i< c.showMembers.length; i++){ + validMembers.push(c.showMembers[i].id); + } + confirmPopup.show(); + //Updates the group name and planner + orgResources.orgGroup.save({groupId: ''}, jQuery.param({ + name: c.data.name, + planner_id: c.addGroup.planner.id, + description: c.data.description + })).$promise + .then(function (response) { + //Updates the group members + orgResources.orgUserInGroup.save({ + groupId: response.id, + userId: '' + }, arrayToUrlParams.process('id', validMembers)).$promise + .then(function () { + confirmPopup.hide(); + $location.path('/organization') + }, function (response) { + //Puts relevant errors in array + if (response.status === 422) { + mixedContentToArray.process(response.data, c.addGroup.errors, true); + confirmPopup.hide(); + } + confirmPopup.hide(); + }) + }, + function (response) { + //Puts relevant errors in array + if (response.status === 422) { + mixedContentToArray.process(response.data, c.addGroup.errors, true); + confirmPopup.hide(); + } + confirmPopup.hide(); + }); + } + } + }; + + + + selectMemberListener(); + getUsers(); + }; + + var app = angular.module('Plunner'); + app.controller('groupAddController', ['$mdDialog','$location','arrayToUrlParams','mixedContentToArray','$scope','orgResources', controller]); +}()); diff --git a/pool/shard011/JavaScript/0069249_deepstream.js b/pool/shard011/JavaScript/0069249_deepstream.js new file mode 100644 index 0000000000000000000000000000000000000000..475c48ba894a824335cbdd71497e5e7e0101f6c9 --- /dev/null +++ b/pool/shard011/JavaScript/0069249_deepstream.js @@ -0,0 +1,14 @@ +"use strict"; +const client_1 = require("./client"); +const constants_1 = require("./constants"); +const C = require("../binary-protocol/src/message-constants"); +const client = (url, options) => { + return new client_1.Client(url, options); +}; +module.exports = Object.assign(client, { + CONNECTION_STATE: constants_1.CONNECTION_STATE, + C, + EVENT: constants_1.EVENT, + deepstream: client +}); +//# sourceMappingURL=deepstream.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069251_saml_auth2.js b/pool/shard011/JavaScript/0069251_saml_auth2.js new file mode 100644 index 0000000000000000000000000000000000000000..6a6c01ded2b53235ad53d75fdf3764e360bf67fe --- /dev/null +++ b/pool/shard011/JavaScript/0069251_saml_auth2.js @@ -0,0 +1,99 @@ +/*global*/ +(function () { + 'use strict'; + + var saml = require('samlify'); + var fs = require('fs'); + var sentKeys = {}; + + // Set up auth + var idp_xml_file = "./keys/uab-shib-metadata.xml"; + // var idp_xml_file = "./keys/sample_idp.xml"; + var service_provider_xml_file = "./keys/sample_sp.xml"; + var service_provider_xml_file_read = fs.readFileSync(service_provider_xml_file, 'utf8'); + + + var idp = saml.IdentityProvider({ + metadata: fs.readFileSync(idp_xml_file, 'utf8') + }); + + var sp = saml.ServiceProvider({ + metadata: service_provider_xml_file_read + }); + + var login = function (req, res, next) { + var loginObj = sp.createLoginRequest(idp, 'redirect'); + //store the callback url + sentKeys[loginObj.id] = req.params; + + //delete the key and the callback after 10 minutes + (function (id) { + setTimeout(function () { + delete sentKeys[id]; + }, 1000 * 60 * 10); + }(loginObj.id)); + + // console.log('sent', loginObj); + return res.redirect(loginObj.context, next); + }; + + var post_token = function (callback) { + return function (req, res, next) { + var body, bodyObj = {}, i, entry, key; + body = req.body.split(/[\&\?]/); + for (i = 0; i < body.length; i += 1) { + entry = body[i].split(/\=/); + key = decodeURIComponent(entry.shift()); + bodyObj[key] = decodeURIComponent(entry.join('=')); + } + + req.body = bodyObj; + + + sp.parseLoginResponse(idp, 'post', req) + .then(function (results) { + //res.send({id: results.extract.nameID, response: results.extract.response}); + // console.log('came back', results.extract.response.inResponseTo, sentKeys[results.extract.response.inResponseTo]); + //make sure this does not return an undefined + var id = results.extract.response.inResponseTo; + sentKeys[id] = sentKeys[id] || {}; + + //double check to delete key in case one is created above + //delete the key and the callback after 10 minutes + (function (tid) { + setTimeout(function () { + delete sentKeys[tid]; + }, 1000 * 60 * 10); + }(id)); + + callback(results.extract.nameID, sentKeys[id].redirect, sentKeys[id].tag, req, res, next); + }) + .catch(function (err) { + console.log(bodyObj); + console.log(err); + res.send(500, { + error: { + code: "500", + message: "Failed to parse message from the IDP server: " + err.message + } + }); + }); + + return [next, res]; + }; + }; + + var metadata = function (req, res, next) { + res.setHeader('content-type', 'application/xml'); + res.end(sp.getMetadata()); + return [next, req]; + }; + + module.exports = { + login: login, + post_token: post_token, + metadata: metadata + }; + + return false; +}()); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069256_filter.js b/pool/shard011/JavaScript/0069256_filter.js new file mode 100644 index 0000000000000000000000000000000000000000..82551c1156cdee9fa0362aaa6dc8b374a336f92e --- /dev/null +++ b/pool/shard011/JavaScript/0069256_filter.js @@ -0,0 +1,63 @@ +let filters = {}; + +class Filter { + static tokenize (signature) { + if (typeof signature !== 'string') { + throw new Error('Cannot tokenize non-string filter signature'); + } + + let [head, ...rest] = signature.split(':'); + rest = rest.join(':'); + rest = rest.length === 0 ? [] : rest.split(','); + + return [head, ...rest]; + } + + static get (signature) { + const signatureType = typeof signature; + + if (signatureType === 'function') { + return signature; + } + + if (signatureType === 'string') { + signature = Filter.tokenize(signature); + } + + if (!Array.isArray(signature)) { + throw new Error(`Unknown filter by ${signatureType}`); + } + + const [fn, ...args] = signature; + + if (fn in filters === false) { + try { + filters[fn] = require('./filters/' + fn); + } catch (err) { + filters[fn] = null; + } + } + + if (!filters[fn]) { + let normalizedSignature = 'unknown'; + try { + normalizedSignature = JSON.stringify(signature); + } catch (err) { + // noop + } + throw new Error(`Filter ${fn} not found <${signatureType}(${normalizedSignature})>`); + } + + return filters[fn](...args); + } + + static put (name, filter) { + filters[name] = filter; + } + + static reset () { + filters = {}; + } +} + +module.exports = Filter; diff --git a/pool/shard011/JavaScript/0069257_cleanOperation.js b/pool/shard011/JavaScript/0069257_cleanOperation.js new file mode 100644 index 0000000000000000000000000000000000000000..e4b5cf3eabc10ca6ac0af0b9fcb1f2828736929b --- /dev/null +++ b/pool/shard011/JavaScript/0069257_cleanOperation.js @@ -0,0 +1,19 @@ +import check from '../core/check'; +import operation from '../model/operation'; +import path from 'path'; +import fs from 'fs-extra'; + +function cleanOperation() { + const thisOperation = operation.create({ id: 'clean', logMessage: 'Cleaning project' }); + thisOperation.perform = ({ rootFolder, buildFolder }) => { + check.definedString('rootFolder', rootFolder); + check.definedString('buildFolder', buildFolder); + fs.removeSync(path.join(rootFolder, buildFolder)); + return Promise.resolve(); + }; + return thisOperation; +} + +export default { + create: cleanOperation +} diff --git a/pool/shard011/JavaScript/0069262_document.js b/pool/shard011/JavaScript/0069262_document.js new file mode 100644 index 0000000000000000000000000000000000000000..c0cabbe847a46e84fc2becd44916c344de3cb37f --- /dev/null +++ b/pool/shard011/JavaScript/0069262_document.js @@ -0,0 +1,56 @@ +/** + * Document onReady hook for sliders + * + * Copyright (C) 2009-2012 Nikolay Nemshilov + */ +$(document).on({ + // preinitializing the sliders + ready: function() { + $$('.rui-slider').each(function(element) { + if (!(element instanceof Slider)) { + element = new Slider(element); + } + }); + }, + + mousedown: document_mousedown, + touchstart: document_mousedown, + + mousemove: document_mousemove, + touchmove: document_mousemove, + + mouseup: document_mouseup, + touchend: document_mouseup +}); + +$(window).onBlur(function() { + if (Slider.current) { + Slider.current = false; + } +}); + +// initiates the slider move +function document_mousedown(event) { + var slider = event.find('.rui-slider'); + if (slider) { + event.stop(); + if (!(slider instanceof Slider)) { + slider = new Slider(slider); + } + Slider.current = slider.start(event); + } +} + +// handles the slider move +function document_mousemove(event) { + if (Slider.current) { + Slider.current.move(event); + } +} + +// handles the slider release +function document_mouseup(event) { + if (Slider.current) { + Slider.current = false; + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069264_mock-example-1.js b/pool/shard011/JavaScript/0069264_mock-example-1.js new file mode 100644 index 0000000000000000000000000000000000000000..eac4ad1ef9f380294d92a1e86520948fe658c657 --- /dev/null +++ b/pool/shard011/JavaScript/0069264_mock-example-1.js @@ -0,0 +1,97 @@ +/*eslint no-unused-vars: 0, no-unused-expr: 0*/ +"use strict"; + +var should = require("should"); + +describe("process factories", function() { + var angular; + + function assertions(example1) { + // Factories with no dependencies + example1.factories[0].name.should.be.equal("NoDependenciesService1"); + example1.factories[1].name.should.be.equal("NoDependenciesService2"); + example1.factories[0].deps.should.have.a.lengthOf(0); + example1.factories[1].deps.should.have.a.lengthOf(0); + + // Factories with angular dependencies + example1.factories[2].name.should.be.equal("OneAngularDependencyService1"); + example1.factories[3].name.should.be.equal("OneAngularDependencyService2"); + example1.factories[2].deps.should.have.a.lengthOf(1); + example1.factories[3].deps.should.have.a.lengthOf(1); + example1.factories[2].deps[0].should.be.equal("$http"); + example1.factories[3].deps[0].should.be.equal("$http"); + + // Factories with angular and other dependencies + example1.factories[4].name.should.be.equal("MixedDependenciesService1"); + example1.factories[5].name.should.be.equal("MixedDependenciesService2"); + example1.factories[4].deps.should.have.a.lengthOf(3); + example1.factories[5].deps.should.have.a.lengthOf(3); + + // Controllers with no dependencies + example1.controllers[0].name.should.be.equal("NoDependenciesCtrl1"); + example1.controllers[1].name.should.be.equal("NoDependenciesCtrl2"); + example1.controllers[0].deps.should.have.a.lengthOf(0); + example1.controllers[1].deps.should.have.a.lengthOf(0); + + + // Controllers with angular dependencies + example1.controllers[2].name.should.be.equal("OneAngularDependencyCtrl1"); + example1.controllers[3].name.should.be.equal("OneAngularDependencyCtrl2"); + example1.controllers[2].deps.should.have.a.lengthOf(1); + example1.controllers[3].deps.should.have.a.lengthOf(1); + example1.controllers[2].deps[0].should.be.equal("$http"); + example1.controllers[3].deps[0].should.be.equal("$http"); + + // Controllers with angular and other dependencies + example1.controllers[4].name.should.be.equal("MixedDependenciesCtrl1"); + example1.controllers[5].name.should.be.equal("MixedDependenciesCtrl2"); + example1.controllers[4].deps.should.have.a.lengthOf(3); + example1.controllers[5].deps.should.have.a.lengthOf(3); + } + + describe("in chained definition", function () { + beforeEach(function() { + angular = require("../src/fake-angular")(); + require("../test-mocks/example1-chained")(angular); + }); + + it("process factories names and dependencies", function () { + assertions(angular.modulesMap.example1); + }); + }); + + describe("in not-chained definition", function () { + beforeEach(function() { + angular = require("../src/fake-angular")(); + require("../test-mocks/example1")(angular); + }); + + it("process factories names and dependencies", function () { + assertions(angular.modulesMap.example1); + }); + }); + + describe("parses options", function () { + + var options = { + hideAngularServices: true + }; + + beforeEach(function() { + angular = require("../src/fake-angular")(options); + require("../test-mocks/example1")(angular); + }); + + it("should hide angular services", function () { + angular.options.hideAngularServices.should.be.equal(true); + + var MixedDependenciesCtrl1 = angular.modulesMap.example1.controllers[4]; + + // Note, the $http dependency was excluded + MixedDependenciesCtrl1.deps.should.have.a.lengthOf(2); + MixedDependenciesCtrl1.deps[0].should.be.equal("ServiceX"); + MixedDependenciesCtrl1.deps[1].should.be.equal("ServiceY"); + }); + + }); +}); diff --git a/pool/shard011/JavaScript/0069269_privateStaticMemberAccessibility.js b/pool/shard011/JavaScript/0069269_privateStaticMemberAccessibility.js new file mode 100644 index 0000000000000000000000000000000000000000..34498e90b4fffbbf60d3b860aba5e73ead0208d1 --- /dev/null +++ b/pool/shard011/JavaScript/0069269_privateStaticMemberAccessibility.js @@ -0,0 +1,41 @@ +//// [privateStaticMemberAccessibility.ts] +class Base { + private static foo: string; +} + +class Derived extends Base { + static bar = Base.foo; // error + bing = () => Base.foo; // error +} + +//// [privateStaticMemberAccessibility.js] +var __extends = (this && this.__extends) || (function () { + var extendStatics = function (d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + return function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; +})(); +var Base = /** @class */ (function () { + function Base() { + } + return Base; +}()); +var Derived = /** @class */ (function (_super) { + __extends(Derived, _super); + function Derived() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.bing = function () { return Base.foo; }; // error + return _this; + } + Derived.bar = Base.foo; // error + return Derived; +}(Base)); diff --git a/pool/shard011/JavaScript/0069273_CollidesAction.js b/pool/shard011/JavaScript/0069273_CollidesAction.js new file mode 100644 index 0000000000000000000000000000000000000000..1c512bc2539518228ab5386d354e8136cb880deb --- /dev/null +++ b/pool/shard011/JavaScript/0069273_CollidesAction.js @@ -0,0 +1,92 @@ +var EntitySelection = require('../../../entities/EntitySelection'); +var Action = require('../../../fsmpack/statemachine/actions/Action'); +var ProximitySystem = require('../../../fsmpack/proximity/ProximitySystem'); + +function CollidesAction(/*id, settings*/) { + Action.apply(this, arguments); +} + +CollidesAction.prototype = Object.create(Action.prototype); +CollidesAction.prototype.constructor = CollidesAction; + +CollidesAction.external = { + key: 'Collides', + name: 'Collision (Bounding volume intersection)', + type: 'collision', + description: 'Checks for collisions or non-collisions with other entities. Collisions are based on the entities\' bounding volumes. Before using collisions you first need to tag your entities.', + canTransition: true, + parameters: [{ + name: 'Tag', + key: 'tag', + type: 'string', + description: 'Checks for collisions with other objects having this tag.', + 'default': 'red' + }], + transitions: [{ + key: 'collides', + description: 'State to transition to when a collision occurs.' + }, { + key: 'notCollides', + description: 'State to transition to when a collision is not occurring.' + }] +}; + +var labels = { + collides: 'On bounds Overlap', + notCollides: 'On bounds Separate' +}; + +CollidesAction.getTransitionLabel = function (transitionKey /*, actionConfig*/){ + return labels[transitionKey]; +}; + +CollidesAction.prototype.ready = function (fsm) { + var entity = fsm.getOwnerEntity(); + var world = entity._world; + if (!world.getSystem('ProximitySystem')) { + world.setSystem(new ProximitySystem()); + } +}; + +CollidesAction.prototype.update = function (fsm) { + var entity = fsm.getOwnerEntity(); + var world = entity._world; + var proximitySystem = world.getSystem('ProximitySystem'); + + var entities = new EntitySelection(proximitySystem.getFor(this.tag)) + .and(world.by.tag(this.tag)) + .toArray(); + + var collides = false; + + entity.traverse(function (entity) { + // Stop traversing when the entity can't collide with anything. + if (!entity.meshRendererComponent || entity.particleComponent) { + return false; + } + + var worldBound = entity.meshRendererComponent.worldBound; + + for (var i = 0; i < entities.length; i++) { + entities[i].traverse(function (entity) { + if (!entity.meshRendererComponent || entity.particleComponent) { + return true; // Move on to other entities. + } + + var otherBound = entity.meshRendererComponent.worldBound; + if (otherBound && worldBound.intersects(otherBound)) { + collides = true; + return false; // Stop traversing. + } + }); + + if (collides) { + return false; // Stop traversing. + } + } + }); + + fsm.send(collides ? this.transitions.collides : this.transitions.notCollides); +}; + +module.exports = CollidesAction; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069277_OperatorFactory.js b/pool/shard011/JavaScript/0069277_OperatorFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..c8ec432ee3b5d167efc66979fa3aa365a85ce77b --- /dev/null +++ b/pool/shard011/JavaScript/0069277_OperatorFactory.js @@ -0,0 +1,18 @@ +App.factory('OperatorFactory', + +['ApiService', + +function (ApiService) +{ + var operator = {}; + + operator.create = function(data, callback) { + ApiService.post('operators', data, callback); + }; + + operator.update = function(data, callback) { + ApiService.post('operators/' + data.id, data, callback); + }; + + return operator; +}]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069278_wildcard.js b/pool/shard011/JavaScript/0069278_wildcard.js new file mode 100644 index 0000000000000000000000000000000000000000..a73d0c7b7cf5097d0a816432ee5e8c6582ad0c96 --- /dev/null +++ b/pool/shard011/JavaScript/0069278_wildcard.js @@ -0,0 +1,31 @@ +define(['base/event'], function(event) { + 'use strict'; + + describe('Event', function() { + + describe('Wildcard', function() { + var spy, target; + + beforeEach(function() { + spy = sinon.spy(); + target = new event.Target(); + }); + + it('should fire events by "*:event" wildcard', function() { + target.on('*:change', spy); + target.fire('name:change'); + + expect(spy).to.be.called(); + }); + + it('should fire events by "event:*" wildcard', function() { + target.on('name:*', spy); + target.fire('name:set'); + + expect(spy).to.be.called(); + }); + }); + + }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069285_gulpfile.js b/pool/shard011/JavaScript/0069285_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..bebd421e558ac4dc25b1d332df573d9ba8a35bd7 --- /dev/null +++ b/pool/shard011/JavaScript/0069285_gulpfile.js @@ -0,0 +1,61 @@ +var gulp = require('gulp'); +var concat = require('gulp-concat'); +var minifyCss = require('gulp-minify-css'); +var rename = require('gulp-rename'); +var addsrc = require('gulp-add-src'); +var replace = require('gulp-replace'); +var jsifyTemplates = require('gulp-jsify-html-templates'); +var uglify = require('gulp-uglify'); +var order = require("gulp-order"); + + +gulp.task('color-picker', function() { + return gulp.src( [ + './src/modal-template-*.html', + + ]) + .pipe(jsifyTemplates()) + .pipe(replace("htmlTemplates", 'colorPickerTemplates')) + .pipe(concat('templates.js')) + .pipe(addsrc( './src/ionic-color-picker.js')) + .pipe(order(['templates.js', 'src/ionic-color-picker.js'])) + .pipe(concat('ionic-color-picker.js')) + .pipe(gulp.dest('./dist/')) + .pipe(uglify({mangle:false})) + .pipe(rename({ extname: '.min.js' })) + .pipe(gulp.dest('./dist/')) + +}); + +gulp.task('color-picker-tiny', function() { + return gulp.src( [ + './src/tinycolor.min.js', + './dist/ionic-color-picker.js']) + .pipe(concat('ionic-color-picker-tinycolor.js')) + .pipe(gulp.dest('./dist/')) + .pipe(uglify({mangle:false})) + .pipe(rename({ extname: '.min.js' })) + .pipe(gulp.dest('./dist/')) + +}); + + +gulp.task('css-color-picker', function() { + return gulp.src( './src/ionic-color-picker.css') + .pipe(gulp.dest('./dist/')) + .pipe(minifyCss({ + keepSpecialComments: 0 + })) + .pipe(rename({ extname: '.min.css' })) + .pipe(gulp.dest('./dist/')) + +}); + + +gulp.task('watch', function() { + gulp.watch(['./src/*.*'], ['color-picker', 'css-color-picker', 'color-picker-tiny']); + +}); + +gulp.task('default', ['color-picker', 'css-color-picker', 'color-picker-tiny']); + diff --git a/pool/shard011/JavaScript/0069289_build.js b/pool/shard011/JavaScript/0069289_build.js new file mode 100644 index 0000000000000000000000000000000000000000..6c79c1eb91e4b587fa269b5c4fafd606e2320739 --- /dev/null +++ b/pool/shard011/JavaScript/0069289_build.js @@ -0,0 +1,53 @@ +'use strict'; + +var chalk = require('chalk'); +var Task = require('../models/task'); +var Builder = require('../models/builder'); + +module.exports = Task.extend({ + // Options: String outputPath + run: function(options) { + var ui = this.ui; + var analytics = this.analytics; + + ui.pleasantProgress.start(chalk.green('Building'), chalk.green('.')); + + var builder = new Builder({ + ui: ui, + outputPath: options.outputPath, + environment: options.environment, + project: this.project + }); + + return builder.build() + .then(function(results) { + var totalTime = results.totalTime / 1e6; + + analytics.track({ + name: 'ember build', + message: totalTime + 'ms' + }); + + analytics.trackTiming({ + category: 'rebuild', + variable: 'build time', + label: 'broccoli build time', + value: parseInt(totalTime, 10) + }); + }) + .finally(function() { + ui.pleasantProgress.stop(); + return builder.cleanup(); + }) + .then(function() { + ui.writeLine(chalk.green('Built project successfully. Stored in "' + + options.outputPath + '".')); + }) + .catch(function(err) { + ui.writeLine(chalk.red('Build failed.')); + ui.writeError(err); + + return 1; + }); + } +}); diff --git a/pool/shard011/JavaScript/0069290_filename.js b/pool/shard011/JavaScript/0069290_filename.js new file mode 100644 index 0000000000000000000000000000000000000000..cc809d419c44390cd42915173fb2bd9148df9d38 --- /dev/null +++ b/pool/shard011/JavaScript/0069290_filename.js @@ -0,0 +1,17 @@ +var fs = require('fs'); +var path = require('path'); + +module.exports = { + exists: function (file) { + try { + fs.statSync(file); + return true; + } catch (_) { + return false; + } + }, + isAbsolute: function (file) { + var dir = path.resolve(file); + return path.normalize(file) === path.normalize(dir); + } +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069297_initializer.js b/pool/shard011/JavaScript/0069297_initializer.js new file mode 100644 index 0000000000000000000000000000000000000000..ba4b861f187366c27b92c900b68d3d4422df8aa6 --- /dev/null +++ b/pool/shard011/JavaScript/0069297_initializer.js @@ -0,0 +1,105 @@ +/** + * Module dependencies. + */ +var debug = require('debug')('bootable'); + + +/** + * Creates an instance of `Initializer`. + * + * @constructor + * @api public + */ +function Initializer(options) { + options = options || {}; + this._phases = []; + this._eventable = options.eventable !== false; +} + +/** + * Run all phases. + * + * When the initializer is run, all phases will be executed sequentially, in + * the order in which they were registered. Once complete, `cb` will be + * invoked. + * + * @param {Function} cb + * @param {Object} [thisArg] + * @api public + */ +Initializer.prototype.run = function(cb, thisArg) { + var phases = this._phases + , idx = 0 + , eventable = !!this._eventable && thisArg && !!thisArg.emit + , name; + + function next(err) { + if (err) { return cb(err); } + + if (eventable && name) thisArg.emit(name + ':after', thisArg); + + var phase = phases[idx++]; + // all done + if (!phase) { return cb(); } + + try { + if (typeof phase == 'object') { + debug('%s', phase.constructor ? phase.constructor.name + '#boot' : 'anonymous#boot'); + name = eventable && phase.constructor && phase.constructor.name; + if (eventable && name) thisArg.emit(name + ':before', thisArg); + phase.boot(next); + } else { + debug('%s', phase.name || 'anonymous'); + name = eventable && phase.name; + if (eventable && name) thisArg.emit(name + ':before', thisArg); + var arity = phase.length; + if (arity == 1) { + phase.call(thisArg, next); + } else { + phase.call(thisArg); + next(); + } + } + } catch (ex) { + next(ex); + } + } + next(); +}; + +/** + * Register a phase. + * + * A phase can be either synchronous or asynchronous. Synchronous phases have + * following function signature + * + * function myPhase() { + * // perform initialization + * } + * + * Asynchronous phases have the following function signature. + * + * function myAsyncPhase(done) { + * // perform initialization + * done(); // or done(err); + * } + * + * The phase may also be an object that has a `boot` function. In this case, + * the object's boot function will be called during the boot sequence. This is + * typically used for objects that need to establish a persistent connection, + * for example to a database or message queue. + * + * @param {Function|Object} fn + * @returns {Initializer} `this`, for a fluent interface. + * @api public + */ +Initializer.prototype.phase = function(fn) { + this._phases.push(fn); + return this; +}; + + +/** + * Expose `Initializer`. + */ +module.exports = Initializer; diff --git a/pool/shard011/JavaScript/0069299_queue.js b/pool/shard011/JavaScript/0069299_queue.js new file mode 100644 index 0000000000000000000000000000000000000000..3ead72c21b7ef6d34b54413c6521abeb9cbcdc74 --- /dev/null +++ b/pool/shard011/JavaScript/0069299_queue.js @@ -0,0 +1,19 @@ +'use strict'; + +var React = require('react'); +var SvgIcon = require('../../svg-icon'); + +var AvQueue = React.createClass({ + displayName: 'AvQueue', + + render: function render() { + return React.createElement( + SvgIcon, + this.props, + React.createElement('path', { d: 'M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z' }) + ); + } + +}); + +module.exports = AvQueue; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069300_mediaService.js b/pool/shard011/JavaScript/0069300_mediaService.js new file mode 100644 index 0000000000000000000000000000000000000000..8eaa1dda92f5ab2f382e68845cd0b12547b2e9ff --- /dev/null +++ b/pool/shard011/JavaScript/0069300_mediaService.js @@ -0,0 +1,20 @@ +'use strict'; +app.factory('mediaService', ["$myhttp", "$q", "ngAuthSettings", "siteService", + function ($http, $q, ngAuthSettings, siteService) { + var uri = 'api/media'; + var mediaFactory = {}; + + mediaFactory.get = function () { + return $http.get(ngAuthSettings.apiServiceBaseUri + uri + '?SiteID=' + siteService.site.SiteID); + }; + + mediaFactory.upload = function (model) { + return $http.post(ngAuthSettings.apiServiceBaseUri + uri, model); + }; + + mediaFactory.remove = function (model) { + return $http.delete(ngAuthSettings.apiServiceBaseUri + uri + '?MediaID=' + model.MediaID + '&SiteID=' + siteService.site.SiteID); + }; + + return mediaFactory; + }]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069305_redis_wrapper.js b/pool/shard011/JavaScript/0069305_redis_wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..9e4cee3a3c7e432e87d553b885bccdaa74a12413 --- /dev/null +++ b/pool/shard011/JavaScript/0069305_redis_wrapper.js @@ -0,0 +1,23 @@ +const promisify = (client, method) => { + return (...params) => { + return new Promise((resolve, reject) => { + client[method](...params, (err, res) => { + if (err) { + reject(err) + return + } + + resolve(res) + }) + }) + } +} + +module.exports.wrap = (client) => { + return { + rpush: promisify(client, 'rpush'), + lrem: promisify(client, 'lrem'), + brpop: promisify(client, 'brpop'), + brpoplpush: promisify(client, 'brpoplpush') + } +} diff --git a/pool/shard011/JavaScript/0069306_post.js b/pool/shard011/JavaScript/0069306_post.js new file mode 100644 index 0000000000000000000000000000000000000000..d68d583e82b32c4702428bd03ed5a146b891707c --- /dev/null +++ b/pool/shard011/JavaScript/0069306_post.js @@ -0,0 +1,46 @@ +var keystone = require('keystone'); + +exports = module.exports = function (req, res) { + + var view = new keystone.View(req, res); + var locals = res.locals; + + // Set locals + locals.section = 'blog'; + locals.filters = { + post: req.params.post, + }; + locals.data = { + posts: [], + }; + + // Load the current post + view.on('init', function (next) { + + var q = keystone.list('Post').model.findOne({ + state: 'published', + slug: locals.filters.post, + }).populate('author categories'); + + q.exec(function (err, result) { + locals.data.post = result; + next(err); + }); + + }); + + // Load other posts + view.on('init', function (next) { + + var q = keystone.list('Post').model.find().where('state', 'published').sort('-publishedDate').populate('author').limit(4); + + q.exec(function (err, results) { + locals.data.posts = results; + next(err); + }); + + }); + + // Render the view + view.render('post'); +}; diff --git a/pool/shard011/JavaScript/0069307_config.js b/pool/shard011/JavaScript/0069307_config.js new file mode 100644 index 0000000000000000000000000000000000000000..d51a9fa7f09fb864eec9b7d0c2b15fcd45cfb567 --- /dev/null +++ b/pool/shard011/JavaScript/0069307_config.js @@ -0,0 +1,44 @@ +// Configuration parameters. + +'use strict'; + +define([], function () { + // Make this negative if the zero point is off the bed, positive + // if it's inside the bed. + var LASER_OFFSET_X = 0.053 - 0.100; + var LASER_OFFSET_Y = 0.117 - 0.100; + + var config = { + // Dots per inch in the SVG file. Don't change this. + DPI: 72, + + // Diameter of rod in inches. + ROD_DIAMETER: 0.8, + + // Total margin within rod as a fraction of the diameter. + MARGIN: 0.1, + + // Final position of model in inches. The rig centers + // the rod at 1.25 inches from the left. + FINAL_X: 1.25 - LASER_OFFSET_X, + FINAL_Y: 1 - LASER_OFFSET_Y, + + // The radius of the laser kerf, in inches. + KERF_RADIUS_IN: 0.002, + + // Extra spacing for rough cuts, in inches. + ROUGH_EXTRA_IN: 1/16.0, + + // Extra spacing for rough cuts on last pass, in inches. + ROUGH_EXTRA_LAST_IN: 1/20.0, + + PASS_SHADES: [80, 40, 0], + + // Number of cuts around the circle. + ANGLE_COUNT: 16 + }; + + config.MODEL_DIAMETER = config.ROD_DIAMETER*(1 - config.MARGIN); + + return config; +}); diff --git a/pool/shard011/JavaScript/0069313_build.js b/pool/shard011/JavaScript/0069313_build.js new file mode 100644 index 0000000000000000000000000000000000000000..e7278ec33f06ea7997ae77649a21bf135e7eb84a --- /dev/null +++ b/pool/shard011/JavaScript/0069313_build.js @@ -0,0 +1,97 @@ +'use strict'; + +var path = require('path'); +var gulp = require('gulp'); +var conf = require('./conf'); + +var $ = require('gulp-load-plugins')({ + pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del'] +}); + +gulp.task('partials', ['markups'], function () { + return gulp.src([ + path.join(conf.paths.src, '/app/**/*.html'), + path.join(conf.paths.tmp, '/serve/app/**/*.html') + ]) + .pipe($.minifyHtml({ + empty: true, + spare: true, + quotes: true + })) + .pipe($.angularTemplatecache('templateCacheHtml.js', { + module: 'surveyTestApp', + root: 'app' + })) + .pipe(gulp.dest(conf.paths.tmp + '/partials/')); +}); + +gulp.task('html', ['inject', 'partials'], function () { + var partialsInjectFile = gulp.src(path.join(conf.paths.tmp, '/partials/templateCacheHtml.js'), { read: false }); + var partialsInjectOptions = { + starttag: '', + ignorePath: path.join(conf.paths.tmp, '/partials'), + addRootSlash: false + }; + + var htmlFilter = $.filter('*.html', { restore: true }); + var jsFilter = $.filter('**/*.js', { restore: true }); + var cssFilter = $.filter('**/*.css', { restore: true }); + var assets; + + return gulp.src(path.join(conf.paths.tmp, '/serve/*.html')) + .pipe($.inject(partialsInjectFile, partialsInjectOptions)) + .pipe(assets = $.useref.assets()) + .pipe($.rev()) + .pipe(jsFilter) + .pipe($.sourcemaps.init()) + .pipe($.ngAnnotate()) + .pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', conf.errorHandler('Uglify')) + .pipe($.sourcemaps.write('maps')) + .pipe(jsFilter.restore) + .pipe(cssFilter) + .pipe($.sourcemaps.init()) + .pipe($.minifyCss({ processImport: false })) + .pipe($.sourcemaps.write('maps')) + .pipe(cssFilter.restore) + .pipe(assets.restore()) + .pipe($.useref()) + .pipe($.revReplace()) + .pipe(htmlFilter) + .pipe($.minifyHtml({ + empty: true, + spare: true, + quotes: true, + conditionals: true + })) + .pipe(htmlFilter.restore) + .pipe(gulp.dest(path.join(conf.paths.dist, '/'))) + .pipe($.size({ title: path.join(conf.paths.dist, '/'), showFiles: true })); + }); + +// Only applies for fonts from bower dependencies +// Custom fonts are handled by the "other" task +gulp.task('fonts', function () { + return gulp.src($.mainBowerFiles()) + .pipe($.filter('**/*.{eot,svg,ttf,woff,woff2}')) + .pipe($.flatten()) + .pipe(gulp.dest(path.join(conf.paths.dist, '/fonts/'))); +}); + +gulp.task('other', function () { + var fileFilter = $.filter(function (file) { + return file.stat.isFile(); + }); + + return gulp.src([ + path.join(conf.paths.src, '/**/*'), + path.join('!' + conf.paths.src, '/**/*.{html,css,js,scss,jade}') + ]) + .pipe(fileFilter) + .pipe(gulp.dest(path.join(conf.paths.dist, '/'))); +}); + +gulp.task('clean', function () { + return $.del([path.join(conf.paths.dist, '/'), path.join(conf.paths.tmp, '/')]); +}); + +gulp.task('build', ['html', 'fonts', 'other']); diff --git a/pool/shard011/JavaScript/0069314_routes.test.js b/pool/shard011/JavaScript/0069314_routes.test.js new file mode 100644 index 0000000000000000000000000000000000000000..c1e10aecf587297090e306ee5251ce35a15dadeb --- /dev/null +++ b/pool/shard011/JavaScript/0069314_routes.test.js @@ -0,0 +1,83 @@ +/* + * decaffeinate suggestions: + * DS102: Remove unnecessary code created because of implicit returns + * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md + */ +const sinon = require("sinon") +const Backbone = require("backbone") +const { fabricate } = require("@artsy/antigravity") +const CurrentUser = require("../../../models/current_user") +const routes = require("../routes") + +describe("/user", function () { + beforeEach(function () { + sinon.stub(Backbone, "sync") + this.req = { url: "/user/edit" } + return (this.res = { + set: sinon.stub(), + json: sinon.stub(), + render: sinon.stub(), + redirect: sinon.stub(), + locals: { sd: { API_URL: "http://localhost:5000" } }, + }) + }) + + afterEach(() => Backbone.sync.restore()) + + describe("#refresh", function () { + it("redirects to the home page without a current user", function () { + routes.refresh(this.req, this.res) + return this.res.redirect.args[0][0].should.equal("/") + }) + + return describe("with a logged in user", function () { + beforeEach(function () { + this.req = { + user: new CurrentUser(fabricate("user")), + login: sinon.stub(), + } + this.next = sinon.stub() + + return Backbone.sync.onCall(0).returns(Promise.resolve(this.req.user)) + }) + + return it("calls req.login to refresh the session", function () { + return routes.refresh(this.req, this.res, this.next).then(() => { + this.req.login.calledOnce.should.be.true() + this.req.login.args[0][1]() + this.next.calledOnce.should.not.be.true() + this.req.login.args[0][1](true) + return this.next.calledOnce.should.be.true() + }) + }) + }) + }) + + return describe("#settings", function () { + it("redirects to the home page without a current user", function () { + routes.settings(this.req, this.res) + return this.res.redirect.args[0][0].should.equal( + "/login?redirectTo=%2Fuser%2Fedit" + ) + }) + + return describe("with a logged in user", function () { + beforeEach(function () { + this.req = { + user: new CurrentUser( + fabricate("user", { type: "User", accessToken: "xxx" }) + ), + } + + return Backbone.sync.onCall(0).returns(Promise.resolve(this.req.user)) + }) + + return it("fetches the authentications", function () { + return routes.settings(this.req, this.res).then(() => { + Backbone.sync.args[1][1].url.should.containEql("/me/authentications") + return Backbone.sync.args[1][2].data.access_token.should.equal("xxx") + }) + }) + }) + }) +}) diff --git a/pool/shard011/JavaScript/0069320_mediawiki.action.edit.stash.js b/pool/shard011/JavaScript/0069320_mediawiki.action.edit.stash.js new file mode 100644 index 0000000000000000000000000000000000000000..abe912de10e9a15e749de5dc02701180089b6c45 --- /dev/null +++ b/pool/shard011/JavaScript/0069320_mediawiki.action.edit.stash.js @@ -0,0 +1,76 @@ +/*! + * Scripts for pre-emptive edit preparing on action=edit + */ +( function ( mw, $ ) { + $( function () { + var idleTimeout = 3000, + api = new mw.Api(), + pending = null, + $form = $( '#editform' ), + $text = $form.find( '#wpTextbox1' ), + data = {}, + timer = null; + + function stashEdit( token ) { + data = $form.serializeObject(); + + pending = api.post( { + action: 'stashedit', + token: token, + title: mw.config.get( 'wgPageName' ), + section: data.wpSection, + sectiontitle: '', + text: data.wpTextbox1, + contentmodel: data.model, + contentformat: data.format, + baserevid: data.parentRevId + } ); + } + + /* Has the edit body text changed since the last stashEdit() call? */ + function isChanged() { + // Normalize line endings to CRLF, like $.fn.serializeObject does. + var newText = $text.val().replace( /\r?\n/g, '\r\n' ); + return newText !== data.wpTextbox1; + } + + function onEditChanged() { + if ( !isChanged() ) { + return; + } + + // If a request is in progress, abort it; its payload is stale. + if ( pending ) { + pending.abort(); + } + + api.getToken( 'edit' ).then( stashEdit ); + } + + function onKeyPress( e ) { + // Ignore keystrokes that don't modify text, like cursor movements. + // See . + if ( e.which === 0 ) { + return; + } + + clearTimeout( timer ); + + if ( pending ) { + pending.abort(); + } + + timer = setTimeout( onEditChanged, idleTimeout ); + } + + // We don't attempt to stash new section edits because in such cases + // the parser output varies on the edit summary (since it determines + // the new section's name). + if ( $form.find( 'input[name=wpSection]' ).val() === 'new' ) { + return; + } + + $text.on( { change: onEditChanged, keypress: onKeyPress } ); + + } ); +}( mediaWiki, jQuery ) ); diff --git a/pool/shard011/JavaScript/0069322_ModalHeader.js b/pool/shard011/JavaScript/0069322_ModalHeader.js new file mode 100644 index 0000000000000000000000000000000000000000..3da6af44dbf1c26f5a9082dd757415fddec41868 --- /dev/null +++ b/pool/shard011/JavaScript/0069322_ModalHeader.js @@ -0,0 +1,34 @@ +import React from 'react'; +import { string } from 'prop-types'; +import classNames from 'classnames'; +import Button from '../Button/Button'; + +const ModalHeader = ({ children, title, onClose, className, ...rest }) => { + return ( +
    + {onClose &&
    + ); +}; + +/** + * ModalHeader property types. + */ +ModalHeader.propTypes = { + title: string, + className: string +}; + +/** + * ModalHeader default properties. + */ +ModalHeader.defaultProps = { + title: '' +}; + +export default ModalHeader; diff --git a/pool/shard011/JavaScript/0069324_2d.imageData.get.source.outside.worker.js b/pool/shard011/JavaScript/0069324_2d.imageData.get.source.outside.worker.js new file mode 100644 index 0000000000000000000000000000000000000000..763700a0d988d65572bbd8f88cd6ddaf876d155a --- /dev/null +++ b/pool/shard011/JavaScript/0069324_2d.imageData.get.source.outside.worker.js @@ -0,0 +1,75 @@ +// DO NOT EDIT! This test has been generated by tools/gentest.py. +// OffscreenCanvas test in a worker:2d.imageData.get.source.outside +// Description:getImageData() returns transparent black outside the canvas +// Note: + +importScripts("/resources/testharness.js"); +importScripts("/2dcontext/resources/canvas-tests.js"); + +var t = async_test("getImageData() returns transparent black outside the canvas"); +var t_pass = t.done.bind(t); +var t_fail = t.step_func(function(reason) { + throw reason; +}); +t.step(function() { + +var offscreenCanvas = new OffscreenCanvas(100, 50); +var ctx = offscreenCanvas.getContext('2d'); + +ctx.fillStyle = '#08f'; +ctx.fillRect(0, 0, 100, 50); +var imgdata1 = ctx.getImageData(-10, 5, 1, 1); +_assertSame(imgdata1.data[0], 0, "imgdata1.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata1.data[1], 0, "imgdata1.data[\""+(1)+"\"]", "0"); +_assertSame(imgdata1.data[2], 0, "imgdata1.data[\""+(2)+"\"]", "0"); +_assertSame(imgdata1.data[3], 0, "imgdata1.data[\""+(3)+"\"]", "0"); +var imgdata2 = ctx.getImageData(10, -5, 1, 1); +_assertSame(imgdata2.data[0], 0, "imgdata2.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata2.data[1], 0, "imgdata2.data[\""+(1)+"\"]", "0"); +_assertSame(imgdata2.data[2], 0, "imgdata2.data[\""+(2)+"\"]", "0"); +_assertSame(imgdata2.data[3], 0, "imgdata2.data[\""+(3)+"\"]", "0"); +var imgdata3 = ctx.getImageData(200, 5, 1, 1); +_assertSame(imgdata3.data[0], 0, "imgdata3.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata3.data[1], 0, "imgdata3.data[\""+(1)+"\"]", "0"); +_assertSame(imgdata3.data[2], 0, "imgdata3.data[\""+(2)+"\"]", "0"); +_assertSame(imgdata3.data[3], 0, "imgdata3.data[\""+(3)+"\"]", "0"); +var imgdata4 = ctx.getImageData(10, 60, 1, 1); +_assertSame(imgdata4.data[0], 0, "imgdata4.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata4.data[1], 0, "imgdata4.data[\""+(1)+"\"]", "0"); +_assertSame(imgdata4.data[2], 0, "imgdata4.data[\""+(2)+"\"]", "0"); +_assertSame(imgdata4.data[3], 0, "imgdata4.data[\""+(3)+"\"]", "0"); +var imgdata5 = ctx.getImageData(100, 10, 1, 1); +_assertSame(imgdata5.data[0], 0, "imgdata5.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata5.data[1], 0, "imgdata5.data[\""+(1)+"\"]", "0"); +_assertSame(imgdata5.data[2], 0, "imgdata5.data[\""+(2)+"\"]", "0"); +_assertSame(imgdata5.data[3], 0, "imgdata5.data[\""+(3)+"\"]", "0"); +var imgdata6 = ctx.getImageData(0, 10, 1, 1); +_assertSame(imgdata6.data[0], 0, "imgdata6.data[\""+(0)+"\"]", "0"); +_assertSame(imgdata6.data[1], 136, "imgdata6.data[\""+(1)+"\"]", "136"); +_assertSame(imgdata6.data[2], 255, "imgdata6.data[\""+(2)+"\"]", "255"); +_assertSame(imgdata6.data[3], 255, "imgdata6.data[\""+(3)+"\"]", "255"); +var imgdata7 = ctx.getImageData(-10, 10, 20, 20); +_assertSame(imgdata7.data[ 0*4+0], 0, "imgdata7.data[ 0*4+0]", "0"); +_assertSame(imgdata7.data[ 0*4+1], 0, "imgdata7.data[ 0*4+1]", "0"); +_assertSame(imgdata7.data[ 0*4+2], 0, "imgdata7.data[ 0*4+2]", "0"); +_assertSame(imgdata7.data[ 0*4+3], 0, "imgdata7.data[ 0*4+3]", "0"); +_assertSame(imgdata7.data[ 9*4+0], 0, "imgdata7.data[ 9*4+0]", "0"); +_assertSame(imgdata7.data[ 9*4+1], 0, "imgdata7.data[ 9*4+1]", "0"); +_assertSame(imgdata7.data[ 9*4+2], 0, "imgdata7.data[ 9*4+2]", "0"); +_assertSame(imgdata7.data[ 9*4+3], 0, "imgdata7.data[ 9*4+3]", "0"); +_assertSame(imgdata7.data[10*4+0], 0, "imgdata7.data[10*4+0]", "0"); +_assertSame(imgdata7.data[10*4+1], 136, "imgdata7.data[10*4+1]", "136"); +_assertSame(imgdata7.data[10*4+2], 255, "imgdata7.data[10*4+2]", "255"); +_assertSame(imgdata7.data[10*4+3], 255, "imgdata7.data[10*4+3]", "255"); +_assertSame(imgdata7.data[19*4+0], 0, "imgdata7.data[19*4+0]", "0"); +_assertSame(imgdata7.data[19*4+1], 136, "imgdata7.data[19*4+1]", "136"); +_assertSame(imgdata7.data[19*4+2], 255, "imgdata7.data[19*4+2]", "255"); +_assertSame(imgdata7.data[19*4+3], 255, "imgdata7.data[19*4+3]", "255"); +_assertSame(imgdata7.data[20*4+0], 0, "imgdata7.data[20*4+0]", "0"); +_assertSame(imgdata7.data[20*4+1], 0, "imgdata7.data[20*4+1]", "0"); +_assertSame(imgdata7.data[20*4+2], 0, "imgdata7.data[20*4+2]", "0"); +_assertSame(imgdata7.data[20*4+3], 0, "imgdata7.data[20*4+3]", "0"); +t.done(); + +}); +done(); diff --git a/pool/shard011/JavaScript/0069325_fayeClient.js b/pool/shard011/JavaScript/0069325_fayeClient.js new file mode 100644 index 0000000000000000000000000000000000000000..24d3dc789333105b4e096e41c808928670686b33 --- /dev/null +++ b/pool/shard011/JavaScript/0069325_fayeClient.js @@ -0,0 +1,13 @@ +define('fayeClient', ['store'], function (store) { + var fayeClient = new Faye.Client(location.origin.replace(/:\d+$/, '') + ':8001/faye'); + + fayeClient.addExtension({ + outgoing: function (event, cb) { + event.ext = event.ext || {}; + event.ext.token = store.user.token; + cb(event); + } + }); + + return fayeClient; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069326_tcl.js b/pool/shard011/JavaScript/0069326_tcl.js new file mode 100644 index 0000000000000000000000000000000000000000..2efd0a3b445def5863e1db366d3091d3660292f2 --- /dev/null +++ b/pool/shard011/JavaScript/0069326_tcl.js @@ -0,0 +1,84 @@ +/* ***** BEGIN LICENSE BLOCK ***** + * Distributed under the BSD license: + * + * Copyright (c) 2010, Ajax.org B.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of Ajax.org B.V. nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * ***** END LICENSE BLOCK ***** */ + +define(function(require, exports, module) { +"use strict"; + +var oop = require("../lib/oop"); +var TextMode = require("./text").Mode; +var Tokenizer = require("../tokenizer").Tokenizer; +var CStyleFoldMode = require("./folding/cstyle").FoldMode; +var TclHighlightRules = require("./tcl_highlight_rules").TclHighlightRules; +var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; +var Range = require("../range").Range; + +var Mode = function() { + this.$tokenizer = new Tokenizer(new TclHighlightRules().getRules()); + this.$outdent = new MatchingBraceOutdent(); + this.foldingRules = new CStyleFoldMode(); +}; +oop.inherits(Mode, TextMode); + +(function() { + + this.lineCommentStart = "#"; + + this.getNextLineIndent = function(state, line, tab) { + var indent = this.$getIndent(line); + + var tokenizedLine = this.$tokenizer.getLineTokens(line, state); + var tokens = tokenizedLine.tokens; + + if (tokens.length && tokens[tokens.length-1].type == "comment") { + return indent; + } + + if (state == "start") { + var match = line.match(/^.*[\{\(\[]\s*$/); + if (match) { + indent += tab; + } + } + + return indent; + }; + + this.checkOutdent = function(state, line, input) { + return this.$outdent.checkOutdent(line, input); + }; + + this.autoOutdent = function(state, doc, row) { + this.$outdent.autoOutdent(doc, row); + }; + +}).call(Mode.prototype); + +exports.Mode = Mode; +}); diff --git a/pool/shard011/JavaScript/0069331_jumping-circle.js b/pool/shard011/JavaScript/0069331_jumping-circle.js new file mode 100644 index 0000000000000000000000000000000000000000..4cfe0a34015c5947bd67be79e5c519a9fd2898a6 --- /dev/null +++ b/pool/shard011/JavaScript/0069331_jumping-circle.js @@ -0,0 +1,35 @@ +(function () { + var canvas = document.getElementById('the-canvas'), + ctx = canvas.getContext('2d'), + x = canvas.width / 2, + y = canvas.height / 2, + dx = 2, + dy = 1; + ctx.fillStyle = 'green'; + + function circle(xPosition, yPosition) { + ctx.beginPath(); + ctx.arc(xPosition, yPosition, 2, 0, 2 * Math.PI); + ctx.closePath(); + ctx.fill(); + } + + function draw() { + ctx.clearRect(0, 0, canvas.width, canvas.height); + circle(x, y); + + if (x + dx >= canvas.width || x + dx < 0) { + dx = -dx; + } + if (y + dy >= canvas.height || y + dy < 0) { + dy = -dy; + } + + x += dx; + y += dy; + + requestAnimationFrame(draw); + } + + draw(); +}()); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069332_FighterAppear.js b/pool/shard011/JavaScript/0069332_FighterAppear.js new file mode 100644 index 0000000000000000000000000000000000000000..22f1bccd49797961cfab5ce8180cdc1f32d63bda --- /dev/null +++ b/pool/shard011/JavaScript/0069332_FighterAppear.js @@ -0,0 +1,54 @@ +/** + * @author weism + * copyright 2015 Qcplay All Rights Reserved. + */ + +var s = qc.Serializer; + +/** + * 战斗者出现的动画表现 + */ +var FighterAppear = qc.defineBehaviour('qc.demo.FighterAppear', qc.Behaviour, function() { + var self = this; + + // 走动的动作名称 + self.moveAni = 'move'; + + // 偏移量,需要加上屏幕的宽度 + self.offset = 20; + + // 在编辑器模式下需要运行 + self.runInEditor = true; +}, { + // 需要序列化的字段 + moveAni: s.STRING, + offset: s.NUMBER +}); + +// 播放动作 +FighterAppear.prototype.play = function() { + var self = this, o = self.gameObject; + var fighter = o.getScript('qc.demo.Fighter'); + o.parent.visible = true; + o.alpha = 1; + + var tp = o.parent.getScript('qc.TweenPosition'); + tp.to.x = o.parent.x; + tp.to.y = o.parent.y; + tp.from.y = tp.to.y; + if (fighter.isPet) + tp.from.x = tp.to.x - self.game.world.width / 2 - self.offset; + else + tp.from.x = tp.to.x + self.game.world.width / 2 + self.offset; + tp.resetToBeginning(); + tp.playForward(); + o.playAnimation(self.moveAni, 1, true); + tp.onFinished.addOnce(function() { + // 动作播放完毕,播放idle动作 + fighter.resumeIdle(); + + // 可以出招了 + fighter.nextRound = 0; + fighter.bigTime = fighter.freeze * 1000; + }); +} diff --git a/pool/shard011/JavaScript/0069333_index.js b/pool/shard011/JavaScript/0069333_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d8b4c941b644d797870767a5272615820eea23a9 --- /dev/null +++ b/pool/shard011/JavaScript/0069333_index.js @@ -0,0 +1,149 @@ +/** + * Created by shraddha on 4/19/17. + */ +import React, { PropTypes } from 'react'; +// import styled from 'styled-components'; +import { connect } from 'react-redux'; +import { createStructuredSelector } from 'reselect'; +import AuthPage from 'components/auth/AuthPage'; +import AuthInputGroup from 'components/auth/AuthInputGroup'; +// import { FormattedMessage } from 'react-intl'; +// import messages from './messages'; +import { Button, FormGroup, ControlLabel, FormControl } from 'react-bootstrap'; +// import { Link } from 'react-router'; +// import styled from 'styled-components'; +import styled from 'styled-components'; +import { + makeChangeUsernameAction, + makeChangePassword1Action, + makeChangePassword2Action, + makeChangeConfirmationCodeAction, + makePasswordChangeSuccessAction, + makePasswordChangedErrorAction, + makeDoPasswordChangeAction, + makeRequestEmailForPasswordChangeAction, +} from './actions'; +import { + makeSelectPasswordChangeError, + makeSelectPasswordChangeErrorMsg, +} from './selectors'; +import Wrapper from './Wrapper'; + +const SpacingDiv = styled.div` + margin-top: 1.5em; + margin-bottom: 2em; +`; + +const SpacingBetween = styled.div` + margin-bottom: 1em; +`; + +const FontColor = styled.div` + color: navy; +`; + +const NewButton = styled(Button)` + background: ${(props) => props.primary ? 'Orange' : 'white'}; + color: ${(props) => props.primary ? 'white' : 'navy'}; + + font-size: 1em; + margin: 0.25em; + padding: 0.25em 0.65em; + border: 2px solid black; + border-radius: 7px; +`; + +const BackgroundImage = styled.div` + background: linear-gradient(to top, #fff, lightblue); + margin-top: 1em; + height: 380px; +`; + +export class ForgotPassword extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function + render() { + return ( +
    + + + + + Username + + + + + + Password + + + + + + Re-enter Password + + + + + + Enter confirmation code + + + + + + Reset password + + + + + +
    + ); + } +} + +ForgotPassword.propTypes = { + onChangeUsername:PropTypes.func.isRequired, + onChangePassword1:PropTypes.func.isRequired, + onChangePassword2:PropTypes.func.isRequired, + onChangeConfirmationCode:PropTypes.func.isRequired, + +}; + +export const mapStateToProps = createStructuredSelector({ + passwordChangeError: makeSelectPasswordChangeError(), + passwordChangeErrorMsg: makeSelectPasswordChangeErrorMsg(), +}); + +export function mapDispatchToProps(dispatch) { + return { + onChangeUsername: (evt) => dispatch(makeChangeUsernameAction(evt.target.value)), + onChangePassword1: (evt) => dispatch(makeChangePassword1Action(evt.target.value)), + onChangePassword2: (evt) => dispatch(makeChangePassword2Action(evt.target.value)), + onChangeConfirmationCode: (evt) => dispatch(makeChangeConfirmationCodeAction(evt.target.value)), + onDoPasswordChangeAction: () => dispatch(makeDoPasswordChangeAction()), + }; +} + +export default connect(mapStateToProps, mapDispatchToProps)(ForgotPassword); + diff --git a/pool/shard011/JavaScript/0069337_load-sub-package.js b/pool/shard011/JavaScript/0069337_load-sub-package.js new file mode 100644 index 0000000000000000000000000000000000000000..b4edfd931d85ad466fd5b8bcf5083ecf6c2dd819 --- /dev/null +++ b/pool/shard011/JavaScript/0069337_load-sub-package.js @@ -0,0 +1,87 @@ +export const loadedSubPackages = [] + +/** + * 指定路由 ready 后,检查是否触发分包预加载 + * @param {Object} route + */ +export function preloadSubPackages (route) { + if (!__uniConfig.preloadRule) { + return + } + const options = __uniConfig.preloadRule[route] + if (!options || !Array.isArray(options.packages)) { + return + } + const packages = options.packages.filter(root => loadedSubPackages.indexOf(root) === -1) + if (!packages.length) { + return + } + loadSubPackages(options.packages) + // 暂不需要网络下载 + // const network = options.network || 'wifi' + // if (network === 'wifi') { + // uni.getNetworkType({ + // success (res) { + // if (process.env.NODE_ENV !== 'production') { + // console.log('UNIAPP[preloadRule]:' + res.networkType + ':' + JSON.stringify(options)) + // } + // if (res.networkType === 'wifi') { + // loadSubPackages(options.packages) + // } + // } + // }) + // } else { + // if (process.env.NODE_ENV !== 'production') { + // console.log('UNIAPP[preloadRule]:' + JSON.stringify(options)) + // } + // loadSubPackages(options.packages) + // } +} + +export function loadPage (route, callback) { + let isInSubPackage = false + const subPackages = __uniConfig.subPackages + if (Array.isArray(subPackages)) { + const subPackage = subPackages.find(subPackage => route.indexOf(subPackage.root) === 0) + if (subPackage) { + isInSubPackage = true + loadSubPackage(subPackage.root, callback) + } + } + if (!isInSubPackage) { + callback() + } +} + +function loadSubPackage (root, callback) { + if (loadedSubPackages.indexOf(root) !== -1) { + return callback() + } + loadSubPackages([root], () => { + callback() + }) +} + +const SUB_FILENAME = 'app-sub-service.js' + +function evaluateScriptFiles (files, callback) { + __uniConfig.onServiceReady(() => { + weex.requireModule('plus').evalJSFiles(files, callback) + }) +} + +function loadSubPackages (packages, callback) { + if (process.env.NODE_ENV !== 'production') { + console.log('UNIAPP[loadSubPackages]:' + JSON.stringify(packages)) + } + const startTime = Date.now() + evaluateScriptFiles(packages.map(root => { + loadedSubPackages.push(root) + return root + '/' + SUB_FILENAME + }), res => { + if (process.env.NODE_ENV !== 'production') { + console.log('UNIAPP[loadSubPackages]:耗时(' + (Date.now() - startTime) + ')') + } + callback && callback(true) + }) +} diff --git a/pool/shard011/JavaScript/0069338_libnodejs.js b/pool/shard011/JavaScript/0069338_libnodejs.js new file mode 100644 index 0000000000000000000000000000000000000000..d0f82a968ec1c953a43a91fd1bcd592d8229b2c5 --- /dev/null +++ b/pool/shard011/JavaScript/0069338_libnodejs.js @@ -0,0 +1,242 @@ +'use strict'; + +const Module = require('module'); +const path = require('path'); +const stream = require('stream'); +const Readable = stream.Readable; +const Writable = stream.Writable; +const util = require('util'); + +// Codes to come from this script (should match nodejsByJSCommandType). +const BY_JS_ERROR = 1; +const BY_JS_INIT_CALLBACK = 2; +const BY_JS_READ_REQUEST_BODY = 3; +const BY_JS_RESPONSE_HEADERS = 4; +const BY_JS_RESPONSE_BODY = 5; +const BY_JS_BEGIN_SUBREQUEST = 6; +const BY_JS_SUBREQUEST_DONE = 7; +// Codes to come from nginx (should match nodejsToJSCallbackCommandType). +const TO_JS_CALLBACK_PUSH_CHUNK = 101; +const TO_JS_CALLBACK_SUBREQUEST_HEADERS = 102; +const TO_JS_CALLBACK_REQUEST_ERROR = 103; +const TO_JS_CALLBACK_RESPONSE_ERROR = 104; + +var modulesVersion; +var modulesCache = {}; + +process.on('SIGQUIT', function() { + console.info('Got SIGQUIT, exiting.'); + process.exit(); +}); + +process.on('SIGABRT', function() { + console.info('Got SIGABRT, exiting.'); + process.exit(); +}); + +process.on('SIGTERM', function() { + console.info('Got SIGTERM, exiting.'); + process.exit(); +}); + +process.on('SIGHUP', function() { + console.info('Got SIGHUP, exiting.'); + process.exit(); +}); + +process.on('SIGINT', function() { + console.info('Got SIGINT, exiting.'); + process.exit(); +}); + + +module.exports = function handleNginxRequest(meta, requestHeaders, configParams, callback, payload) { + var module; + + try { + module = loadModule(meta[0], meta[1]); + } catch (e) { + console.error(e.message); + callback(BY_JS_ERROR, payload); + return; + } + + const i = new Request(meta, requestHeaders, callback, payload); + const o = new Response(callback, payload); + + callback(BY_JS_INIT_CALLBACK, payload, function(what, arg) { + switch (what) { + case TO_JS_CALLBACK_PUSH_CHUNK: + i.push(arg); + break; + + case TO_JS_CALLBACK_REQUEST_ERROR: + i.emit('error', arg); + break; + + case TO_JS_CALLBACK_RESPONSE_ERROR: + o.emit('error', arg); + break; + } + }); + + o.on('finish', function finish() { + callback(BY_JS_RESPONSE_BODY, payload, null); + }); + + module(i, o, function subrequest(settings, cb) { + var sr; + + var url = settings.url || ''; + var method = settings.method || 'GET'; + var headers = settings.headers || {}; + var body = settings.body || null; + + callback( + BY_JS_BEGIN_SUBREQUEST, + payload, + url, // SR_URL + method, // SR_METHOD + headers, // SR_HEADERS + body, // SR_BODY + function(what, arg, arg2) { // SR_CALLBACK + if (!sr) { + if (what === TO_JS_CALLBACK_SUBREQUEST_HEADERS) { + sr = new Subrequest(arg, arg2); + } else { + sr = new Subrequest(); + } + + if (cb) { + cb(sr); + } + } + + switch (what) { + case TO_JS_CALLBACK_REQUEST_ERROR: + sr.emit('error', arg); + break; + + case TO_JS_CALLBACK_PUSH_CHUNK: + sr.push(arg); + + if (arg === null) { + // Notify nginx that subrequest is done. + callback(BY_JS_SUBREQUEST_DONE, payload, null); + } + + break; + } + } + ); + }, configParams); +} + + +function loadModule(filename, version) { + if (modulesVersion !== version) { + modulesVersion = version; + modulesCache = {}; + Module._cache = {}; + } + + filename = Module._resolveFilename(path.resolve(filename), null); + + var cached = modulesCache[filename]; + if (cached) { + return cached; + } + + var module = new Module(filename, null); + + module.load(filename); + + if (typeof module.exports !== 'function') { + throw new Error(`Module '${filename}' should export a function.`); + } + + console.info(`Loaded module '${filename}'.`); + + return ((modulesCache[filename] = module.exports)); +} + + +function Request(meta, headers, callback, payload) { + var requestBodyRequested = false; + var self = this; + + if (meta) { + self.module = meta[0]; + self.method = meta[2]; + self.uri = meta[3]; + self.httpProtocol = meta[4]; + } + + this.headers = headers; + + Readable.call(this, { + read: function read() { + if (!requestBodyRequested) { + callback(BY_JS_READ_REQUEST_BODY, payload); + requestBodyRequested = true; + } + } + }); + + this.resume(); +} +util.inherits(Request, Readable); +Request.prototype.getHeader = function getHeader(name) { + return this.headers[name]; +}; + + +function Response(callback, payload) { + var headersSent = false; + + this.headers = {}; + this.statusCode = 200; + this.statusMessage = ''; + + Writable.call(this, { + write: function write(chunk, encoding, cb) { + if (!headersSent) { + var code = +this.statusCode || 200; + callback( + BY_JS_RESPONSE_HEADERS, + payload, + [code, this.statusMessage ? code + ' ' + this.statusMessage : ''], + this.headers + ); + headersSent = true; + } + + callback(BY_JS_RESPONSE_BODY, payload, chunk.toString()); + + cb(); + } + }); +} +util.inherits(Response, Writable); +Response.prototype.setHeader = function setHeader(name, value) { + this.headers[name] = value; +}; + + +function Subrequest(meta, headers) { + if (meta) { + this.statusCode = meta[0]; + this.statusMessage = meta[1]; + } + this.headers = headers; + + Readable.call(this, { + read: function read() {} + }); + + this.resume(); +} +util.inherits(Subrequest, Readable); +Subrequest.prototype.getHeader = function getHeader(name) { + return this.headers[name]; +}; diff --git a/pool/shard011/JavaScript/0069341_test-math-clz32.js b/pool/shard011/JavaScript/0069341_test-math-clz32.js new file mode 100644 index 0000000000000000000000000000000000000000..1cf473ec12c6952c18420ef255d0dcccf07b395d --- /dev/null +++ b/pool/shard011/JavaScript/0069341_test-math-clz32.js @@ -0,0 +1,57 @@ +if (typeof print !== 'function') { print = console.log; } + +function test() { + var clz32 = Math.clz32; + var i; + + for (i = 0; i < 1e6; i++) { + void clz32(0x80000000); + void clz32(0x40000000); + void clz32(0x20000000); + void clz32(0x10000000); + + void clz32(0x08000000); + void clz32(0x04000000); + void clz32(0x02000000); + void clz32(0x01000000); + + void clz32(0x00800000); + void clz32(0x00400000); + void clz32(0x00200000); + void clz32(0x00100000); + + void clz32(0x00080000); + void clz32(0x00040000); + void clz32(0x00020000); + void clz32(0x00010000); + + void clz32(0x00008000); + void clz32(0x00004000); + void clz32(0x00002000); + void clz32(0x00001000); + + void clz32(0x00000800); + void clz32(0x00000400); + void clz32(0x00000200); + void clz32(0x00000100); + + void clz32(0x00000080); + void clz32(0x00000040); + void clz32(0x00000020); + void clz32(0x00000010); + + void clz32(0x00000008); + void clz32(0x00000004); + void clz32(0x00000002); + void clz32(0x00000001); + + void clz32(0x00000000); + } +} + +try { + test(); +} catch (e) { + print(e.stack || e); + throw e; +} diff --git a/pool/shard011/JavaScript/0069347_ConnectionTest.js b/pool/shard011/JavaScript/0069347_ConnectionTest.js new file mode 100644 index 0000000000000000000000000000000000000000..c7d6dcd8c863d8ef023511a64cabcff24c3d3140 --- /dev/null +++ b/pool/shard011/JavaScript/0069347_ConnectionTest.js @@ -0,0 +1,81 @@ +// ConnectionTest.js (c) 2012 Loren West and other contributors +// May be freely distributed under the MIT license. +// For further details and documentation: +// http://lorenwest.github.com/monitor +(function(root){ + + // Dependencies + var Monitor = require('../lib/index'), + Connection = Monitor.Connection, Backbone = Monitor.Backbone, + server, serverPort; + + /** + * Unit tests for the Connection class. + * @class ConnectionTest + */ + + /** + * Test group for connection functionality + * @method Connection + */ + module.exports['Connection'] = { + + /** + * Create a Server to test connections with + * @method Connection-setUp + */ + setUp: function(callback) { + server = new Monitor.Server(); + server.start(callback); + }, + + /** + * Tests that the Connection classes are available + * @method Connection-Classes + */ + Classes: function(test) { + test.ok(Connection.prototype instanceof Backbone.Model, 'The Connection data model is in place'); + test.ok(Connection.List.prototype instanceof Backbone.Collection, 'The Connection.List collection is in place'); + test.done(); + }, + + /** + * Assure that a connect / disconnect to the server host/port works + * @method Connection-ConnectDisconnect + */ + ConnectDisconnect: function(test) { + var port = server.get('port'), conn = new Monitor.Connection({hostName:'localhost', hostPort:port}); + conn.on('connect', function() { + test.ok(conn.get('remoteHostName'), 'The remote host name is known'); + conn.on('disconnect', test.done); + conn.disconnect(); + }); + }, + + /** + * Test pinging the remote connection + * @method Connection-PingPong + */ + PingPong: function(test) { + var port = server.get('port'), conn = new Monitor.Connection({hostName:'localhost', hostPort:port}); + conn.on('connect', function() { + test.ok(conn.get('remoteHostName'), 'The remote host name is known'); + conn.ping(function(){ + test.ok(true, 'Ping made its way to and from the remote server'); + conn.on('disconnect', test.done); + conn.disconnect(); + }); + }); + }, + + /** + * Tear down the test Server + * @method Connection-tearDown + */ + tearDown: function(callback) { + server.stop(callback); + } + + }; + +}(this)); diff --git a/pool/shard011/JavaScript/0069348_builder.js b/pool/shard011/JavaScript/0069348_builder.js new file mode 100644 index 0000000000000000000000000000000000000000..17a48b308597babefd46a61fb2ed74621eeb93c3 --- /dev/null +++ b/pool/shard011/JavaScript/0069348_builder.js @@ -0,0 +1,34 @@ +'use strict'; + +var builder = function(options){ + if(!options){ + options = {}; + } + var exported = { + commandMap : { + bind: 'Bind', + bindResp: 'BindResp', + }, + commands: {}, + }; + + exported.add = function(key,Command){ + exported.commands[key] = function(arg){ + return new Command(arg,options); + }; + exported.commands[key]._constructor = Command; + exported.commands[key].fromBuffer = function(buffer){ + var message = exported.commands[key](); + message.setPayload(buffer); + return message; + }; + }; + + Object.keys(exported.commandMap).forEach(function(key){ + commands[key] = exported.add(key, require('./commands' + key)); + }); + + return exported; +} + +exports = module.exports = builder; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069350_index.js b/pool/shard011/JavaScript/0069350_index.js new file mode 100644 index 0000000000000000000000000000000000000000..92b03cca6414ca5fe4c213fd90778d75227877fd --- /dev/null +++ b/pool/shard011/JavaScript/0069350_index.js @@ -0,0 +1,39 @@ +'use strict' + +var Event = require('geval/event') +var poll = require('pole') +var watch = require('observ/watch') +var nextTick = require('next-tick') +var partial = require('ap').partial +var Thunk = require('observ-thunk') + +module.exports = function observPoll (observable, options, callback) { + var poller = null + nextTick(partial(watch, observable, Thunk(onChange))) + + var DataEvent = Event() + var ErrorEvent = Event() + + return { + onData: DataEvent.listen, + onError: ErrorEvent.listen, + cancel: cancel + } + + function onChange (value) { + return (value ? create : cancel)() + } + + function create () { + if (poller) return + poller = poll(options, callback) + poller.onData(DataEvent.broadcast) + poller.onError(ErrorEvent.broadcast) + } + + function cancel () { + if (!poller) return + poller.cancel() + poller = null + } +} diff --git a/pool/shard011/JavaScript/0069351_tables.model.js b/pool/shard011/JavaScript/0069351_tables.model.js new file mode 100644 index 0000000000000000000000000000000000000000..b4a08872ee1e73ffff3fe83d311bb478a887a12e --- /dev/null +++ b/pool/shard011/JavaScript/0069351_tables.model.js @@ -0,0 +1,108 @@ +(function ($, app) { + + var TablesModel = (function () { + function TablesModel() {} + + /** + * Sends the request to the Tables module. + * @param {string} action + * @param {object} data + * @returns {jQuery.Deferred.promise} + */ + TablesModel.prototype.request = function (action, data) { + return app.request({ + module: 'tables', + action: action + }, data); + }; + + /** + * Removes table by id. + * @param {int} id + * @returns {jQuery.Deferred.promise} + */ + TablesModel.prototype.remove = function (id) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('remove', { id: id }); + }; + + /** + * Renames table. + * @param {int} id + * @param {string} title + * @returns {jQuery.Deferred.promise} + */ + TablesModel.prototype.rename = function (id, title) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('rename', { id: id, title: title }); + }; + + TablesModel.prototype.getColumns = function (id) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('getColumns', { id: id }); + }; + + TablesModel.prototype.setColumns = function (id, columns) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('updateColumns', { id: id, columns: columns }) + }; + + TablesModel.prototype.getRows = function (id) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('getRows', { id: id }); + }; + + TablesModel.prototype.setRows = function (id, rows) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('updateRows', { id: id, rows: JSON.stringify(rows) }); + }; + + TablesModel.prototype.setMeta = function (id, meta) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('updateMeta', { id: id, meta: JSON.stringify(meta) }); + }; + + TablesModel.prototype.getMeta = function (id) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('getMeta', { id: id }); + }; + + TablesModel.prototype.render = function (id) { + if (isNaN(id = parseInt(id))) { + throw new Error('Invalid table id.'); + } + + return this.request('render', { id: id }); + }; + + return TablesModel; + })(); + + app.Models = app.Models || {}; + app.Models.Tables = new TablesModel(); + +}(window.jQuery, window.supsystic.Tables)); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069354_SignIn.js b/pool/shard011/JavaScript/0069354_SignIn.js new file mode 100644 index 0000000000000000000000000000000000000000..d033b94a8092c4f672be25248371572d65a9cc61 --- /dev/null +++ b/pool/shard011/JavaScript/0069354_SignIn.js @@ -0,0 +1,65 @@ +import React, {Component} from 'react' +import PropTypes from 'prop-types' +import {FlatButton, Dialog, RaisedButton, TextField} from 'material-ui' + +class SignIn extends Component { + constructor(props) { + super(props) + this.closeSignInModal = this.closeSignInModal.bind(this) + this.verifyUser = this.verifyUser.bind(this) + } + + closeSignInModal = () => { + this.props.setSigninnModalVisibility(false) + } + verifyUser = () => { + return this.props.router.push('home') + } + + render() { + const {isSigninModalOpen} = this.props; + const customContentStyle = { + width: '400px', + padding: '0px' + } + // add html content here for sign in + return ( + isSigninModalOpen && + +
    +
    +

    Welcome

    +

    Sign in below to see
    all your amazing stats!

    + + + login +
    +
    +

    Don't have an account?

    + +
    +
    +
    + ) + } +} + +SignIn.propTypes = { + isSigninModalOpen: PropTypes.bool.isRequired, + router: React.PropTypes.object, + setSigninnModalVisibility: PropTypes.func.isRequired +} + +export default SignIn diff --git a/pool/shard011/JavaScript/0069355_xmlhttp.js b/pool/shard011/JavaScript/0069355_xmlhttp.js new file mode 100644 index 0000000000000000000000000000000000000000..da64e9fb710638a2adb5d71afb5667403f198751 --- /dev/null +++ b/pool/shard011/JavaScript/0069355_xmlhttp.js @@ -0,0 +1,228 @@ +// Copyright 2006 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Low level handling of XMLHttpRequest. + * @author arv@google.com (Erik Arvidsson) + * @author dbk@google.com (David Barrett-Kahn) + */ + +goog.provide('goog.net.DefaultXmlHttpFactory'); +goog.provide('goog.net.XmlHttp'); +goog.provide('goog.net.XmlHttp.OptionType'); +goog.provide('goog.net.XmlHttp.ReadyState'); + +goog.require('goog.net.WrapperXmlHttpFactory'); +goog.require('goog.net.XmlHttpFactory'); + + +/** + * Static class for creating XMLHttpRequest objects. + * @return {!(XMLHttpRequest|GearsHttpRequest)} A new XMLHttpRequest object. + */ +goog.net.XmlHttp = function() { + return goog.net.XmlHttp.factory_.createInstance(); +}; + + +/** + * @define {boolean} Whether to assume XMLHttpRequest exists. Setting this to + * true strips the ActiveX probing code. + */ +goog.net.XmlHttp.ASSUME_NATIVE_XHR = false; + + +/** + * Gets the options to use with the XMLHttpRequest objects obtained using + * the static methods. + * @return {Object} The options. + */ +goog.net.XmlHttp.getOptions = function() { + return goog.net.XmlHttp.factory_.getOptions(); +}; + + +/** + * Type of options that an XmlHttp object can have. + * @enum {number} + */ +goog.net.XmlHttp.OptionType = { + /** + * Whether a goog.nullFunction should be used to clear the onreadystatechange + * handler instead of null. + */ + USE_NULL_FUNCTION: 0, + + /** + * NOTE(user): In IE if send() errors on a *local* request the readystate + * is still changed to COMPLETE. We need to ignore it and allow the + * try/catch around send() to pick up the error. + */ + LOCAL_REQUEST_ERROR: 1 +}; + + +/** + * Status constants for XMLHTTP, matches: + * http://msdn.microsoft.com/library/default.asp?url=/library/ + * en-us/xmlsdk/html/0e6a34e4-f90c-489d-acff-cb44242fafc6.asp + * @enum {number} + */ +goog.net.XmlHttp.ReadyState = { + /** + * Constant for when xmlhttprequest.readyState is uninitialized + */ + UNINITIALIZED: 0, + + /** + * Constant for when xmlhttprequest.readyState is loading. + */ + LOADING: 1, + + /** + * Constant for when xmlhttprequest.readyState is loaded. + */ + LOADED: 2, + + /** + * Constant for when xmlhttprequest.readyState is in an interactive state. + */ + INTERACTIVE: 3, + + /** + * Constant for when xmlhttprequest.readyState is completed + */ + COMPLETE: 4 +}; + + +/** + * The global factory instance for creating XMLHttpRequest objects. + * @type {goog.net.XmlHttpFactory} + * @private + */ +goog.net.XmlHttp.factory_; + + +/** + * Sets the factories for creating XMLHttpRequest objects and their options. + * @param {Function} factory The factory for XMLHttpRequest objects. + * @param {Function} optionsFactory The factory for options. + * @deprecated Use setGlobalFactory instead. + */ +goog.net.XmlHttp.setFactory = function(factory, optionsFactory) { + goog.net.XmlHttp.setGlobalFactory(new goog.net.WrapperXmlHttpFactory( + (/** @type {function() : !(XMLHttpRequest|GearsHttpRequest)} */ factory), + (/** @type {function() : !Object}*/ optionsFactory))); +}; + + +/** + * Sets the global factory object. + * @param {!goog.net.XmlHttpFactory} factory New global factory object. + */ +goog.net.XmlHttp.setGlobalFactory = function(factory) { + goog.net.XmlHttp.factory_ = factory; +}; + + + +/** + * Default factory to use when creating xhr objects. You probably shouldn't be + * instantiating this directly, but rather using it via goog.net.XmlHttp. + * @extends {goog.net.XmlHttpFactory} + * @constructor + */ +goog.net.DefaultXmlHttpFactory = function() { + goog.net.XmlHttpFactory.call(this); +}; +goog.inherits(goog.net.DefaultXmlHttpFactory, goog.net.XmlHttpFactory); + + +/** @override */ +goog.net.DefaultXmlHttpFactory.prototype.createInstance = function() { + var progId = this.getProgId_(); + if (progId) { + return new ActiveXObject(progId); + } else { + return new XMLHttpRequest(); + } +}; + + +/** @override */ +goog.net.DefaultXmlHttpFactory.prototype.internalGetOptions = function() { + var progId = this.getProgId_(); + var options = {}; + if (progId) { + options[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] = true; + options[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] = true; + } + return options; +}; + + +/** + * The ActiveX PROG ID string to use to create xhr's in IE. Lazily initialized. + * @type {string|undefined} + * @private + */ +goog.net.DefaultXmlHttpFactory.prototype.ieProgId_; + + +/** + * Initialize the private state used by other functions. + * @return {string} The ActiveX PROG ID string to use to create xhr's in IE. + * @private + */ +goog.net.DefaultXmlHttpFactory.prototype.getProgId_ = function() { + if (goog.net.XmlHttp.ASSUME_NATIVE_XHR) { + return ''; + } + + // The following blog post describes what PROG IDs to use to create the + // XMLHTTP object in Internet Explorer: + // http://blogs.msdn.com/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx + // However we do not (yet) fully trust that this will be OK for old versions + // of IE on Win9x so we therefore keep the last 2. + if (!this.ieProgId_ && typeof XMLHttpRequest == 'undefined' && + typeof ActiveXObject != 'undefined') { + // Candidate Active X types. + var ACTIVE_X_IDENTS = ['MSXML2.XMLHTTP.6.0', 'MSXML2.XMLHTTP.3.0', + 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP']; + for (var i = 0; i < ACTIVE_X_IDENTS.length; i++) { + var candidate = ACTIVE_X_IDENTS[i]; + /** @preserveTry */ + try { + new ActiveXObject(candidate); + // NOTE(user): cannot assign progid and return candidate in one line + // because JSCompiler complaings: BUG 658126 + this.ieProgId_ = candidate; + return candidate; + } catch (e) { + // do nothing; try next choice + } + } + + // couldn't find any matches + throw Error('Could not create ActiveXObject. ActiveX might be disabled,' + + ' or MSXML might not be installed'); + } + + return /** @type {string} */ (this.ieProgId_); +}; + + +//Set the global factory to an instance of the default factory. +goog.net.XmlHttp.setGlobalFactory(new goog.net.DefaultXmlHttpFactory()); diff --git a/pool/shard011/JavaScript/0069360_modal.js b/pool/shard011/JavaScript/0069360_modal.js new file mode 100644 index 0000000000000000000000000000000000000000..42e0b241b22a11a94178a83f5fb65e105321b81b --- /dev/null +++ b/pool/shard011/JavaScript/0069360_modal.js @@ -0,0 +1,219 @@ +/** + * wp.media.view.Modal + * + * A modal view, which the media modal uses as its default container. + * + * @class + * @augments wp.media.View + * @augments wp.Backbone.View + * @augments Backbone.View + */ +var $ = jQuery, + Modal; + +Modal = wp.media.View.extend({ + tagName: 'div', + template: wp.template('media-modal'), + + attributes: { + tabindex: 0 + }, + + events: { + 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler', + 'keydown': 'keydown' + }, + + clickedOpenerEl: null, + + initialize: function() { + _.defaults( this.options, { + container: document.body, + title: '', + propagate: true, + freeze: true + }); + + this.focusManager = new wp.media.view.FocusManager({ + el: this.el + }); + }, + /** + * @returns {Object} + */ + prepare: function() { + return { + title: this.options.title + }; + }, + + /** + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + attach: function() { + if ( this.views.attached ) { + return this; + } + + if ( ! this.views.rendered ) { + this.render(); + } + + this.$el.appendTo( this.options.container ); + + // Manually mark the view as attached and trigger ready. + this.views.attached = true; + this.views.ready(); + + return this.propagate('attach'); + }, + + /** + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + detach: function() { + if ( this.$el.is(':visible') ) { + this.close(); + } + + this.$el.detach(); + this.views.attached = false; + return this.propagate('detach'); + }, + + /** + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + open: function() { + var $el = this.$el, + options = this.options, + mceEditor; + + if ( $el.is(':visible') ) { + return this; + } + + this.clickedOpenerEl = document.activeElement; + + if ( ! this.views.attached ) { + this.attach(); + } + + // If the `freeze` option is set, record the window's scroll position. + if ( options.freeze ) { + this._freeze = { + scrollTop: $( window ).scrollTop() + }; + } + + // Disable page scrolling. + $( 'body' ).addClass( 'modal-open' ); + + $el.show(); + + // Try to close the onscreen keyboard + if ( 'ontouchend' in document ) { + if ( ( mceEditor = window.tinymce && window.tinymce.activeEditor ) && ! mceEditor.isHidden() && mceEditor.iframeElement ) { + mceEditor.iframeElement.focus(); + mceEditor.iframeElement.blur(); + + setTimeout( function() { + mceEditor.iframeElement.blur(); + }, 100 ); + } + } + + this.$el.focus(); + + return this.propagate('open'); + }, + + /** + * @param {Object} options + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + close: function( options ) { + var freeze = this._freeze; + + if ( ! this.views.attached || ! this.$el.is(':visible') ) { + return this; + } + + // Enable page scrolling. + $( 'body' ).removeClass( 'modal-open' ); + + // Hide modal and remove restricted media modal tab focus once it's closed + this.$el.hide().undelegate( 'keydown' ); + + // Put focus back in useful location once modal is closed. + if ( null !== this.clickedOpenerEl ) { + this.clickedOpenerEl.focus(); + } else { + $( '#wpbody-content' ).focus(); + } + + this.propagate('close'); + + // If the `freeze` option is set, restore the container's scroll position. + if ( freeze ) { + $( window ).scrollTop( freeze.scrollTop ); + } + + if ( options && options.escape ) { + this.propagate('escape'); + } + + return this; + }, + /** + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + escape: function() { + return this.close({ escape: true }); + }, + /** + * @param {Object} event + */ + escapeHandler: function( event ) { + event.preventDefault(); + this.escape(); + }, + + /** + * @param {Array|Object} content Views to register to '.media-modal-content' + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + content: function( content ) { + this.views.set( '.media-modal-content', content ); + return this; + }, + + /** + * Triggers a modal event and if the `propagate` option is set, + * forwards events to the modal's controller. + * + * @param {string} id + * @returns {wp.media.view.Modal} Returns itself to allow chaining + */ + propagate: function( id ) { + this.trigger( id ); + + if ( this.options.propagate ) { + this.controller.trigger( id ); + } + + return this; + }, + /** + * @param {Object} event + */ + keydown: function( event ) { + // Close the modal when escape is pressed. + if ( 27 === event.which && this.$el.is(':visible') ) { + this.escape(); + event.stopImmediatePropagation(); + } + } +}); + +module.exports = Modal; diff --git a/pool/shard011/JavaScript/0069365_adminPageInternalController.js b/pool/shard011/JavaScript/0069365_adminPageInternalController.js new file mode 100644 index 0000000000000000000000000000000000000000..adff7c0cf2459af5a834657b9c267f7760fca209 --- /dev/null +++ b/pool/shard011/JavaScript/0069365_adminPageInternalController.js @@ -0,0 +1,49 @@ +/** + * Class AdminPageInternalController + * Prints HTML templates to AngularJS using different layouts (empty, main, main_admin, etc...) + * @property {Array} auth authorization of methods (index, list, etc...) + * @property {Object} req ExpressJS request object (req) + * @property {Object} res ExpressJS response object (res) + */ +function AdminPageInternalController() { + //this.auth = ['index', 'list', 'view', 'new', 'edit', 'delete']; + this.auth = []; +} + +AdminPageInternalController.prototype.list = function() { + this.res.render('admin_page/list.html', { + layout: 'layout/empty.html', + title: 'Página Interior', + location: 'interior', + url: 'admin-page-internal' + }); +}; + +AdminPageInternalController.prototype.new = function() { + this.res.render('admin_page/new.html', { + layout: 'layout/empty.html', + title: 'Página Interior', + location: 'interior', + url: 'admin-page-internal' + }); +}; + +AdminPageInternalController.prototype.edit = function() { + this.res.render('admin_page/edit.html', { + layout: 'layout/empty.html', + title: 'Página Interior', + location: 'interior', + url: 'admin-page-internal' + }); +}; + +AdminPageInternalController.prototype.delete = function() { + this.res.render('admin_page/delete.html', { + layout: 'layout/empty.html' + }); +}; + +/** + * Module exports + */ +module.exports = new AdminPageInternalController(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069366_qlComment.js b/pool/shard011/JavaScript/0069366_qlComment.js new file mode 100644 index 0000000000000000000000000000000000000000..149e4486a1718d7d4af1b7e14e88ea77d5c8d807 --- /dev/null +++ b/pool/shard011/JavaScript/0069366_qlComment.js @@ -0,0 +1,94 @@ +/** + * Manapaho (https://github.com/manapaho/) + * + * Copyright © 2015 Manapaho. All rights reserved. + * + * This source code is licensed under the MIT license found in the + * LICENSE.txt file in the root directory of this source tree. + */ + +/** + * Import GraphQL types. + */ +import { + GraphQLBoolean, + GraphQLFloat, + GraphQLID, + GraphQLInt, + GraphQLList, + GraphQLNonNull, + GraphQLObjectType, + GraphQLSchema, + GraphQLString, +} from 'graphql'; + +/** + * Import Relay helpers. + */ +import { + connectionArgs, + connectionDefinitions, + connectionFromArray, + fromGlobalId, + globalIdField, + mutationWithClientMutationId, + nodeDefinitions, +} from 'graphql-relay'; + +/** + * Import GraphQL helpers. + */ +import { + nodeInterface, + nodeField, + registerType +} from './ql'; + +/** + * Import GraphQL Types. + */ +import qlPost from './qlPost'; + +/** + * Import Database Entities. + */ +import db from '../database/db'; + +/** + * Create the GraphQL Type. + */ +// Type name and global id. +const typeName = 'Comment'; + +// Type creation. +var qlComment = new GraphQLObjectType({ + name: typeName, + description: 'A comment to a post a person posted', + fields: () => ({ + id: globalIdField(typeName), + content: { + type: GraphQLString, + resolve(dbComment) { + return dbComment.content; + } + }, + post: { + type: qlPost, + resolve(dbComment){ + return dbComment.getPost(); + } + } + }), + interfaces: [nodeInterface] +}); + +// Type registration. +registerType({ + name: typeName, + getByID: (id)=>db.comment.findOne({where: {id: id}}), + dbType: db.comment.Instance, + qlType: qlComment +}); + +// Type export. +export default qlComment; diff --git a/pool/shard011/JavaScript/0069372_index.js b/pool/shard011/JavaScript/0069372_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2d328a179273837c0b28890d5f371461c2617a30 --- /dev/null +++ b/pool/shard011/JavaScript/0069372_index.js @@ -0,0 +1,57 @@ +'use strict' + +const electron = require('electron') +const app = electron.app // Module to control application life. +const BrowserWindow = electron.BrowserWindow // Module to create native browser window. + +const opts = { + productName: 'ESRScan Desktop', + companyName: 'Michael Weibel', + submitURL: 'https://ecs.openflex.net' +} + +// Report crashes to our server. +electron.crashReporter.start(opts) + +if (process.env.NODE_ENV === 'development') { + require('electron-debug')({ + showDevTools: true + }) +} + +// Keep a global reference of the window object, if you don't, the window will +// be closed automatically when the JavaScript object is garbage collected. +var mainWindow = null + +// Quit when all windows are closed. +app.on('window-all-closed', function () { + // On OS X it is common for applications and their menu bar + // to stay active until the user quits explicitly with Cmd + Q + if (process.platform !== 'darwin') { + app.quit() + } +}) + +// This method will be called when Electron has finished +// initialization and is ready to create browser windows. +app.on('ready', function () { + // Create the browser window. + mainWindow = new BrowserWindow({width: 800, height: 600}) + + // and load the index.html of the app. + if (process.env.NODE_ENV === 'development') { + mainWindow.loadURL('http://localhost:8080/index.html') + } else { + mainWindow.loadURL('file://' + __dirname + '/index.html') // eslint-disable-line no-path-concat + } + + // Emitted when the window is closed. + mainWindow.on('closed', function () { + // Dereference the window object, usually you would store windows + // in an array if your app supports multi windows, this is the time + // when you should delete the corresponding element. + mainWindow = null + }) + + require('./server')(app, mainWindow.webContents) +}) diff --git a/pool/shard011/JavaScript/0069373_compare.js b/pool/shard011/JavaScript/0069373_compare.js new file mode 100644 index 0000000000000000000000000000000000000000..a2cf5415622d6c75219bbfda1e2ece34bdf7d209 --- /dev/null +++ b/pool/shard011/JavaScript/0069373_compare.js @@ -0,0 +1,9 @@ +test('.prototype.compare()', 3, function () { + var r1 = new MathLib.Rational(3, 2), + r2 = new MathLib.Rational(6, 4), + r3 = new MathLib.Rational(1, 1), + r4 = new MathLib.Rational(7, 2); + equal(r1.compare(r2), 0, '.compare()'); + equal(r1.compare(r3), 1, '.compare()'); + equal(r1.compare(r4), -1, '.compare()'); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069375_boot.js b/pool/shard011/JavaScript/0069375_boot.js new file mode 100644 index 0000000000000000000000000000000000000000..86dfd74a237ddc3b44dd16d04e6ffee056b54571 --- /dev/null +++ b/pool/shard011/JavaScript/0069375_boot.js @@ -0,0 +1,156 @@ +/* +Copyright (c) 2008-2018 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ +/** + Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. + + If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. + + The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. + + [jasmine-gem]: http://github.com/pivotal/jasmine-gem + */ + +(function() { + + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + window.jasmine = jasmineRequire.core(jasmineRequire); + + /** + * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. + */ + jasmineRequire.html(jasmine); + + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + var env = jasmine.getEnv(); + + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + var jasmineInterface = jasmineRequire.interface(jasmine, env); + + /** + * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + extend(window, jasmineInterface); + + /** + * ## Runner Parameters + * + * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. + */ + + var queryString = new jasmine.QueryString({ + getWindowLocation: function() { return window.location; } + }); + + var filterSpecs = !!queryString.getParam("spec"); + + var stoppingOnSpecFailure = queryString.getParam("failFast"); + env.stopOnSpecFailure(stoppingOnSpecFailure); + + var throwingExpectationFailures = queryString.getParam("throwFailures"); + env.throwOnExpectationFailure(throwingExpectationFailures); + + var random = queryString.getParam("random"); + + if (random !== undefined && random !== "") { + env.randomizeTests(random); + } + + var seed = queryString.getParam("seed"); + if (seed) { + env.seed(seed); + } + + /** + * ## Reporters + * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). + */ + var htmlReporter = new jasmine.HtmlReporter({ + env: env, + navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, + addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, + getContainer: function() { return document.body; }, + createElement: function() { return document.createElement.apply(document, arguments); }, + createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + timer: new jasmine.Timer(), + filterSpecs: filterSpecs + }); + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jasmineInterface.jsApiReporter); + env.addReporter(htmlReporter); + + /** + * Filter which specs will be run by matching the start of the full name against the `spec` query param. + */ + var specFilter = new jasmine.HtmlSpecFilter({ + filterString: function() { return queryString.getParam("spec"); } + }); + + env.specFilter = function(spec) { + return specFilter.matches(spec.getFullName()); + }; + + /** + * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. + */ + window.setTimeout = window.setTimeout; + window.setInterval = window.setInterval; + window.clearTimeout = window.clearTimeout; + window.clearInterval = window.clearInterval; + + /** + * ## Execution + * + * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. + */ + var currentWindowOnload = window.onload; + + window.onload = function() { + if (currentWindowOnload) { + currentWindowOnload(); + } + htmlReporter.initialize(); + env.execute(); + }; + + /** + * Helper function for readability above. + */ + function extend(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; + } + +}()); diff --git a/pool/shard011/JavaScript/0069376_todo.js b/pool/shard011/JavaScript/0069376_todo.js new file mode 100644 index 0000000000000000000000000000000000000000..2c06595b4737e7e18b979e4ab033307168e4e5fc --- /dev/null +++ b/pool/shard011/JavaScript/0069376_todo.js @@ -0,0 +1,44 @@ +import Backbone from 'backbone'; +import BackboneLocalStorage from 'backbone.localStorage'; + +import Todo from 'app/models/todo' + +// Todo Collection +// --------------- + +// The collection of todos is backed by *localStorage* instead of a remote +// server. +class Todos extends Backbone.Collection { + + constructor () { + // Reference to this collection's model. + this.model = Todo; + + // Save all of the todo items under the `"todos"` namespace. + this.localStorage = new BackboneLocalStorage('todos-backbone'); + + // Todos are sorted by their original insertion order. + this.comparator = 'order'; + + super(); + } + + // Filter down the list of all todo items that are finished. + completed () { + return this.where({completed: true}); + } + + // Filter down the list to only todo items that are still not finished. + remaining () { + return this.where({completed: false}); + } + + // We keep the Todos in sequential order, despite being saved by unordered + // GUID in the database. This generates the next order number for new items. + nextOrder () { + return this.length ? this.last().get('order') + 1 : 1; + } +} + +// Create our global collection of **Todos**. +export default new Todos(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069381_preview-sources.js b/pool/shard011/JavaScript/0069381_preview-sources.js new file mode 100644 index 0000000000000000000000000000000000000000..c2e1736b900a60eae42118600f921e8cd7535f9a --- /dev/null +++ b/pool/shard011/JavaScript/0069381_preview-sources.js @@ -0,0 +1,41 @@ +import DemoLink from "~/components/parts/demo-link" + +import pkg from "../../../package.json" +import pjt from "../../../project.json" + +export default ({ title, docsPath, scssPath }) => { + const docsUrl = pkg.repository + "/tree/master/src/pages/" + docsPath + ".mdx" + const scssUrl = pkg.repository + "/tree/master/src/scss/" + scssPath + ".scss" + return ( +
    +
    +
      + {(() => { + if (docsPath) { + return ( +
    • + Document: + + {title} / {pjt.site.title} - GitHub Repository Source (MDX) + +
    • + ) + } + })()} + {(() => { + if (scssPath) { + return ( +
    • + SCSS: + + {title} / {pjt.site.title} - GitHub Repository Source (SCSS) + +
    • + ) + } + })()} +
    +
    +
    + ) +} diff --git a/pool/shard011/JavaScript/0069382_yotils.js b/pool/shard011/JavaScript/0069382_yotils.js new file mode 100644 index 0000000000000000000000000000000000000000..3fdb586d38d9c1a5b19a80b384dfd5b2796f6fd9 --- /dev/null +++ b/pool/shard011/JavaScript/0069382_yotils.js @@ -0,0 +1,38 @@ +'use strict'; + +var fs = require('fs'), + yosay = require('yosay'), + chalk = require('chalk'), + Prompts = require('./prompts'); + +var flapjacks = chalk.red('flapjacks'); + +module.exports = { + + preCheck: function(dir) { + var exists = fs.existsSync(this.destinationPath() + '/' + dir); + + if (!exists) { + console.log(yosay('Uhoh, you\'re not in the right directory. I should see ' + chalk.bgRed(dir) + ' in a sub-directory.')); + process.exit(1); + } + }, + + inquire: function (component) { + var done = this.async(), + PROMPTS = new Prompts(this); + + if (this.options.composed) { + this.props = this.options.props; + return done(); + } + + this.log(yosay('Let\'s build a ' + flapjacks + ' ' + component + '!')); + + this.prompt([ PROMPTS.items ], function (props) { + this.props = props; + done(); + }.bind(this)); + } + +}; diff --git a/pool/shard011/JavaScript/0069383_fehler_global_dialog.js b/pool/shard011/JavaScript/0069383_fehler_global_dialog.js new file mode 100644 index 0000000000000000000000000000000000000000..f90b2c025280845a0670a909d092e902fb4f43eb --- /dev/null +++ b/pool/shard011/JavaScript/0069383_fehler_global_dialog.js @@ -0,0 +1,56 @@ +define('tempo30/view/fehler_global_dialog', [ + 'jquery', + 'tempo30/model/version', + 'bootstrap', + 'bootstrap-dialog', + 'gettext!tempo30', +], function ($, version, bootstrap, BootstrapDialog, gt) { + + 'use strict'; + + var mailadr='adfcmap-fehler-2016@sven.anders.hamburg'; + var githubUrl='https://github.com/tabacha/adfc-tempo30/issues/new'; + function getDialog(subject, msg, title, startmsg) { + subject = '('+version.revision+') '+subject; + msg = msg+' Version:'+version.revision+'\n'; + msg = msg+' Browser-Agent String:'+navigator.userAgent+'\n'; + + var buttons=[ + { + id: 'btn-mail', + label:'Mail an '+mailadr, + cssClass: 'btn-diabled', + }, + { + id: 'github', + label: 'GitHub-Issue', + cssClass: 'btn-info', + action: function (dialogRef) { + window.open(githubUrl, '_blank'); + } + }, + { + id: 'cancel-btn', + label: gt('schließen'), + cssClass: 'btn-default', + action: function (dialogRef) { + dialogRef.close(); + } + }]; + + var dialog = new BootstrapDialog({ + 'type': BootstrapDialog.TYPE_WARNING, + 'title': title, + 'message': startmsg+' '+gt('Bitte schicken Sie eine E-Mail oder (wenn Sie sich gut mit Computern auskennen) erstellen Sie einen Github-Issue.')+gt('Bitte erwähnen Sie folgende Details (gerne noch mehr):')+'
    Betreff: '+subject+'

    '+gt('Vielen Dank!'), + 'buttons': buttons, + onshown: function(dialogRef){ + dialogRef.getModalBody().find('#errtxt').text(msg); + $(dialogRef.getButton('btn-mail')).replaceWith( + $('').prop("href", "mailto:"+mailadr+'?subject='+encodeURIComponent(subject)+'&body='+encodeURIComponent(msg)) + .text('Mail an '+mailadr)); + } + }); + return dialog; + } + return getDialog; +}); diff --git a/pool/shard011/JavaScript/0069386_vc_admin.js b/pool/shard011/JavaScript/0069386_vc_admin.js new file mode 100644 index 0000000000000000000000000000000000000000..706e90b9aa5aa6440887325d811f6f834f27c820 --- /dev/null +++ b/pool/shard011/JavaScript/0069386_vc_admin.js @@ -0,0 +1,15 @@ +jQuery(document).ready(function($) { + $('.vc_navbar li .wpb_edit_inline').parent().parent().addClass('pull-right'); + + setTimeout(function() { + $('.wpb_column_container .vc_shortcodes_container:not(.vc_tta-container):not(.wpb_vc_tta_section) > .wpb_element_wrapper > .wpb_element_title').each(function() { + + var t = $(this); + var title = t.attr('title'); + if(typeof title !== 'undefined'){ + t.text(''+title+''); + } + }); + }, 500); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069387_test.js b/pool/shard011/JavaScript/0069387_test.js new file mode 100644 index 0000000000000000000000000000000000000000..4dc574d62d2a301a2cc4d2ce0398a9570d8e75f5 --- /dev/null +++ b/pool/shard011/JavaScript/0069387_test.js @@ -0,0 +1,26 @@ +#!/usr/bin/env node +require('qunitjs'); + +if (process.argv[2] === 'testem') { + // use basic TAP output for testem + var sys = require('sys'); + var num = 1; + QUnit.begin(function (details) { + sys.puts('1..'+details.totalTests); + }); + QUnit.testDone(function (details) { + sys.puts((details.failed ? 'not ok ' : 'ok ') + (num++) + ' - ' + details.module + ' - ' + details.name); + }); +} else { + // otherwise use a nicer test reporter + var qe = require('qunit-extras'); + qe.runInContext(global); +} + +// we share the test file between browser/node +// export the global +global.HTML5Tokenizer = require('../dist/simple-html-tokenizer'); +require('../test/tokenizer-tests.js'); + +// run tests +QUnit.load(); diff --git a/pool/shard011/JavaScript/0069389_rename.js b/pool/shard011/JavaScript/0069389_rename.js new file mode 100644 index 0000000000000000000000000000000000000000..0cc6d5c202063a3890ac3088f16d821fec2e10a8 --- /dev/null +++ b/pool/shard011/JavaScript/0069389_rename.js @@ -0,0 +1,32 @@ +'use strict'; + +if(!config.rename || config.rename.length < 1) return; + +var gulp = require('gulp'); +var path = require('path'); +var rename = require("gulp-rename"); +var merge = require('merge-stream'); + +function getPaths() { + var paths = []; + config.rename.forEach(function(copyPath) { + var src = path.join(projectPath, copyPath.src); + var dest = path.join(projectPath, copyPath.dest); + var rename = copyPath.rename; + paths.push({src: src, dest: dest, rename: rename}); + }); + + return paths; +} + +gulp.task('rename', function() { + var paths = getPaths(); + + var tasks = paths.map(function(path) { + return gulp.src(path.src) + .pipe(rename(path.rename)) + .pipe(gulp.dest(path.dest)); + }); + + return merge(tasks); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069395_app.js b/pool/shard011/JavaScript/0069395_app.js new file mode 100644 index 0000000000000000000000000000000000000000..f5398c9cb9048a6d9e1110bb9c4657ac5d94f2c9 --- /dev/null +++ b/pool/shard011/JavaScript/0069395_app.js @@ -0,0 +1,87 @@ +"use strict"; + +var express = require('express'); +var logger = require('morgan'); +var bodyParser = require('body-parser'); + +var r_index = require('../routes/index'); +var r_account = require('../routes/account'); +var r_registerdevice = require('../routes/registerdevice'); + +var api_device = require('../routes/api/device'); +var api_child = require('../routes/api/child'); +var api_game = require('../routes/api/game'); +var api_parent = require('../routes/api/parent'); +var api_stat = require('../routes/api/stat'); + +var app = express(); + +// uncomment after placing your favicon in /public +app.use(logger('dev')); + +app.use(function (req, res, next) { + + // Website you wish to allow to connect + res.setHeader('Access-Control-Allow-Origin', '*'); + + // Request methods you wish to allow + res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); + + // Request headers you wish to allow + res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,Authorization'); + + // Set to true if you need the website to include cookies in the requests sent + // to the API (e.g. in case you use sessions) + res.setHeader('Access-Control-Allow-Credentials', true); + + // Pass to next layer of middleware + next(); +}); + + +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({extended: false})); + +app.use('/', r_index); +app.use('/account', r_account); +app.use('/registerdevice', r_registerdevice); + +app.use('/api/v1/child', api_child); +app.use('/api/v1/device', api_device); +app.use('/api/v1/game', api_game); +app.use('/api/v1/parent', api_parent); +app.use('/api/v1/stat', api_stat); + +// catch 404 and forward to error handler +app.use(function (req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handlers + +// development error handler +// will print stacktrace +if (app.get('env') === 'development') { + app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.json({ + message: err.message, + error: err + }); + }); +} + +// production error handler +// no stacktraces leaked to user +app.use(function (err, req, res, next) { + res.status(err.status || 500); + res.json({ + message: err.message, + error: {} + }); +}); + + +module.exports = app; diff --git a/pool/shard011/JavaScript/0069398_angular-common-draw.js b/pool/shard011/JavaScript/0069398_angular-common-draw.js new file mode 100644 index 0000000000000000000000000000000000000000..bbe7092f63f86afeae2403eda671e5848cbbbd68 --- /dev/null +++ b/pool/shard011/JavaScript/0069398_angular-common-draw.js @@ -0,0 +1,104 @@ +/* + * https://github.com/clouddueling/angular-common + */ +(function() { + + 'use strict'; + + angular.module('common.draw', []) + + .directive("draw", ['$timeout', function($timeout){ + return { + scope: { + ngChange: '&', + ngModel: '=', + strokeColor: '=?', + strokeWidth: '=?' + }, + link: function(scope, element){ + scope.strokeWidth = scope.strokeWidth || 3; + scope.strokeColor = scope.strokeColor || '#343536'; + + var canvas = element[0]; + var ctx = canvas.getContext('2d') + + // variable that decides if something should be drawn on mousemove + var drawing = false; + + // the last coordinates before the current move + var lastX; + var lastY; + + element.bind('mousedown', function(event){ + lastX = event.offsetX; + lastY = event.offsetY; + + // begins new line + ctx.beginPath(); + + drawing = true; + }); + + element.bind('mouseup', function(event){ + // stop drawing + drawing = false; + exportImage(); + }); + + element.bind('mousemove', function(event){ + if (!drawing) { + return; + } + + draw(lastX, lastY, event.offsetX, event.offsetY); + + // set current coordinates to last one + lastX = event.offsetX; + lastY = event.offsetY; + }); + + scope.$watch('ngModel', function(newVal, oldVal) { + if (!newVal && !oldVal) { + return; + } + + if (!newVal && oldVal) { + reset(); + } + }); + + // canvas reset + function reset(){ + element[0].width = element[0].width; + } + + function draw(lX, lY, cX, cY) { + // line from + ctx.moveTo(lX,lY); + + // to + ctx.lineTo(cX,cY); + + ctx.lineCap = 'round'; + + // stroke width + ctx.lineWidth = scope.strokeWidth; + + // color + ctx.strokeStyle = scope.strokeColor; + + // draw it + ctx.stroke(); + } + + function exportImage() { + $timeout(function() { + scope.ngModel = canvas.toDataURL(); + scope.ngChange(); + }); + } + } + }; + }]); + +})(); diff --git a/pool/shard011/JavaScript/0069400_index.js b/pool/shard011/JavaScript/0069400_index.js new file mode 100644 index 0000000000000000000000000000000000000000..5c2c9e52dd76c75a289491bcea2bff95a8a4bc62 --- /dev/null +++ b/pool/shard011/JavaScript/0069400_index.js @@ -0,0 +1,27 @@ +require('harmony-reflect'); + +function handler(module, filename) { + module.exports = new Proxy({}, { + get: function(target, property, receiver) { + // Without this, __esModule will return "__esModule" which will confuse + // babel into thinking this module was built with ES6 exports since it's + // "truthy". So, in this one special case, we return a value (false). + if (property === '__esModule') return false; + return property; + } + }); +}; + +function registerHandlers(extensions) { + if (extensions.constructor !== Array) + extensions = [extensions]; + extensions.forEach(function(ext) { + require.extensions[ext] = handler; + }); +} + +registerHandlers('.css'); +module.exports = { + register: registerHandlers +}; + diff --git a/pool/shard011/JavaScript/0069403_gulpfile.js b/pool/shard011/JavaScript/0069403_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..88a671be88c06d06aef9db701dcf695aac889a37 --- /dev/null +++ b/pool/shard011/JavaScript/0069403_gulpfile.js @@ -0,0 +1,58 @@ +var gulp = require('gulp'); +var sass = require('gulp-sass'); +var concat = require('gulp-concat'); +var exec = require('child_process').exec; +var del = require('del'); +var livereload = require('gulp-livereload'); + +var paths = { + index: 'app/index.html', + sass: ['app/sass/**/*.scss'], + lib: ['app/lib/**/*.js'], + jsx: ['app/js/App.jsx', 'app/js/Menu.jsx', 'app/js/SubHeader.jsx', 'app/js/NewTask.jsx', 'app/js/Task.jsx', 'app/js/Tasks.jsx', 'app/js/Header.jsx', 'app/js/Main.jsx'] +} + +gulp.task('clean', function() { + return del.sync(['dist']); +}); + +gulp.task('index', function() { + return gulp.src(paths.index).pipe(gulp.dest('./dist/')); +}); + +gulp.task('lib', function() { + return gulp.src(paths.lib) + .pipe(concat('lib.js')) + .pipe(gulp.dest('./dist/')); +}); + +gulp.task('sass', function() { + gulp.src(paths.sass) + .pipe(sass().on('error', sass.logError)) + .pipe(gulp.dest('./dist/')) + .pipe(livereload()); +}); + +gulp.task('jsx', function() { + gulp.src(paths.jsx) + .pipe(concat('app.jsx')) + .pipe(gulp.dest('./dist/')) + .pipe(livereload()); +}); + +gulp.task('watch', function() { + livereload.listen(); + gulp.watch(paths.sass, ['sass']); + gulp.watch(paths.lib, ['lib']); + gulp.watch(paths.jsx, ['jsx']); +}); + +gulp.task('run', function(callback) { + exec(__dirname + '/node_modules/.bin/electron .', function(err, stdout, stderr) { + console.log(stdout); + console.log(stderr); + callback(err); + }); +}); + +gulp.task('default', ['clean', 'index', 'lib', 'sass', 'jsx', 'watch', 'run']); diff --git a/pool/shard011/JavaScript/0069405_squareSymbol.js b/pool/shard011/JavaScript/0069405_squareSymbol.js new file mode 100644 index 0000000000000000000000000000000000000000..41ff7331875c83e0f0bb5bb2b430ad0d32636c27 --- /dev/null +++ b/pool/shard011/JavaScript/0069405_squareSymbol.js @@ -0,0 +1,232 @@ +/** + * @file + */ + +/*global d3:false */ +/*global dataStoreManager:false */ +/*jshint unused:true */ +/*exported addSquareSymbol, updateSquareSymbols, zoomSquareSymbol */ + +import {dataStoreManager} from '../../dataStore/dataStoreManager.js'; +import {dropLinesToAxes} from './scatterSymbolUtils.js'; +import {EventMediator} from '../../events/eventMediator.js'; +import {eventChannelNames} from '../../events/eventChannelNames.js'; + + +/** + * + * @constructor + */ +export function SquareSymbol() { + + "use strict"; + var _name = dataStoreManager.getInstance().generateUUID(); + var _selector = null; + + + /** + * + * @param plot + * @param plotProp + * @param scales + * @param toolTip + * @param transitionProperties + * @returns {*} + */ + this.addSymbol = function(uuid, plot, parentSVG, plotProp, scales, toolTip, transitionProperties) { + + function hoverStartEventHandler(params) { + + d3.selectAll(_selector).each(function(d) { + + if (d[plotProp.xProp] === params) { + d3.select(this).style("stroke", plotProp.display.hoverColor) + .style("fill", plotProp.display.hoverColor) + .style("stroke-width", plotProp.display.strokeHoverWidth ); + } + + }); + + } + + function hoverEndEventHandler(params) { + + d3.selectAll(_selector).each(function(d) { + + if (d[plotProp.xProp] === params) { + + d3.select(this) .style("stroke", plotProp.display.strokeColor) + .style("fill", plotProp.display.fillColor) + .style("stroke-width", plotProp.display.strokeWidth ); + } + + }); + + } + + + + + /** + * + * @param d + * @param that + */ + function handleHoverStart(d, that) { + + var hoverWidth = plotProp.display.width * transitionProperties.sizeFactor; + var hoverHeight = plotProp.display.height * transitionProperties.sizeFactor; + + toolTip.show(d, d3.event.pageX, d3.event.pageY, plotProp.xProp, plotProp.yProp); + + dropLinesToAxes(uuid, d, plotProp, transitionProperties, parentSVG); + + d3.select(that).transition() + .delay(transitionProperties.hoverDelayTime) + .duration(transitionProperties.hoverTransitionDuration) + .style("stroke", plotProp.display.strokeColor) + .style("fill", plotProp.display.hoverColor) + .style("stroke-width", plotProp.display.strokeHoverWidth ) + .attr("width", hoverWidth) + .attr("height", hoverHeight) + .ease(transitionProperties.hoverEaseType); + + EventMediator.getInstance().notify(eventChannelNames.hoverStart, _name, d[plotProp.xProp] ); + + } + + /** + * + * @param d + * @param that + */ + function handleHoverEnd(d, that) { + + toolTip.hide(); + + + d3.select(that).transition() + .delay(transitionProperties.hoverDelayTime) + .duration(transitionProperties.hoverTransitionDuration) + .style("stroke", plotProp.display.strokeColor) + .style("fill", plotProp.display.fillColor) + .style("stroke-width", plotProp.display.strokeWidth ) + .attr("width", plotProp.display.width) + .attr("height", plotProp.display.height) + .ease(transitionProperties.hoverEaseType); + + parentSVG.selectAll(".drop-line").data([]).exit().remove(); + + EventMediator.getInstance().notify(eventChannelNames.hoverEnd, _name, d[plotProp.xProp] ); + + } + + + plot = plot.enter().append("rect") + .attr("class", plotProp.plotClassName) + .attr("width", plotProp.display.width) + .attr("height", plotProp.display.height) + .attr("x", function (d) { + return (scales.xScale(d[plotProp.xProp]) - (plotProp.display.width / 2)); + }) + .attr("y", function (d) { + return (scales.yScale(d[plotProp.yProp])- (plotProp.display.height / 2)); + }); + + plot.style("opacity", "0") + .transition() + .style('fill', transitionProperties.enterColor) + .style('opacity', 1) + .transition() + .style('stroke', plotProp.display.strokeColor) + .duration(transitionProperties.startDurationTime) + .style("fill", function () { + return plotProp.display.fillColor; + }); + + plot.on("mouseover", function (d) { + handleHoverStart(d, this); + }) + .on("mouseout", function (d) { + handleHoverEnd(d, this); + }) + .on("touchstart", function (d) { + handleHoverStart(d, this); + }) + .on("touchend", function (d) { + handleHoverEnd(d, this); + }); + + EventMediator.getInstance().register(eventChannelNames.hoverStart, _name, hoverStartEventHandler); + EventMediator.getInstance().register(eventChannelNames.hoverEnd, _name, hoverEndEventHandler); + + _selector = "rect." + plotProp.plotClassName; + + return plot; + + }; + + /** + * + * @param svg + * @param plotProp + * @param scales + * @param data + * @param transitionProperties + * @returns {*} + */ + this.updateSymbol = function(svg, plotProp, scales, data, transitionProperties) { + + + + svg.transition() // Transition from old to new + .duration(transitionProperties.startDurationTime) // Length of animation + .each("start", function () { // Start animation + var currentFillColor = d3.select(this).style("fill"); + var transitionColor = d3.rgb(currentFillColor).brighter(); + d3.select(this) // 'this' means the current element + .style("fill", transitionColor) // Change color + .attr("width", plotProp.display.width * transitionProperties.sizeFactor) + .attr("height", plotProp.display.height * transitionProperties.sizeFactor); + }) + .delay(function (d, i) { + return i / data.length * transitionProperties.delayAdjustment; // Dynamic delay (i.e. each item delays a little longer) + }) + .ease(transitionProperties.easeType) // Transition easing - default 'variable' (i.e. has acceleration), also: 'circle', 'elastic', 'bounce', 'linear' + .attr("x", function (d) { + return (scales.xScale(d[plotProp.xProp]) - (plotProp.display.width / 2)); + }) + .attr("y", function (d) { + return (scales.yScale(d[plotProp.yProp])- (plotProp.display.height / 2)); + }) + .each("end", function () { // End animation + d3.select(this) // 'this' means the current element + .transition() + .duration(transitionProperties.endDurationTime) + .style("fill", plotProp.display.fillColor) // Change color + .attr("width", plotProp.display.width) + .attr("height", plotProp.display.height); + }); + + return svg; + }; + + /** + * + * @param plot + * @param plotProp + * @param scales + */ + this.zoomSymbol = function(plot, plotProp, scales) { + + + plot.selectAll('rect.' + plotProp.plotClassName).attr('y', function (d) { + return scales.yScale(d[plotProp.yProp]); + }).attr('x', function (d) { + return (scales.xScale(d[plotProp.xProp]) - (plotProp.display.width / 2)); + }); + + }; + +} + diff --git a/pool/shard011/JavaScript/0069407_PeerManager.js b/pool/shard011/JavaScript/0069407_PeerManager.js new file mode 100644 index 0000000000000000000000000000000000000000..d24d96ed48e81f2fef06bfd6c121277e721f50b4 --- /dev/null +++ b/pool/shard011/JavaScript/0069407_PeerManager.js @@ -0,0 +1,47 @@ +'use strict'; + +var run = function() { + // Replace '../bitcore' with 'bitcore' if you use this code elsewhere. + var bitcore = require('../bitcore'); + var Peer = bitcore.Peer; + var PeerManager = bitcore.PeerManager; + + var handleBlock = function(info) { + console.log('** Block Received **'); + console.log(info.message); + }; + + var handleTx = function(info) { + var tx = info.message.tx.getStandardizedObject(); + + console.log('** TX Received **'); + console.log(tx); + }; + + var handleInv = function(info) { + console.log('** Inv **'); + console.log(info.message); + + var invs = info.message.invs; + info.conn.sendGetData(invs); + }; + + var peerman = new PeerManager({ + network: 'testnet' + }); + + peerman.addPeer(new Peer('127.0.0.1', 18608)); + + peerman.on('connection', function(conn) { + conn.on('inv', handleInv); + conn.on('block', handleBlock); + conn.on('tx', handleTx); + }); + + peerman.start(); +}; + +module.exports.run = run; +if (require.main === module) { + run(); +} diff --git a/pool/shard011/JavaScript/0069408_ExcelGrid.js b/pool/shard011/JavaScript/0069408_ExcelGrid.js new file mode 100644 index 0000000000000000000000000000000000000000..0de4a77237ed9efb1011056002994c9b5b58af39 --- /dev/null +++ b/pool/shard011/JavaScript/0069408_ExcelGrid.js @@ -0,0 +1,156 @@ +/** + * @jsx React.DOM + * @copyright Prometheus Research, LLC 2014 + */ +"use strict"; + +var React = require('react'); +var PropTypes = React.PropTypes; +var BaseGrid = require('../../Grid'); +var ExcelCell = require('../cells/ExcelCell'); +var merge = require('../../merge'); +var SelectableGridMixin = require('./mixins/SelectableGridMixin'); +var DraggableGridMixin = require('./mixins/DraggableGridMixin'); +var CopyPasteGridMixin = require('./mixins/CopyPasteGridMixin'); +var EditableGridMixin = require('./mixins/EditableGridMixin'); +var SortableGridMixin = require('./mixins/SortableGridMixin'); +var FilterableGridMixin = require('./mixins/FilterableGridMixin'); +var CheckboxEditor = require('../editors/CheckboxEditor'); +var MixinHelper = require('../utils/MixinHelper'); + +var cloneWithProps = React.addons.cloneWithProps; + +var ExcelGrid = React.createClass({ + + getInitialState(){ + return {selectedRows : [], expandedRows : []}; + }, + + getDefaultProps() { + return { + rowHeight: 35, + shouldDisplayToolbar : true, + isRowSelectable : true, + minHeight : 350 + }; + }, + + handleCheckboxChange : function(e){ + if(e.currentTarget.checked === true){ + var selectedRows = this.props.rows.map(() => true); + this.setState({selectedRows : selectedRows}); + }else{ + var selectedRows = this.props.rows.map(() => false); + this.setState({selectedRows : selectedRows}); + } + }, + + handleRowSelect(row){ + var selectedRows = this.state.selectedRows; + if(selectedRows[row] == null || selectedRows[row] == false){ + selectedRows[row] = true; + }else{ + selectedRows[row] = false; + } + this.setState({selectedRows : selectedRows}); + }, + + handleShowMore(row, newHeight){ + var expandedRows = this.state.expandedRows; + if(expandedRows[row]){ + if(expandedRows[row]== null || expandedRows[row] < newHeight){ + expandedRows[row] = newHeight; + } + }else{ + expandedRows[row] = newHeight; + } + this.setState({expandedRows : expandedRows}); + }, + + handleShowLess(row){ + var expandedRows = this.state.expandedRows; + if(expandedRows[row]){ + expandedRows[row] = null; + } + this.setState({expandedRows : expandedRows}); + }, + + mixins : MixinHelper.mix([SelectableGridMixin, EditableGridMixin, DraggableGridMixin, CopyPasteGridMixin, SortableGridMixin, FilterableGridMixin]), + + overrides : { + getColumns : function(){ + var cols = this.getDecoratedColumns(this.props.columns) + if(this.props.isRowSelectable){ + cols.unshift({ + key: 'select-row', + name: '', + formatter : CheckboxEditor, + width : '3%', + onRowSelect :this.handleRowSelect, + filterable : false, + headerRenderer : + }); + } + return cols; + } + }, + + render: function() { + var cellRenderer = ( + + ); + + var rows = this.filterRows(); + return( +
    + + {this.transferPropsTo()} +
    + ) + }, + + renderToolbar(){ + if(this.props.shouldDisplayToolbar === true){ + return(
    +
    +
    + +
    +
    +
    ) + } + + } + + +}) + + +module.exports = ExcelGrid; diff --git a/pool/shard011/JavaScript/0069410_calendar_job.js b/pool/shard011/JavaScript/0069410_calendar_job.js new file mode 100644 index 0000000000000000000000000000000000000000..be70c91c5afc299ead60789f7930765577b98732 --- /dev/null +++ b/pool/shard011/JavaScript/0069410_calendar_job.js @@ -0,0 +1,113 @@ + +function calender_job() { + + + var nx=1; + var c=0; + var today,d,fst,fst_week,last,lastday; +function promiss(){ + today = new Date(); + d = today.getDate(); + fst = new Date(today.getFullYear(), today.getMonth()+nx-1, 1); + + fst_week = fst.getDay(); + last = new Date(today.getFullYear(),today.getMonth() +nx,0); + lastday = last.getDate(); +} +promiss(); + var s=(lastday + fst_week - 1>34)?6:5; + function calemder_wkwk(){ + +$('#calendar_month').html( +'
    日
    ' + +'
    月
    ' + +'
    火
    ' + +'
    水
    ' + +'
    木
    ' + +'
    金
    ' + +'
    土
    ' +); + +for(var i=0;i ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' ++'
    ' + +); +} + +} +calemder_wkwk(); + + function calender_jobjob(){ + + $(".calendar_day_top").each(function(idx, e) { + var a = idx - fst_week + 1; + if(d + fst_week - 1==idx && c==0){ + $(e).css("background","#00fa9a"); + }else{ + $(e).css("background","#aaf"); + } + $(this).html(a > 0 && a <= lastday ? a : ""); + }); + + + $("#topMonth").html(today.getFullYear() + "年" + (today.getMonth()+nx) + "月"); + // alert(lastday); + + + + } +calender_jobjob(); + +$("#next_month_button").click(function(){ + nx += 1; + c += 1; + promiss(); + s=(lastday + fst_week - 1>34)?6:5; + calemder_wkwk(); +calender_jobjob(); +}); + +$("#last_month_button").click(function(){ + nx -= 1; + c -= 1; + promiss(); + s=(lastday + fst_week - 1>34)?6:5; + calemder_wkwk(); +calender_jobjob(); +}); + +$("#today_button").click(function(){ + nx = 1; + c = 0; + promiss(); + s=(lastday + fst_week - 1>34)?6:5; + + calemder_wkwk(); +calender_jobjob(); +}); + + + + + + + +} + + + +$(function() {; + calender_job(); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069411_serial.js b/pool/shard011/JavaScript/0069411_serial.js new file mode 100644 index 0000000000000000000000000000000000000000..2781c42109a63145b46234c22aa99d330495c0c0 --- /dev/null +++ b/pool/shard011/JavaScript/0069411_serial.js @@ -0,0 +1,72 @@ +/* MicroFlo - Flow-Based Programming for microcontrollers + * Copyright (c) 2014 Jon Nordby + * MicroFlo may be freely distributed under the MIT license + */ + +var serialport = require("serialport"); + +var isLikelyArduinoSerial = function (e) { + return e.comName.indexOf("usbserial") !== -1 || e.comName.indexOf("usbmodem") !== -1 +} + +var guessSerialPort = function(wantedPortName, callback) { + serialport.list(function (err, ports) { + if (err) { + callback(err); + return; + } else { + if (ports.length === 0) { + callback("No serial port found", undefined, undefined); + return; + } + + var p = undefined; + ports.forEach(function(port) { + if (wantedPortName && wantedPortName !== "auto" + && wantedPortName === port.comName) { + p = port.comName; + } + }); + if (p) { + callback(err, p, ports); + return; + } else if (wantedPortName && wantedPortName !== "auto") { + console.log("WARN: unable to find serial port: ", wantedPortName); + } + + var preferred = ports.filter(isLikelyArduinoSerial) + p = preferred.length > 0 ? preferred[0].comName : ports[0].comName; + callback(err, p, ports); + return; + } + }); +} + + +var getSerial = function(serialPortToUse, baudRate, cb) { + console.log("Using serial baudrate", baudRate); + var serial = undefined; + guessSerialPort(serialPortToUse, function(err, portName, ports) { + if (err) { + console.log("No serial port found!: ", err); + if (cb) { + cb(err, undefined); + } + } else { + ports = ports.map(function(item) { return item.comName; }); + console.log("Available serial ports: ", ports); + console.log("Using serial port: " + portName); + serial = new serialport.SerialPort(portName, {baudrate: baudRate}, false); + serial.open(function() { + if (cb) { + cb(undefined, serial) + } + }); + serial.getTransportType = function () { return "Serial"; } + } + }); + return function() { return serial }; +} + + +module.exports.openTransport = getSerial diff --git a/pool/shard011/JavaScript/0069413_helpers.js b/pool/shard011/JavaScript/0069413_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..52e36cf7ecb7137a068f773a2f723d2e34f451a5 --- /dev/null +++ b/pool/shard011/JavaScript/0069413_helpers.js @@ -0,0 +1,111 @@ +/** + * Returns true if keyCode represents a printable character + * @param {Number} keyCode + * @return {Boolean} + */ +Handsontable.helper.isPrintableChar = function (keyCode) { + return ((keyCode == 32) || //space + (keyCode >= 48 && keyCode <= 57) || //0-9 + (keyCode >= 96 && keyCode <= 111) || //numpad + (keyCode >= 186 && keyCode <= 192) || //;=,-./` + (keyCode >= 219 && keyCode <= 222) || //[]{}\|"' + keyCode >= 226 || //special chars (229 for Asian chars) + (keyCode >= 65 && keyCode <= 90)); //a-z +}; + +/** + * Converts a value to string + * @param value + * @return {String} + */ +Handsontable.helper.stringify = function (value) { + switch (typeof value) { + case 'string': + case 'number': + return value + ''; + break; + + case 'object': + if (value === null) { + return ''; + } + else { + return value.toString(); + } + break; + + case 'undefined': + return ''; + break; + + default: + return value.toString(); + } +}; + +/** + * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc + * @param index + * @returns {String} + */ +Handsontable.helper.spreadsheetColumnLabel = function (index) { + var dividend = index + 1; + var columnLabel = ''; + var modulo; + while (dividend > 0) { + modulo = (dividend - 1) % 26; + columnLabel = String.fromCharCode(65 + modulo) + columnLabel; + dividend = parseInt((dividend - modulo) / 26, 10); + } + return columnLabel; +}; + +/** + * Checks if child is a descendant of given parent node + * http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another + * @param parent + * @param child + * @returns {boolean} + */ +Handsontable.helper.isDescendant = function (parent, child) { + var node = child.parentNode; + while (node != null) { + if (node == parent) { + return true; + } + node = node.parentNode; + } + return false; +}; + +/** + * Generates a random hex string. Used as namespace for Handsontable instance events. + * @return {String} - 16 character random string: "92b1bfc74ec4" + */ +Handsontable.helper.randomString = function () { + function s4() { + return Math.floor((1 + Math.random()) * 0x10000) + .toString(16) + .substring(1); + } + + return s4() + s4() + s4() + s4(); +}; + +/** + * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. + * Creates temporary dummy function to call it as constructor. + * Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516 + * @param {Object} Child child class + * @param {Object} Parent parent class + * @return {Object} extended Child + */ +Handsontable.helper.inherit = function (Child, Parent) { + function Bridge() { + } + + Bridge.prototype = Parent.prototype; + Child.prototype = new Bridge(); + Child.prototype.constructor = Child; + return Child; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069416_15.2.3.5-4-188.js b/pool/shard011/JavaScript/0069416_15.2.3.5-4-188.js new file mode 100644 index 0000000000000000000000000000000000000000..46aef9df2814a14889204f2170d5b6c1958985a0 --- /dev/null +++ b/pool/shard011/JavaScript/0069416_15.2.3.5-4-188.js @@ -0,0 +1,24 @@ +// Copyright (c) 2012 Ecma International. All rights reserved. +// This code is governed by the BSD license found in the LICENSE file. + +/*--- +es5id: 15.2.3.5-4-188 +description: > + Object.create - 'writable' property of one property in + 'Properties' is own accessor property without a get function + (8.10.5 step 6.a) +includes: [propertyHelper.js] +---*/ + +var descObj = { value: 100 }; + +Object.defineProperty(descObj, "writable", { + set: function () { } +}); + +var newObj = Object.create({}, { + prop: descObj +}); + +assert.sameValue(newObj.prop, 100); +verifyNotWritable(newObj, "prop"); diff --git a/pool/shard011/JavaScript/0069417_2_deploy_contracts.js b/pool/shard011/JavaScript/0069417_2_deploy_contracts.js new file mode 100644 index 0000000000000000000000000000000000000000..6494a70c91ffb6b37920548ed11d4b217cc9acfb --- /dev/null +++ b/pool/shard011/JavaScript/0069417_2_deploy_contracts.js @@ -0,0 +1,45 @@ +var ROKToken = artifacts.require("./ROKToken.sol"); +var Crowdsale = artifacts.require("./Crowdsale.sol"); +var SafeMath = artifacts.require("./SafeMath.sol"); +var MultiSigWallet = artifacts.require("./MultiSigWallet.sol"); + +module.exports = function(deployer, network){ + + var owner = web3.eth.accounts[0]; + var accounts = web3.eth.accounts.slice(0,3); + var signaturesRequired = 2; + + console.log("Owner address: " + owner); + if (network = 'development') { + deployer.deploy(SafeMath); + deployer.link(SafeMath, ROKToken); + deployer.deploy(ROKToken); + deployer.link(ROKToken, Crowdsale); + deployer.deploy(Crowdsale); + } + if (network == 'ropsten') { + deployer.deploy(SafeMath, { from: owner }); + console.log("SafeMath deploy"); + + deployer.link(SafeMath, ROKToken); + return deployer.deploy(ROKToken, { from: owner }).then(function(){ + console.log("ROKToken address: " + ROKToken.address); + + return deployer.deploy(MultiSigWallet, accounts, signaturesRequired).then(function(){ + console.log("MultiSigWallet address: " + MultiSigWallet.address); + + return deployer.deploy(Crowdsale, ROKToken.address, MultiSigWallet.address, { from: owner }).then(function(){ + console.log("Crowdsale address: " + Crowdsale.address); + return ROKToken.deployed().then(function(rok){ + return rok.owner.call().then(function(owner){ + console.log("ROKToken owner : " + owner); + return rok.transferOwnership(Crowdsale.address, {from: owner}).then(function(txn){ + console.log("ROKToken owner was changed: " + Crowdsale.address); + }); + }); + }); + }); + }); + }); + } + }; diff --git a/pool/shard011/JavaScript/0069419_HeroDeathManager.js b/pool/shard011/JavaScript/0069419_HeroDeathManager.js new file mode 100644 index 0000000000000000000000000000000000000000..f4ccf61a7bffaad5d95000853396b6b0df554e90 --- /dev/null +++ b/pool/shard011/JavaScript/0069419_HeroDeathManager.js @@ -0,0 +1,14 @@ +game.HeroDeathManager = Object.extend({ + init: function(x, y, settings){ + this.alwaysUpdate = true; + }, + //this basically resets my player if died// + update: function(){ + if(game.data.player.dead){ + me.game.world.removeChild(game.data.player); + me.state.current().resetPlayer(10, 0); + } + + return true; + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069422_ChangePassword.js b/pool/shard011/JavaScript/0069422_ChangePassword.js new file mode 100644 index 0000000000000000000000000000000000000000..5cc73c5def3c3dc2d33191758292ec15ff80a8f1 --- /dev/null +++ b/pool/shard011/JavaScript/0069422_ChangePassword.js @@ -0,0 +1,78 @@ +/* +Copyright 2015 OpenMarket 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. +*/ + +'use strict'; + +var React = require('react'); +var MatrixClientPeg = require("../../MatrixClientPeg"); + +var dis = require("../../dispatcher"); + +module.exports = { + propTypes: { + onFinished: React.PropTypes.func, + }, + + Phases: { + Edit: "edit", + Uploading: "uploading", + Error: "error", + Success: "Success" + }, + + getDefaultProps: function() { + return { + onFinished: function() {}, + }; + }, + + getInitialState: function() { + return { + phase: this.Phases.Edit, + errorString: '' + } + }, + + changePassword: function(old_password, new_password) { + var cli = MatrixClientPeg.get(); + + var authDict = { + type: 'm.login.password', + user: cli.credentials.userId, + password: old_password + }; + + this.setState({ + phase: this.Phases.Uploading, + errorString: '', + }) + + var d = cli.setPassword(authDict, new_password); + + var self = this; + d.then(function() { + self.setState({ + phase: self.Phases.Success, + errorString: '', + }) + }, function(err) { + self.setState({ + phase: self.Phases.Error, + errorString: err.toString() + }) + }); + }, +} diff --git a/pool/shard011/JavaScript/0069423_test-js.js b/pool/shard011/JavaScript/0069423_test-js.js new file mode 100644 index 0000000000000000000000000000000000000000..2b26714c1796d381d2ff99923e159900b7e94a6e --- /dev/null +++ b/pool/shard011/JavaScript/0069423_test-js.js @@ -0,0 +1,43 @@ +var gulp = require("gulp"), + config = require(process.cwd() + "/tasks/config.json"), + plugins = require("gulp-load-plugins")(); + +var testFiles = [ + config.paths.js.src + "**/*.js", + "!" + config.paths.js.src + "vendor/**/*", + "gulpfile.js", + config.paths.tasks + "**/*.js" + ]; + +gulp.task("js:test:jshint", function () { + var jshint = plugins.jshint; + + return gulp.src(testFiles) + .pipe(jshint()) + .pipe(jshint.reporter("jshint-stylish")) + .pipe(jshint.reporter("fail")); +}); + +gulp.task("js:test:jscs", function () { + return gulp.src(testFiles) + .pipe(plugins.jscs(".jscsrc")); +}); + +gulp.task("js:test:jsonlint", function () { + return gulp.src([ + "./package.json", + ".src/**/*.json" + ]) + .pipe(plugins.jsonlint()) + .pipe(plugins.jsonlint.reporter()); +}); + +gulp.task("js:test:cpd", function () { + return gulp.src([ + config.paths.js.src + "**/*.js", + "!" + config.paths.js.src + "vendor/**/*" + ]) + .pipe(plugins.jscpd()); +}); + +gulp.task("js:test", ["js:test:jshint", "js:test:jsonlint", "js:test:cpd"]); diff --git a/pool/shard011/JavaScript/0069424_app.js b/pool/shard011/JavaScript/0069424_app.js new file mode 100644 index 0000000000000000000000000000000000000000..1d2b1346b045a408c8e952ee51bbb14d3240b94e --- /dev/null +++ b/pool/shard011/JavaScript/0069424_app.js @@ -0,0 +1,95 @@ +$(function(){ + var $ticker = $('#ticker'), + $detener = $('#detener'); + + //Metodo generalista para llamar a ajax. + //$.ajax(); + + /* Forma básica -- no se guarda nada en ningún sitio + $.ajax('../servidor/generaContenidos.php'); + */ + /*Podemos pasarle un parametro: + $.ajax('../servidor/generaContenidos.php', { + data:{ + user : 'Miren', + pass : '1234' + } + }); + */ + /*Podemos decirle que va con el método POST + $.ajax('../servidor/generaContenidos.php', { + data:{ + user : 'Miren', + pass : '1234' + }, + method: 'POST' + }); + */ + /*Podemos decirle lo que debe hacer en caso de acierto (success) + $.ajax('../servidor/generaContenidos.php', { + data:{ + user : 'Miren', + pass : '1234' + }, + method: 'POST', + success: function(data, status, jqXHR){ + console.log(data); + console.log(status); + consoloe.log(ojqXHR); + } + }); + */ + /* Podemos decirle que lo "pinte" en un elemento HTML + $.ajax('../servidor/generaContenidos.php', { + success: function(data, status, jqXHR){ + $ticker.text(data); + } + }); + */ + /*No hacer nunca esto: (ES ASINCRONO!!!) + var resul = $.ajax('../servidor/generaContenidos.php', { + success: function(data, status, jqXHR){ + $ticker.text(data); + } + }); + //resul es un obj jquery por lo que nunca será vacío así que + if(resul){ + //siempres entrará aqui... preguntar por resul.length + console.log(resul); + } + */ + + /*en javascript podemos retardar una unica vez una función: + setTimeout(fn, 1000); + Y podemos decirle que algo se ejecute cada x tiempo: + setInterval(fn, 1000); + */ + + var peticionAJAX = function(){ + $.ajax('../servidor/generaContenidos.php', { + success: function(data, status, jqXHR){ + $ticker.text(data); + } + }); + }; + + var interval = setInterval(peticionAJAX, 1000); + /*para parar el intervalo, al pulsar el boton.*/ + $detener.on ('click', function(e){ + clearinterval(interval); + }); + + /*Suponiendo que tuvieramos un boton para activarlo de nuevo: + $play.on ('click', function(e){ + interval = setInterval(peticionAJAX, 1000); + }); + */ + /*Otra manera de hacer la funcion de peticionAJAX (en este caso) de forma más directa es: + var peticionAJAX = function(){ + $get('../servidor/generaContenidos.php', null, function(data){ + $ticker.text(data); + }) + }; + + */ +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069425_pattern-factory.js b/pool/shard011/JavaScript/0069425_pattern-factory.js new file mode 100644 index 0000000000000000000000000000000000000000..b8cd7c3de770b07098bee505c3ea8ef544de1094 --- /dev/null +++ b/pool/shard011/JavaScript/0069425_pattern-factory.js @@ -0,0 +1,110 @@ +"use strict"; + +var P = require("parsimmon"); + +var H = require("../parse-helpers"); +var _ = require("./whitespace")(null); +var ast = require("../ast"); + +var wrap = H.wrap; +var word = H.word; +var ione = H.ione; +var iseq = H.iseq; +var list0 = H.list0; + +function patternFactory(type, ps) { + var Pattern = P.lazy(function() { + return P.alt( + PatternArray, + PatternObject, + PatternLeaf + ); + }); + + var helpers = { + Let: function() { + return PatternSimple; + }, + Match: function() { + return P.alt( + PatternLiteral, + PatternSimple, + PatternParenExpr + ); + } + }; + + if (!helpers.hasOwnProperty(type)) { + throw new Error("cannot make pattern factory for " + type); + } + + var PatternLeaf = P.lazy(helpers[type]); + + var PatternSimple = + ione(ast.PatternSimple, ps.Identifier); + + var PatternParenExpr = + ione(ast.PatternParenExpr, ps.ParenExpr); + + var PatternLiteral = + ione(ast.PatternLiteral, + P.alt( + ps.Number, + ps.String, + ps.NamedLiteral + )); + + var PatternObjectPairBasic = + iseq(ast.PatternObjectPair, + P.seq( + ps.ObjectPairKey.skip(_), + word(":").then(Pattern) + )); + + var PatternObjectPairShorthand = + ps.Identifier + .map(function(i) { + var str = ast.String(i.index, i.data); + var expr = ast.PatternSimple(i.index, i); + return ast.PatternObjectPair(i.index, str, expr); + }); + + var PatternObjectPair = + P.alt( + PatternObjectPairBasic, + PatternObjectPairShorthand + ); + + var PatternObject = + ione(ast.PatternObject, + wrap("{", list0(ps.Separator, PatternObjectPair), "}")); + + var PatternArrayStrict = + ione(ast.PatternArray, + wrap("[", list0(ps.Separator, Pattern), "]")); + + var BareSlurp = + ione(ast.PatternSimple, + ione(ast.Identifier, P.of("_"))); + + var PatternArraySlurpy = + iseq(ast.PatternArraySlurpy, + wrap( + "[", + P.seq( + Pattern.skip(ps.Separator).many(), + word("...").then(Pattern.or(BareSlurp)) + ), + "]" + )); + + var PatternArray = + P.alt( + PatternArrayStrict, + PatternArraySlurpy + ); + + return Pattern; +} + +module.exports = patternFactory; diff --git a/pool/shard011/JavaScript/0069428_server.js b/pool/shard011/JavaScript/0069428_server.js new file mode 100644 index 0000000000000000000000000000000000000000..0c741cef3e565d8cffc0d8fc6ad8ade9b653f597 --- /dev/null +++ b/pool/shard011/JavaScript/0069428_server.js @@ -0,0 +1,65 @@ +require('rootpath')(); +var express = require('express'); +var ejs = require('ejs'); +var app = express(); +var compression = require('compression'); +var session = require('express-session'); +var MongoStore = require('connect-mongo')(session); +var bodyParser = require('body-parser'); +var config = require('config.json'); + +// enable ejs templates to have .html extension +app.engine('html', ejs.renderFile); +app.set('view engine', 'html'); + +// set default views folder +app.set('views', __dirname + '/../client'); + +// enable gzip compression +app.use(compression()); + +app.use(bodyParser.urlencoded({ extended: false })); +app.use(bodyParser.json()); +app.use(session({ + secret: config.secret, + store: new MongoStore({ url: config.connectionString }), + resave: false, + saveUninitialized: true +})); + +// redirect to the install page if first time running +app.use(function (req, res, next) { + if (!config.installed && req.path !== '/install') { + return res.redirect('/install'); + } + + next(); +}); + +// api routes +app.use('/api/contact', require('./controllers/api/contact.controller')); +app.use('/api/pages', require('./controllers/api/pages.controller')); +app.use('/api/posts', require('./controllers/api/posts.controller')); +app.use('/api/redirects', require('./controllers/api/redirects.controller')); +app.use('/api/users', require('./controllers/api/users.controller')); + +// make JWT token available to angular app +app.get('/token', function (req, res) { + res.send(req.session.token); +}); + +// standalone pages +app.use('/install', require('./controllers/install.controller')); +app.use('/login', require('./controllers/login.controller')); + +// admin section +app.use('/admin', require('./controllers/admin.controller')); + +// blog front end +app.use('/', require('./controllers/blog.controller')); + +// start server +var port = process.env.NODE_ENV === 'production' ? 80 : 3000; +var server = app.listen(port, function () { + console.log('Server listening on port ' + port); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069429_charts-ariapie-tests.js b/pool/shard011/JavaScript/0069429_charts-ariapie-tests.js new file mode 100644 index 0000000000000000000000000000000000000000..964e6f7b562fca711ed5d03fca538fae8e42765d --- /dev/null +++ b/pool/shard011/JavaScript/0069429_charts-ariapie-tests.js @@ -0,0 +1,79 @@ +YUI.add('charts-ariapie-tests', function(Y) { + var suite = new Y.Test.Suite("Charts: AriaPie"), + pieDataValues = [ + {category:"5/1/2010", revenue:2200}, + {category:"5/2/2010", revenue:100}, + {category:"5/3/2010", revenue:1500}, + {category:"5/4/2010", revenue:2800}, + {category:"5/5/2010", revenue:2650} + ], + defaultPieAriaDescription = "Use the left and right keys to navigate through items.", + width = 400, + height = 300, + parentDiv = Y.DOM.create('
    '), + DOC = Y.config.doc; + DOC.body.appendChild(parentDiv); + + function AriaTests(cfg, testConfig) + { + AriaTests.superclass.constructor.apply(this); + this.attrConfig = cfg; + this.name = testConfig.type + " Aria Tests"; + this.defaultAriaDescription = testConfig.defaultAriaDescription; + } + Y.extend(AriaTests, Y.Test.Case, { + defaultAriaLabel: "Chart Application", + + changedAriaLabel: "This is a new ariaLabel value.", + + setUp: function() { + var mychart = new Y.Chart(this.attrConfig); + this.chart = mychart; + }, + + tearDown: function() { + this.chart.destroy(true); + Y.Event.purgeElement(DOC, false); + }, + + "test:getAriaLabel()": function() + { + Y.Assert.isTrue(this.chart.get("ariaLabel") == this.defaultAriaLabel); + }, + + "test:setAriaLabel()": function() + { + var chart = this.chart; + chart.set("ariaLabel", this.changedAriaLabel); + Y.Assert.isTrue(chart.get("ariaLabel") == this.changedAriaLabel); + }, + + "test:getAriaDescription()": function() + { + Y.Assert.isTrue(this.chart.get("ariaDescription") == this.defaultAriaDescription); + }, + + "test:setAriaDescription()": function() + { + var chart = this.chart; + chart.set("ariaDescription", this.changedAriaLabel); + Y.Assert.isTrue(chart.get("ariaDescription") == this.changedAriaLabel); + } + }); + Y.AriaTests = AriaTests; + + var pieTests = new Y.AriaTests({ + dataProvider: pieDataValues, + render: "#testdiv", + type: "pie", + width: width, + height: height + }, { + type: "Pie", + defaultAriaDescription: defaultPieAriaDescription + }); + + suite.add(pieTests); + + Y.Test.Runner.add(suite); +}, '@VERSION@' ,{requires:['charts', 'test']}); diff --git a/pool/shard011/JavaScript/0069430_details-text-controller.spec.js b/pool/shard011/JavaScript/0069430_details-text-controller.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..6330770b8b55fc9e857dd57fa1392a411af7fdef --- /dev/null +++ b/pool/shard011/JavaScript/0069430_details-text-controller.spec.js @@ -0,0 +1,22 @@ +'use strict'; + +describe('driver.details: DetailsTextController', function () { + + beforeEach(module('driver.details')); + + var $controller; + var $rootScope; + var $scope; + var Controller; + + beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) { + $controller = _$controller_; + $rootScope = _$rootScope_; + $scope = $rootScope.$new(); + })); + + it('should pass this placeholder test', function () { + Controller = $controller('DetailsTextController', { $scope: $scope }); + $scope.$apply(); + }); +}); diff --git a/pool/shard011/JavaScript/0069431_index.js b/pool/shard011/JavaScript/0069431_index.js new file mode 100644 index 0000000000000000000000000000000000000000..abd85b751a0e90ed89c805d6f477847945540ed1 --- /dev/null +++ b/pool/shard011/JavaScript/0069431_index.js @@ -0,0 +1,47 @@ +import React, {PropTypes} from 'react'; +import {View, Text} from 'react-native'; +import Avatar from '../../../components/Avatar' +import s from './styles' +import {createGhAvatarLink} from '../../../utils/links' + +const UserTop = ({displayName, username, github}) => { + return ( + + + + + + + {displayName} + + + @{username} + + + + + {github.followers} + followers + + + {github.public_repos} + repos + + + {github.following} + following + + + + ) +} + +UserTop.propTypes = { + displayName: PropTypes.string, + username: PropTypes.string, + github: PropTypes.object +} + +export default UserTop diff --git a/pool/shard011/JavaScript/0069434_workspace-dashboards.js b/pool/shard011/JavaScript/0069434_workspace-dashboards.js new file mode 100644 index 0000000000000000000000000000000000000000..d58142564f1c76b0fb323470eba9f66f6451befb --- /dev/null +++ b/pool/shard011/JavaScript/0069434_workspace-dashboards.js @@ -0,0 +1,102 @@ +angular.module('team-task') + .controller('WorkspaceDashboardsController', ['$scope', '$rootScope', '$state', '$stateParams', 'Atividade', 'Time', + '$resource', '$filter', 'Pessoa', 'Projeto', '$q', 'DTOptionsBuilder', '$uibModal', 'Hora', 'uiCalendarConfig', + function ($scope, $rootScope, $state, $stateParams, Atividade, Time, $resource, $filter, Pessoa, Projeto, $q, + DTOptionsBuilder, $uibModal, Hora) { + $scope.dataPesquisa = moment().toDate(); + $scope.heatmapData = []; + $scope.initWorkspaceDashboards = function () { + $scope.daysInMonth = moment($scope.dataPesquisa).daysInMonth(); + $scope.heatmapData = []; + generateHeatMapData(); + }; + + $scope.prevMonth = function () { + $scope.dataPesquisa = moment($scope.dataPesquisa).subtract(1, 'month').toDate(); + $scope.daysInMonth = moment($scope.dataPesquisa).daysInMonth(); + $scope.heatmapData = []; + generateHeatMapData(); + }; + + $scope.nextMonth = function () { + $scope.dataPesquisa = moment($scope.dataPesquisa).add(1, 'month').toDate(); + $scope.daysInMonth = moment($scope.dataPesquisa).daysInMonth(); + $scope.heatmapData = []; + generateHeatMapData(); + }; + + function generateHeatMapData() { + $scope.daysInMonth = moment($scope.dataPesquisa).daysInMonth(); + $scope.datas = []; + var primeiroDia = moment($scope.dataPesquisa).startOf('month').startOf('day'); + var ultimoDia = moment($scope.dataPesquisa).endOf('month').endOf('day'); + var dia = moment(primeiroDia); + var tempDia = []; + var datasStr = []; + while (dia.month() === primeiroDia.month()) { + tempDia.push(Number(dia.format("D"))); + datasStr.push(dia.format("YYYY-MM-DD")); + dia.add(1, 'd'); + } + $scope.datas = tempDia; + var qPessoa = { + cadastrado: $rootScope.usuarioLogado._id.$oid + }; + var start = moment(primeiroDia.toDate()); + var end = moment(ultimoDia.toDate()); + + + Pessoa.query(qPessoa, { + s: {'nome': 1}, + f: {'nome': 1, '_id': 1, 'usuario': 1} + }).then(function (pessoas) { + var query = { + 'data': { + '$gte': { + '$date': start.toDate() + }, + '$lte': { + '$date': end.toDate() + } + }, + usuario: { + $in: [] + } + }; + var tempHeatmapData = []; + for (var index = 0; index < pessoas.length; index++) { + query.usuario.$in.push(pessoas[index]._id.$oid); + + var tempHoras = []; + for (var j = 0; j < $scope.daysInMonth; j++) { + tempHoras.push({ + recurso: (index + 1), + data: (j + 1), + horas: 0 + }); + } + + tempHeatmapData.push({ + recurso: pessoas[index].usuario.toUpperCase(), + horas: tempHoras + }); + } + Hora.query(query, {sort: {usuario: 1, data: 1}}).then(function (horas) { + for (var i = 0; i < datasStr.length; i++) { + var horasNaData = $filter('filter')(horas, {dataStr: datasStr[i]}); + if (horasNaData && horasNaData.length > 0) { + for (var z = 0; z < horasNaData.length; z++) { + var usuario = $filter('filter')(pessoas, {_id : {$oid: horasNaData[z].usuario}})[0]; + var heatMapRecurso = $filter('filter')(tempHeatmapData, {recurso : usuario.usuario.toUpperCase()})[0]; + var tempTempo = moment(horasNaData[z].tempo.$date); + heatMapRecurso.horas[i].horas += (tempTempo.hours() + (tempTempo.minutes() / 60)); + + } + } + } + $scope.heatmapData = tempHeatmapData; + }); + }); + } + + }]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069437_ShowBefore.js b/pool/shard011/JavaScript/0069437_ShowBefore.js new file mode 100644 index 0000000000000000000000000000000000000000..76da5c832f073e9e4e5a0391009d208ad9d706ef --- /dev/null +++ b/pool/shard011/JavaScript/0069437_ShowBefore.js @@ -0,0 +1,32 @@ +import React from 'react'; + +import { Box, InfiniteScroll, Text } from 'grommet'; + +const allItems = Array(240) + .fill() + .map((_, i) => `item ${i + 1}`); + +const Example = (props) => ( + // Uncomment lines when using outside of storybook + // + + {(item) => ( + + {item} + + )} + + // +); + +export const ShowBefore = () => ; + +ShowBefore.storyName = 'Replace, show before step'; + +ShowBefore.parameters = { + chromatic: { disable: true }, +}; + +export default { + title: 'Utilities/InfiniteScroll/Replace, show before step', +}; diff --git a/pool/shard011/JavaScript/0069442_main.js b/pool/shard011/JavaScript/0069442_main.js new file mode 100644 index 0000000000000000000000000000000000000000..14590a098cf51de235606a54baea1d2e80a72a6e --- /dev/null +++ b/pool/shard011/JavaScript/0069442_main.js @@ -0,0 +1,46 @@ +define(["infobox/link", "infobox/node"], function (Link, Node) { + return function (config, sidebar, router) { + var self = this + var el + + function destroy() { + if (el && el.parentNode) { + el.parentNode.removeChild(el) + el = undefined + sidebar.reveal() + } + } + + function create() { + destroy() + sidebar.ensureVisible() + sidebar.hide() + + el = document.createElement("div") + sidebar.container.insertBefore(el, sidebar.container.firstChild) + + el.scrollIntoView(false) + el.classList.add("infobox") + el.destroy = destroy + + var closeButton = document.createElement("button") + closeButton.classList.add("close") + closeButton.onclick = router.reset + el.appendChild(closeButton) + } + + self.resetView = destroy + + self.gotoNode = function (d) { + create() + new Node(config, el, router, d) + } + + self.gotoLink = function (d) { + create() + new Link(config, el, router, d) + } + + return self + } +}) diff --git a/pool/shard011/JavaScript/0069446_Message.js b/pool/shard011/JavaScript/0069446_Message.js new file mode 100644 index 0000000000000000000000000000000000000000..eb47aaf2839952e70a6d632e34fe08eb54d8621e --- /dev/null +++ b/pool/shard011/JavaScript/0069446_Message.js @@ -0,0 +1,23 @@ +function sendTestMessage() +{ + var xhrArgs = { + form: dojo.byId("test_message"), + handleAs: "json", + load: function(data) { + // dojo.byId("flash_message").innerHTML = "Test messages have been successfully sent"; + bizsense.dom.flashMessage("Test message has been successfully sent"); + }, + error: function(error) { + // dojo.byId("flash_message").innerHTML = "Test messages could not be sent"; + bizsense.dom.flashMessage("Test message could not be sent"); + } + } + + //Call the asynchronous xhrPost + var deferred = dojo.xhrPost(xhrArgs); + + //scroll to top of page + window.scrollTo(0,0); +} + + diff --git a/pool/shard011/JavaScript/0069448_producto.js b/pool/shard011/JavaScript/0069448_producto.js new file mode 100644 index 0000000000000000000000000000000000000000..91bdec21bec852ee44d334bd39d855c52d1b6b2b --- /dev/null +++ b/pool/shard011/JavaScript/0069448_producto.js @@ -0,0 +1,23 @@ +// Import the initialized Bookshelf +var Bookshelf = require('bookshelf').DB; +var Linea = require("./linea").model; + + +exports.model = Bookshelf.Model.extend({ + tableName: "productos", + insumos: function() { + var Insumo = require("./insumo").model; + return this.belongsToMany(Insumo).withPivot(['cantidad']); + }, + lineas: function() { + return this.hasMany(Linea); + }, + lineas_ns: function() { + return this.hasMany(Linea).query({where: {estado: 'ingresado'}}); + }, + ventas: function() { + var Venta = require("./venta").model; + return this.belongsToMany(Venta).through(Linea); + } +}); + diff --git a/pool/shard011/JavaScript/0069450_AboutFunctions.js b/pool/shard011/JavaScript/0069450_AboutFunctions.js new file mode 100644 index 0000000000000000000000000000000000000000..e57ad45c9bd9e6d41dc8482af57c408efe5d898d --- /dev/null +++ b/pool/shard011/JavaScript/0069450_AboutFunctions.js @@ -0,0 +1,110 @@ +describe("About Functions", function() { + + it("should declare functions", function() { + + function add(a, b) { + return a + b; + } + + expect(add(1, 2)).toBe(3); + }); + + it("should know internal variables override outer variables", function () { + var message = "Outer"; + + function getMessage() { + return message; + } + + function overrideMessage() { + var message = "Inner"; + return message; + } + + expect(getMessage()).toBe("Outer"); + expect(overrideMessage()).toBe("Inner"); + expect(message).toBe("Outer"); + }); + + it("should have lexical scoping", function () { + var variable = "top-level"; + function parentfunction() { + var variable = "local"; + function childfunction() { + return variable; + } + return childfunction(); + } + expect(parentfunction()).toBe("local"); + }); + + it("should use lexical scoping to synthesise functions", function () { + + function makeIncreaseByFunction(increaseByAmount) { + return function (numberToIncrease) { + return numberToIncrease + increaseByAmount; + }; + } + + var increaseBy3 = makeIncreaseByFunction(3); + var increaseBy5 = makeIncreaseByFunction(5); + + expect(increaseBy3(10) + increaseBy5(10)).toBe(28); + }); + + it("should allow extra function arguments", function () { + + function returnFirstArg(firstArg) { + return firstArg; + } + + expect(returnFirstArg("first", "second", "third")).toBe("first"); + + function returnSecondArg(firstArg, secondArg) { + return secondArg; + } + + expect(returnSecondArg("only give first arg")).toBe(undefined); + + function returnAllArgs() { + var argsArray = []; + for (var i = 0; i < arguments.length; i += 1) { + argsArray.push(arguments[i]); + } + return argsArray.join(","); + } + + expect(returnAllArgs("first", "second", "third")).toBe("first,second,third"); + }); + + it("should pass functions as values", function () { + + var appendRules = function (name) { + return name + " rules!"; + }; + + var appendDoubleRules = function (name) { + return name + " totally rules!"; + }; + + var praiseSinger = { givePraise: appendRules }; + expect(praiseSinger.givePraise("John")).toBe("John rules!"); + + praiseSinger.givePraise = appendDoubleRules; + expect(praiseSinger.givePraise("Mary")).toBe("Mary totally rules!"); + + }); + + it("should use function body as a string", function () { + var add = new Function("a", "b", "return a + b;"); + expect(add(1, 2)).toBe(3); + + var multiply = function (a, b) { + //An internal comment + return a * b; + }; + + var funcstring = multiply.toString(); + expect(multiply.toString()).toBe(funcstring); + }); +}); diff --git a/pool/shard011/JavaScript/0069451_commands.js b/pool/shard011/JavaScript/0069451_commands.js new file mode 100644 index 0000000000000000000000000000000000000000..6387eb50aa7c39d1d7cd7e184e05a439b82654b4 --- /dev/null +++ b/pool/shard011/JavaScript/0069451_commands.js @@ -0,0 +1,79 @@ +module.exports = function() { + // Register new commands via this method + this.regCommand = function(name, callback) { + + // Validate the command name + if (typeof name == 'string' && name.length >= 3 && name.length <= 20) { + + // Check if callback is a function + if (typeof callback == 'function') { + + /* + Check if the command isn't already registered, + if it is, replace the callback with the new one + */ + if (!this.availableCommands[name]) { + this.availableCommands[name] = {name:undefined, callback:undefined}; + this.availableCommands[name].name = name; + this.availableCommands[name].callback = callback; + } else { + this.availableCommands[name].callback = callback; + } + + } else { + callback({ + err: "regCommand: callback must be a function." + }); + } + } else { + callback({ + err: "regCommand: name must be a string with a length from 3 to (including) 20." + }); + } + } + + // Fire a command + this.fireCommand = function(name, data, callback, author) { + if (this.availableCommands[name]) { + var result = this.availableCommands[name].callback({ + command: name, + arguments: data, + err: data.err + }, author); + return callback( + result[0], + result[1] + ); + } + } + + // Extract the command name and arguments from a string + this.parseCommand = function(string) { + // Check if there is a slash in the beginning + if (string[0] == '/') { + var command = string.match( + /^(\/[\w]{3,20})[\s]*(.*)/ + ); // wtf? + + // Check if there were any results + if (command) { + // Remove the lash in the beginning of the command + if (command[1][0] == '/') { + command[1] = command[1].split('/').join(''); + + if (this.availableCommands[command[1]]) { + return { + full: command.input, + command: command[1], + arguments: command[2] + }; + } + } + } + } + return false; + } + + // List of available commands + this.availableCommands = {}; +} diff --git a/pool/shard011/JavaScript/0069453_change-password.client.controller.js b/pool/shard011/JavaScript/0069453_change-password.client.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..1d3501f6364266f90ad965345de1eb452fbbc343 --- /dev/null +++ b/pool/shard011/JavaScript/0069453_change-password.client.controller.js @@ -0,0 +1,41 @@ +(function() { + 'use strict'; + + angular + .module('users') + .controller('ChangePasswordController', ChangePasswordController); + + ChangePasswordController.$inject = ['$scope', 'usersService', 'authenticationService', 'passwordValidatorService']; + + function ChangePasswordController ($scope, usersService, authenticationService, passwordValidatorService) { + var vm = this; + + vm.changeUserPassword = changeUserPassword; + vm.popoverMsg = passwordValidatorService.getPopoverMsg; + vm.user = authenticationService.user; + + // Change user password + function changeUserPassword(isValid) { + vm.success = vm.error = null; + + if (!isValid) { + $scope.$broadcast('show-errors-check-validity', 'passwordForm'); + if($scope.passwordForm.newPassword.$error.weakpassword){ + vm.error='WEAK_PASSWORD'; + } + return false; + } + + usersService.changePassword(vm.passwordDetails) + .success(function (response) { + // If successful show success message and clear form + $scope.$broadcast('show-errors-reset', 'passwordForm'); + vm.success = true; + vm.passwordDetails = null; + }) + .error(function (response) { + vm.error = response.message; + }); + } + } +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069454_derivedClassFunctionOverridesBaseClassAccessor.js b/pool/shard011/JavaScript/0069454_derivedClassFunctionOverridesBaseClassAccessor.js new file mode 100644 index 0000000000000000000000000000000000000000..64da47e68e020d5b052330e83b77c81412aff4ac --- /dev/null +++ b/pool/shard011/JavaScript/0069454_derivedClassFunctionOverridesBaseClassAccessor.js @@ -0,0 +1,47 @@ +//// [derivedClassFunctionOverridesBaseClassAccessor.ts] +class Base { + get x() { + return 1; + } + set x(v) { + } +} + +// error +class Derived extends Base { + x() { + return 1; + } +} + +//// [derivedClassFunctionOverridesBaseClassAccessor.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var Base = (function () { + function Base() { + } + Object.defineProperty(Base.prototype, "x", { + get: function () { + return 1; + }, + set: function (v) { + }, + enumerable: true, + configurable: true + }); + return Base; +})(); +// error +var Derived = (function (_super) { + __extends(Derived, _super); + function Derived() { + _super.apply(this, arguments); + } + Derived.prototype.x = function () { + return 1; + }; + return Derived; +})(Base); diff --git a/pool/shard011/JavaScript/0069455_SHA256.js b/pool/shard011/JavaScript/0069455_SHA256.js new file mode 100644 index 0000000000000000000000000000000000000000..c2ee8168eae43256a2746cc42fe1c6334e28af73 --- /dev/null +++ b/pool/shard011/JavaScript/0069455_SHA256.js @@ -0,0 +1,110 @@ +kryptos.hash.SHA256 = function(str) { + inherit(this, new kryptos.hash.baseHash(str)); +} + +kryptos.hash.SHA256.digest_size = 32; + +kryptos.hash.SHA256.prototype = { + type : 'sha256' +}; + +// http://code.google.com/p/crypto-js/source/browse/branches/2.x/src/SHA256.js +// BSD license: http://www.opensource.org/licenses/bsd-license.php +if (!Components) { // Chrome + kryptos.hash.SHA256.prototype = { + digest: function() { + var hashData = kryptos.toByteArray(this.data); + + // Constants + var K = [ 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, + 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, + 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, + 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, + 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, + 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, + 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, + 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, + 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, + 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, + 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, + 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, + 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, + 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, + 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, + 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 ]; + + var m = kryptos.bytesToWords(hashData), + l = hashData.length * 8, + H = [ 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, + 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19 ], + w = [], + a, b, c, d, e, f, g, h, i, j, + t1, t2; + + // Padding + m[l >> 5] |= 0x80 << (24 - l % 32); + m[((l + 64 >> 9) << 4) + 15] = l; + + for (var i = 0; i < m.length; i += 16) { + a = H[0]; + b = H[1]; + c = H[2]; + d = H[3]; + e = H[4]; + f = H[5]; + g = H[6]; + h = H[7]; + + for (var j = 0; j < 64; j++) { + if (j < 16) { + w[j] = m[j + i]; + } else { + var gamma0x = w[j - 15], + gamma1x = w[j - 2], + gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ + ((gamma0x << 14) | (gamma0x >>> 18)) ^ + (gamma0x >>> 3), + gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ + ((gamma1x << 13) | (gamma1x >>> 19)) ^ + (gamma1x >>> 10); + + w[j] = gamma0 + (w[j - 7] >>> 0) + + gamma1 + (w[j - 16] >>> 0); + } + + var ch = e & f ^ ~e & g, + maj = a & b ^ a & c ^ b & c, + sigma0 = ((a << 30) | (a >>> 2)) ^ + ((a << 19) | (a >>> 13)) ^ + ((a << 10) | (a >>> 22)), + sigma1 = ((e << 26) | (e >>> 6)) ^ + ((e << 21) | (e >>> 11)) ^ + ((e << 7) | (e >>> 25)); + + t1 = (h >>> 0) + sigma1 + ch + (K[j]) + (w[j] >>> 0); + t2 = sigma0 + maj; + + h = g; + g = f; + f = e; + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + a = (t1 + t2) >>> 0; + } + + H[0] += a; + H[1] += b; + H[2] += c; + H[3] += d; + H[4] += e; + H[5] += f; + H[6] += g; + H[7] += h; + } + + return kryptos.fromByteArray(kryptos.wordsToBytes(H)); + } + }; +} diff --git a/pool/shard011/JavaScript/0069458_Link.js b/pool/shard011/JavaScript/0069458_Link.js new file mode 100644 index 0000000000000000000000000000000000000000..379a3f26f1a6368db14ef0aea73a85b475a4eab9 --- /dev/null +++ b/pool/shard011/JavaScript/0069458_Link.js @@ -0,0 +1,28 @@ +import React from 'react'; +import PropTypes from 'prop-types'; +import { Link as GatsbyLink } from 'gatsby'; + +const propTypes = { + children: PropTypes.any, + external: PropTypes.bool, + to: PropTypes.string.isRequired +}; + +const Link = ({ children, to, external, ...other }) => { + if (!external && /^\/(?!\/)/.test(to)) { + return ( + + {children} + + ); + } + + return ( +
    + {children} + + ); +}; +Link.propTypes = propTypes; + +export default Link; diff --git a/pool/shard011/JavaScript/0069461_keyCodeUtils.spec.js b/pool/shard011/JavaScript/0069461_keyCodeUtils.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..25352c743f8b95194c596e8db4a84be289b8bf4a --- /dev/null +++ b/pool/shard011/JavaScript/0069461_keyCodeUtils.spec.js @@ -0,0 +1,147 @@ +import * as keyCodeUtils from './keyCodeUtils' + +describe('calculateMovement', () => { + const state = { + bigJump: false, + mode: 'game', + showDie: false, + showLevelAccomplished: false, + } + + describe('returns undefined', () => { + it('if the mode is not `game`', () => { + const testState = { ...state, mode: 'menu' } + const action = { payload: { keyCode: 0 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toBe(undefined) + }) + + it('if the die-page is shown', () => { + const testState = { ...state, showDie: false } + const action = { payload: { keyCode: 0 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toBe(undefined) + }) + + it('if the level-accomplished-page is shown', () => { + const testState = { ...state, showLevelAccomplished: false } + const action = { payload: { keyCode: 0 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toBe(undefined) + }) + + it('if keyCode is no arrow or vim movement key', () => { + const action = { payload: { keyCode: 0 } } + expect(keyCodeUtils.calculateMovement(state, action)).toBe(undefined) + }) + }) + + describe('moves left', () => { + describe('without bigJump', () => { + it('on left-key', () => { + const action = { payload: { keyCode: 37 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: -1, y: 0 }) + }) + + it('on h-key', () => { + const action = { payload: { keyCode: 72 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: -1, y: 0 }) + }) + }) + + describe('with bigJump', () => { + it('on left-key', () => { + const testState = { ...state, bigJump: true } + const action = { payload: { keyCode: 37 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: -2, y: 0 }) + }) + + it('on h-key', () => { + const testState = { ...state, bigJump: true } + const action = { payload: { keyCode: 72 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: -2, y: 0 }) + }) + }) + }) + + describe('moves right', () => { + describe('without bigJump', () => { + it('on right-key', () => { + const action = { payload: { keyCode: 39 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 1, y: 0 }) + }) + + it('on l-key', () => { + const action = { payload: { keyCode: 76 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 1, y: 0 }) + }) + }) + + describe('with bigJump', () => { + const testState = { ...state, bigJump: true } + + it('on right-key', () => { + const action = { payload: { keyCode: 39 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 2, y: 0 }) + }) + + it('on l-key', () => { + const action = { payload: { keyCode: 76 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 2, y: 0 }) + }) + }) + }) + + describe('moves up', () => { + describe('without bigJump', () => { + it('on up-key', () => { + const action = { payload: { keyCode: 38 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 0, y: -1 }) + }) + + it('on k-key', () => { + const action = { payload: { keyCode: 75 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 0, y: -1 }) + }) + }) + + describe('with bigJump', () => { + const testState = { ...state, bigJump: true } + + it('on up-key', () => { + const action = { payload: { keyCode: 38 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 0, y: -2 }) + }) + + it('on k-key', () => { + const action = { payload: { keyCode: 75 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 0, y: -2 }) + }) + }) + }) + + describe('moves down', () => { + describe('without bigJump', () => { + it('on down-key', () => { + const action = { payload: { keyCode: 40 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 0, y: 1 }) + }) + + it('on j-key', () => { + const action = { payload: { keyCode: 74 } } + expect(keyCodeUtils.calculateMovement(state, action)).toEqual({ x: 0, y: 1 }) + }) + }) + + describe('with bigJump', () => { + it('on down-key', () => { + const testState = { ...state, bigJump: true } + const action = { payload: { keyCode: 40 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 0, y: 2 }) + }) + + it('on j-key', () => { + const testState = { ...state, bigJump: true } + const action = { payload: { keyCode: 74 } } + expect(keyCodeUtils.calculateMovement(testState, action)).toEqual({ x: 0, y: 2 }) + }) + }) + }) +}) diff --git a/pool/shard011/JavaScript/0069462_index.js b/pool/shard011/JavaScript/0069462_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d929fb7e740a301f36a7119c903f9e3502d7cfc3 --- /dev/null +++ b/pool/shard011/JavaScript/0069462_index.js @@ -0,0 +1,43 @@ +var fs = require('fs'); + +/** +* Metalsmith plugin to read json data from directory and make it available as metadata.json +* +* @param {Object} opts +* @return {Function} +*/ + +function plugin(opts){ + var obj = {}; + var dir = opts.dir; + var stats = fs.lstatSync(dir); + + if (stats.isDirectory()) { + fs.readdir(dir, function(err, files) { + files.forEach(function (file) { + if (file.indexOf('.json') !== -1) { + var path = dir + file; + var basename = file.slice(0, -5); + + fs.readFile(path, 'utf8', function (err, data) { + if (err) { throw err; } + obj[basename] = JSON.parse(data); + }); + } + }); + }); + } + + return function(files, metalsmith, done){ + var metadata = metalsmith.metadata(); + metadata.json = obj; + done(); + }; + +} + +/** +* Expose `plugin`. +*/ + +module.exports = plugin; diff --git a/pool/shard011/JavaScript/0069463_app.js b/pool/shard011/JavaScript/0069463_app.js new file mode 100644 index 0000000000000000000000000000000000000000..96f4b5566271cfcac63e45936f2e0597d215de3a --- /dev/null +++ b/pool/shard011/JavaScript/0069463_app.js @@ -0,0 +1,78 @@ +/* + Copyright (c) 2015 The Polymer Project Authors. All rights reserved. + This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt + The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt + The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt + Code distributed by Google as part of the polymer project is also + subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt + */ + +(function(document) { + 'use strict'; + + // Grab a reference to our auto-binding template + // and give it some initial binding values + // Learn more about auto-binding templates at http://goo.gl/Dx1u2g + var app = document.querySelector('#app'); + + // Sets app default base URL + app.baseUrl = '/'; + if (window.location.port === '') { // if production + // Uncomment app.baseURL below and + // set app.baseURL to '/your-pathname/' if running from folder in production + // app.baseUrl = '/polymer-starter-kit/'; + } + + app.displayInstalledToast = function() { + // Check to make sure caching is actually enabled—it won't be in the dev environment. + if (!Polymer.dom(document).querySelector('platinum-sw-cache').disabled) { + Polymer.dom(document).querySelector('#caching-complete').show(); + } + }; + + // Listen for template bound event to know when bindings + // have resolved and content has been stamped to the page + app.addEventListener('dom-change', function() { + console.log('Our app is ready to rock!'); + }); + + // See https://github.com/Polymer/polymer/issues/1381 + window.addEventListener('WebComponentsReady', function() { + // imports are loaded and elements have been registered + }); + + // Main area's paper-scroll-header-panel custom condensing transformation of + // the appName in the middle-container and the bottom title in the bottom-container. + // The appName is moved to top and shrunk on condensing. The bottom sub title + // is shrunk to nothing on condensing. + window.addEventListener('paper-header-transform', function(e) { + var appName = Polymer.dom(document).querySelector('#mainToolbar .app-name'); + var middleContainer = Polymer.dom(document).querySelector('#mainToolbar .middle-container'); + var detail = e.detail; + var heightDiff = detail.height - detail.condensedHeight; + var yRatio = Math.min(1, detail.y / heightDiff); + // appName max size when condensed. The smaller the number the smaller the condensed size. + var maxMiddleScale = 0.50; + var auxHeight = heightDiff - detail.y; + var auxScale = heightDiff / (1 - maxMiddleScale); + var scaleMiddle = Math.max(maxMiddleScale, auxHeight / auxScale + maxMiddleScale); + var scaleBottom = 1 - yRatio; + + // Move/translate middleContainer + Polymer.Base.transform('translate3d(0,' + yRatio * 100 + '%,0)', middleContainer); + + + // Scale middleContainer appName + Polymer.Base.transform('scale(' + scaleMiddle + ') translateZ(0)', appName); + }); + + // Scroll page to top and expand header + app.scrollPageToTop = function() { + app.$.headerPanelMain.scrollToTop(true); + }; + + app.closeDrawer = function() { + app.$.paperDrawerPanel.closeDrawer(); + }; + +})(document); diff --git a/pool/shard011/JavaScript/0069466_karma.conf.js b/pool/shard011/JavaScript/0069466_karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..cdf05f38da5918f860393a774e12420873ef640c --- /dev/null +++ b/pool/shard011/JavaScript/0069466_karma.conf.js @@ -0,0 +1,103 @@ +'use strict'; + +var path = require('path'); +var conf = require('./gulp/conf'); + +var _ = require('lodash'); +var wiredep = require('wiredep'); + +var pathSrcHtml = [ + path.join(conf.paths.src, '/**/*.html') +]; + +function listFiles() { + var wiredepOptions = _.extend({}, conf.wiredep, { + dependencies: true, + devDependencies: true + }); + + var patterns = wiredep(wiredepOptions).js + .concat([ + path.join(conf.paths.tmp, '/serve/app/index.module.js'), + ]) + .concat(pathSrcHtml); + + var files = patterns.map(function(pattern) { + return { + pattern: pattern + }; + }); + files.push({ + pattern: path.join(conf.paths.src, '/assets/**/*'), + included: false, + served: true, + watched: false + }); + return files; +} + +module.exports = function(config) { + + var configuration = { + files: listFiles(), + + singleRun: true, + + autoWatch: false, + + ngHtml2JsPreprocessor: { + stripPrefix: conf.paths.src + '/', + moduleName: 'rigiViewerWeb' + }, + + logLevel: 'WARN', + + frameworks: ['phantomjs-shim', 'jasmine'], + + browsers : ['PhantomJS'], + + plugins : [ + 'karma-phantomjs-launcher', + 'karma-phantomjs-shim', + 'karma-coverage', + 'karma-jasmine', + 'karma-ng-html2js-preprocessor' + ], + + coverageReporter: { + type : 'html', + dir : 'coverage/' + }, + + reporters: ['progress'], + + proxies: { + '/assets/': path.join('/base/', conf.paths.src, '/assets/') + } + }; + + // This is the default preprocessors configuration for a usage with Karma cli + // The coverage preprocessor is added in gulp/unit-test.js only for single tests + // It was not possible to do it there because karma doesn't let us now if we are + // running a single test or not + configuration.preprocessors = {}; + pathSrcHtml.forEach(function(path) { + configuration.preprocessors[path] = ['ng-html2js']; + }); + + // This block is needed to execute Chrome on Travis + // If you ever plan to use Chrome and Travis, you can keep it + // If not, you can safely remove it + // https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076 + if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) { + configuration.customLaunchers = { + 'chrome-travis-ci': { + base: 'Chrome', + flags: ['--no-sandbox'] + } + }; + configuration.browsers = ['chrome-travis-ci']; + } + + config.set(configuration); +}; diff --git a/pool/shard011/JavaScript/0069467_colorContributions.js b/pool/shard011/JavaScript/0069467_colorContributions.js new file mode 100644 index 0000000000000000000000000000000000000000..d87760e0b5b1d19a6ee9106f6d3912e9465b2497 --- /dev/null +++ b/pool/shard011/JavaScript/0069467_colorContributions.js @@ -0,0 +1,41 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ +// import color detector contribution +import './colorDetector.js'; +import { Disposable } from '../../../base/common/lifecycle.js'; +import { registerEditorContribution } from '../../browser/editorExtensions.js'; +import { ModesHoverController } from '../hover/hover.js'; +import { Range } from '../../common/core/range.js'; +export class ColorContribution extends Disposable { + constructor(_editor) { + super(); + this._editor = _editor; + this._register(_editor.onMouseDown((e) => this.onMouseDown(e))); + } + dispose() { + super.dispose(); + } + onMouseDown(mouseEvent) { + var _a; + const targetType = mouseEvent.target.type; + if (targetType !== 6 /* CONTENT_TEXT */) { + return; + } + const hoverOnColorDecorator = [...((_a = mouseEvent.target.element) === null || _a === void 0 ? void 0 : _a.classList.values()) || []].find(className => className.startsWith('ced-colorBox')); + if (!hoverOnColorDecorator) { + return; + } + if (!mouseEvent.target.range) { + return; + } + const hoverController = this._editor.getContribution(ModesHoverController.ID); + if (!hoverController.isColorPickerVisible()) { + const range = new Range(mouseEvent.target.range.startLineNumber, mouseEvent.target.range.startColumn + 1, mouseEvent.target.range.endLineNumber, mouseEvent.target.range.endColumn + 1); + hoverController.showContentHover(range, 0 /* Delayed */, false); + } + } +} +ColorContribution.ID = 'editor.contrib.colorContribution'; // ms +registerEditorContribution(ColorContribution.ID, ColorContribution); diff --git a/pool/shard011/JavaScript/0069471_AbstractFactory.js b/pool/shard011/JavaScript/0069471_AbstractFactory.js new file mode 100644 index 0000000000000000000000000000000000000000..7a36c2b1e7caee2f306fb593028752ad6dd99083 --- /dev/null +++ b/pool/shard011/JavaScript/0069471_AbstractFactory.js @@ -0,0 +1,97 @@ +'use strict'; + +class AbstractFactory { + constructor() { + console.log("AbstractFactory class created"); + } + + createProductA(product) { + console.log("AbstractFactory.createProductA created"); + } + + createProductB(product) { + console.log("AbstractFactory.createProductB created"); + } +} + +class ConcreteFactory1 extends AbstractFactory { + constructor() { + super(); + console.log("ConcreteFactory1 class created"); + } + + createProductA(product) { + console.log('ConcreteFactory1 createProductA'); + return new ProductA1(); + } + + createProductB(product) { + console.log('ConcreteFactory1 createProductB'); + return new ProductB1(); + } +} + +class ConcreteFactory2 extends AbstractFactory { + constructor() { + super(); + console.log("ConcreteFactory2 class created"); + } + + createProductA(product) { + console.log('ConcreteFactory2 createProductA'); + return new ProductA2(); + } + + createProductB(product) { + console.log('ConcreteFactory2 createProductB'); + return new ProductB2(); + } +} + +class AbstractProductA { + constructor() { + console.log('AbstractProductA class created'); + } +} + +class AbstractProductB { + constructor() { + console.log('AbstractProductB class created'); + } +} + +class ProductA1 extends AbstractProductA { + constructor() { + super(); + console.log('ProductA1 class created'); + } +} + +class ProductA2 extends AbstractProductA { + constructor() { + super(); + console.log('ProductA2 class created'); + } +} + +class ProductB1 extends AbstractProductB { + constructor() { + super(); + console.log('ProductB1 class created'); + } +} + +class ProductB2 extends AbstractProductB { + constructor() { + super(); + console.log('ProductB2 class created'); + } +} + +var factory1 = new ConcreteFactory1(); +var productB1 = factory1.createProductB(); +var productA1 = factory1.createProductA(); + +var factory2 = new ConcreteFactory2(); +var productA2 = factory2.createProductA(); +var productB2 = factory2.createProductB(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069475_index.js b/pool/shard011/JavaScript/0069475_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d20df7023858a717579d8c888d72059d8a1fd872 --- /dev/null +++ b/pool/shard011/JavaScript/0069475_index.js @@ -0,0 +1,199 @@ +"use strict"; + +var express = require('express'); +var router = express.Router(); +var Client = require('node-rest-client').Client; +var client = new Client(); +var url = require('url'); + +// For REST calls to the '/tasks' service +var tasksRoute = '/api/v1/tasks'; +var tasksProtocol = 'http'; +var tasksPort = process.env.TASKS_PORT || 8081; +var tasksDomain = process.env.TASKS_DOMAIN || '192.168.33.33'; // as configured in Vagrantfile +var tasksUrl = url.resolve(tasksProtocol + "://" + tasksDomain + ":" + tasksPort, tasksRoute); + +// Non-persistent items list +var nonPersistentItems = [ + { id: 1, text: 'vagrant up', complete: true }, + { id: 2, text: 'Login through VirtualBox as vagrant', complete: true }, + { id: 3, text: 'startxfce4 &', complete: true }, + { id: 4, text: 'cd /var/www/node/', complete: true }, + { id: 5, text: 'npm install', complete: true}, + { id: 6, text: 'npm start', complete: true }, + { id: 7, text: 'Browse to 192.168.33.33:8080 from the host', complete: true }, + { id: 8, text: 'Add, change status, and delete tasks', complete: false } +]; + +var persistentItems = []; + +var nonPersistentTaskFoundAtIndex; +var searchForId; +function getNonPersistentTaskFromArrayById(element, index, array) { + nonPersistentTaskFoundAtIndex = -1; + if (element.id == searchForId) { + nonPersistentTaskFoundAtIndex = index; + return true; + } + return false; +}; + + +// My Task List home page +router.get('/', function (req, res) { + client.get(tasksUrl, function (data, response) { + if (response.statusCode === 200) { + persistentItems = data; + res.render('index', { + title: 'My Task List', + nonPersistentTasks: nonPersistentItems, + persistentTasks: persistentItems + }); + } + else { + res.render('errorPage', { + title: "Couldn't load tasks!", + body: "Please try reloading the page in a few minutes" + }); + } + }); +}); + +// Post/add to the non-persistent list +router.post('/nonPersistentTasks', function (req, res) { + nonPersistentItems.push({ + id: nonPersistentItems.length + 1, + text: req.body.newNonPersistentTaskName, + complete: false + }); + + // Send back to home / refresh view + res.redirect('/'); +}); + +// Complete a task from the nonPersistent list +router.get('/nonPersistentTasks/:id/complete', function (req, res) { + searchForId = req.params.id; + nonPersistentItems.find(getNonPersistentTaskFromArrayById); + + // If found, change to complete at that index + if (nonPersistentTaskFoundAtIndex > -1) { + nonPersistentItems[nonPersistentTaskFoundAtIndex].complete = true; + } + + // Send back to home / refresh view + res.redirect('/'); +}); + +// Incomplete a task from the nonPersistent list +router.get('/nonPersistentTasks/:id/incomplete', function (req, res) { + searchForId = req.params.id; + nonPersistentItems.find(getNonPersistentTaskFromArrayById); + + // If found, change to incomplete at that index + if (nonPersistentTaskFoundAtIndex > -1) { + nonPersistentItems[nonPersistentTaskFoundAtIndex].complete = false; + } + + // Send back to home / refresh view + res.redirect('/'); +}); + +// Remove a task from the nonPersistent list +router.get('/nonPersistentTasks/:id/delete', function (req, res) { + searchForId = req.params.id; + nonPersistentItems.find(getNonPersistentTaskFromArrayById); + + // If found, remove 1 item from that index + if (nonPersistentTaskFoundAtIndex > -1) { + nonPersistentItems.splice(nonPersistentTaskFoundAtIndex, 1); + } + + // Send back to home / refresh view + res.redirect('/'); +}); + +/////////////////////////////////////////////////////////////////// + +// Post to the persistent list +router.post('/persistentTasks', function (req, res) { + postPersistentTask(req.body.newPersistentTaskName, false, res); +}); + +// Patch to the persistent list +router.get("/persistentTasks/:id/complete", function (req, res) { + patchTaskCompleteStatus(req.params.id, true, res); +}); + +// Patch to the persistent list +router.get("/persistentTasks/:id/incomplete", function (req, res) { + patchTaskCompleteStatus(req.params.id, false, res); +}); + +// Delete from the persistent list +router.get("/persistentTasks/:id/delete", function (req, res) { + deleteTask(req.params.id, res); +}); + +function postPersistentTask(text, complete, res) { + var args = { + data: { + text: text, + complete: complete + }, + headers: { "Content-Type": "application/json" } + } + + client.post(tasksUrl, args, function (data, response) { + if (response.statusCode !== 201) { + console.log('Error: status code = ' + response.statusCode); + res.status(response.statusCode).send("Well, that didn't seem to work out so well. [" + response.statusCode + "]"); + } + else { + // Send back to home / refresh view + res.redirect("/"); + } + }); +} + +function patchTaskCompleteStatus(id, complete, res) { + var args = { + data: { + complete: complete + }, + headers: { "Content-Type": "application/json" } + } + + var thisUrl = tasksUrl + "/" + id; + client.patch(thisUrl, args, function (data, response) { + if (response.statusCode !== 200) { + console.log('Error: status code = ' + response.statusCode); + res.status(response.statusCode).send("Well, that didn't seem to work out so well. [" + response.statusCode + "]"); + } + else { + // Send back to home / refresh view + res.redirect("/"); + } + }); +} + +function deleteTask(id, res) { + var args = { + data: {}, + headers: { "Content-Type": "application/json" } + } + + var thisUrl = tasksUrl + "/" + id; + client.delete(thisUrl, args, function (data, response) { + if (response.statusCode !== 200) { + console.log('Error: status code = ' + response.statusCode); + res.status(response.statusCode).send("Well, that didn't seem to work out so well. [" + response.statusCode + "]"); + } + else { + // Send back to home / refresh view + res.redirect("/"); + } + }); +} + +module.exports = router; diff --git a/pool/shard011/JavaScript/0069476_MenuGroup.js b/pool/shard011/JavaScript/0069476_MenuGroup.js new file mode 100644 index 0000000000000000000000000000000000000000..565685a01ceb72eaf6bf620e8f36fa26fc553e2e --- /dev/null +++ b/pool/shard011/JavaScript/0069476_MenuGroup.js @@ -0,0 +1,65 @@ +/* + * Sonatype Nexus (TM) Open Source Version + * Copyright (c) 2008-present Sonatype, Inc. + * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. + * + * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, + * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. + * + * Sonatype Nexus (TM) Open Source Version is distributed with Sencha Ext JS pursuant to a FLOSS Exception agreed upon + * between Sonatype, Inc. and Sencha Inc. Sencha Ext JS is licensed under GPL v3 and cannot be redistributed as part of a + * closed source work. + * + * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks + * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the + * Eclipse Foundation. All other trademarks are the property of their respective owners. + */ +/*global Ext, NX*/ + +/** + * Menu group controller. + * + * @since 3.0 + */ +Ext.define('NX.controller.MenuGroup', { + extend: 'NX.app.Controller', + requires: [ + 'NX.Bookmarks' + ], + + views: [ + 'feature.Group' + ], + + /** + * @override + */ + init: function () { + var me = this; + + me.listen({ + component: { + 'nx-feature-group dataview': { + selectionchange: me.onSelection + } + } + }); + }, + + /** + * Invoked when {@link NX.view.feature.Group} item is selected. + * + * @private + * @param {NX.view.feature.Group} view + * @param {NX.model.Feature[]} records + */ + onSelection: function (view, records) { + var feature; + + if (records.length > 0) { + feature = records[0]; + NX.Bookmarks.navigateTo(NX.Bookmarks.fromToken(feature.get('bookmark')), this); + } + } + +}); diff --git a/pool/shard011/JavaScript/0069480_dom.js b/pool/shard011/JavaScript/0069480_dom.js new file mode 100644 index 0000000000000000000000000000000000000000..7676e6f3afcbbb391912bbd01a87f65b058ab18f --- /dev/null +++ b/pool/shard011/JavaScript/0069480_dom.js @@ -0,0 +1,159 @@ +import _ from './__'; + + +/** + * DOM + */ +class DOM { + + + /** + * jQuery like selector type, $$ for double the fun. + * + * @param {String} selector ID, className or a html structure string. + * @param {Object} Selector's context, able to .find inside HTMLElements to narrow results. + * @return {HTMLElement|[]} + */ + $$(selector, context) { + context = context || document; + + let el; + + if (this.isHTML(selector)) { + el = this.htmlToHTMLElement(selector); + } else { + el = context.querySelectorAll(selector); + el = el.length === 1 ? el[0] : el; + } + + return el; + } + + + /** + * Creates a new DOMElement with properties. + * + * @param {String} tag - HTML tag name to create. + * @param {Object} properties - HTML propreties to apply. + * @param {Object} attributes - HTML attributes to apply. + */ + createEl(tag = 'div', properties = {}, attributes = {}) { + let el = document.createElement(tag); + + // assign properties. + Object.getOwnPropertyNames(properties).forEach(propertyName => { + let property = properties[propertyName]; + el[propertyName] = property; + }); + + // assign attributes. + Object.getOwnPropertyNames(properties).forEach(attributeName => { + let attribute = properties[attributeName]; + el.setAttribute(attributeName, attribute); + }); + + return el; + } + + + /** + * Converts HTMLString to HTMLElement. + * + * @param {String} HTML representing a single element + * @return {HTMLElement} + */ + htmlToHTMLElement(html) { + var template = document.createElement('template'); + template.innerHTML = html; + + return template.content.firstChild; + } + + + /** + * Getter for the body + * + * @return {HTMLElement} + */ + getBody() { + return this.$$('body'); + } + + + /** + * Check whether the string input is in an valid XML/HTML format. + * + * @param {String} input + * @return {Boolean} + */ + isHTML(input) { + let matchHTML = new RegExp('<([A-Za-z][A-Za-z0-9]*)\\b[^>]*>(.*?)'); + + return matchHTML.test(input); + } + + + /** + * Appends an html element to another html element. + * + * @param {HTMLElement} el + * @param {HTMLElement} dst + * @return {DOM} Instance for chaning + */ + append(el, dst) { + if (!dst || !_.isElement(dst)) { + console.log('Err, not a proper selector'); + return this; + } + + if (_.isArray(el)) { + for (let i = 0, len = el.length; i < len; i++) { + this.append(el[i], dst); + } + + return this; + } + + if (!el || this.isHTML(el)) { + el = this.$$(el); + } + + dst.appendChild(el); + + return this; + } + + + /** + * Getter for a selectors physical dimensions. + * + * @param {String} selector to locate + * @return {Object} + */ + getDimensions(selector) { + let style = this.getStyle(selector); + + return { + width: Number(style.width.replace('px', '')), + height: Number(style.height.replace('px', '')) + }; + } + + + /** + * Getter for a selector's computed style. + * + * @param {String} selector to locate + * @return {Object|null} ComputedStyle properties of the selector + */ + getStyle(selector) { + if (0 === this.$$(selector).length) { + console.log(['ERROR: selector was not found.', selector]); + return; + } + return window.getComputedStyle(this.$$(selector)); + } + +} + +export default new DOM(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069481_test-tls-junk-closes-server.js b/pool/shard011/JavaScript/0069481_test-tls-junk-closes-server.js new file mode 100644 index 0000000000000000000000000000000000000000..b0e29ec9f8cffc42870282b86ea781f2414e52d9 --- /dev/null +++ b/pool/shard011/JavaScript/0069481_test-tls-junk-closes-server.js @@ -0,0 +1,49 @@ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +'use strict'; +const common = require('../common'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +const tls = require('tls'); +const fs = require('fs'); +const net = require('net'); + +const options = { + key: fs.readFileSync(`${common.fixturesDir}/keys/agent2-key.pem`), + cert: fs.readFileSync(`${common.fixturesDir}/keys/agent2-cert.pem`) +}; + +const server = tls.createServer(options, common.mustNotCall()); + +server.listen(0, common.mustCall(function() { + const c = net.createConnection(this.address().port); + + c.on('connect', common.mustCall(function() { + c.write('blah\nblah\nblah\n'); + })); + + c.on('end', common.mustCall(function() { + server.close(); + })); +})); diff --git a/pool/shard011/JavaScript/0069482_History.js b/pool/shard011/JavaScript/0069482_History.js new file mode 100644 index 0000000000000000000000000000000000000000..2cc946488c2f4d64dbd63648921adefe50520915 --- /dev/null +++ b/pool/shard011/JavaScript/0069482_History.js @@ -0,0 +1,118 @@ +define(['summernote/core/range', 'summernote/core/dom'], function (range, dom) { // ODOO: suggest upstream + /** + * @class editing.History + * + * Editor History + * + */ + var History = function ($editable) { + var stack = [], stackOffset = -1; + var editable = $editable[0]; + + var makeSnapshot = function () { + var rng = range.create(); + var emptyBookmark = {s: {path: [], offset: 0}, e: {path: [], offset: 0}}; + + return { + contents: $editable.html(), + bookmark: (rng && dom.ancestor(rng.sc, dom.isEditable) ? rng.bookmark(editable) : emptyBookmark) + // ODOO: suggest upstream added " && dom.ancestor(rng.sc, dom.isEditable) " + }; + }; + + var applySnapshot = function (snapshot) { + if (snapshot.contents !== null) { + $editable.html(snapshot.contents); + } + if (snapshot.bookmark !== null) { + range.createFromBookmark(editable, snapshot.bookmark).select(); + } + }; + + /** + * undo + */ + this.undo = function () { + // Create snap shot if not yet recorded + if ($editable.html() !== stack[stackOffset].contents) { + this.recordUndo(); + } + + if (0 < stackOffset) { + stackOffset--; + applySnapshot(stack[stackOffset]); + } + }; + + /* ODOO: to suggest upstream */ + this.hasUndo = function () { + return 0 < stackOffset; + }; + + /** + * redo + */ + this.redo = function () { + if (stack.length - 1 > stackOffset) { + stackOffset++; + applySnapshot(stack[stackOffset]); + } + }; + + /* ODOO: to suggest upstream */ + this.hasRedo = function () { + return stack.length - 1 > stackOffset; + }; + + var last; // ODOO: to suggest upstream (since we may have several editor) + /** + * recorded undo + */ + this.recordUndo = function () { + // ODOO: method totally rewritten + // test event for firefox: remove stack of history because event doesn't exists + var key = typeof event !== 'undefined' ? event : false; + if (key && !event.metaKey && !event.ctrlKey && !event.altKey && event.type === "keydown") { + key = event.type + "-"; + if (event.which === 8 || event.which === 46) key += 'delete'; + else if (event.which === 13) key += 'enter'; + else key += 'other'; + if (key === last) return; + hasUndo = true; + } + last = key; + + // Wash out stack after stackOffset + if (stack.length > stackOffset+1) { + stack = stack.slice(0, stackOffset+1); + } + + if (stack[stackOffset] && stack[stackOffset].contents === $editable.html()) { + return; + } + + stackOffset++; + + // Create new snapshot and push it to the end + stack.push(makeSnapshot()); + }; + + /* ODOO: to suggest upstream */ + this.splitNext = function () { + last = false; + }; + + /* ODOO: to suggest upstream */ + this.reset = function () { + last = false; + stack = []; + stackOffset = -1; + this.recordUndo(); + }; + + // Create first undo stack + this.recordUndo(); + }; + + return History; +}); diff --git a/pool/shard011/JavaScript/0069487_search.js b/pool/shard011/JavaScript/0069487_search.js new file mode 100644 index 0000000000000000000000000000000000000000..d998106bab629f7e0303852dd845111e15b529b3 --- /dev/null +++ b/pool/shard011/JavaScript/0069487_search.js @@ -0,0 +1,27 @@ +Search = function() { + this._timeout = null; + this._initHandlers(); +} + +Search.prototype = { + _initHandlers: function() { + $('a.topbar__right').on("click",function () { + $('.topbar__search').focus(); + return false; + }); + + $('.empty_search').on("click",function () { + $('.topbar__search').val(''); + RemoteEvent.create("showstyles"); + }); + var that = this; + $(".topbar__search").on("keyup", function() { + clearTimeout(that._timeout); + var t = $(this); + that._timeout = setTimeout(function() { + RemoteEvent.create("search", t.val()); + },500); + }); + } + +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069491_game.js b/pool/shard011/JavaScript/0069491_game.js new file mode 100644 index 0000000000000000000000000000000000000000..648c86b9029b8accc7f03501ce5f6468a8f8ceb7 --- /dev/null +++ b/pool/shard011/JavaScript/0069491_game.js @@ -0,0 +1,23 @@ +module.exports = (sequelize, DataTypes) => { + const Game = sequelize.define('Game', { + gameNumber: DataTypes.INTEGER, + rank: DataTypes.INTEGER, + outcome: DataTypes.TEXT, + }, { + hooks: { + beforeCreate: (game, options) => { + return Game + .findAll({ + attributes: [[sequelize.fn('MAX', sequelize.col('gameNumber')), 'maxGameNumber']] + }) + .then((games) => game.gameNumber = games[0].get('maxGameNumber') + 1); + } + }, + classMethods: { + associate(models) { + // associations can be defined here + } + } + }); + return Game; +}; diff --git a/pool/shard011/JavaScript/0069492_user.js b/pool/shard011/JavaScript/0069492_user.js new file mode 100644 index 0000000000000000000000000000000000000000..05144b9cf98c40e9c730d244eb284157568e8c37 --- /dev/null +++ b/pool/shard011/JavaScript/0069492_user.js @@ -0,0 +1,71 @@ +//Array to store users +var users = []; + +exports.printMethodUrl = function (req, res) { + res.json(req.method + ' ' + req.url); +}; + +//Creating user method +exports.create = function (req, res) { + var user = req.body.user; + if (user) { + user.id = Number(user.id); + users.push(user); + res.json(200, {message: 'User created!'}); + } + else { + res.json(400, {message: 'Invalid input, try again'}); + } +}; + +//Reading users array method +exports.read = function (req, res) { + if (req.params.id) { + var id = Number(req.params.id); + for (var i = 0; i < users.length; i++) { + if (users[i].id === id) { + res.json(200, users[i]); + } + } + res.json(400, {message: 'User not found'}); + } + else { + res.json(200, users); + } +}; + +//Update user info method +exports.update = function (req, res) { + var user = req.body.user; + if (user) { + user.id = Number(user.id); + for (var i = 0; i < users.length; i++) { + if (users[i].id === user.id) { + users[i] = user; + res.json(200, {message: 'User updated!'}); + } + } + res.json(400, {message: 'User not found'}); + } + else { + res.json(400, {message: 'Invalid input, try again'}); + } +}; + +//Delete user method +exports.delete = function (req, res) { + var user = req.body.user; + if (user) { + user.id = Number(user.id); + for (var i = 0; i < users.length; i++) { + if (users[i].id === user.id) { + users.splice(i, 1); + res.json(200, {message: 'User deleted!'}); + } + } + res.json(400, {message: 'User not found'}); + } + else { + res.json(400, {message: 'Invalid input, try again'}); + } +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069493_permission.js b/pool/shard011/JavaScript/0069493_permission.js new file mode 100644 index 0000000000000000000000000000000000000000..64fc1f386f87fe9fb0b88a6b134b5f67a37583c8 --- /dev/null +++ b/pool/shard011/JavaScript/0069493_permission.js @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2014 Hewlett-Packard Development Company, L.P. + * + * 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. + */ + +/** + * Permission provider, which hides particular controls based on whether the + * passed permission flag has been set. + */ +angular.module('sb.util').directive('permission', + function ($log, PermissionManager) { + 'use strict'; + + return { + restrict: 'A', + link: function ($scope, element, attrs) { + // Start by hiding it. + element.hide(); + + var permName = attrs.permission; + var permValue = attrs.permissionValue || true; + + PermissionManager.listen($scope, permName, + function (actualValue) { + + if (!!actualValue && + actualValue.toString() === permValue.toString()) { + element.show(); + } else { + element.hide(); + } + } + ); + } + }; + }); diff --git a/pool/shard011/JavaScript/0069494_uploadView.js b/pool/shard011/JavaScript/0069494_uploadView.js new file mode 100644 index 0000000000000000000000000000000000000000..6070f08fdcf9257fd4a664341e07253a0d1c790b --- /dev/null +++ b/pool/shard011/JavaScript/0069494_uploadView.js @@ -0,0 +1,143 @@ +define(["plugins/http", 'durandal/app'], function (http, app) { + var ctor = function (file, replacing, brainWave) { + var that = this; + + this.file = file; //File to be replaced, if replacing + this.replacing = replacing; //Bool asking if replacing + this.brainWave = brainWave; //Reference to brainwave.js + this.processing = false; + + this.attached = function () { + if (that.replacing) { + $("#displayName").attr("value", file.DisplayName); + $("#description").attr("value", file.Description); + } + }; + + this.canDeactivate = function () { + return !that.processing; + }; + + this.getCantDeactivateReason = function () { + return "Please wait for the dialog to finish processing before closing."; + } + + this.handleSelectedFile = function () { + $("#submit").prop("disabled", false); + $("#required").hide(); + $("#confirmation").html(""); //Clear upload confirmation + }; + + this.submit = function () { + $("#confirmation").html(""); //Clear upload confirmation + + var file = $("#fileUpload")[0].files[0]; //Get the new file + var displayName = $("#displayName").val(); //Get display name of file + if (displayName == null || displayName === "") { //If no display name given, set to file name + displayName = file.name; + } + var description = $("#description").val(); //Get description of file + var authorName = "Sam"; + var fileType = "." + file.name.split(".").pop(); //Get the file type from the file name + + if (that.replacing) { + that.replace(file, displayName, description, fileType, authorName); + } else { + that.upload(file, displayName, description, fileType, authorName); + } + }; + + this.replace = function (file, displayName, description, fileType, authorName) { + var r = new FileReader(); + + r.onload = function (fileEvent) { //Based off of old code + var readFile = fileEvent.target.result; //Get file from binary string reading + var data = { //Create http post header file + Id: that.file.Id, + Body: readFile, //File to be uploaded + DisplayName: displayName, //File's name + AuthorId: 1, //Authored by admin x + AuthorName: authorName, //Author's name (potentially resolved by login, but for now is a dummy user) + FileType: fileType, //Type of the file + Description: description //File description + }; + + try { + fileEvent.preventDefault(); //Prevent stuff + that.processing = true; + http.post("api/BrainWaveFiles", data).then( //Send file to database + function (response) { //After upload + that.messageResponse(response, true); + }).fail( + function () { + $("#confirmation").html("Upload Failed"); + }).always(function() { + that.processing = false; + }); + } catch (e) { + alert(e); //Error? Notify the user + } + } + + r.readAsBinaryString(file); //Read file + }; + + this.upload = function (file, displayName, description, fileType, authorName) { + var r = new FileReader(); + + r.onload = function (fileEvent) { //Based off of old code + var readFile = fileEvent.target.result; //Get file from binary string reading + var data = { //Create http post header file + Body: readFile, //File to be uploaded + DisplayName: displayName, //File's name + AuthorId: 1, //Authored by admin x + AuthorName: authorName, //Author's name (potentially resolved by login, but for now is a dummy user) + FileType: fileType, //Type of the file + Description: description //File description + }; + + try { + fileEvent.preventDefault(); //Prevent stuff + that.processing = true; + http.put("api/BrainWaveFiles", data).then( //Send file to database + function (response) { //After upload + that.messageResponse(response, false); + }).fail( + function () { + $("#confirmation").html("Upload Failed"); + + }).always(function () { + that.processing = false; + }); + } catch (e) { + alert(e); //Error? Notify the user + } + } + + r.readAsBinaryString(file); //Read file + }; + + this.messageResponse = function (response, replace) { + $("#confirmation").html("Upload Confirmed"); //Notify the user that the upload succeeded + response = that.brainWave.modifyResponse([response]); //The post returns the file, sanitize it + response = response[0]; + var index = that.brainWave.files.indexOf(that.file); //Find the place the new file will be taking + var data = that.brainWave.files.slice(0); //Get the array + data[index] = response; //Add the new file in place of the old + that.brainWave.files([]); //Dirty refresh + that.brainWave.files(data); + + if (!replace) { + // clear old data + $("#displayName").val(""); + $("#warning").html(""); + $("#fileUpload").val(""); + $("#description").val(""); + $("#submit").prop("disabled", true); + $("#required").show(); + } + } + } + + return ctor; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069496_testplugin_test.js b/pool/shard011/JavaScript/0069496_testplugin_test.js new file mode 100644 index 0000000000000000000000000000000000000000..f2174be6192a63a3085ef66453b1bf2dbf4e869f --- /dev/null +++ b/pool/shard011/JavaScript/0069496_testplugin_test.js @@ -0,0 +1,48 @@ +'use strict'; + +var grunt = require('grunt'); + +/* + ======== A Handy Little Nodeunit Reference ======== + https://github.com/caolan/nodeunit + + Test methods: + test.expect(numAssertions) + test.done() + Test assertions: + test.ok(value, [message]) + test.equal(actual, expected, [message]) + test.notEqual(actual, expected, [message]) + test.deepEqual(actual, expected, [message]) + test.notDeepEqual(actual, expected, [message]) + test.strictEqual(actual, expected, [message]) + test.notStrictEqual(actual, expected, [message]) + test.throws(block, [error], [message]) + test.doesNotThrow(block, [error], [message]) + test.ifError(value) +*/ + +exports.testplugin = { + setUp: function(done) { + // setup here if necessary + done(); + }, + default_options: function(test) { + test.expect(1); + + var actual = grunt.file.read('tmp/default_options'); + var expected = grunt.file.read('test/expected/default_options'); + test.equal(actual, expected, 'should describe what the default behavior is.'); + + test.done(); + }, + custom_options: function(test) { + test.expect(1); + + var actual = grunt.file.read('tmp/custom_options'); + var expected = grunt.file.read('test/expected/custom_options'); + test.equal(actual, expected, 'should describe what the custom option(s) behavior is.'); + + test.done(); + }, +}; diff --git a/pool/shard011/JavaScript/0069498_gulpfile.js b/pool/shard011/JavaScript/0069498_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..3295f117c6709e8331596a0f7b4d7242dccc9705 --- /dev/null +++ b/pool/shard011/JavaScript/0069498_gulpfile.js @@ -0,0 +1,139 @@ +'use strict'; + +var gulp = require('gulp') + , browserify = require('browserify') + , bump = require('gulp-bump') + , connect = require('gulp-connect') + , eslint = require('gulp-eslint') + , insert = require('gulp-insert') + , rename = require('gulp-rename') + , rimraf = require('gulp-rimraf') + , sass = require('gulp-sass') + , transform = require('vinyl-transform') + , uglify = require('gulp-uglify') + , zip = require('gulp-zip'); + +var version = '/* perfect-scrollbar v' + require('./package').version + ' */\n'; + +gulp.task('lint', function () { + return gulp.src(['./src/**/*.js', './gulpfile.js']) + .pipe(eslint()) + .pipe(eslint.format()) + .pipe(eslint.failOnError()); +}); + +gulp.task('clean:js', function () { + return gulp.src('./dist/js/*.js', {read: false}) + .pipe(rimraf()); +}); + +gulp.task('clean:js:min', function () { + return gulp.src('./dist/js/min/*.js', {read: false}) + .pipe(rimraf()); +}); + +function browserified() { + return transform(function (filename) { + var b = browserify(filename); + return b.bundle(); + }); +} + +gulp.task('js', ['clean:js'], function () { + return gulp.src('./src/js/adaptor/*.js') + .pipe(browserified()) + .pipe(insert.prepend(version)) + .pipe(rename(function (path) { + if (path.basename === 'global') { + path.basename = 'perfect-scrollbar'; + } else { + path.basename = 'perfect-scrollbar.' + path.basename; + } + })) + .pipe(gulp.dest('./dist/js')) + .pipe(connect.reload()); +}); + +gulp.task('js:min', ['clean:js:min'], function () { + return gulp.src('./src/js/adaptor/*.js') + .pipe(browserified()) + .pipe(uglify()) + .pipe(insert.prepend(version)) + .pipe(rename(function (path) { + if (path.basename === 'global') { + path.basename = 'perfect-scrollbar.min'; + } else { + path.basename = 'perfect-scrollbar.' + path.basename + '.min'; + } + })) + .pipe(gulp.dest('./dist/js/min')); +}); + +gulp.task('clean:css', function () { + return gulp.src('./dist/css/perfect-scrollbar.css', {read: false}) + .pipe(rimraf()); +}); + +gulp.task('clean:css:min', function () { + return gulp.src('./dist/css/perfect-scrollbar.min.css', {read: false}) + .pipe(rimraf()); +}); + +gulp.task('sass', ['clean:css'], function () { + return gulp.src('./src/css/main.scss') + .pipe(sass()) + .pipe(insert.prepend(version)) + .pipe(rename('perfect-scrollbar.css')) + .pipe(gulp.dest('./dist/css')) + .pipe(connect.reload()); +}); + +gulp.task('sass:min', ['clean:css:min'], function () { + return gulp.src('./src/css/main.scss') + .pipe(sass({outputStyle: 'compressed'})) + .pipe(insert.prepend(version)) + .pipe(rename('perfect-scrollbar.min.css')) + .pipe(gulp.dest('./dist/css')); +}); + +function bumpType() { + if (gulp.env.major) { + return 'major'; + } else if (gulp.env.minor) { + return 'minor'; + } else { + return 'patch'; + } +} + +gulp.task('bump', function () { + gulp.src('./*.json') + .pipe(bump({type: bumpType()})) + .pipe(gulp.dest('./')); +}); + +gulp.task('release', ['bump', 'build']); + +gulp.task('build', ['js', 'js:min', 'sass', 'sass:min']); + +gulp.task('connect', ['build'], function () { + connect.server({ + root: __dirname, + livereload: true + }); +}); + +gulp.task('watch', function () { + gulp.watch(['src/js/**/*'], ['js']); + gulp.watch(['src/css/**/*'], ['sass']); +}); + +gulp.task('serve', ['connect', 'watch']); + +gulp.task('compress', function () { + return gulp.src('./dist/**') + .pipe(zip('perfect-scrollbar.zip')) + .pipe(gulp.dest('./dist')); +}); + +gulp.task('default', ['lint', 'build']); diff --git a/pool/shard011/JavaScript/0069500_render.js b/pool/shard011/JavaScript/0069500_render.js new file mode 100644 index 0000000000000000000000000000000000000000..f8a407de2708251a752c1621f518d7a7c058e07a --- /dev/null +++ b/pool/shard011/JavaScript/0069500_render.js @@ -0,0 +1,34 @@ +var container = require("./init.js").container; +var globals = require("./init.js").globals; +var constant = require("../layout/constant_layout.js"); +var controlUI = require("../view/controlUI.js"); + +function renderGraph() { + var graph = graph || window.graph; + if(!graph) { + throw new Error("No graph object present, unable to render anything."); + } + + if(!window.nodes_obj || !window.node_keys) { + window.nodes_obj = window.graph.getNodes(); + window.node_keys = Object.keys(window.nodes_obj); + window.und_edges = window.graph.getUndEdges(); + window.und_edges_keys = Object.keys(window.und_edges); + window.dir_edges = window.graph.getDirEdges(); + window.dir_edges_keys = Object.keys(window.dir_edges); + } + + constant.renderGraph(graph); + window.requestAnimationFrame(updateGraph); + controlUI.setDirectionUnchecked(); + console.log("rendering graph..."); +} + +function updateGraph () { + globals.renderer.render(globals.scene, globals.camera); +}; + +module.exports = { + renderGraph: renderGraph, + update: updateGraph +}; diff --git a/pool/shard011/JavaScript/0069503_04Circle.js b/pool/shard011/JavaScript/0069503_04Circle.js new file mode 100644 index 0000000000000000000000000000000000000000..124fade25d1f5e9388c595ce790468ac94de1561 --- /dev/null +++ b/pool/shard011/JavaScript/0069503_04Circle.js @@ -0,0 +1,31 @@ +// https://judge.softuni.bg/Contests/Compete/Index/336#3 +'use strict'; + +class Circle { + constructor(radius) { + this.radius = radius; + } + + get radius() { + return this._radius; + } + + set radius(radius) { + if (radius <= 0) { + throw new RangeError('Radius must be positive'); + } + this._radius = radius; + } + + get diameter() { + return this.radius * 2; + } + + set diameter(diameter) { + this.radius = diameter / 2; + } + + get area() { + return Math.PI * Math.pow(this.radius, 2); + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069504_DynamicViscosity.js b/pool/shard011/JavaScript/0069504_DynamicViscosity.js new file mode 100644 index 0000000000000000000000000000000000000000..e5ee54aa5c22f99829385b63094879b2e309f773 --- /dev/null +++ b/pool/shard011/JavaScript/0069504_DynamicViscosity.js @@ -0,0 +1,36 @@ +/* +Copyright 2013 - $Date $ by PeopleWare n.v. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + +http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +define(["dojo/_base/declare", "./ScalarQuantitativeValue", "ppwcode-util-collections/ArraySet", "dojo/_base/lang", "module"], + function(declare, ScalarQuantitativeValue, Set, lang, module) { + + var DynamicViscosity = declare([ScalarQuantitativeValue], { + + _c_invar: [ + // NOP + ] + + }); + + DynamicViscosity.format = ScalarQuantitativeValue.format; + DynamicViscosity.parse = lang.partial(ScalarQuantitativeValue.parse, "mPa.s", DynamicViscosity); + + DynamicViscosity._supportedUnits = new Set({elementType: "string", data: ["mPa.s"]}); + DynamicViscosity.mid = module.id; + + return DynamicViscosity; + } +); diff --git a/pool/shard011/JavaScript/0069505_SearchBox.js b/pool/shard011/JavaScript/0069505_SearchBox.js new file mode 100644 index 0000000000000000000000000000000000000000..2090ffd13f075f779ddb578dcd1d07cf4e2488cd --- /dev/null +++ b/pool/shard011/JavaScript/0069505_SearchBox.js @@ -0,0 +1,19 @@ +import React, { PropTypes } from 'react'; + +const SearchBox = ({ onSearch }) => { + const onChange = event => onSearch(event.target.value); + + return ( + + ); +}; + +SearchBox.propTypes = { + onSearch: PropTypes.func.isRequired +}; + +export default SearchBox; diff --git a/pool/shard011/JavaScript/0069508_ExtendedClientLastViewed.js b/pool/shard011/JavaScript/0069508_ExtendedClientLastViewed.js new file mode 100644 index 0000000000000000000000000000000000000000..6f194f1b39fd632802afc98a26b3d504ea35e740 --- /dev/null +++ b/pool/shard011/JavaScript/0069508_ExtendedClientLastViewed.js @@ -0,0 +1,62 @@ +BASE.require(["LG.core.dataModel.sales.Client"], function () { + BASE.namespace("LG.core.dataModel.sales"); + + var _globalObject = this; + + LG.core.dataModel.sales.ExtendedClientLastViewed = (function (Super) { + var Client = function () { + var self = this; + if (self === _globalObject) { + throw new Error("Client constructor invoked with global context. Say new."); + } + + Super.call(self); + + self["id"] = null; + self["name"] = null; + + self["isArchived"] = null; + self["street1"] = null; + self["street2"] = null; + self["city"] = null; + self["state"] = null; + self["zip"] = null; + self["country"] = null; + self["county"] = null; + self["longitude"] = null; + self["latitude"] = null; + self["primaryContactFirstName"] = null; + self["primaryContactLastName"] = null; + self["primaryContactWorkAreaCode"] = null; + self["primaryContactWorkCountryCode"] = null; + self["primaryContactWorkExtension"] = null; + self["primaryContactWorkLineNumber"] = null; + self["expirationDate"] = null; + self["potentialRevenue"] = null; + self["policyDaysToExpiration"] = null; + self["distance"] = null; + self["lastViewed"] = null; + + self["ownerId"] = null; + self["createdDate"] = null; + self["lastModifiedDate"] = null; + self["startDate"] = null; + self["endDate"] = null; + + self['clientToClientTags'] = []; + self['clientUserSettings'] = []; + self['clientAddresses'] = []; + self['opportunities'] = []; + self['partners'] = []; + self['attachments'] = []; + self['contacts'] = []; + self['notes'] = []; + + return self; + }; + + BASE.extend(Client, Super); + + return Client; + }(LG.core.dataModel.sales.Client)); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069515_main.js b/pool/shard011/JavaScript/0069515_main.js new file mode 100644 index 0000000000000000000000000000000000000000..2669c068ff5286cf60d2454a9f8c349df9eaa48c --- /dev/null +++ b/pool/shard011/JavaScript/0069515_main.js @@ -0,0 +1,287 @@ + +/*! + * kue - http - main + * Copyright (c) 2011 LearnBoost + * MIT Licensed + */ + +// TODO: clean up +// TODO: server-side config for this stuff +// TODO: optimize! many of these jQuery objects can be cached + +/** + * Active state. + */ + +var active; + +/** + * Active type filter. + */ + +var filter; + +/** + * Number of jobs fetched when "more" is clicked. + */ + +var more = 10; + +/** + * Number of jobs shown. + */ + +var to = more; + +/** + * Sort order. + */ + +var sort = 'asc'; + +/** + * Loading indicator. + */ + +var loading; + +/** + * Initialize UI. + */ + +function init(state) { + var canvas = o('#loading canvas').get(0) + , ctx = canvas.getContext('2d'); + + loading = new LoadingIndicator; + loading.ctx = ctx; + loading.size(canvas.width); + + pollStats(1000); + show(state)(); + o('li.inactive a').click(show('inactive')); + o('li.complete a').click(show('complete')); + o('li.active a').click(show('active')); + o('li.failed a').click(show('failed')); + o('li.delayed a').click(show('delayed')); + + o('#filter').change(function(){ + filter = $(this).val(); + }); + + o('#sort').change(function(){ + sort = $(this).val(); + o('#jobs .job').remove(); + }); + + onpopstate = function(e){ + if (e.state) show(e.state.state)(); + }; +} + +/** + * Show loading indicator. + */ + +function showLoading() { + var n = 0; + o('#loading').show(); + showLoading.timer = setInterval(function(){ + loading.update(++n).draw(loading.ctx); + }, 50); +} + +/** + * Hide loading indicator. + */ + +function hideLoading() { + o('#loading').hide(); + clearInterval(showLoading.timer); +} + +/** + * Infinite scroll. + */ + +function infiniteScroll() { + if (infiniteScroll.bound) return; + var body = o('body'); + hideLoading(); + infiniteScroll.bound = true; + + o(window).scroll(function(e){ + var top = body.scrollTop() + , height = body.innerHeight() + , windowHeight = window.innerHeight + , pad = 30; + + if (top + windowHeight + pad >= height) { + to += more; + infiniteScroll.bound = false; + showLoading(); + o(window).unbind('scroll'); + } + }); +} + +/** + * Show jobs with `state`. + * + * @param {String} state + * @param {Boolean} init + * @return {Function} + */ + +function show(state) { + return function(){ + active = state; + if (pollForJobs.timer) clearTimeout(pollForJobs.timer); + history.pushState({ state: state }, state, state); + o('#jobs .job').remove(); + o('#menu li a').removeClass('active'); + o('#menu li.' + state + ' a').addClass('active'); + pollForJobs(state, 2000); + return false; + } +} + +/** + * Poll for jobs with `state` every `ms`. + * + * @param {String} state + * @param {Number} ms + */ + +function pollForJobs(state, ms) { + o('h1').text(state); + refreshJobs(state, function(){ + infiniteScroll(); + pollForJobs.timer = setTimeout(function(){ + pollForJobs(state, ms); + }, 1000); + }); +}; + +/** + * Re-request and refresh job elements. + * + * @param {String} state + * @param {Function} fn + */ + +function refreshJobs(state, fn) { + // TODO: clean this crap up + var jobHeight = o('#jobs .job .block').outerHeight(true) + , top = o(window).scrollTop() + , height = window.innerHeight + , visibleFrom = Math.max(0, Math.floor(top / jobHeight)) + , visibleTo = Math.floor((top + height) / jobHeight) + , url = './jobs/' + + (filter ? filter + '/' : '') + + state + '/0..' + to + + '/' + sort; + + // var color = ['blue', 'red', 'yellow', 'green', 'purple'][Math.random() * 5 | 0]; + + request(url, function(jobs){ + var len = jobs.length + , job + , el; + + // remove jobs which have changed their state + o('#jobs .job').each(function(i, el){ + var el = $(el) + , id = (el.attr('id') || '').replace('job-', '') + , found = jobs.some(function(job){ + return job && id == job.id; + }); + if (!found) el.remove(); + }); + + for (var i = 0; i < len; ++i) { + if (!jobs[i]) continue; + + // exists + if (o('#job-' + jobs[i].id).length) { + if (i < visibleFrom || i > visibleTo) continue; + el = o('#job-' + jobs[i].id); + // el.css('background-color', color); + job = el.get(0).job; + job.update(jobs[i]) + .showProgress('active' == active) + .showErrorMessage('failed' == active) + .render(); + // new + } else { + job = new Job(jobs[i]); + el = job.showProgress('active' == active) + .showErrorMessage('failed' == active) + .render(true); + + el.get(0).job = job; + el.appendTo('#jobs'); + } + } + + fn(); + }); +} + +/** + * Poll for stats every `ms`. + * + * @param {Number} ms + */ + +function pollStats(ms) { + request('./stats', function(data){ + o('li.inactive .count').text(data.inactiveCount); + o('li.active .count').text(data.activeCount); + o('li.complete .count').text(data.completeCount); + o('li.failed .count').text(data.failedCount); + o('li.delayed .count').text(data.delayedCount); + setTimeout(function(){ + pollStats(ms); + }, ms); + }); +} + +/** + * Request `url` and invoke `fn(res)`. + * + * @param {String} url + * @param {Function} fn + */ + +function request(url, fn) { + var method = 'GET'; + + if ('string' == typeof fn) { + method = url; + url = fn; + fn = arguments[2]; + } + + fn = fn || function(){}; + + o.ajax({ type: method, url: url }) + .success(function(res){ + res.error + ? error(res.error) + : fn(res); + }); +} + +/** + * Display error `msg`. + * + * @param {String} msg + */ + +function error(msg) { + o('#error').text(msg).addClass('show'); + setTimeout(function(){ + o('#error').removeClass('show'); + }, 4000); +} diff --git a/pool/shard011/JavaScript/0069516_index.js b/pool/shard011/JavaScript/0069516_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1f32bf69f56ddf405c6c357733bec4ba73a307cd --- /dev/null +++ b/pool/shard011/JavaScript/0069516_index.js @@ -0,0 +1,97 @@ +"use strict" + +const hasBlock = require("../../utils/hasBlock") +const optionsMatches = require("../../utils/optionsMatches") +const report = require("../../utils/report") +const ruleMessages = require("../../utils/ruleMessages") +const validateOptions = require("../../utils/validateOptions") +const _ = require("lodash") + +const ruleName = "max-nesting-depth" + +const messages = ruleMessages(ruleName, { + expected: depth => `Expected nesting depth to be no more than ${depth}`, +}) + +const rule = function (max, options) { + const ignoreAtRulesWithoutDeclarationBlocks = optionsMatches(options, "ignore", "at-rules-without-declaration-blocks") || optionsMatches(options, "ignore", "blockless-at-rules") + const isIgnoreAtRule = node => node.type === "atrule" && optionsMatches(options, "ignoreAtRules", node.name) + + return (root, result) => { + validateOptions(result, ruleName, { + actual: max, + possible: [_.isNumber], + }, { + optional: true, + actual: options, + possible: { + ignore: [ + "at-rules-without-declaration-blocks", + "blockless-at-rules", + ], + ignoreAtRules: [_.isString], + }, + }) + + if (optionsMatches(options, "ignore", "at-rules-without-declaration-blocks")) { + result.warn(( + "'max-nesting-depth\'s' \"at-rules-without-declaration-blocks\" option has been deprecated and in 8.0 will be removed. Instead use the \"blockless-at-rules\" option." + ), { + stylelintType: "deprecation", + stylelintReference: "https://stylelint.io/user-guide/rules/max-nesting-depth/", + }) + } + + root.walkRules(checkStatement) + root.walkAtRules(checkStatement) + + function checkStatement(statement) { + if (isIgnoreAtRule(statement)) { + return + } + if (!hasBlock(statement)) { + return + } + const depth = nestingDepth(statement) + if (depth > max) { + report({ + ruleName, + result, + node: statement, + message: messages.expected(max), + }) + } + } + } + + function nestingDepth(node, level) { + level = level || 0 + const parent = node.parent + + if (isIgnoreAtRule(parent)) { + return 0 + } + + // The nesting depth level's computation has finished + // when this function, recursively called, receives + // a node that is not nested -- a direct child of the + // root node + if (parent.type === "root" || parent.type === "atrule" && parent.parent.type === "root") { + return level + } + + if (ignoreAtRulesWithoutDeclarationBlocks && node.type === "atrule" && node.every(child => child.type !== "decl")) { + return nestingDepth(parent, level) + } + + // Unless any of the conditions above apply, we want to + // add 1 to the nesting depth level and then check the parent, + // continuing to add and move up the hierarchy + // until we hit the root node + return nestingDepth(parent, level + 1) + } +} + +rule.ruleName = ruleName +rule.messages = messages +module.exports = rule diff --git a/pool/shard011/JavaScript/0069517_order.js b/pool/shard011/JavaScript/0069517_order.js new file mode 100644 index 0000000000000000000000000000000000000000..d6e50f8b457075c0004205bc9fa1b8a17f6f15ab --- /dev/null +++ b/pool/shard011/JavaScript/0069517_order.js @@ -0,0 +1,120 @@ +define(function () { + /** + * Returns a ds of a new order for the selected customer + * @param {Object[]} bezl - A reference to the calling Bezl + */ + function NewOrder (bezl) { + + bezl.dataService.add('newOrder','brdb','Epicor10','SalesOrder_NewOrderByCustomer', + { "Connection": bezl.vars.connection, + "Company": bezl.vars.company, + "CustNum": bezl.vars.selectedCustomer.CustNum, + },0); + + bezl.vars.newOrder = true; + + } + + function SubmitOrder (bezl) { + // Update our order head info + bezl.vars.ds.OrderHed.forEach(oh => { + oh.BTCustNum = oh.CustNum; + + oh.ShipToCustNum = oh.CustNum; + + oh.TermsCode = bezl.vars.selectedCustomer.TermsCode; + + oh.ShipToNum = bezl.vars.selectedShipTo.ShipToNum; + + if (bezl.vars.selectedCustomer.Attention) { + oh.PrcConNum = bezl.vars.selectedCustomer.Attention; + } + + if (bezl.vars.selectedShipTo.Attention) { + oh.ShpConNum = bezl.vars.selectedShipTo.Attention; + } + + if (bezl.vars.PONumber) { + oh.PONum = bezl.vars.PONumber; + } + if (bezl.vars.OrderDate) { + oh.OrderDate = bezl.vars.OrderDate; + } + if (bezl.vars.NeedBy) { + oh.NeedByDate = bezl.vars.NeedBy; + } + if (bezl.vars.ShipBy) { + oh.RequestDate = bezl.vars.ShipBy; + } + + if (bezl.vars.ShipVia) { + oh.ShipViaCode = bezl.vars.ShipVia; + } + + if (bezl.vars.OrderComment) { + oh.OrderComment = bezl.vars.OrderComment; + } + + if (bezl.vars.NotifyEmail && bezl.vars.NotifyEmail != '') { + oh.NotifyFlag = true; + oh.NotifyEMail = bezl.vars.NotifyEmail; + } + + if (bezl.vars.ShipToNum == 'CreateNew') { + oh.CustAllowOTS = true; + oh.UseOTS = true; + oh.OTSSaveAs = 'T'; + oh.OTSShipToNum = bezl.vars.selectedShipTo.ID; + oh.OTSName = bezl.vars.selectedShipTo.Name; + oh.OTSAddress1 = bezl.vars.selectedShipTo.Address1; + oh.OTSAddress2 = bezl.vars.selectedShipTo.Address2; + oh.OTSAddress3 = bezl.vars.selectedShipTo.Address3; + oh.OTSCity = bezl.vars.selectedShipTo.City; + oh.OTSState = bezl.vars.selectedShipTo.State; + oh.OTSZIP = bezl.vars.selectedShipTo.Zip; + } + + oh.OrderHeld = true; + }); + + // This will take the structure from our bezl vars and stuff it into the ds specific to Epicor + bezl.vars.partList.forEach(p => { + bezl.vars.ds.OrderDtl.push({ + OpenLine: true, + VoidLine: false, + Company: bezl.vars.company, + OrderNum: 0, + OrderLine: 0, + LineType: 'PART', + PartNum: p.PartNum, + LineDesc: p.PartDescription, + OrderComment: p.Comment, + IUM: p.UOM, + RevisionNum: '', + SellingQuantity: p.Qty, + UnitPrice: p.UnitPrice, + DocUnitPrice: p.UnitPrice, + MktgCampaignID: 'CURR', + MktgEvntSeq: 1, + CustNum: bezl.vars.selectedCustomer.CustNum, + LockQty: false, + RowMod: 'U', + ShortChar10: '' + }) + }); + // Now we will submit the order for processing + bezl.dataService.add('submitOrder','brdb','Epicor10','SalesOrder_SubmitNewOrder', + { "Connection": bezl.vars.connection, + "Company": bezl.vars.company, + "ds": JSON.stringify(bezl.vars.ds) + },0); + + bezl.vars.submitOrder = true; + + } + + return { + newOrder: NewOrder, + submitOrder: SubmitOrder + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069519_api.js b/pool/shard011/JavaScript/0069519_api.js new file mode 100644 index 0000000000000000000000000000000000000000..307ab6b2e16a5989411879df8747a8d78a4c3997 --- /dev/null +++ b/pool/shard011/JavaScript/0069519_api.js @@ -0,0 +1,196 @@ +module('Player Minified'); + +test('should be able to access expected player API methods', function() { + var player = PlayerTest.makePlayer(); + + // Native HTML5 Methods + ok(player.error, 'error exists'); + ok(player.src, 'src exists'); + ok(player.currentSrc, 'currentSrc exists'); + ok(player.buffered, 'buffered exists'); + ok(player.load, 'load exists'); + ok(player.seeking, 'seeking exists'); + ok(player.currentTime, 'currentTime exists'); + ok(player.duration, 'duration exists'); + ok(player.paused, 'paused exists'); + ok(player.ended, 'ended exists'); + ok(player.autoplay, 'autoplay exists'); + ok(player.loop, 'loop exists'); + ok(player.play , 'play exists'); + ok(player.pause , 'pause exists'); + ok(player.controls, 'controls exists'); + ok(player.volume, 'volume exists'); + ok(player.muted, 'muted exists'); + ok(player.width, 'width exists'); + ok(player.height, 'height exists'); + ok(player.poster, 'poster exists'); + ok(player.textTracks, 'textTracks exists'); + ok(player.requestFullScreen, 'requestFullScreen exists'); + ok(player.cancelFullScreen, 'cancelFullScreen exists'); + + // Unsupported Native HTML5 Methods + // ok(player.canPlayType, 'canPlayType exists'); + // ok(player.readyState, 'readyState exists'); + // ok(player.networkState, 'networkState exists'); + // ok(player.startTime, 'startTime exists'); + // ok(player.defaultPlaybackRate, 'defaultPlaybackRate exists'); + // ok(player.playbackRate, 'playbackRate exists'); + // ok(player.played, 'played exists'); + // ok(player.seekable, 'seekable exists'); + // ok(player.videoWidth, 'videoWidth exists'); + // ok(player.videoHeight, 'videoHeight exists'); + + // Additional player methods + ok(player.bufferedPercent, 'bufferedPercent exists'); + ok(player.reportUserActivity, 'reportUserActivity exists'); + ok(player.userActive, 'userActive exists'); + ok(player.usingNativeControls, 'usingNativeControls exists'); + ok(player.isFullScreen, 'isFullScreen exists'); + + player.dispose(); +}); + +test('should be able to access expected component API methods', function() { + var comp = videojs.Component.create({ id: function(){ return 1; }, reportUserActivity: function(){} }); + + // Component methods + ok(comp.player, 'player exists'); + ok(comp.options, 'options exists'); + ok(comp.init, 'init exists'); + ok(comp.dispose, 'dispose exists'); + ok(comp.createEl, 'createEl exists'); + ok(comp.contentEl, 'contentEl exists'); + ok(comp.el, 'el exists'); + ok(comp.addChild, 'addChild exists'); + ok(comp.getChild, 'getChild exists'); + ok(comp.getChildById, 'getChildById exists'); + ok(comp.children, 'children exists'); + ok(comp.initChildren, 'initChildren exists'); + ok(comp.removeChild, 'removeChild exists'); + ok(comp.on, 'on exists'); + ok(comp.off, 'off exists'); + ok(comp.one, 'one exists'); + ok(comp.trigger, 'trigger exists'); + ok(comp.triggerReady, 'triggerReady exists'); + ok(comp.show, 'show exists'); + ok(comp.hide, 'hide exists'); + ok(comp.width, 'width exists'); + ok(comp.height, 'height exists'); + ok(comp.dimensions, 'dimensions exists'); + ok(comp.ready, 'ready exists'); + ok(comp.addClass, 'addClass exists'); + ok(comp.removeClass, 'removeClass exists'); + ok(comp.buildCSSClass, 'buildCSSClass exists'); +}); + +test('should export ready api call to public', function() { + var videoTag = PlayerTest.makeTag(); + + var fixture = document.getElementById('qunit-fixture'); + fixture.appendChild(videoTag); + + var player = videojs('example_1'); + ok(player.ready !== undefined, 'ready callback is defined'); + player.dispose(); +}); + +test('should export useful components to the public', function () { + ok(videojs.TOUCH_ENABLED !== undefined, 'Touch detection should be public'); + ok(videojs.ControlBar, 'ControlBar should be public'); + ok(videojs.Button, 'Button should be public'); + ok(videojs.PlayToggle, 'PlayToggle should be public'); + ok(videojs.FullscreenToggle, 'FullscreenToggle should be public'); + ok(videojs.BigPlayButton, 'BigPlayButton should be public'); + ok(videojs.LoadingSpinner, 'LoadingSpinner should be public'); + ok(videojs.CurrentTimeDisplay, 'CurrentTimeDisplay should be public'); + ok(videojs.DurationDisplay, 'DurationDisplay should be public'); + ok(videojs.TimeDivider, 'TimeDivider should be public'); + ok(videojs.RemainingTimeDisplay, 'RemainingTimeDisplay should be public'); + ok(videojs.Slider, 'Slider should be public'); + ok(videojs.ProgressControl, 'ProgressControl should be public'); + ok(videojs.SeekBar, 'SeekBar should be public'); + ok(videojs.LoadProgressBar, 'LoadProgressBar should be public'); + ok(videojs.PlayProgressBar, 'PlayProgressBar should be public'); + ok(videojs.SeekHandle, 'SeekHandle should be public'); + ok(videojs.VolumeControl, 'VolumeControl should be public'); + ok(videojs.VolumeBar, 'VolumeBar should be public'); + ok(videojs.VolumeLevel, 'VolumeLevel should be public'); + ok(videojs.VolumeMenuButton, 'VolumeMenuButton should be public'); + ok(videojs.VolumeHandle, 'VolumeHandle should be public'); + ok(videojs.MuteToggle, 'MuteToggle should be public'); + ok(videojs.PosterImage, 'PosterImage should be public'); + ok(videojs.Menu, 'Menu should be public'); + ok(videojs.MenuItem, 'MenuItem should be public'); + ok(videojs.MenuButton, 'MenuButton should be public'); + + ok(videojs.util, 'util namespace should be public'); + ok(videojs.util.mergeOptions, 'mergeOptions should be public'); +}); + +test('should be able to initialize player twice on the same tag using string reference', function() { + var videoTag = PlayerTest.makeTag(); + var id = videoTag.id; + + var fixture = document.getElementById('qunit-fixture'); + fixture.appendChild(videoTag); + + var player = videojs('example_1'); + player.dispose(); + ok(!document.getElementById(id), 'element is removed'); + + videoTag = PlayerTest.makeTag(); + fixture.appendChild(videoTag); + + player = videojs('example_1'); + player.dispose(); +}); + +test('videojs.players should be available after minification', function() { + var videoTag = PlayerTest.makeTag(); + var id = videoTag.id; + + var fixture = document.getElementById('qunit-fixture'); + fixture.appendChild(videoTag); + + var player = videojs(id); + ok(videojs.players[id] === player, 'videojs.players is available'); + + player.dispose(); +}); + +// NOTE: This test could be removed after we've landed on a permanent +// externs/exports strategy. See comment on videojs/video.js#853 +test('fullscreenToggle does not depend on minified player methods', function(){ + var noop, player, fullscreen, requestFullScreen, cancelFullScreen, isFullScreen_; + noop = function(){}; + requestFullScreen = false; + cancelFullScreen = false; + player = { + id: noop, + on: noop, + ready: noop, + reportUserActivity: noop + }; + + player['requestFullScreen'] = function(){ + requestFullScreen = true; + }; + player['cancelFullScreen'] = function(){ + cancelFullScreen = true; + }; + + isFullScreen_ = false; + player['isFullScreen'] = function(){ + return isFullScreen_; + }; + + fullscreen = new videojs.FullscreenToggle(player); + fullscreen.trigger('click'); + + ok(requestFullScreen, 'requestFullScreen called'); + + isFullScreen_ = true; + fullscreen.trigger('click'); + + ok(cancelFullScreen, 'cancelFullScreen called'); +}); diff --git a/pool/shard011/JavaScript/0069521_decision-tables-controllers.js b/pool/shard011/JavaScript/0069521_decision-tables-controllers.js new file mode 100644 index 0000000000000000000000000000000000000000..268a4cec6b10d14a38ea77d7b571409eff2d6e59 --- /dev/null +++ b/pool/shard011/JavaScript/0069521_decision-tables-controllers.js @@ -0,0 +1,92 @@ +/* + * Copyright 2005-2015 Alfresco Software, Ltd. All rights reserved. + * License rights for this program may be obtained from Alfresco Software, Ltd. + * pursuant to a written agreement and any use of this program without such an + * agreement is prohibited. + */ +'use strict'; + +/* Controllers */ + +activitiAdminApp.controller('DecisionTablesController', ['$rootScope', '$scope', '$http', '$timeout', '$location', '$translate', '$q', '$modal', 'gridConstants', + function ($rootScope, $scope, $http, $timeout, $location, $translate, $q, $modal, gridConstants) { + + $rootScope.navigation = {selection: 'decision-tables'}; + + $scope.filter = {}; + $scope.decisionTablesData = {}; + + // Array to contain selected properties (yes - we only can select one, but ng-grid isn't smart enough) + $scope.selectedDecisionTables = []; + + var filterConfig = { + url: '/app/rest/activiti/decision-tables', + method: 'GET', + success: function (data, status, headers, config) { + $scope.decisionTablesData = data; + }, + error: function (data, status, headers, config) { + if (data && data.message) { + // Extract error-message + $rootScope.addAlert(data.message, 'error'); + } else { + // Use default error-message + $rootScope.addAlert($translate.instant('ALERT.GENERAL.HTTP-ERROR'), 'error'); + } + }, + + sortObjects: [ + {name: 'DECISION-TABLES.SORT.ID', id: 'id'}, + {name: 'DECISION-TABLES.SORT.NAME', id: 'name'} + ], + + supportedProperties: [ + {id: 'nameLike', name: 'DECISION-TABLES.FILTER.NAME', showByDefault: true}, + {id: 'keyLike', name: 'DECISION-TABLES.FILTER.KEY', showByDefault: true}, + {id: 'tenantIdLike', name: 'DECISION-TABLES.FILTER.TENANTID', showByDefault: true} + ] + }; + + if ($rootScope.filters && $rootScope.filters.decisionTableFilter) { + // Reuse the existing filter + $scope.filter = $rootScope.filters.decisionTableFilter; + $scope.filter.config = filterConfig; + } else { + $scope.filter = new ActivitiAdmin.Utils.Filter(filterConfig, $http, $timeout, $rootScope); + $rootScope.filters.decisionTableFilter = $scope.filter; + } + + $scope.decisionTableSelected = function (decisionTable) { + if (decisionTable && decisionTable.getProperty('id')) { + $location.path('/decision-table/' + decisionTable.getProperty('id')); + } + }; + + $q.all([$translate('DECISION-TABLES.HEADER.ID'), + $translate('DECISION-TABLES.HEADER.NAME'), + $translate('DECISION-TABLES.HEADER.KEY'), + $translate('DECISION-TABLES.HEADER.VERSION'), + $translate('DECISION-TABLES.HEADER.TENANT-ID')]) + .then(function (headers) { + // Config for grid + $scope.gridDecisionTables = { + data: 'decisionTablesData.data', + enableRowReordering: true, + multiSelect: false, + keepLastSelected: false, + rowHeight: 36, + afterSelectionChange: $scope.decisionTableSelected, + columnDefs: [ + {field: 'id', displayName: headers[0], cellTemplate: gridConstants.defaultTemplate}, + {field: 'name', displayName: headers[1], cellTemplate: gridConstants.defaultTemplate}, + {field: 'key', displayName: headers[2], cellTemplate: gridConstants.defaultTemplate}, + {field: 'version', displayName: headers[3], cellTemplate: gridConstants.defaultTemplate}, + {field: 'tenantId', displayName: headers[4], cellTemplate: gridConstants.defaultTemplate}] + }; + }); + + $scope.executeWhenReady(function () { + $scope.filter.refresh(); + }); + + }]); diff --git a/pool/shard011/JavaScript/0069523_Adelaide.js b/pool/shard011/JavaScript/0069523_Adelaide.js new file mode 100644 index 0000000000000000000000000000000000000000..c5643d336ae1e5dadca034e501f1b5e07917ba8f --- /dev/null +++ b/pool/shard011/JavaScript/0069523_Adelaide.js @@ -0,0 +1,67 @@ +describe('format spec', function () { + + describe('formatting times', function () { + var amDate = new Date(2015, 0, 1, 9, 59, 3, 12); + var pmDate = new Date(2015, 0, 1, 20, 9, 40, 345); + + it('should return a numeric representation of the Swatch Internet time with "B"', function () { + expect(amDate.format('B')).toBe('020'); + expect(pmDate.format('B')).toBe('444'); + }); + }); + + describe('formatting timezones', function () { + + it('should return a timezone identifer with "e"', function () { + expect(new Date(2015, 0).format('e')).toBe('ACDT'); + }); + + it('should return 1 or 0 when given date is in DST or not with "I"', function () { + expect(new Date(2015, 0).format('I')).toBe('1'); // July 1st is in DST + expect(new Date(2015, 6).format('I')).toBe('0'); // I forgot it's in south hemisphere + }); + + it('should return the difference to Greenwich time without colon with "O"', function () { + var date = new Date(2015, 0); + + expect(date.format('O')).toBe(date.format('I') === '1' ? '+1030' : '+0930'); + }); + + it('should return the difference to Greenwich time with colon with "P"', function () { + var date = new Date(2015, 0); + + expect(date.format('P')).toBe(date.format('I') === '1' ? '+10:30' : '+09:30'); + }); + + it('should return the timezone abbreviation with "T"', function () { + expect(new Date(2015, 0).format('T')).toBe('ACDT'); + }); + + it('should return the timezone offset is seconds with "Z"', function () { + var date = new Date(2015, 0); + + expect(date.format('Z')).toBe(date.format('I') === '1' ? '37800' : '34200'); + }); + }); + + describe('formatting full dates and times', function () { + var date = new Date(Date.UTC(2015, 0, 1, 11, 30, 12)); + + it('should return a ISO 8601 representation of date and time with "c"', function () { + expect(date.format('c')).toBe('2015-01-01T22:00:12+10:30'); + }); + + it('should return a representation of date and time following RFC 2822 with "r"', function () { + expect(date.format('r')).toBe('Thu, 1 Jan 2015 22:00:12 +1030'); + }); + }); + + describe('formatting with composed pattern', function () { + var date = new Date(2015, 0, 1, 11, 30, 12); + + it('should return "le 01/01/2015 à 11:30:12"', function () { + expect(date.format('\\l\\e d/m/Y \\à H:i:s')).toBe('le 01/01/2015 à 11:30:12'); + }); + }); + +}); diff --git a/pool/shard011/JavaScript/0069525_e3e1ca6bbb0ffd538b6ab838dd0020c7770783ReactNativeStack.js b/pool/shard011/JavaScript/0069525_e3e1ca6bbb0ffd538b6ab838dd0020c7770783ReactNativeStack.js new file mode 100644 index 0000000000000000000000000000000000000000..8562b6f29574057a7db09825124e019a687cbd09 --- /dev/null +++ b/pool/shard011/JavaScript/0069525_e3e1ca6bbb0ffd538b6ab838dd0020c7770783ReactNativeStack.js @@ -0,0 +1,66 @@ + +'use strict'; + +var ReactNativeComponentTree = require('ReactNativeComponentTree'); +var ReactNativeInjection = require('ReactNativeInjection'); +var ReactNativeMount = require('ReactNativeMount'); +var ReactNativeStackInjection = require('ReactNativeStackInjection'); +var ReactUpdates = require('ReactUpdates'); + +var _findNodeHandle = require('findNodeHandle'); +var takeSnapshot = require('takeSnapshot'); + +ReactNativeInjection.inject(); +ReactNativeStackInjection.inject(); + +var render = function render(element, mountInto, callback) { + return ReactNativeMount.renderComponent(element, mountInto, callback); +}; + +var ReactNative = { + hasReactNativeInitialized: false, + + findNodeHandle: function findNodeHandle(componentOrHandle) { + var nodeHandle = _findNodeHandle(componentOrHandle); + if (nodeHandle == null || typeof nodeHandle === 'number') { + return nodeHandle; + } + return nodeHandle.getHostNode(); + }, + + + render: render, + + takeSnapshot: takeSnapshot, + + unmountComponentAtNode: ReactNativeMount.unmountComponentAtNode, + + unstable_batchedUpdates: ReactUpdates.batchedUpdates, + + + unmountComponentAtNodeAndRemoveContainer: ReactNativeMount.unmountComponentAtNodeAndRemoveContainer +}; + +if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { + __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ + ComponentTree: { + getClosestInstanceFromNode: function getClosestInstanceFromNode(node) { + return ReactNativeComponentTree.getClosestInstanceFromNode(node); + }, + getNodeFromInstance: function getNodeFromInstance(inst) { + while (inst._renderedComponent) { + inst = inst._renderedComponent; + } + if (inst) { + return ReactNativeComponentTree.getNodeFromInstance(inst); + } else { + return null; + } + } + }, + Mount: ReactNativeMount, + Reconciler: require('ReactReconciler') + }); +} + +module.exports = ReactNative; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069526_insights.js b/pool/shard011/JavaScript/0069526_insights.js new file mode 100644 index 0000000000000000000000000000000000000000..f283e8f0feb70a03e2ae607da7a95d7dc6d947db --- /dev/null +++ b/pool/shard011/JavaScript/0069526_insights.js @@ -0,0 +1,52 @@ +const request = require('request'); +const config = require('config'); + +// Define the initial API +var insights = {}; +insights.query = function query(nrql, configId, cb) { + + // Look up config items + var accountId = config.get(configId + '.accountId'); + var insightsQueryKey = config.get(configId + '.insightsQueryKey'); + + // URI changes for every account + var uri = 'https://insights-api.newrelic.com/v1/accounts/' + + accountId + '/query'; + + var options = { + 'method': 'GET', + 'uri': uri, + 'headers': {'X-Query-Key': insightsQueryKey}, + 'json': true, + 'qs': { + 'nrql': nrql + } + }; + + // Call the API + request(options, cb); +} + +insights.publish = function publish(eventArr, configId, cb) { + + // Look up config items + var accountId = config.get(configId + '.accountId'); + var insightsInsertKey = config.get(configId + '.insightsInsertKey'); + + // URI changes for every account + var uri = 'https://insights-collector.newrelic.com/v1/accounts/' + + accountId + '/events'; + + var options = { + 'method': 'POST', + 'uri': uri, + 'headers': {'X-Insert-Key': insightsInsertKey}, + 'json': true, + 'body': eventArr + } + + // Call the API + request(options, cb); +} + +module.exports = insights; diff --git a/pool/shard011/JavaScript/0069529_gulpfile.js b/pool/shard011/JavaScript/0069529_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..ee4e5d41f5184cef8a888da8cbf218e325c031ff --- /dev/null +++ b/pool/shard011/JavaScript/0069529_gulpfile.js @@ -0,0 +1,120 @@ +var gulp = require('gulp'); +var sass = require('gulp-sass'); +var browserSync = require('browser-sync').create(); +var header = require('gulp-header'); +var cleanCSS = require('gulp-clean-css'); +var rename = require("gulp-rename"); +var uglify = require('gulp-uglify'); +var filter = require('gulp-filter'); +var pkg = require('./package.json'); + +var banner = ['/*\n', + ' * Theme Name: Lucas Moreira\n', + ' * Theme URI: https://lucasmoreira.com.br/\n', + ' * Author: Start Bootstrap\n', + ' * Author URI: https://startbootstrap.com/\n', + ' * Description: \n', + ' * Version: 1.0\n', + ' * Start Bootstrap - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n', + ' * Copyright 2013-' + (new Date()).getFullYear(), ' <%= pkg.author %>\n', + ' * Licensed under <%= pkg.license %> (https://github.com/BlackrockDigital/<%= pkg.name %>/blob/master/LICENSE)\n', + ' */\n', + '' +].join(''); + +// Compiles SCSS files from /scss into /css +gulp.task('sass', function() { + return gulp.src('scss/style.scss') + .pipe(sass()) + .pipe(header(banner, { + pkg: pkg + })) + .pipe(gulp.dest('.')) + .pipe(browserSync.reload({ + stream: true + })) +}); + +// Minify compiled CSS +gulp.task('minify-css', ['sass'], function() { + return gulp.src('css/style.css') + .pipe(cleanCSS({ + compatibility: 'ie8' + })) + .pipe(rename({ + suffix: '.min' + })) + .pipe(gulp.dest('css')) + .pipe(browserSync.reload({ + stream: true + })) +}); + +// Minify custom JS +gulp.task('minify-js', function() { + return gulp.src('js/freelancer.js') + .pipe(uglify()) + .pipe(header(banner, { + pkg: pkg + })) + .pipe(rename({ + suffix: '.min' + })) + .pipe(gulp.dest('js')) + .pipe(browserSync.reload({ + stream: true + })) +}); + +// Copy vendor files from /node_modules into /vendor +// NOTE: requires `npm install` before running! +gulp.task('copy', function() { + gulp.src([ + 'node_modules/bootstrap/dist/**/*', + '!**/npm.js', + '!**/bootstrap-theme.*', + '!**/*.map' + ]) + .pipe(gulp.dest('vendor/bootstrap')) + + gulp.src(['node_modules/jquery/dist/jquery.js', 'node_modules/jquery/dist/jquery.min.js']) + .pipe(gulp.dest('vendor/jquery')) + + gulp.src(['node_modules/popper.js/dist/umd/popper.js', 'node_modules/popper.js/dist/umd/popper.min.js']) + .pipe(gulp.dest('vendor/popper')) + + gulp.src(['node_modules/jquery.easing/*.js']) + .pipe(gulp.dest('vendor/jquery-easing')) + + gulp.src([ + 'node_modules/font-awesome/**', + '!node_modules/font-awesome/**/*.map', + '!node_modules/font-awesome/.npmignore', + '!node_modules/font-awesome/*.txt', + '!node_modules/font-awesome/*.md', + '!node_modules/font-awesome/*.json' + ]) + .pipe(gulp.dest('vendor/font-awesome')) +}) + +// Default task +gulp.task('default', ['sass', 'minify-css', 'minify-js', 'copy']); + +// Configure the browserSync task +gulp.task('browserSync', function() { + browserSync.init({ + server: { + baseDir: '' + }, + }) +}) + +// Dev task with browserSync +gulp.task('dev', ['browserSync', 'sass', 'minify-css', 'minify-js'], function() { + gulp.watch('scss/*.scss', ['sass']); + gulp.watch('css/*.css', ['minify-css']); + gulp.watch('js/*.js', ['minify-js']); + // Reloads the browser whenever HTML or JS files change + gulp.watch('*.html', browserSync.reload); + gulp.watch('js/**/*.js', browserSync.reload); +}); diff --git a/pool/shard011/JavaScript/0069530_AutoQueue.js b/pool/shard011/JavaScript/0069530_AutoQueue.js new file mode 100644 index 0000000000000000000000000000000000000000..52b1b6b8ad3b38d93a82ba624bd390046110f10a --- /dev/null +++ b/pool/shard011/JavaScript/0069530_AutoQueue.js @@ -0,0 +1,74 @@ +var EverliveError = require('./EverliveError').EverliveError; +var constants = require('./constants'); +var _ = require('underscore'); + +module.exports = (function () { + + function AutoQueue(maxConcurrentTasks) { + maxConcurrentTasks = parseInt(maxConcurrentTasks || constants.MaxConcurrentDownloadTasks); + + if (isNaN(maxConcurrentTasks) || maxConcurrentTasks <= 0) { + throw new EverliveError('The maxConcurrentTasks must be a number larger than 0'); + } + + this.maxConcurrentTasks = maxConcurrentTasks; + this.runningTasksCount = 0; + this.tasks = []; + } + + AutoQueue.prototype = { + /** + * @param {Function} task + * @param {Function} taskSuccess + * @param {Function} taskError + */ + enqueue: function (task, taskSuccess, taskError) { + if (!_.isFunction(taskSuccess) || !_.isFunction(taskError)) { + throw new EverliveError('taskSuccess and taskError functions must be provided'); + } + + var args = [].splice.call(arguments, 3); + + this.tasks.push({ + task: task, + args: args, + success: taskSuccess, + error: taskError + }); + + this._runNext(); + }, + + _runNext: function () { + var self = this; + + if (self.runningTasksCount === self.maxConcurrentTasks || !self.tasks.length) { + return; + } + + self.runningTasksCount++; + + var nextTask = this.tasks.shift(); + var task = nextTask.task; + var args = nextTask.args; + var taskSuccess = nextTask.success; + var taskError = nextTask.error; + + args.unshift(function executedCallback(err) { + self.runningTasksCount--; + + if (err) { + taskError(err); + } else { + taskSuccess.apply(null, [].splice.call(arguments, 1)); + } + + self._runNext(); + }); + + task.apply(null, args); + } + }; + + return AutoQueue; +}()); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069533_Vec3.js b/pool/shard011/JavaScript/0069533_Vec3.js new file mode 100644 index 0000000000000000000000000000000000000000..fe89aa1130e3c6cba617e8cc2aed6aac74abbf5b --- /dev/null +++ b/pool/shard011/JavaScript/0069533_Vec3.js @@ -0,0 +1,109 @@ + +/** @class Vec3 Operations */ +osg.Vec3 = { + init: function(a) { + a[0] = 0; a[1] = 0; a[2] = 0; + return a; + }, + + copy: function(a, r) { + r[0] = a[0]; + r[1] = a[1]; + r[2] = a[2]; + return r; + }, + + cross: function(a, b, r) { + var x = a[1]*b[2]-a[2]*b[1]; + var y = a[2]*b[0]-a[0]*b[2]; + var z = a[0]*b[1]-a[1]*b[0]; + r[0] = x; + r[1] = y; + r[2] = z; + return r; + }, + + valid: function(a) { + if (isNaN(a[0])) { + return false; + } + if (isNaN(a[1])) { + return false; + } + if (isNaN(a[2])) { + return false; + } + return true; + }, + + mult: function(a, b, r) { + r[0] = a[0] * b; + r[1] = a[1] * b; + r[2] = a[2] * b; + return r; + }, + + length2: function(a) { + return a[0]*a[0] + a[1]*a[1] + a[2]*a[2]; + }, + + length: function(a) { + return Math.sqrt( a[0]*a[0] + a[1]* a[1] + a[2]*a[2] ); + }, + + distance: function(a, b) { + var x = a[0]-b[0]; + var y = a[1]-b[1]; + var z = a[2]-b[2]; + return Math.sqrt( x*x + y*y + z*z ); + }, + + normalize: function(a, r) { + var norm = this.length2(a); + if (norm > 0.0) { + var inv = 1.0/Math.sqrt(norm); + r[0] = a[0] * inv; + r[1] = a[1] * inv; + r[2] = a[2] * inv; + } else { + r[0] = a[0]; + r[1] = a[1]; + r[2] = a[2]; + } + return r; + }, + + dot: function(a, b) { + return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]; + }, + + sub: function(a, b, r) { + r[0] = a[0]-b[0]; + r[1] = a[1]-b[1]; + r[2] = a[2]-b[2]; + return r; + }, + + add: function(a, b, r) { + r[0] = a[0]+b[0]; + r[1] = a[1]+b[1]; + r[2] = a[2]+b[2]; + return r; + }, + + neg: function(a, r) { + r[0] = -a[0]; + r[1] = -a[1]; + r[2] = -a[2]; + return r; + }, + + lerp: function(t, a, b, r) { + r[0] = a[0] + (b[0]-a[0])*t; + r[1] = a[1] + (b[1]-a[1])*t; + r[2] = a[2] + (b[2]-a[2])*t; + return r; + } + +}; + diff --git a/pool/shard011/JavaScript/0069534_generate_port_string_from_service.js b/pool/shard011/JavaScript/0069534_generate_port_string_from_service.js new file mode 100644 index 0000000000000000000000000000000000000000..e137963f59051100bb424e1d0bfb009c651ec9a1 --- /dev/null +++ b/pool/shard011/JavaScript/0069534_generate_port_string_from_service.js @@ -0,0 +1,22 @@ +/* eslint-disable no-unused-vars */ +/* globals Session Services _ Meteor */ + +function generatePortStringFromService (service) { + // Generates a comma separated unique list of open services for the current project that matches + // the regular expression provided as 'service'. + + // Usage: generatePortStringFromService(/http/) + // + // Created by: Tom Steele + // Requires client-side updates: false + + var projectId = Session.get('projectId') + var query = { + 'projectId': projectId, + 'service': service + } + var services = Services.find(query).fetch() + return _.uniq(_.pluck(services, 'port')).sort(function (a, b) { + return a - b + }).join(',') +} diff --git a/pool/shard011/JavaScript/0069535_relation-review.js b/pool/shard011/JavaScript/0069535_relation-review.js new file mode 100644 index 0000000000000000000000000000000000000000..1fa880f1fd4a68d1b048edcb82104d66a09c8c69 --- /dev/null +++ b/pool/shard011/JavaScript/0069535_relation-review.js @@ -0,0 +1,120 @@ +(function(window, $, undefined) { + + // CURRENT APP INSTANCE + var page = {}; + + /** + * Init the page + * @function + * @public + */ + page.init = function() { + + // RATE SLIDER WITH JQUERY UI + $("#rate-slider" ).slider({ + value:3, + min: 1, + max: 5, + step: 0.1, + slide: function( event, ui ) { + $( ":input[name=rate]" ).val( ui.value ); + + $("#rate-slider .ui-slider-handle").attr("title", ""+ui.value+"/5"); + + // to paralelle execution + setTimeout(function () { + $("#rate-slider .ui-slider-handle").tipsy("show"); + }, 0); + }, + change: function() { + $("#rate-slider .ui-slider-handle").tipsy("show"); + } + }); + + // LEAVE RATE SLIDER + $("#rate-slider .ui-slider-handle").blur(function() { + $("#rate-slider .ui-slider-handle").tipsy("hide"); + }) + + // RATE SLIDER PROPERTY AND TOOLTIPS + $("#rate-slider .ui-slider-handle") + .attr("title", ""+$( ":input[name=rate]" ).val()+"/5") + .tipsy({ + gravity: 's', + html: true, + opacity:1 + }); + + + // FORM SUBMIT + $(".classic-form form").submit(page.submitForm); + + // WEBSITE TOUR + page.checkWebsiteTour(); + + }; + + + /** + * Load template files + * @function + * @public + */ + page.loadTemplate = function() { + // node property + $.get("./appinc/template/tmpl/node-property.tmpl", {}, function(tmpl) {$.template( "node-property", tmpl);} ); + }; + + + /** + * Submit the form (or not) + * @function + * @public + * @return boolean + */ + page.submitForm = function() { + + return true; + + }; + + + /** + * Make a website tour (or not) + * @function + * @public + */ + page.checkWebsiteTour = function() { + + if(0 && ! $.cookies.get("no-website-tour") && window.isConnected ) { + + new makeWebsiteTour([ + { + "selector" : ".up_menu li.current", + "position" : "T", + "text" : "See a random relation between 2 nodes to estimate its trust level." + }, + { + "selector" : "h3:eq(2)", + "position" : "B", + "text" : "How valid does this piece of information sounds to you?" + }, { + "selector" : ".rate-legend:eq(0)", + "position" : "BR", + "text" : "Looks fishy" + }, { + "selector" : ".rate-legend:eq(1)", + "position" : "BL", + "text" : "Looks solid" + }, { + "url" : "./?screen=relation-visualise" + } + + ], 0); + } + }; + + // WHEN THE DOCUMENT IS READY, INIT THE APP + $(document).ready(page.init); + +})(window, jQuery); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069536_child.js b/pool/shard011/JavaScript/0069536_child.js new file mode 100644 index 0000000000000000000000000000000000000000..ac95e08e2479a350e0bb98275bf9f0dc0f0a8520 --- /dev/null +++ b/pool/shard011/JavaScript/0069536_child.js @@ -0,0 +1,138 @@ +var QUnit = require('qunitjs'), + path = require('path'), + _ = require('underscore'), + trace = require('tracejs').trace, + coverage = require('./coverage'); + +// cycle.js: This file contains two functions, JSON.decycle and JSON.retrocycle, +// which make it possible to encode cyclical structures and dags in JSON, and to +// then recover them. JSONPath is used to represent the links. +// http://GOESSNER.net/articles/JsonPath/ +require('../support/json/cycle'); + +var options = JSON.parse(process.argv[2]), + currentModule = path.basename(options.code.path, '.js'), + currentTest; + +process.on('uncaughtException', function(err) { + if (QUnit.config.current) { + QUnit.ok(false, 'Test threw unexpected exception: ' + err.message); + QUnit.start(); + } + process.send({ + event: 'uncaughtException', + data: { + message: err.message, + stack: err.stack + } + }); +}); + +QUnit.config.autorun = false; +QUnit.config.autostart = false; + +// make qunit api global, like it is in the browser +_.extend(global, QUnit); + +// as well as the QUnit variable itself +global.QUnit = QUnit; + +/** + * Require a resource. + * @param {Object} res + */ +function _require(res, addToGlobal) { + var exports = require(res.path.replace(/\.js$/, '')); + + if (addToGlobal) { + // resource can define 'namespace' to expose its exports as a named object + if (res.namespace) { + global[res.namespace] = exports; + } else { + _.extend(global, exports); + } + } + + QUnit.start(); +} + +/** + * Callback for each started test. + * @param {Object} test + */ +QUnit.testStart(function(test) { + // currentTest is undefined while first test is not done yet + currentTest = test.name; + + // use last module name if no module name defined + currentModule = test.module || currentModule; +}); + +/** + * Callback for each assertion. + * @param {Object} data + */ +QUnit.log(function(data) { + data.test = this.config.current.testName; + data.module = currentModule; + process.send({ + event: 'assertionDone', + data: JSON.decycle(data) + }); +}); + +/** + * Callback for one done test. + * @param {Object} test + */ +QUnit.testDone(function(data) { + // use last module name if no module name defined + data.module = data.module || currentModule; + process.send({ + event: 'testDone', + data: data + }); +}); + +/** + * Callback for all done tests in the file. + * @param {Object} res + */ +QUnit.done(_.debounce(function(data) { + data.coverage = global.__coverage__; + + process.send({ + event: 'done', + data: data + }); +}, 1000)); + +/** + * Provide better stack traces + */ +var error = console.error; +console.error = function(obj) { + // log full stacktrace + if (obj && obj.stack) { + obj = trace(obj); + } + + return error.apply(this, arguments); +}; + +if (options.coverage) { + coverage.instrument(options); +} + +// require deps +options.deps.forEach(function(dep) { + _require(dep, true); +}); + +// require code +_require(options.code, true); + +// require tests +options.tests.forEach(function(test) { + _require(test, false); +}); diff --git a/pool/shard011/JavaScript/0069539_topic-test.js b/pool/shard011/JavaScript/0069539_topic-test.js new file mode 100644 index 0000000000000000000000000000000000000000..6383bcd056e29cfe1ba2934bd3da94fa60418a83 --- /dev/null +++ b/pool/shard011/JavaScript/0069539_topic-test.js @@ -0,0 +1,205 @@ +import expect from 'expect'; +import md5 from 'spark-md5'; +import * as types from '../../types'; + +describe('Topics reducer', () => { + const s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + + function createTopic() { + return Array(5).join().split(',') + .map(() => { + return s.charAt(Math.floor(Math.random() * s.length)); + }) + .join(''); + } + + const topic = createTopic(); + + function createData() { + return { + text: createTopic(), + id: md5.hash(createTopic()), + count: Math.floor(Math.random() * 100) + }; + } + + const data = createData(); + + function createTopics(x) { + const arr = []; + for (let i = 0; i < x; i++) { + arr.push(createData()); + } + return arr; + } + + it('Should return the initial state', () => { + expect( + reducer(undefined, {}) + ).toEqual( + { + topics: [], + newTopic: '' + } + ); + }); + + it('Should add a new topic to an empty initial state', () => { + expect( + reducer(undefined, { + type: types.CREATE_TOPIC_REQUEST, + id: data.id, + count: 1, + text: topic + }) + ).toEqual({ + topics: [ + { + id: data.id, + count: 1, + text: topic + } + ], + newTopic: '' + }); + }); + + it('Should handle TYPING', () => { + expect( + reducer(undefined, { + type: types.TYPING, + newTopic: topic + }) + ).toEqual({ + topics: [], + newTopic: topic + }); + }); + + it('Should handle CREATE_REQUEST', () => { + expect( + reducer(undefined, { + type: types.CREATE_REQUEST + }) + ).toEqual({ + topics: [], + newTopic: '' + }); + }); + + it('Should handle REQUEST_SUCCESS', () => { + expect( + reducer(undefined, { + type: types.REQUEST_SUCCESS, + data: topic + }) + ).toEqual({ + topics: topic, + newTopic: '' + }); + }); + + it('Should handle CREATE_TOPIC_REQUEST', () => { + const topics = createTopics(20); + const newTopics = [...topics, data]; + expect( + reducer({ + topics + }, + { + type: types.CREATE_TOPIC_REQUEST, + id: data.id, + count: data.count, + text: data.text + + }) + ).toEqual({ + newTopic: '', + topics: newTopics + }); + }); + + it('should handle CREATE_TOPIC_FAILURE', () => { + const topics = createTopics(20); + topics.push(data); + const newTopics = [...topics]; + expect( + reducer({ + topics, + newTopic: topic + }, + { + type: types.CREATE_TOPIC_FAILURE, + id: data.id + }) + ).toEqual({ + topics: newTopics.pop() && newTopics, + newTopic: topic + }); + }); + + it('should handle DESTROY_TOPIC', () => { + const topics = createTopics(20); + topics.push(data); + const newTopics = [...topics]; + expect( + reducer({ + topics, + newTopic: topic + }, + { + type: types.DESTROY_TOPIC, + id: topics[topics.length - 1].id, + }) + ).toEqual({ + topics: newTopics.pop() && newTopics, + newTopic: topic + }); + }); + + it('should handle INCREMENT_COUNT', () => { + const topics = createTopics(20); + const newTopics = [...topics]; + topics.push(data); + const newData = Object.assign({}, data); + newData.count++; + newTopics.push(newData); + + expect( + reducer({ + topics, + newTopic: topic + }, + { + type: types.INCREMENT_COUNT, + id: topics[topics.length - 1].id, + }) + ).toEqual({ + topics: newTopics, + newTopic: topic + }); + }); + + it('should handle DECREMENT_COUNT', () => { + const topics = createTopics(20); + const newTopics = [...topics]; + topics.push(data); + const newData = Object.assign({}, data); + newData.count--; + newTopics.push(newData); + + expect( + reducer({ + topics, + newTopic: topic + }, + { + type: types.DECREMENT_COUNT, + id: topics[topics.length - 1].id, + }) + ).toEqual({ + topics: newTopics, + newTopic: topic + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069542_context.js b/pool/shard011/JavaScript/0069542_context.js new file mode 100644 index 0000000000000000000000000000000000000000..04048142acfc31298570f632a3e5c65904938e3c --- /dev/null +++ b/pool/shard011/JavaScript/0069542_context.js @@ -0,0 +1,46 @@ +.pragma library + +//scale - number px in unit +function CartesianContext(ctx, scale, startX, startY) { + this.ctx = ctx; + this.scale = scale; + + // private variable + this.startX = ctx.canvas.width / 2 + scale * startX; + this.startY = ctx.canvas.height / 2 - scale * startY; + + // public variable + this.leftX = -this.startX / scale; + this.downY = (this.startY - ctx.canvas.height) / scale; + this.rightX = (ctx.canvas.width - this.startX) / scale; + this.upY = this.startY / scale; + + // context2d properties + this.lineWidth = 1; + // function from context2d + this.moveTo = function(x, y) { + this.ctx.moveTo(this.fromCortesianX(x), this.fromCortesianY(y)); + } + + this.lineTo = function(x, y) { + this.ctx.lineTo(this.fromCortesianX(x), this.fromCortesianY(y)); + } + + this.reset = function() { + this.ctx.reset(); + } + + this.stroke = function() { + this.ctx.lineWidth = 1; + this.ctx.stroke(); + } + + //private functions + this.fromCortesianX = function(x) { + return this.startX + x * scale; + } + + this.fromCortesianY = function(y) { + return this.startY - y * scale; + } +} diff --git a/pool/shard011/JavaScript/0069544_tag.js b/pool/shard011/JavaScript/0069544_tag.js new file mode 100644 index 0000000000000000000000000000000000000000..6cb238c831a1dcaa7039ee2ccde4ea63942e19a5 --- /dev/null +++ b/pool/shard011/JavaScript/0069544_tag.js @@ -0,0 +1,125 @@ +// Copyright 2007 The Closure Library Authors. All Rights Reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS-IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview DOM pattern to match a tag. + * + * @author robbyw@google.com (Robby Walker) + */ + +goog.provide('goog.dom.pattern.Tag'); + +goog.require('goog.dom.pattern'); +goog.require('goog.dom.pattern.AbstractPattern'); +goog.require('goog.dom.pattern.MatchType'); +goog.require('goog.object'); + + + +/** + * Pattern object that matches an tag. + * + * @param {string|RegExp} tag Name of the tag. Also will accept a regular + * expression to match against the tag name. + * @param {goog.dom.TagWalkType} type Type of token to match. + * @param {Object=} opt_attrs Optional map of attribute names to desired values. + * This pattern will only match when all attributes are present and match + * the string or regular expression value provided here. + * @param {Object=} opt_styles Optional map of CSS style names to desired + * values. This pattern will only match when all styles are present and + * match the string or regular expression value provided here. + * @param {Function=} opt_test Optional function that takes the element as a + * parameter and returns true if this pattern should match it. + * @constructor + * @extends {goog.dom.pattern.AbstractPattern} + */ +goog.dom.pattern.Tag = function(tag, type, opt_attrs, opt_styles, opt_test) { + /** + * The tag to match. + * + * @private {string|RegExp} + */ + this.tag_ = goog.isString(tag) ? tag.toUpperCase() : tag; + + /** + * The type of token to match. + * + * @private {goog.dom.TagWalkType} + */ + this.type_ = type; + + /** + * The attributes to test for. + * + * @private {Object} + */ + this.attrs_ = opt_attrs || null; + + /** + * The styles to test for. + * + * @private {Object} + */ + this.styles_ = opt_styles || null; + + /** + * Function that takes the element as a parameter and returns true if this + * pattern should match it. + * + * @private {Function} + */ + this.test_ = opt_test || null; +}; +goog.inherits(goog.dom.pattern.Tag, goog.dom.pattern.AbstractPattern); + + +/** + * Test whether the given token is a tag token which matches the tag name, + * style, and attributes provided in the constructor. + * @param {Node} token Token to match against. + * @param {goog.dom.TagWalkType} type The type of token. + * @return {goog.dom.pattern.MatchType} MATCH if the pattern + * matches, NO_MATCH otherwise. + * @override + * @suppress {strictMissingProperties} Part of the go/strict_warnings_migration + */ +goog.dom.pattern.Tag.prototype.matchToken = function(token, type) { + // Check the direction and tag name. + if (type == this.type_ && + goog.dom.pattern.matchStringOrRegex(this.tag_, token.nodeName)) { + // Check the attributes. + if (this.attrs_ && + !goog.object.every( + this.attrs_, goog.dom.pattern.matchStringOrRegexMap, token)) { + return goog.dom.pattern.MatchType.NO_MATCH; + } + // Check the styles. + if (this.styles_ && + !goog.object.every( + this.styles_, goog.dom.pattern.matchStringOrRegexMap, + token.style)) { + return goog.dom.pattern.MatchType.NO_MATCH; + } + + if (this.test_ && !this.test_(token)) { + return goog.dom.pattern.MatchType.NO_MATCH; + } + + // If we reach this point, we have a match and should save it. + this.matchedNode = token; + return goog.dom.pattern.MatchType.MATCH; + } + + return goog.dom.pattern.MatchType.NO_MATCH; +}; diff --git a/pool/shard011/JavaScript/0069550_main.js b/pool/shard011/JavaScript/0069550_main.js new file mode 100644 index 0000000000000000000000000000000000000000..2175779421ab205194ba38516f1a50028609a54b --- /dev/null +++ b/pool/shard011/JavaScript/0069550_main.js @@ -0,0 +1,22 @@ +import webpack from 'webpack'; +import webpackDev from 'webpack-dev-middleware'; +import webpackHot from 'webpack-hot-middleware'; +import makeWebpackConfig from '../makeConfig'; +import express from 'express'; + +const app = express(); + +const webpackConfig = makeWebpackConfig(true); +const compiler = webpack(webpackConfig); + +app.use(webpackDev(compiler, { + headers: {'Access-Control-Allow-Origin': '*'}, + noInfo: true, + publicPath: webpackConfig.output.publicPath +})); + +app.use(webpackHot(compiler)); + +app.listen(webpackConfig.hotPort, () => { + console.log('Hot server started at port %d', webpackConfig.hotPort); // eslint-disable-line no-console +}); diff --git a/pool/shard011/JavaScript/0069551_mongoAuthSpec.js b/pool/shard011/JavaScript/0069551_mongoAuthSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..87167b8ce970d912c578f7006f1735a30640a47f --- /dev/null +++ b/pool/shard011/JavaScript/0069551_mongoAuthSpec.js @@ -0,0 +1,66 @@ +var should = require('should'); +var Promise = require('bluebird') +var sinon = require('sinon'); +var request = require('supertest'); +var setup = require('./../mocks/setup'); +var fixtures = Promise.promisifyAll(require('node-mongoose-fixtures')); +var service = require('./../../src/services/user'); + +setup.makeSuite('Authentication', function() { + + before(function before(done) { + fixtures.resetAsync('User') + .then(function(result) { + service.register({ + email: 'joe@mailinator.com', + password: 'joe' + }) + .then(function(result) { + done() + }) + }) + }) + + it('should login', function test(done) { + request(setup.server) + .post('/login') + .send({ + username: 'joe@mailinator.com', + password: 'joe' + }) + .end(function afterRequest(err, res) { + res.res.headers.location.should.eql('/'); + res.statusCode.should.eql(302) + done(); + }); + }) + + it('should not login with not existent user', function test(done) { + request(setup.server) + .post('/login') + .send({ + username: 'wrong', + password: 'wrong' + }) + .end(function afterRequest(err, res) { + res.res.headers.location.should.eql('/login'); + res.statusCode.should.eql(302) + done(); + }); + }) + + it('should not login with incorrect password', function test(done) { + request(setup.server) + .post('/login') + .send({ + username: 'joe@mailinator.com', + password: 'wrong' + }) + .end(function afterRequest(err, res) { + res.res.headers.location.should.eql('/login'); + res.statusCode.should.eql(302) + done(); + }) + }) + +}); diff --git a/pool/shard011/JavaScript/0069552_logger.js b/pool/shard011/JavaScript/0069552_logger.js new file mode 100644 index 0000000000000000000000000000000000000000..3737d5b3c1f5a28122bbc6bc772d3dd6f03e7d9d --- /dev/null +++ b/pool/shard011/JavaScript/0069552_logger.js @@ -0,0 +1,30 @@ +//module meant for logging to stdout and stderr to the user of immediate information +var winston = require('winston'); + +module.exports = function (logEnv) { + var env = logEnv; + var logLevel = "debug"; //default + if (env === "PRODUCTION") { + logLevel = "error"; //logs errors + } + else if (env === "INFO") { + logLevel = "info"; //logs info, error + } + + var logger = new winston.Logger({ + transports: [ + new winston.transports.Console({ + colorize: true, + timestamp: true, + level: logLevel + }), + new winston.transports.File({ + level: logLevel, + name: 'manticore', + filename: 'manticore.log' + }) + ], + exitOnError: false + }); + return logger; +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069553_ajax.js b/pool/shard011/JavaScript/0069553_ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..b122bcfb6d10d78a6aeda4aed633e9fe8065b6cf --- /dev/null +++ b/pool/shard011/JavaScript/0069553_ajax.js @@ -0,0 +1,19 @@ +const database = require('database/database'); // eslint-disable-line + +function getChartData(req, res) { + // data from last 24h + const goBack = (24 * 60 * 60 * 1000); + const tempData = database.getTemperatures(new Date(Date.now() - goBack)); + const targetData = database.getTargets(new Date(Date.now() - goBack)); + const weatherData = database.getWeather(new Date(Date.now() - goBack)); + + Promise.all([tempData, targetData, weatherData]) + .then((result) => { + res.send(result); + }).catch(() => res.end()); +} + + +module.exports = { + getChartData, +}; diff --git a/pool/shard011/JavaScript/0069555_server.js b/pool/shard011/JavaScript/0069555_server.js new file mode 100644 index 0000000000000000000000000000000000000000..85a8d7612bd1db5fdfa7c7b1074afae14770758d --- /dev/null +++ b/pool/shard011/JavaScript/0069555_server.js @@ -0,0 +1,36 @@ +// Generated by CoffeeScript 1.3.3 +(function() { + var fs, http, index, mundleCoffee, mundleJade, server, serverRequire; + + http = require('http'); + + fs = require('fs'); + + mundleCoffee = require('mundle-coffee-script'); + + mundleJade = require('mundle-jade'); + + serverRequire = require('../../lib/server'); + + serverRequire.setBasePath('./'); + + serverRequire.use(mundleCoffee); + + serverRequire.use(mundleJade); + + index = fs.readFileSync('./index.html'); + + (server = http.createServer(function(req, res) { + if (req.url === '/') { + res.writeHead(200, { + 'Content-Type': 'text/html' + }); + return res.end(index); + } + })).listen(1337, '127.0.0.1'); + + serverRequire.listen(server); + + console.log('Server running at http://127.0.0.1:1337/'); + +}).call(this); diff --git a/pool/shard011/JavaScript/0069557_Domo.js b/pool/shard011/JavaScript/0069557_Domo.js new file mode 100644 index 0000000000000000000000000000000000000000..79af1209284f09d1d701e35093fd495117b687d9 --- /dev/null +++ b/pool/shard011/JavaScript/0069557_Domo.js @@ -0,0 +1,51 @@ +var _ = require('underscore'); +var models = require('../models'); + +var Domo = models.Domo; + +var makerPage = function(req, res){ + Domo.DomoModel.findByOwner(req.session.account._id, function(err, docs) { + if(err) { + console.log(err); + return res.status(400).json({error:'An error occurred'}); + } + res.render('app', {csrfToken: req.csrfToken(), domos: docs}); + }); +}; + +var leaderBoard = function(req, res){ + Domo.DomoModel.findByTop('age', function(err, docs) { + if(err) { + console.log(err); + return res.status(400).json({error:'An error occurred'}); + } + res.render('leader', {csrfToken: req.csrfToken(), domos: docs}); + }); +}; + +var makeDomo = function(req, res){ + if(!req.body.name || !req.body.age) { + return res.status(400).json({error: "RAWR! Both name and age are required!"}); + } + var domoData = { + name: req.body.name, + age: req.body.age, + gender: req.body.gender, + owner: req.session.account._id, + }; + + var newDomo = new Domo.DomoModel(domoData); + + newDomo.save(function(err){ + if(err){ + console.log(err); + return res.status(400).json({error:'An error occurred'}); + } + + res.json({redirect: '/maker'}); + }); +}; + +module.exports.makerPage = makerPage; +module.exports.leaderBoard = leaderBoard; +module.exports.make = makeDomo; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069560_FiltersWithValuesCqlBuilder.js b/pool/shard011/JavaScript/0069560_FiltersWithValuesCqlBuilder.js new file mode 100644 index 0000000000000000000000000000000000000000..493e72da4b83d19402a385d756e1c24704b58b89 --- /dev/null +++ b/pool/shard011/JavaScript/0069560_FiltersWithValuesCqlBuilder.js @@ -0,0 +1,15 @@ +Ext.namespace('Portal.filter.combiner'); + +Portal.filter.combiner.FiltersWithValuesCqlBuilder = Ext.extend(Portal.filter.combiner.FilterCqlBuilder, { + + + buildCql: function() { + + var cqlParts = this._filtersWithValues().map(function(filter) { + + return filter.getCql(); + }); + + return this._joinCql(cqlParts); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069562_spot.controller.js b/pool/shard011/JavaScript/0069562_spot.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..ef3e4b8476b226aee8c057056ea84da88a380f8b --- /dev/null +++ b/pool/shard011/JavaScript/0069562_spot.controller.js @@ -0,0 +1,234 @@ +(function () { + 'use strict'; + + angular + .module('app') + .controller('SpotController', SpotController); + + SpotController.$inject = ['$scope', '$http', '$filter', '$interval']; + + function SpotController($scope, $http, $filter, $interval) { + $scope.title = 'SpotController'; + $scope.model = {}; + $scope.personalities = []; + $scope.spotTonality = false; + var Report = function () { + this.Id = 0; + this.PersonalityId = 0; + this.Message = ''; + this.Customer = ''; + this.Personality = {}; + }; + $scope.report = new Report(); + $scope.reports = new Array(); + + $scope.groups = []; + // Get report from storage + var names = { + 'Center': 'Centers', + 'HarmonicGroup': 'HarmonicGroups', + 'SocialStyle': 'SocialStyles', + 'Tonality': 'Tonalities' + }; + + var Strategy = function (Id, $index) { + this.Id = Id || null; + this.$index = $index || null; + }; + + var SelectedViewModel = function (Center, hg, ss, t) { + this.Center; + this.HarmonicGroup; + this.SocialStyle; + this.Tonality; + }; + + $scope.selected = new SelectedViewModel(null, null, null, null); + + $scope.message = { + classes: '', + text: '', + show: function () { + $scope.message._show = true; + $interval(function () { + $scope.message._show = false; + }, 5000); + }, + _show: false + }; + + $scope.loading = true; + $scope.getAll = function () { + $http.get("/Spot/GetAll").success(function (data) { + $scope.model = data; + $scope.reports = []; + + angular.forEach(data.Reports, function (obj) { + // Parse dates values + var report = obj; + report.CreateDate = moment(report.CreateDate); + if (report.UpdateDate !== null) { + report.UpdateDate = moment(report.UpdateDate); + } + $scope.reports.push(report); + }); + + activate(); + }); + }; + $scope.getAll(); + + if (localStorage !== undefined) { + $scope.spotTonality = localStorage.getItem('spotToanlity'); + }; + $scope.toggleSpot = function () { + $scope.spotTonality = !$scope.spotTonality; + if (localStorage !== undefined) { + localStorage.setItem('spotToanlity', $scope.spotTonality); + }; + }; + + function activate() { + $scope.loading = false; + $scope.selectPersonality = function () { + var CenterId = $scope.getSelectedId('Center'); + var HarmonicGroupId = $scope.getSelectedId('HarmonicGroup'); + var SocialStyleId = $scope.getSelectedId('SocialStyle'); + var TonalityId = $scope.getSelectedId('Tonality'); + + $scope.personalities = []; + angular.forEach($scope.model.Personalities, function (personality) { + if (CenterId != null || SocialStyleId != null || HarmonicGroupId != null || TonalityId != null) { + if ((personality.CenterId == CenterId || CenterId == null) + && (personality.SocialStyleId == SocialStyleId || SocialStyleId == null) + && (personality.TonalityId == TonalityId || TonalityId == null) + && (personality.HarmonicGroupId == HarmonicGroupId || HarmonicGroupId == null)) { + $scope.personalities.push(personality); + }; + }; + }); + }; + + $scope.getSelectedId = function (name) { + var s = $scope.selected[name]; + return angular.isDefined(s) ? s.Id : null; + }; + + $scope.select = function (name, Id, $index) { + var s = $scope.selected[name]; + if (angular.isDefined(s) && s.Id == Id) { + // Deselect + $scope.selected[name] = undefined; + } else { + // Select + $scope.selected[name] = $scope.model[names[name]][$index]; + $scope.selected[name].$index = $index; + }; + + $scope.selectPersonality(); + }; + // Reset all selected and model + $scope.clear = function () { + $scope.selected = new SelectedViewModel(); + $scope.report = new Report(); + $scope.personalities = []; + }; + + $scope.submit = function () { + $scope.loading = true; + $scope.report.PersonalityId = $scope.personalities[0].Id; + $http.post('/Spot/Create', $scope.report) + .success(function () { + // Success + $scope.report.Personality = $scope.personalities[0]; + $scope.reports.push($scope.report); + + $scope.clear(); + $scope.loading = false; + + // Increment + $scope.model.TotalToday += 1; + $scope.model.TotalReports += 1; + + $scope.message.classes = ['alert-success']; + $scope.message.text = "Gemt! - Din raport er modtaget"; + $scope.message.show(); + }).error(function () { + // Error + // Display an error message + }); + }; + + $scope.preselect = function (name, Id) { + var contains = false; + + angular.forEach($scope.personalities, function (personality) { + + // TODO: Make faster + if (!angular.isDefined($scope.selected[name])) { + var newName = name + "Id"; + if (personality[newName] == Id) { + contains = true; + }; + }; + }); + + return contains; + }; + + $scope.classes = function (name, Id) { + var classes = [], + contains = false; + + if ($scope.getSelectedId(name) == Id) { + return ['active']; + }; + + if ($scope.personalities.length == 0) { + return []; + }; + + contains = $scope.preselect(name, Id); + + if ($scope.personalities.length == 1 && contains) { + return ['active']; + } else if ($scope.personalities.length == 1 && !contains && $scope.getSelectedId(name) == null) { + return ['disabled']; + }; + + return []; + }; + + // Default images + var defaultImages = { + 'Center': '/Content/images/Centers.png', + 'Tonality': '/Content/images/Tonalities.png', + 'HarmonicGroup': '/Content/images/HarmonicGroups.png', + 'SocialStyle': '/Content/images/SocialStyles.png' + }; + + // Return the apropiate url for current object name + $scope.getImage = function (name) { + if ($scope.personalities.length == 1) { + return $scope.personalities[0][name].Url; + } else if (angular.isDefined($scope.selected[name]) + && ($scope.selected[name].Url !== null && $scope.selected[name].Url.length > 0)) { + return $scope.selected[name].Url; + } else { + return defaultImages[name]; + }; + }; + + $scope.getDescription = function (name) { + //

    + //

    + if (angular.isDefined($scope.selected[name])) { + return $scope.selected[name].Description; + } else if($scope.personalities.length == 1) { + return $scope.personalities[0][name].Description; + } + return null; + }; + }; + }; +})(); diff --git a/pool/shard011/JavaScript/0069563_scrollTop.js b/pool/shard011/JavaScript/0069563_scrollTop.js new file mode 100644 index 0000000000000000000000000000000000000000..887bd6aca629e16fce41d292c7dbe5f0c35dccdb --- /dev/null +++ b/pool/shard011/JavaScript/0069563_scrollTop.js @@ -0,0 +1,42 @@ +function adjustAnchor(hash){ + // this used to work + // var $anchor = $(':target') + // after tubolinks upgrade i have to pash the has in + var $anchor = $(hash), + fixedElementHeight = 100; + console.log($anchor); + + + $anchor.css({backgroundColor: "yellow"}); + $anchor.animate({backgroundColor: "none"}, 5000); + + + if ($anchor.length > 0) { + + $('html, body') + .stop() + .animate({ + scrollTop: $anchor.offset().top - fixedElementHeight + //scrollTop: $anchor.offset().top + }, 500); + + } + +} + + + +$(document).on('turbolinks:load', function () { + $(document).ready(function(){ + if(window.location.hash){ + // this is a strange fix. I used to be able to let the function + //find the target; but after turbolinks upgrade this no longer works + //hash must be passed to function + adjustAnchor(window.location.hash); + } + }); +}); + +//$(window).on('hashchange load', function() { + // adjustAnchor(); + // }); diff --git a/pool/shard011/JavaScript/0069564_index.js b/pool/shard011/JavaScript/0069564_index.js new file mode 100644 index 0000000000000000000000000000000000000000..88eed1ecfae1994bd02579eb16d98bb07fc0d555 --- /dev/null +++ b/pool/shard011/JavaScript/0069564_index.js @@ -0,0 +1,66 @@ +var fs = require('fs'); +var path = require('path'); +var util = require('util'); +var assert = require('assert'); + +var xtend = require('xtend'); +var through = require('through2'); +var browserify = require('browserify'); +var browserifyCache = require('browserify-cache-api'); + +module.exports = browserifyIncremental; +browserifyIncremental.browserify = browserify; +browserifyIncremental.args = browserifyCache.args; + +function browserifyIncremental(files, opts) { + var b; // browserify instance + + // browserify plugin boilerplate, normalises variable arguments + if (files && typeof files.bundle === 'function') { + // browserify instance as first arg + b = files; + opts = opts || b._options; + } else { + if (!opts) { + // opts as first arg (or no args) + opts = files || {}; + files = undefined; + b = browserify(xtend(browserifyCache.args, opts)); + } else { + // files as first arg, opts as second arg + b = browserify(files, xtend(browserifyCache.args, opts)); + } + } + + browserifyCache(b, opts); + + if (!b.pipeline) b.emit('error', new Error('missing pipeline: incompatible browserify version (< 5.x)')); + b.on('reset', function() { attachMetrics(b); }); + attachMetrics(b); + + return b; +} + +function attachMetrics(b) { + var time = null; + var bytes = 0; + b.pipeline.get('record').on('end', function () { + time = Date.now(); + }); + + b.pipeline.get('wrap').push(through(write, end)); + function write (buf, enc, next) { + bytes += buf.length; + this.push(buf); + next(); + } + function end () { + var delta = Date.now() - time; + b.emit('time', delta); + b.emit('bytes', bytes); + b.emit('log', bytes + ' bytes written (' + + (delta / 1000).toFixed(2) + ' seconds)' + ); + this.push(null); + } +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069566_daemon.test.js b/pool/shard011/JavaScript/0069566_daemon.test.js new file mode 100644 index 0000000000000000000000000000000000000000..88e1b6e9ed47d2c288bf2b4bde670c848cdab985 --- /dev/null +++ b/pool/shard011/JavaScript/0069566_daemon.test.js @@ -0,0 +1,92 @@ +'use strict'; +var path = require('path'); + +var co = require('co'); +var cothunkify = require('co-thunkify'); +var sleep = require('co-sleep'); + +var chai = require('chai'); +var expect = chai.expect; +var sinon = require('sinon'); +var sinonChai = require("sinon-chai"); + +var session = require(path.resolve('./')); +var modulePath = './daemon'; +var underTest = require(path.resolve(modulePath)); +var sessionData = { + elec: {accountNumber: '1234567890'}, + gas: {accountNumber: '1234567890'} + }; + +chai.use(sinonChai); + +describe.skip('su-apisession/daemon', function() { + + it('should invalidate a token if it be timeded out', cothunkify(function* () { + var token = yield session.set(sessionData); + + yield sleep(225); + + yield underTest.cleanup(); + + yield sleep(225); + + expect(yield session.get(token)).to.be.null; + + })); + + it('should allow listeners to observe `session:expired` events expecting the goddamn session `token, data` as the callback args', cothunkify(function* () { + var token = yield session.set(sessionData); + var fired = false; + underTest.listen(function(session, data) { + if (fired === true) { + return; + } + + fired = true; + + expect(session).to.be.equal(token); + + expect(data).to.be.an.object; + + expect(data.isValid).to.be.false; + }); + + yield sleep(225); + + yield underTest.cleanup(); + + yield sleep(225); + + })); + + it('should allow starting and stoping of the daemon', cothunkify(function* () { + yield sleep(225); + + yield underTest.cleanup(); + + yield sleep(225); + + var token = yield session.set(sessionData); + + yield sleep(100); + + underTest.listen(function(session, data) { + expect(session).to.be.a.string; + + expect(data).to.be.an.object; + }); + + underTest.start(); + + yield sleep(250); + + underTest.stop(); + + yield sleep(250); + + expect(yield session.get(token)).to.be.null; + + })); + +}); diff --git a/pool/shard011/JavaScript/0069569_app-routing.module.js b/pool/shard011/JavaScript/0069569_app-routing.module.js new file mode 100644 index 0000000000000000000000000000000000000000..7a10aeab9a5c5118188dffc44ed635894438393e --- /dev/null +++ b/pool/shard011/JavaScript/0069569_app-routing.module.js @@ -0,0 +1,35 @@ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var core_1 = require('@angular/core'); +var router_1 = require('@angular/router'); +var dashboard_component_1 = require('./dashboard/dashboard.component'); +var journalentriescomponent_1 = require('./Journal/journalentriescomponent'); +var journal_detail_component_1 = require('./Journal/journal-detail.component'); +var routes = [ + { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, + { path: 'dashboard', component: dashboard_component_1.DashboardComponent }, + { path: 'detail/:id', component: journal_detail_component_1.JournalDetailComponent }, + { path: 'journalEntries', component: journalentriescomponent_1.JournalEntriesComponent }, +]; +var AppModule = (function () { + function AppModule() { + } + AppModule = __decorate([ + core_1.NgModule({ + imports: [router_1.RouterModule.forRoot(routes)], + exports: [router_1.RouterModule] + }), + __metadata('design:paramtypes', []) + ], AppModule); + return AppModule; +}()); +exports.AppModule = AppModule; +//# sourceMappingURL=app-routing.module.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069570_Gruntfile.js b/pool/shard011/JavaScript/0069570_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..e04bf055247c09e76c4bf1f7589f306f86e08fa6 --- /dev/null +++ b/pool/shard011/JavaScript/0069570_Gruntfile.js @@ -0,0 +1,164 @@ +'use strict'; + +var assign = require('object-assign'); +var path = require('path'); +var process = require('process'); + +var GULP_EXE = 'gulp'; +if (process.platform === 'win32') { + GULP_EXE += '.cmd'; +} + +module.exports = function(grunt) { + + grunt.initConfig({ + pkg: grunt.file.readJSON('package.json'), + jsx: require('./grunt/config/jsx'), + browserify: require('./grunt/config/browserify'), + npm: require('./grunt/config/npm'), + clean: [ + './build', + './*.gem', + './docs/_site', + './examples/shared/*.js', + '.module-cache', + ], + 'compare_size': require('./grunt/config/compare_size'), + }); + + grunt.config.set('compress', require('./grunt/config/compress')); + + function spawnGulp(args, opts, done) { + + grunt.util.spawn({ + // This could be more flexible (require.resolve & lookup bin in package) + // but if it breaks we'll fix it then. + cmd: path.join('node_modules', '.bin', GULP_EXE), + args: args, + opts: assign({stdio: 'inherit'}, opts), + }, function(err, result, code) { + if (err) { + grunt.fail.fatal('Something went wrong running gulp: ', result); + } + done(code === 0); + }); + } + + Object.keys(grunt.file.readJSON('package.json').devDependencies) + .filter(function(npmTaskName) { + return npmTaskName.indexOf('grunt-') === 0; + }) + .filter(function(npmTaskName) { + return npmTaskName !== 'grunt-cli'; + }) + .forEach(function(npmTaskName) { + grunt.loadNpmTasks(npmTaskName); + }); + + grunt.registerTask('eslint', require('./grunt/tasks/eslint')); + + grunt.registerTask('lint', ['eslint']); + + grunt.registerTask('delete-build-modules', function() { + // Use gulp here. + spawnGulp(['react:clean'], null, this.async()); + }); + + // Register jsx:normal and :release tasks. + grunt.registerMultiTask('jsx', require('./grunt/tasks/jsx')); + + // Our own browserify-based tasks to build a single JS file build. + grunt.registerMultiTask('browserify', require('./grunt/tasks/browserify')); + + grunt.registerMultiTask('npm', require('./grunt/tasks/npm')); + + var npmReactTasks = require('./grunt/tasks/npm-react'); + grunt.registerTask('npm-react:release', npmReactTasks.buildRelease); + grunt.registerTask('npm-react:pack', npmReactTasks.packRelease); + + var npmReactDOMTasks = require('./grunt/tasks/npm-react-dom'); + grunt.registerTask('npm-react-dom:release', npmReactDOMTasks.buildRelease); + grunt.registerTask('npm-react-dom:pack', npmReactDOMTasks.packRelease); + + var npmReactAddonsTasks = require('./grunt/tasks/npm-react-addons'); + grunt.registerTask('npm-react-addons:release', npmReactAddonsTasks.buildReleases); + grunt.registerTask('npm-react-addons:pack', npmReactAddonsTasks.packReleases); + + grunt.registerTask('version-check', require('./grunt/tasks/version-check')); + + grunt.registerTask('build:basic', [ + 'build-modules', + 'version-check', + 'browserify:basic', + ]); + grunt.registerTask('build:addons', [ + 'build-modules', + 'browserify:addons', + ]); + grunt.registerTask('build:min', [ + 'build-modules', + 'version-check', + 'browserify:min', + ]); + grunt.registerTask('build:addons-min', [ + 'build-modules', + 'browserify:addonsMin', + ]); + grunt.registerTask('build:npm-react', [ + 'version-check', + 'build-modules', + 'npm-react:release', + ]); + grunt.registerTask('build:react-dom', require('./grunt/tasks/react-dom')); + + grunt.registerTask('test', ['jest']); + grunt.registerTask('npm:test', ['build', 'npm:pack']); + + grunt.registerTask('jest', require('./grunt/tasks/jest')); + + // Optimized build task that does all of our builds. The subtasks will be run + // in order so we can take advantage of that and only run build-modules once. + grunt.registerTask('build', [ + 'delete-build-modules', + 'build-modules', + 'version-check', + 'browserify:basic', + 'browserify:addons', + 'browserify:min', + 'browserify:addonsMin', + 'build:react-dom', + 'npm-react:release', + 'npm-react:pack', + 'npm-react-dom:release', + 'npm-react-dom:pack', + 'npm-react-addons:release', + 'npm-react-addons:pack', + 'compare_size', + ]); + + // Automate the release! + var releaseTasks = require('./grunt/tasks/release'); + grunt.registerTask('release:setup', releaseTasks.setup); + grunt.registerTask('release:bower', releaseTasks.bower); + grunt.registerTask('release:docs', releaseTasks.docs); + grunt.registerTask('release:msg', releaseTasks.msg); + grunt.registerTask('release:starter', releaseTasks.starter); + + grunt.registerTask('release', [ + 'release:setup', + 'clean', + 'build', + 'release:bower', + 'release:starter', + 'compress', + 'release:docs', + 'release:msg', + ]); + + grunt.registerTask('build-modules', function() { + spawnGulp(['react:modules'], null, this.async()); + }); + + // The default task - build - to keep setup easy. + grunt.registerTask('default', ['build']); +}; diff --git a/pool/shard011/JavaScript/0069575_io-query.js b/pool/shard011/JavaScript/0069575_io-query.js new file mode 100644 index 0000000000000000000000000000000000000000..d66134ba85aacf768d8a61aaab585a3240e7e1b6 --- /dev/null +++ b/pool/shard011/JavaScript/0069575_io-query.js @@ -0,0 +1,51 @@ +/* + Copyright (c) 2004-2016, The JS Foundation All Rights Reserved. + Available via Academic Free License >= 2.1 OR the modified BSD license. + see: http://dojotoolkit.org/license for details +*/ + +//>>built +define("dojo/io-query",["./_base/lang"],function(_1){ +var _2={}; +return {objectToQuery:function objectToQuery(_3){ +var _4=encodeURIComponent,_5=[]; +for(var _6 in _3){ +var _7=_3[_6]; +if(_7!=_2[_6]){ +var _8=_4(_6)+"="; +if(_1.isArray(_7)){ +for(var i=0,l=_7.length;i= 0) && !selected) { + index = CheckBox.selectedStateNames.indexOf(state); + state = CheckBox.stateNames[index]; + } else if ((CheckBox.stateNames.indexOf(state) >= 0) && selected) { + index = CheckBox.stateNames.indexOf(state); + state = CheckBox.selectedStateNames[index]; + } + + this._selected = selected; + this._pressed = false; //to prevent toggling on touch/mouse up + this.currentState = state; + }, + get: function() { + return this._selected; + } +}); + +CheckBox.prototype.toggleSelected = function () { + this.selected = !this.selected; + if (this.change) { + this.change(this.selected); + } +}; + +CheckBox.prototype.handleEvent = function (type) { + switch (type) { + case CheckBox.UP: + if (this._mousedown) { + this._mousedown = false; + this.toggleSelected(); + this.currentState = this.selected ? CheckBox.SELECTED_UP : CheckBox.UP; + } + break; + case CheckBox.DOWN: + if (!this._mousedown) { + this._mousedown = true; + this.currentState = this.selected ? CheckBox.SELECTED_DOWN : CheckBox.DOWN; + } + break; + case CheckBox.HOVER: + if (!this._mousedown) { + this.currentState = this.selected ? CheckBox.SELECTED_HOVER : CheckBox.HOVER; + } + break; + case 'out': + this.currentState = this.selected ? CheckBox.SELECTED_UP : CheckBox.UP; + break; + default: + break; + } +}; diff --git a/pool/shard011/JavaScript/0069589_information.js b/pool/shard011/JavaScript/0069589_information.js new file mode 100644 index 0000000000000000000000000000000000000000..7b993dabf4407dd872a8463be5130078d27dc5a2 --- /dev/null +++ b/pool/shard011/JavaScript/0069589_information.js @@ -0,0 +1,176 @@ +/** + * Tweet information rendering functions. + + * @package status + */ + +var Status = Status || {}; + +Status.Information = Status.Information || {}; + +Status.Information.Display = function() { +}; + +Status.Information.Display.prototype.renderText = function( text ) { + return text + .replace( /(^|\s)#(\S*)/g, + "$1#$2" ) + .replace( /(^|\s)@([a-zA-Z0-9]*)/g, + "$1@$2" ) + .replace( /(^|\s)http(\S*)/g, + "$1http$2" ) + .replace( /(^|\s)(@\S*)/g, "$1$2" ); +}; + +Status.Information.Display.prototype.renderDate = function( date ) { + return moment( date ).format( "DD/MM/YY HH:mm:ss (Z)" ); +}; + +Status.Information.Display.prototype.createNormalTweet = function( tweet ) { + return "
    • Text: " + + this.renderText( tweet.data.text ) + + "
    • Date: " + + this.renderDate( tweet.date ) + + "
    • " + + (tweet.in_reply_to_screen_name + ? "
    • Sent in reply to @" + + tweet.in_reply_to_screen_name + "
    • " + : "") + + ( tweet.analytics == null ? "" + : "
    • Impressions: " + tweet.analytics.impressions + "
    • Engagements: " + + tweet.analytics.engagements + "
    • Engagement rate: " + + ( ( tweet.analytics.engagements / tweet.analytics.impressions) * 100 ).toFixed( 2 ) + "%
    • Retweets: " + + tweet.analytics.retweets + "
    • Replies: " + + tweet.analytics.replies + "
    • Likes: " + + tweet.analytics.likes + "
    • User profile clicks: " + + tweet.analytics.user_profile_clicks + "
    • URL clicks: " + + tweet.analytics.url_clicks + "
    • Hashtag clicks: " + + tweet.analytics.hashtag_clicks + "
    • Detail expands: " + + tweet.analytics.detail_expands + "
    • Permalink clicks: " + + tweet.analytics.permalink_clicks + "
    • ") + + "
    "; +}; + +Status.Information.Display.prototype.createMention = function( tweet ) { + return "
    "; +}; + +Status.Information.Display.prototype.createRetweet = function( tweet ) { + return "
    "; +}; + +Status.Information.Display.prototype.createFavourited = function( tweet ) { + var status = tweet.data.status; + var screen_name = ""; + if (tweet.event == "YOU_FAVOURITED") { + screen_name = tweet.data.targetUserName; + } else if (tweet.event == "YOU_UNFAVOURITED") { + screen_name = tweet.data.targetUserName; + } else if (tweet.event == "FAVOURITED_YOU") { + screen_name = tweet.data.sourceName; + } else if (tweet.event == "UNFAVOURITED_YOU") { + screen_name = tweet.data.sourceName; + } else if (tweet.event == "FAVOURITED_RETWEET") { + screen_name = tweet.data.sourceName; + } + return "
    • Text: " + + this.renderText( status.text ) + + "
    • Date: " + + this.renderDate( tweet.date ) + + "
    • By @" + + screen_name + + "
    "; +} + +Status.Information.Display.prototype.createFollowed = function( tweet ) { + var text = ""; + if (tweet.event == "YOU_FOLLOWED") { + text = "You started following @" + + tweet.data.followedUserName + + ""; + } else if (tweet.event == "YOU_UNFOLLOWED") { + text = "You stopped following @" + + tweet.data.unfollowedUserName + + ""; + } else if (tweet.event == "FOLLOWED_YOU") { + text = "@" + + tweet.data.sourceName + + " started following you"; + } + return "
    • " + + text + "
    "; +} + +Status.Information.Display.prototype.createQuotedTweet = function( tweet ) { + return "
    • Text: " + + this.renderText( tweet.data.status.text ) + + "
    • Quoted Text: " + + this.renderText( tweet.data.status.quoted_status.text ) + "
    • Date: " + + this.renderDate( tweet.date ) + + "
    • Quoted by @" + + tweet.data.sourceName + + "
    "; +} + +Status.Information.Display.prototype.createBlock = function( tweet ) { + return "
    • You blocked " + + this.renderText( "@" + tweet.data.blockedUserName ) + + "
    "; +} + +Status.Information.Display.prototype.createUnblock = function( tweet ) { + return "
    • You unblocked " + + this.renderText( "@" + tweet.data.unblockedUserName ) + + "
    "; +} + +Status.Information.Display.prototype.createTweet = function( tweet ) { + if ( tweet.event == "TWEET" ) { + return this.createNormalTweet( tweet ); + } else if ( tweet.event == "MENTION" ) { + return this.createMention( tweet ); + } else if ( tweet.event == "RETWEET" + || tweet.event == "FRIEND_RETWEET" + || tweet.event == "FRIEND_OF_FRIEND_RETWEET" ) { + return this.createRetweet( tweet ); + } else if ( tweet.event == "YOU_FAVOURITED" + || tweet.event == "YOU_UNFAVOURITED" + || tweet.event == "FAVOURITED_YOU" + || tweet.event == "UNFAVOURITED_YOU" + || tweet.event == "FAVOURITED_RETWEET") { + return this.createFavourited( tweet ); + } else if (tweet.event == "YOU_FOLLOWED" + || tweet.event == "YOU_UNFOLLOWED" + || tweet.event == "FOLLOWED_YOU") { + return this.createFollowed( tweet ); + } else if (tweet.event == "QUOTED_TWEET") { + return this.createQuotedTweet( tweet ); + } else if (tweet.event == "BLOCK") { + return this.createBlock( tweet ); + } else if (tweet.event == "UNBLOCK") { + return this.createUnblock( tweet ); + } else { + console.log( "Don't know how to render event type '" + tweet.event + "'" ); + return ""; + } +}; diff --git a/pool/shard011/JavaScript/0069592_signup.js b/pool/shard011/JavaScript/0069592_signup.js new file mode 100644 index 0000000000000000000000000000000000000000..fd81f99e6c814c287a5ca120e8dbbbd4644a7a6b --- /dev/null +++ b/pool/shard011/JavaScript/0069592_signup.js @@ -0,0 +1,198 @@ +// JavaScript Document +var isName_taken = false; +function checkUserName_Taken() +{ + $('#username_test').popover('hide'); + var xmlhttp; + if (window.XMLHttpRequest) + { + xmlhttp = new XMLHttpRequest(); + } + else + { + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } + xmlhttp.onreadystatechange = function() + { + if (xmlhttp.readyState == 4 && xmlhttp.status == 200) + { + var result = new String(xmlhttp.responseText); + var test = result.slice(0, 1); + if (test == "N") + { + $('#username_test_isTaken').popover('show'); + isName_taken = true; + } + else + { + $('#username_test_isTaken').popover('hide'); + isName_taken = false; + } + + } + } + xmlhttp.open("GET", "deal_page/deal_signup.php?username="+form_signup.username.value, true); + //xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); + xmlhttp.send(); +} + +function onkeyup_mail_input() +{ + $('#email_test').popover('hide'); + $('#email_format_test').popover('hide'); +} + +function onkeyup_password_input() +{ + $('#password_test').popover('hide'); +} +function onkeyup_password_cofirm_input() +{ + $('#password_confirm_test').popover('hide'); +} + +function check_signup() +{ + if(form_signup.username.value=="") + { + $('#username_test').popover('show'); + form_signup.username.select(); + return false; + } + if(isName_taken) + { + $('#username_test_isTaken').popover('show'); + form_signup.username.select(); + return false; + } + + if(form_signup.email.value==""){ + $('#email_test').popover('show'); + form_signup.email.select(); + return(false); + } + if(!check_email(form_signup.email.value)){ + $('#email_format_test').popover('show'); + form_signup.email.select(); + return(false); + } + + + if(form_signup.password.value==""){ + $('#password_test').popover('show'); + form_signup.password.select(); + return(false); + } + if(form_signup.password.value!=form_signup.password_confirm.value){ + $('#password_confirm_test').popover('show'); + form_signup.password_confirm.select(); + return(false); + } + return(true); +} + +function check_email(email){ + var strs=email; + var Expression=/\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/; + var objExp=new RegExp(Expression); + if(objExp.test(strs)==true){ + return true; + }else{ + return false; + } +} + + + +function change_code() +{ + var xmlhttp; + if (window.XMLHttpRequest) + { + xmlhttp = new XMLHttpRequest(); + } + else + { + xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); + } + xmlhttp.onreadystatechange = function() + { + if (xmlhttp.readyState == 4 && xmlhttp.status == 200) + { + var str = xmlhttp.responseText.split(","); + js_checkcode = str[0]; + document.getElementById("img_check_code").src="http://onlinebs-maindomain.stor.sinaapp.com/tmp/" + str[1]; + } + } + xmlhttp.open("GET", "changecode.php", true); + xmlhttp.send(); +} + +function check_login() +{ + if (form_login.username.value == "") + { + alert("Please enter your name!"); + return false; + } + if (form_login.password.value == "") + { + alert("Please enter your password!"); + return false; + } + if (form_login.check_code.value == "") + { + alert("Please enter checkcode!"); + return false; + } + if (form_login.check_code.value != js_checkcode) + { + alert("Wrong checkcode! "); + change_code(); + return false; + } + return true; +} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pool/shard011/JavaScript/0069593_index.js b/pool/shard011/JavaScript/0069593_index.js new file mode 100644 index 0000000000000000000000000000000000000000..95324b4753835bcb04a3a252338b54a7b2981dcc --- /dev/null +++ b/pool/shard011/JavaScript/0069593_index.js @@ -0,0 +1,36 @@ +/* globals counter */ +var readFile = require('fs').readFile; +var assert = require('assert'); +var exec = require('child_process').exec; + +exec('node .', function(error, stdout, stderr) { + if (error) { + throw error; + } + if (stdout !== "There are 36 P's in Peter Piper.\n") { + // Try to provide helpful error messages. + readFile('./peter-piper.js', "utf-8", function(err, value) { + if (err) throw err; + + eval(value); + + assert(counter, "Counter should contain the number of P's in Peter Piper."); + + if (counter == 8) { + assert(false, "There are more than 8 P's in Peter Piper. Are you counting upper and lowercase P's?"); + } + + if (counter == 28) { + assert(false, "There are more than 28 P's in Peter Piper. Are you counting upper and lowercase P's?"); + } + + if (counter !== 36) { + assert.equal(false, "That's not the correct number of P's in Peter Piper"); + } + console.log("All tests pass!") + }); + } + else { + console.log("All tests pass!"); + } +}); diff --git a/pool/shard011/JavaScript/0069596_moduleStreamsTab.test.js b/pool/shard011/JavaScript/0069596_moduleStreamsTab.test.js new file mode 100644 index 0000000000000000000000000000000000000000..6dbee3bbe0a2c4fa08033423e91d4c0157309339 --- /dev/null +++ b/pool/shard011/JavaScript/0069596_moduleStreamsTab.test.js @@ -0,0 +1,108 @@ +import React from 'react'; +import { act } from 'react-test-renderer'; +import { renderWithRedux, patientlyWaitFor } from 'react-testing-lib-wrapper'; +import { nockInstance, assertNockRequest, mockForemanAutocomplete, mockSetting } from '../../../../../../test-utils/nockWrapper'; +import { foremanApi } from '../../../../../../services/api'; +import { ModuleStreamsTab } from '../ModuleStreamsTab'; +import mockModuleStreams from './modules.fixtures.json'; +import { MODULE_STREAMS_KEY } from '../ModuleStreamsConstants'; + +const contentFacetAttributes = { + id: 11, + uuid: 'e5761ea3-4117-4ecf-83d0-b694f99b389e', + content_view_default: false, + lifecycle_environment_library: false, +}; + +const renderOptions = (facetAttributes = contentFacetAttributes) => ({ + apiNamespace: MODULE_STREAMS_KEY, + initialState: { + API: { + HOST_DETAILS: { + response: { + id: 1, + name: 'test-host', + content_facet_attributes: { ...facetAttributes }, + }, + status: 'RESOLVED', + }, + }, + }, +}); + +const hostModuleStreams = foremanApi.getApiUrl('/hosts/1/module_streams'); +const autocompleteUrl = '/hosts/1/module_streams/auto_complete_search'; + +let firstModuleStreams; +let searchDelayScope; +let autoSearchScope; + +beforeEach(() => { + const { results } = mockModuleStreams; + [firstModuleStreams] = results; + searchDelayScope = mockSetting(nockInstance, 'autosearch_delay', 0); + autoSearchScope = mockSetting(nockInstance, 'autosearch_while_typing'); +}); + +afterEach(() => { + assertNockRequest(searchDelayScope); + assertNockRequest(autoSearchScope); +}); + +beforeEach(() => { + const { results } = mockModuleStreams; + [firstModuleStreams] = results; + searchDelayScope = mockSetting(nockInstance, 'autosearch_delay', 0); + autoSearchScope = mockSetting(nockInstance, 'autosearch_while_typing'); +}); + +afterEach(() => { + assertNockRequest(searchDelayScope); + assertNockRequest(autoSearchScope); +}); + +test('Can call API for Module streams and show on screen on page load', async (done) => { + // Setup autocomplete with mockForemanAutoComplete since we aren't adding /katello + const autocompleteScope = mockForemanAutocomplete(nockInstance, autocompleteUrl); + const scope = nockInstance + .get(hostModuleStreams) + .query(true) + .reply(200, mockModuleStreams); + + const { getAllByText } = renderWithRedux(, renderOptions()); + + // Assert that the Module streams are now showing on the screen, but wait for them to appear. + await patientlyWaitFor(() => + expect(getAllByText(firstModuleStreams.name)[0]).toBeInTheDocument()); + // Assert request was made and completed, see helper function + assertNockRequest(autocompleteScope); + assertNockRequest(scope, done); // Pass jest callback to confirm test is done + act(done); +}); + +test('Can handle no Module streams being present', async (done) => { + // Setup autocomplete with mockForemanAutoComplete since we aren't adding /katello + const autocompleteScope = mockForemanAutocomplete(nockInstance, autocompleteUrl); + + const noResults = { + total: 0, + subtotal: 0, + page: 1, + per_page: 20, + results: [], + }; + + const scope = nockInstance + .get(hostModuleStreams) + .query(true) + .reply(200, noResults); + + const { queryByText } = renderWithRedux(, renderOptions()); + + // Assert that there are not any Module streams showing on the screen. + await patientlyWaitFor(() => expect(queryByText('This host does not have any Module streams.')).toBeInTheDocument()); + // Assert request was made and completed, see helper function + assertNockRequest(autocompleteScope); + assertNockRequest(scope, done); // Pass jest callback to confirm test is done + act(done); +}); diff --git a/pool/shard011/JavaScript/0069597_state-point-manager-test.js b/pool/shard011/JavaScript/0069597_state-point-manager-test.js new file mode 100644 index 0000000000000000000000000000000000000000..ca03efa784fb3478971ffdadbd49c52e448682f0 --- /dev/null +++ b/pool/shard011/JavaScript/0069597_state-point-manager-test.js @@ -0,0 +1,106 @@ +import Ember from 'ember'; +import { moduleFor, test } from 'ember-qunit'; +import { deepStub, initialize as initializeEngine } from 'affinity-engine'; +import { initializeQUnitAssertions } from 'ember-message-bus'; +import multiton from 'ember-multiton-service'; + +const { + getOwner +} = Ember; + +const Publisher = Ember.Object.extend({ eBus: multiton('message-bus', 'engineId'), engineId: 'foo' }); +let publisher; + +moduleFor('service:affinity-engine/data-manager-rewindable-lokijs/state-point-manager', 'Unit | Service | affinity engine/rewindable save adapter/state point manager', { + integration: true, + + beforeEach() { + const appInstance = getOwner(this); + + initializeEngine(appInstance); + initializeQUnitAssertions(appInstance, 'eBus', Ember.Object.extend({ eBus: multiton('message-bus', 'engineId'), engineId: 'foo' })); + appInstance.register('ember-message-bus:publisher', Publisher); + publisher = appInstance.lookup('ember-message-bus:publisher'); + } +}); + +test('stateBuffer returns a clone of the latest statePoint', function(assert) { + assert.expect(4); + + const engineId = 'foo'; + const statePoint = { bar: 'baz' }; + const service = this.subject({ engineId, statePoints: Ember.A([statePoint]) }); + + assert.deepEqual(service.get('stateBuffer'), statePoint, 'content is the same'); + assert.notEqual(service.get('stateBuffer'), statePoint, 'object is different'); + + service.set('statePoints', Ember.A([{ babble: 'fish' }])); + + assert.deepEqual(service.get('stateBuffer'), { babble: 'fish' }, 'updates if statePoints changes'); + + service.get('statePoints').pushObject({ ocra: 'corn' }); + + assert.deepEqual(service.get('stateBuffer'), { ocra: 'corn' }, 'updates if statePoint length changes'); +}); + +test('restartingEngine resets the statePoints', function(assert) { + assert.expect(1); + + const engineId = 'foo'; + const service = this.subject({ engineId, statePoints: ['foo'] }); + + publisher.get('eBus').publish('restartingEngine'); + + assert.deepEqual(service.get('statePoints'), [], 'statePoints got reset'); +}); + +test('shouldLoadLatestStatePoint sets the statePoints', function(assert) { + assert.expect(1); + + const engineId = 'foo'; + const service = this.subject({ engineId, statePoints: ['foo'] }); + + publisher.get('eBus').publish('shouldLoadLatestStatePoint', ['bar']); + + assert.deepEqual(service.get('statePoints'), ['bar'], 'statePoints got set'); +}); + +test('shouldFileStateBuffer pushes the stateBuffer to the statePoints', function(assert) { + assert.expect(1); + + const engineId = 'foo'; + const service = this.subject({ engineId, statePoints: Ember.A([{ foo: 'bar' }]) }); + + service.set('stateBuffer.baz', 'bumble'); + + publisher.get('eBus').publish('shouldFileStateBuffer'); + + assert.deepEqual(service.get('statePoints'), [{ foo: 'bar' }, { foo: 'bar', baz: 'bumble' }], 'stateBuffer got filed'); +}); + +test('shouldFileStateBuffer shifts old state points if they exceed maxStatePoints', function(assert) { + assert.expect(1); + + const engineId = 'foo'; + const service = this.subject({ engineId, maxStatePoints: 3, statePoints: Ember.A([{ foo: 1 }, { foo: 2 }, { foo: 3 }]) }); + + publisher.get('eBus').publish('shouldFileStateBuffer'); + + assert.deepEqual(service.get('statePoints'), [{ foo: 2 }, { foo: 3 }, { foo: 3 }], 'stateBuffer got filed and shifted'); +}); + +const configurationTiers = [ + 'config.attrs.plugin.dataManager', + 'config.attrs.all' +]; + +configurationTiers.forEach((tier) => { + test(`maxStatePoints is defined by ${tier}`, function(assert) { + assert.expect(1); + + const config = deepStub(tier, 'maxStatePoints', 123); + const service = this.subject({ config, engineId: 'foo' }); + + assert.equal(service.get('maxStatePoints', 123, 'maxStatePoints is correct')) + }); +}); diff --git a/pool/shard011/JavaScript/0069599_authorizer.test.js b/pool/shard011/JavaScript/0069599_authorizer.test.js new file mode 100644 index 0000000000000000000000000000000000000000..7712e8441a1b81046425458b1967b7f31246bc6e --- /dev/null +++ b/pool/shard011/JavaScript/0069599_authorizer.test.js @@ -0,0 +1,19 @@ +"use strict"; + +var sira = require('sira'); +var s = require('./support'); +var authorizer = require('../lib/authorizer'); + +describe('authorizer', function () { + + var sapp; + beforeEach(function (done) { + sapp = s.sapp(); + sapp.phase(authorizer); + sapp.boot(done); + }); + +// it('should allow create user', function () { +// }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069600_config.js b/pool/shard011/JavaScript/0069600_config.js new file mode 100644 index 0000000000000000000000000000000000000000..f807e04ba50f0bfce55b6d33ab638321eca5fe1d --- /dev/null +++ b/pool/shard011/JavaScript/0069600_config.js @@ -0,0 +1,23 @@ +(function () { + 'use strict'; + + var base = __dirname + '/'; + var src = base + 'src/'; + var dist = base + 'dist/'; + + module.exports = { + src: base, + css: { + src: src + 'css/*.scss', + dest: dist + 'css/' + }, + js: { + src: src + '**/*.js', + dest: dist + 'js/app.js' + }, + template: { + src: src + 'views/**/*.jade', + dest: dist + } + }; +}()); diff --git a/pool/shard011/JavaScript/0069603_checkbox.js b/pool/shard011/JavaScript/0069603_checkbox.js new file mode 100644 index 0000000000000000000000000000000000000000..9ccf7638632e381eec2bc7a66d4f14bbadbf5a48 --- /dev/null +++ b/pool/shard011/JavaScript/0069603_checkbox.js @@ -0,0 +1,328 @@ +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +(function (factory) { + if (typeof module === 'object' && typeof module.exports === 'object') { + var v = factory(require, exports); if (v !== undefined) module.exports = v; + } + else if (typeof define === 'function' && define.amd) { + define(["require", "exports", '@angular/core', '@angular/forms', '../../config/config', '../../util/form', '../ion', '../../util/util', '../item/item'], factory); + } +})(function (require, exports) { + "use strict"; + var core_1 = require('@angular/core'); + var forms_1 = require('@angular/forms'); + var config_1 = require('../../config/config'); + var form_1 = require('../../util/form'); + var ion_1 = require('../ion'); + var util_1 = require('../../util/util'); + var item_1 = require('../item/item'); + exports.CHECKBOX_VALUE_ACCESSOR = { + provide: forms_1.NG_VALUE_ACCESSOR, + useExisting: core_1.forwardRef(function () { return Checkbox; }), + multi: true + }; + /** + * \@name Checkbox + * \@module ionic + * + * \@description + * The Checkbox is a simple component styled based on the mode. It can be + * placed in an `ion-item` or used as a stand-alone checkbox. + * + * See the [Angular 2 Docs](https://angular.io/docs/ts/latest/guide/forms.html) + * for more info on forms and inputs. + * + * + * \@usage + * ```html + * + * + * + * + * Pepperoni + * + * + * + * + * Sausage + * + * + * + * + * Mushrooms + * + * + * + * + * ``` + * + * \@demo /docs/v2/demos/src/checkbox/ + * @see {\@link /docs/v2/components#checkbox Checkbox Component Docs} + */ + var Checkbox = (function (_super) { + __extends(Checkbox, _super); + /** + * @param {?} config + * @param {?} _form + * @param {?} _item + * @param {?} elementRef + * @param {?} renderer + * @param {?} _cd + */ + function Checkbox(config, _form, _item, elementRef, renderer, _cd) { + _super.call(this, config, elementRef, renderer, 'checkbox'); + this._form = _form; + this._item = _item; + this._cd = _cd; + /** @private */ + this._checked = false; + /** @private */ + this._disabled = false; + /** + * @output {Checkbox} Emitted when the checkbox value changes. + */ + this.ionChange = new core_1.EventEmitter(); + _form.register(this); + if (_item) { + this.id = 'chk-' + _item.registerInput('checkbox'); + this._labelId = 'lbl-' + _item.id; + this._item.setElementClass('item-checkbox', true); + } + } + Object.defineProperty(Checkbox.prototype, "color", { + /** + * \@input {string} The color to use from your Sass `$colors` map. + * Default options are: `"primary"`, `"secondary"`, `"danger"`, `"light"`, and `"dark"`. + * For more information, see [Theming your App](/docs/v2/theming/theming-your-app). + * @param {?} val + * @return {?} + */ + set: function (val) { + this._setColor(val); + }, + enumerable: true, + configurable: true + }); + Object.defineProperty(Checkbox.prototype, "mode", { + /** + * \@input {string} The mode determines which platform styles to use. + * Possible values are: `"ios"`, `"md"`, or `"wp"`. + * For more information, see [Platform Styles](/docs/v2/theming/platform-specific-styles). + * @param {?} val + * @return {?} + */ + set: function (val) { + this._setMode(val); + }, + enumerable: true, + configurable: true + }); + /** + * @param {?} ev + * @return {?} + */ + Checkbox.prototype._click = function (ev) { + (void 0) /* console.debug */; + ev.preventDefault(); + ev.stopPropagation(); + this.onChange(!this._checked); + }; + Object.defineProperty(Checkbox.prototype, "checked", { + /** + * \@input {boolean} If true, the element is selected. + * @return {?} + */ + get: function () { + return this._checked; + }, + /** + * @param {?} val + * @return {?} + */ + set: function (val) { + this._setChecked(util_1.isTrueProperty(val)); + this.onChange(this._checked); + }, + enumerable: true, + configurable: true + }); + /** + * @param {?} isChecked + * @return {?} + */ + Checkbox.prototype._setChecked = function (isChecked) { + if (isChecked !== this._checked) { + this._checked = isChecked; + if (this._init) { + this.ionChange.emit(this); + } + this._item && this._item.setElementClass('item-checkbox-checked', isChecked); + } + }; + /** + * @param {?} val + * @return {?} + */ + Checkbox.prototype.writeValue = function (val) { + this._setChecked(util_1.isTrueProperty(val)); + }; + /** + * @param {?} fn + * @return {?} + */ + Checkbox.prototype.registerOnChange = function (fn) { + var _this = this; + this._fn = fn; + this.onChange = function (isChecked) { + (void 0) /* console.debug */; + fn(isChecked); + _this._setChecked(isChecked); + _this.onTouched(); + _this._cd.detectChanges(); + }; + }; + /** + * @param {?} fn + * @return {?} + */ + Checkbox.prototype.registerOnTouched = function (fn) { this.onTouched = fn; }; + Object.defineProperty(Checkbox.prototype, "disabled", { + /** + * \@input {boolean} If true, the user cannot interact with this element. + * @return {?} + */ + get: function () { + return this._disabled; + }, + /** + * @param {?} val + * @return {?} + */ + set: function (val) { + this._disabled = util_1.isTrueProperty(val); + this._item && this._item.setElementClass('item-checkbox-disabled', this._disabled); + }, + enumerable: true, + configurable: true + }); + /** + * @param {?} isChecked + * @return {?} + */ + Checkbox.prototype.onChange = function (isChecked) { + // used when this input does not have an ngModel or formControlName + (void 0) /* console.debug */; + this._setChecked(isChecked); + this.onTouched(); + this._cd.detectChanges(); + }; + /** + * @return {?} + */ + Checkbox.prototype.initFocus = function () { + this._elementRef.nativeElement.querySelector('button').focus(); + }; + /** + * @return {?} + */ + Checkbox.prototype.onTouched = function () { }; + /** + * @return {?} + */ + Checkbox.prototype.ngAfterContentInit = function () { + this._init = true; + }; + /** + * @param {?} isDisabled + * @return {?} + */ + Checkbox.prototype.setDisabledState = function (isDisabled) { + this.disabled = isDisabled; + }; + /** + * @return {?} + */ + Checkbox.prototype.ngOnDestroy = function () { + this._form.deregister(this); + }; + Checkbox.decorators = [ + { type: core_1.Component, args: [{ + selector: 'ion-checkbox', + template: '
    ' + + '
    ' + + '
    ' + + '', + host: { + '[class.checkbox-disabled]': '_disabled' + }, + providers: [exports.CHECKBOX_VALUE_ACCESSOR], + encapsulation: core_1.ViewEncapsulation.None, + },] }, + ]; + /** @nocollapse */ + Checkbox.ctorParameters = function () { return [ + { type: config_1.Config, }, + { type: form_1.Form, }, + { type: item_1.Item, decorators: [{ type: core_1.Optional },] }, + { type: core_1.ElementRef, }, + { type: core_1.Renderer, }, + { type: core_1.ChangeDetectorRef, }, + ]; }; + Checkbox.propDecorators = { + 'color': [{ type: core_1.Input },], + 'mode': [{ type: core_1.Input },], + 'ionChange': [{ type: core_1.Output },], + '_click': [{ type: core_1.HostListener, args: ['click', ['$event'],] },], + 'checked': [{ type: core_1.Input },], + 'disabled': [{ type: core_1.Input },], + }; + return Checkbox; + }(ion_1.Ion)); + exports.Checkbox = Checkbox; + function Checkbox_tsickle_Closure_declarations() { + /** @type {?} */ + Checkbox.decorators; + /** + * @nocollapse + * @type {?} + */ + Checkbox.ctorParameters; + /** @type {?} */ + Checkbox.propDecorators; + /** @type {?} */ + Checkbox.prototype._checked; + /** @type {?} */ + Checkbox.prototype._init; + /** @type {?} */ + Checkbox.prototype._disabled; + /** @type {?} */ + Checkbox.prototype._labelId; + /** @type {?} */ + Checkbox.prototype._fn; + /** @type {?} */ + Checkbox.prototype.id; + /** + * \@output {Checkbox} Emitted when the checkbox value changes. + * @type {?} + */ + Checkbox.prototype.ionChange; + /** @type {?} */ + Checkbox.prototype._form; + /** @type {?} */ + Checkbox.prototype._item; + /** @type {?} */ + Checkbox.prototype._cd; + } +}); +//# sourceMappingURL=checkbox.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069604_app-login.js b/pool/shard011/JavaScript/0069604_app-login.js new file mode 100644 index 0000000000000000000000000000000000000000..10f339caac8365da57921111eafcec33013dd838 --- /dev/null +++ b/pool/shard011/JavaScript/0069604_app-login.js @@ -0,0 +1,46 @@ +$(function() { + $('#submitSesion').on('click touch', function(event) { + + event.preventDefault(); + + var dataLogin = $('#formLogin').serialize(); + + $.ajax({ + method: 'POST', + //url: 'http://soporte.policiatijuana.gob.mx:88/Api/Default1/', + async: true, + crossDomain: true, + data: dataLogin, + cache: false, + beforeSend: function(){ $("#submitSesion").val('Iniciando...'); }, + success: function(data) { + $("body").load("home.html").hide().fadeIn(1500).delay(6000); + window.location.href = "home.html"; + }, + error : function(xhr, textStatus, errorThrown ) { + if (textStatus == 'timeout') { + this.tryCount++; + if (this.tryCount <= this.retryLimit) { + $.ajax(this); + return; + } + return; + } + $("#submitSesion").val('Iniciar sesión'); + if (xhr.status == 500) { + $.snackbar({ + content: "Ocurrio un error, no desistas e intentalo nuevamente", + timeout: 5000 + }); + } else { + $.snackbar({ + content: "Usuario y/o contraseña son invalidas, intentalo nuevamente", + timeout: 5000 + }); + } + } + }); + + return false; + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069605_main.js b/pool/shard011/JavaScript/0069605_main.js new file mode 100644 index 0000000000000000000000000000000000000000..e898c80ae750f5482ade856e4f966ef628de5ec7 --- /dev/null +++ b/pool/shard011/JavaScript/0069605_main.js @@ -0,0 +1,151 @@ +/** +* Template Name: Personal - v2.1.0 +* Template URL: https://bootstrapmade.com/personal-free-resume-bootstrap-template/ +* Author: BootstrapMade.com +* License: https://bootstrapmade.com/license/ +*/ +!(function($) { + "use strict"; + + // Nav Menu + $(document).on('click', '.nav-menu a, .mobile-nav a', function(e) { + if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { + var hash = this.hash; + var target = $(hash); + if (target.length) { + e.preventDefault(); + + if ($(this).parents('.nav-menu, .mobile-nav').length) { + $('.nav-menu .active, .mobile-nav .active').removeClass('active'); + $(this).closest('li').addClass('active'); + } + + if (hash == '#header') { + $('#header').removeClass('header-top'); + $("section").removeClass('section-show'); + return; + } + + if (!$('#header').hasClass('header-top')) { + $('#header').addClass('header-top'); + setTimeout(function() { + $("section").removeClass('section-show'); + $(hash).addClass('section-show'); + }, 350); + } else { + $("section").removeClass('section-show'); + $(hash).addClass('section-show'); + } + + if ($('body').hasClass('mobile-nav-active')) { + $('body').removeClass('mobile-nav-active'); + $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close'); + $('.mobile-nav-overly').fadeOut(); + } + + return false; + + } + } + }); + + // Activate/show sections on load with hash links + if (window.location.hash) { + var initial_nav = window.location.hash; + if ($(initial_nav).length) { + $('#header').addClass('header-top'); + $('.nav-menu .active, .mobile-nav .active').removeClass('active'); + $('.nav-menu, .mobile-nav').find('a[href="' + initial_nav + '"]').parent('li').addClass('active'); + setTimeout(function() { + $("section").removeClass('section-show'); + $(initial_nav).addClass('section-show'); + }, 350); + } + } + + // Mobile Navigation + if ($('.nav-menu').length) { + var $mobile_nav = $('.nav-menu').clone().prop({ + class: 'mobile-nav d-lg-none' + }); + $('body').append($mobile_nav); + $('body').prepend(''); + $('body').append('
    '); + + $(document).on('click', '.mobile-nav-toggle', function(e) { + $('body').toggleClass('mobile-nav-active'); + $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close'); + $('.mobile-nav-overly').toggle(); + }); + + $(document).click(function(e) { + var container = $(".mobile-nav, .mobile-nav-toggle"); + if (!container.is(e.target) && container.has(e.target).length === 0) { + if ($('body').hasClass('mobile-nav-active')) { + $('body').removeClass('mobile-nav-active'); + $('.mobile-nav-toggle i').toggleClass('icofont-navigation-menu icofont-close'); + $('.mobile-nav-overly').fadeOut(); + } + } + }); + } else if ($(".mobile-nav, .mobile-nav-toggle").length) { + $(".mobile-nav, .mobile-nav-toggle").hide(); + } + + // jQuery counterUp + $('[data-toggle="counter-up"]').counterUp({ + delay: 10, + time: 1000 + }); + + // Skills section + $('.skills-content').waypoint(function() { + $('.progress .progress-bar').each(function() { + $(this).css("width", $(this).attr("aria-valuenow") + '%'); + }); + }, { + offset: '80%' + }); + + // Testimonials carousel (uses the Owl Carousel library) + $(".testimonials-carousel").owlCarousel({ + autoplay: true, + dots: true, + loop: true, + responsive: { + 0: { + items: 1 + }, + 768: { + items: 2 + }, + 900: { + items: 3 + } + } + }); + + // Porfolio isotope and filter + $(window).on('load', function() { + var portfolioIsotope = $('.portfolio-container').isotope({ + itemSelector: '.portfolio-item', + layoutMode: 'fitRows' + }); + + $('#portfolio-flters li').on('click', function() { + $("#portfolio-flters li").removeClass('filter-active'); + $(this).addClass('filter-active'); + + portfolioIsotope.isotope({ + filter: $(this).data('filter') + }); + }); + + }); + + // Initiate venobox (lightbox feature used in portofilo) + $(document).ready(function() { + $('.venobox').venobox(); + }); + +})(jQuery); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069607_workspaces_view.js b/pool/shard011/JavaScript/0069607_workspaces_view.js new file mode 100644 index 0000000000000000000000000000000000000000..f9b86b9b94f992d399d6a0eceec7e6b084a1576d --- /dev/null +++ b/pool/shard011/JavaScript/0069607_workspaces_view.js @@ -0,0 +1,25 @@ +define(['views/composite_view', 'views/workspace_view'], function(CompositeView, WorkspaceView){ + + var WorkspacesView = CompositeView.extend({ + className: 'workspaces', + attributes: {id: 'workspaces'}, + initialize: function(options){ + _.bindAll(this); + this.workspaces = options.workspaces; + this.options = options; + var self = this; + this.workspaces.bind('added', function(ws){ + $(self.el).prepend(new WorkspaceView({workspace: ws, controllers: options.controllers}).render().el); + }); + }, + items: function(){ + var options = this.options; + return this.workspaces.map(function(ws){ + return new WorkspaceView({workspace: ws, controllers: options.controllers}); + }); + } + }); + + return WorkspacesView; + +}); diff --git a/pool/shard011/JavaScript/0069609_mockComponent.js b/pool/shard011/JavaScript/0069609_mockComponent.js new file mode 100644 index 0000000000000000000000000000000000000000..32f06bd117c88617044098efe60c45bea65828bb --- /dev/null +++ b/pool/shard011/JavaScript/0069609_mockComponent.js @@ -0,0 +1,27 @@ +/** + * Copyright (c) 2013-present, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ +'use strict'; + +module.exports = moduleName => { + const RealComponent = require.requireActual(moduleName); + const React = require('react'); + + const Component = class extends RealComponent { + render() { + const name = RealComponent.displayName || RealComponent.name; + + return React.createElement( + name.replace(/^(RCT|RK)/,''), + this.props, + this.props.children, + ); + } + }; + return Component; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069611_push-state.js b/pool/shard011/JavaScript/0069611_push-state.js new file mode 100644 index 0000000000000000000000000000000000000000..f3b85ef3eaed4b08399fc728bacbd9828f232492 --- /dev/null +++ b/pool/shard011/JavaScript/0069611_push-state.js @@ -0,0 +1,82 @@ +/* eslint-disable import/no-extraneous-dependencies, import/no-unresolved, import/extensions */ + +import { Observable } from 'rxjs-es/Observable'; +import 'rxjs-es/add/operator/debounceTime'; +import 'rxjs-es/add/operator/do'; +import 'rxjs-es/add/observable/fromEvent'; + +import PushState from 'y-push-state/src/vanilla'; +// import HTMLPushStateElement from 'y-push-state/src/webcomponent'; + +import { hasFeatures /* , defineCustomElement */ } from './common'; +import upgradeMathBlocks from './katex'; + +const REQUIREMENTS = [ + 'eventlistener', + 'queryselector', + 'requestanimationframe', + 'classlist', + 'documentfragment', + 'history', +]; + +const pushState = document.querySelector('y-push-state'); + +function beforeCallback() { + document.body.classList.add('is-loading'); + + // unshow(error); + + // if a link on the drawer has been clicked, close it + if (!window.isDesktop && window.drawer.opened) { + window.drawer.close(); + } +} + +function afterSequence($) { + return $ + .do(() => document.body.classList.remove('is-loading')) + .debounceTime(200) + .subscribe(() => { + // send google analytics pageview + if (window.ga) window.ga('send', 'pageview'); + + // upgrade math blocks + upgradeMathBlocks(); + }); +} + +function errorCallback() { + // TODO + // show(error); +} + +// function withCustomElements() { +// const setup = () => { +// pushState.startHistory(); +// pushState.removeEventListener('y-push-state-attached', setup); +// }; +// +// pushState.addEventListener('y-push-state-attached', setup); +// defineCustomElement('y-push-state', HTMLPushStateElement); +// } + +function withoutCustomElements() { + new PushState(pushState, { + replaceIds: ['_main', '_asidebar'], + linkSelector: 'a[href^="/"]', + scrollRestoration: true, + }).startHistory(); +} + +if (hasFeatures(REQUIREMENTS)) { + pushState.addEventListener('y-push-state-before', beforeCallback); + pushState.addEventListener('y-smooth-state-error', errorCallback); + afterSequence(Observable.fromEvent(pushState, 'y-push-state-after')); + + // if ('customElement' in window || 'registerElement' in document) { + // withCustomElements(); + // } else { + withoutCustomElements(); + // } +} diff --git a/pool/shard011/JavaScript/0069614_base58check.js b/pool/shard011/JavaScript/0069614_base58check.js new file mode 100644 index 0000000000000000000000000000000000000000..318b1d972243fdc9787c501a7f7d3d9650d1f5b8 --- /dev/null +++ b/pool/shard011/JavaScript/0069614_base58check.js @@ -0,0 +1,76 @@ +var assert = require('assert') +var base58check = require('../').base58check + +describe('base58check', function() { + var evec, dvec + + beforeEach(function() { + function fromHex(h) { return new Buffer(h, 'hex') } + + // base58check encoded strings + evec = [ + '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAbuatmU', // 0x00 WIF + '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf', // 0x01 WIF + '5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreQyNNN1W', // 0x7f WIF + '1EHNa6Q4Jz2uvNExL497mE43ikXhwF6kZm', // uncompressed 0x01 address + '1FB8cZijTpRQp3HX8AEkNuQJBqApqfTcX7' // uncompressed 0x7f address + ] + + // decoded equivalent of above + dvec = [ + { + version: 0x80, + payload: '0000000000000000000000000000000000000000000000000000000000000000', + checksum: '0565fba7' + }, + { + version: 0x80, + payload: '0000000000000000000000000000000000000000000000000000000000000001', + checksum: 'a85aa87e', + }, + { + version: 0x80, + payload: '000000000000000000000000000000000000000000000000000000000000007f', + checksum: '64046be9', + }, + { + version: 0x00, + payload: '91b24bf9f5288532960ac687abb035127b1d28a5', + checksum: '0074ffe0', + }, + { + version: 0x00, + payload: '9b7c46977b68474e12066a370b169ec6b9b02644', + checksum: '4d210d6e' + } + ].map(function(x) { + return { + version: x.version, + payload: fromHex(x.payload), + checksum: fromHex(x.checksum) + } + }) + }) + + describe('decode', function() { + it('decodes the test vectors', function() { + evec.forEach(function(x, i) { + var actual = base58check.decode(x) + var expected = dvec[i] + + assert.deepEqual(actual, expected) + }) + }) + }) + + describe('encode', function() { + it('encodes the test vectors', function() { + dvec.forEach(function(x, i) { + var actual = base58check.encode(x.payload, x.version) + var expected = evec[i] + + assert.deepEqual(actual, expected) + }) + }) + }) +}) diff --git a/pool/shard011/JavaScript/0069615_todolists.js b/pool/shard011/JavaScript/0069615_todolists.js new file mode 100644 index 0000000000000000000000000000000000000000..ce41db73d4975d7fd809b193c10403af8742871e --- /dev/null +++ b/pool/shard011/JavaScript/0069615_todolists.js @@ -0,0 +1,82 @@ +(() => { + + window.ToDoList = new Vue({ + el: '#ToDoLists', + props: ['currentTasks', 'isReadonly', 'translations'], + data: { + newTask: { + bug_id: 0, + description: '', + }, + tasks: [], + lang: undefined + }, + computed: { + action() { + return this.$el.getElementsByTagName('FORM')[0].action; + }, + finishedTasks() { + return this.tasks.filter((task) => task.finished); + }, + counter() { + const tasksLeft = this.tasks.length - this.finishedTasks.length; + + return [tasksLeft, this.tasks.length].join('/'); + }, + }, + methods: { + insertTask() { + if (!this.validateDescription(this.newTask.description)) { + return; + } + + this.$http.post(this.action, {task: this.newTask}, (response) => { + this.tasks.push(...response); + this.newTask.description = ''; + }); + }, + updateTask(task) { + return this.$http.put(this.action, {task: task}); + }, + deleteTask(task) { + if (!task.finished && !confirm(this.lang.confirmDeletion)) { + return; + } + + this.$http.delete( + this.action + '&id=' + task.id, {id: task.id}, + () => this.tasks.$remove(task), + ); + }, + toggleFinished(task) { + task.finished = !!task.finished; + + this.updateTask(task).error(() => { + task.finished = !task.finished; + }); + }, + changeDescription(task) { + const origDesc = task.description; + const newDesc = prompt(this.lang.enterNewDescription, task.description); + + if (!this.validateDescription(newDesc) || newDesc === origDesc) { + return; + } + + task.description = newDesc; + + this.updateTask(task).error(() => { + task.description = origDesc; + }); + }, + validateDescription(description) { + return (description ? description.length : 0) > 0; + }, + }, + created() { + this.tasks = JSON.parse(this.currentTasks); + this.lang = JSON.parse(this.translations); + }, + }); + +})(); diff --git a/pool/shard011/JavaScript/0069619_index.js b/pool/shard011/JavaScript/0069619_index.js new file mode 100644 index 0000000000000000000000000000000000000000..dce2cd3d9426746f7f2957f441912711a06ce694 --- /dev/null +++ b/pool/shard011/JavaScript/0069619_index.js @@ -0,0 +1,191 @@ +/* */ +(function(process) { + 'use strict'; + module.exports = morgan; + module.exports.compile = compile; + module.exports.format = format; + module.exports.token = token; + var auth = require("basic-auth"); + var debug = require("debug")('morgan'); + var deprecate = require("depd")('morgan'); + var onFinished = require("on-finished"); + var onHeaders = require("on-headers"); + var clfmonth = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + var defaultBufferDuration = 1000; + function morgan(format, options) { + var fmt = format; + var opts = options || {}; + if (format && typeof format === 'object') { + opts = format; + fmt = opts.format || 'default'; + deprecate('morgan(options): use morgan(' + (typeof fmt === 'string' ? JSON.stringify(fmt) : 'format') + ', options) instead'); + } + if (fmt === undefined) { + deprecate('undefined format: specify a format'); + } + var immediate = opts.immediate; + var skip = opts.skip || false; + var formatLine = typeof fmt !== 'function' ? getFormatFunction(fmt) : fmt; + var buffer = opts.buffer; + var stream = opts.stream || process.stdout; + if (buffer) { + deprecate('buffer option'); + var interval = typeof buffer !== 'number' ? defaultBufferDuration : buffer; + stream = createBufferStream(stream, interval); + } + return function logger(req, res, next) { + req._startAt = undefined; + req._startTime = undefined; + req._remoteAddress = getip(req); + res._startAt = undefined; + res._startTime = undefined; + recordStartTime.call(req); + function logRequest() { + if (skip !== false && skip(req, res)) { + debug('skip request'); + return; + } + var line = formatLine(morgan, req, res); + if (null == line) { + debug('skip line'); + return; + } + debug('log request'); + stream.write(line + '\n'); + } + ; + if (immediate) { + logRequest(); + } else { + onHeaders(res, recordStartTime); + onFinished(res, logRequest); + } + next(); + }; + } + morgan.format('combined', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); + morgan.format('common', ':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length]'); + morgan.format('default', ':remote-addr - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"'); + deprecate.property(morgan, 'default', 'default format: use combined format'); + morgan.format('short', ':remote-addr :remote-user :method :url HTTP/:http-version :status :res[content-length] - :response-time ms'); + morgan.format('tiny', ':method :url :status :res[content-length] - :response-time ms'); + morgan.format('dev', function developmentFormatLine(tokens, req, res) { + var status = res._header ? res.statusCode : undefined; + var color = status >= 500 ? 31 : status >= 400 ? 33 : status >= 300 ? 36 : status >= 200 ? 32 : 0; + var fn = developmentFormatLine[color]; + if (!fn) { + fn = developmentFormatLine[color] = compile('\x1b[0m:method :url \x1b[' + color + 'm:status \x1b[0m:response-time ms - :res[content-length]\x1b[0m'); + } + return fn(tokens, req, res); + }); + morgan.token('url', function getUrlToken(req) { + return req.originalUrl || req.url; + }); + morgan.token('method', function getMethodToken(req) { + return req.method; + }); + morgan.token('response-time', function getResponseTimeToken(req, res) { + if (!req._startAt || !res._startAt) { + return; + } + var ms = (res._startAt[0] - req._startAt[0]) * 1e3 + (res._startAt[1] - req._startAt[1]) * 1e-6; + return ms.toFixed(3); + }); + morgan.token('date', function getDateToken(req, res, format) { + var date = new Date(); + switch (format || 'web') { + case 'clf': + return clfdate(date); + case 'iso': + return date.toISOString(); + case 'web': + return date.toUTCString(); + } + }); + morgan.token('status', function getStatusToken(req, res) { + return res._header ? String(res.statusCode) : undefined; + }); + morgan.token('referrer', function getReferrerToken(req) { + return req.headers['referer'] || req.headers['referrer']; + }); + morgan.token('remote-addr', getip); + morgan.token('remote-user', function getRemoteUserToken(req) { + var credentials = auth(req); + return credentials ? credentials.name : undefined; + }); + morgan.token('http-version', function getHttpVersionToken(req) { + return req.httpVersionMajor + '.' + req.httpVersionMinor; + }); + morgan.token('user-agent', function getUserAgentToken(req) { + return req.headers['user-agent']; + }); + morgan.token('req', function getRequestToken(req, res, field) { + var header = req.headers[field.toLowerCase()]; + return Array.isArray(header) ? header.join(', ') : header; + }); + morgan.token('res', function getResponseTime(req, res, field) { + if (!res._header) { + return undefined; + } + var header = res.getHeader(field); + return Array.isArray(header) ? header.join(', ') : header; + }); + function clfdate(dateTime) { + var date = dateTime.getUTCDate(); + var hour = dateTime.getUTCHours(); + var mins = dateTime.getUTCMinutes(); + var secs = dateTime.getUTCSeconds(); + var year = dateTime.getUTCFullYear(); + var month = clfmonth[dateTime.getUTCMonth()]; + return pad2(date) + '/' + month + '/' + year + ':' + pad2(hour) + ':' + pad2(mins) + ':' + pad2(secs) + ' +0000'; + } + function compile(format) { + if (typeof format !== 'string') { + throw new TypeError('argument format must be a string'); + } + var fmt = format.replace(/"/g, '\\"'); + var js = ' return "' + fmt.replace(/:([-\w]{2,})(?:\[([^\]]+)\])?/g, function(_, name, arg) { + return '"\n + (tokens["' + name + '"](req, res, ' + String(JSON.stringify(arg)) + ') || "-") + "'; + }) + '";'; + return new Function('tokens, req, res', js); + } + function createBufferStream(stream, interval) { + var buf = []; + var timer = null; + function flush() { + timer = null; + stream.write(buf.join('')); + buf.length = 0; + } + function write(str) { + if (timer === null) { + timer = setTimeout(flush, interval); + } + buf.push(str); + } + return {write: write}; + } + function format(name, fmt) { + morgan[name] = fmt; + return this; + } + function getFormatFunction(name) { + var fmt = morgan[name] || name || morgan.default; + return typeof fmt !== 'function' ? compile(fmt) : fmt; + } + function getip(req) { + return req.ip || req._remoteAddress || (req.connection && req.connection.remoteAddress) || undefined; + } + function pad2(num) { + var str = String(num); + return (str.length === 1 ? '0' : '') + str; + } + function recordStartTime() { + this._startAt = process.hrtime(); + this._startTime = new Date(); + } + function token(name, fn) { + morgan[name] = fn; + return this; + } +})(require("process")); diff --git a/pool/shard011/JavaScript/0069621_BRFv4SetupChooser.js b/pool/shard011/JavaScript/0069621_BRFv4SetupChooser.js new file mode 100644 index 0000000000000000000000000000000000000000..292b8f9f7c908a0fd2b4b6cee308c2692172ce9b --- /dev/null +++ b/pool/shard011/JavaScript/0069621_BRFv4SetupChooser.js @@ -0,0 +1,32 @@ +(function() { + "use strict"; + + if(typeof QuickSettings === "undefined") return; + + var example = brfv4.example; + var dom = example.dom; + var gui = example.gui; + + var urlMap = { + "Webcam Setup": "webcam", + "Picture Setup": "picture" + }; + var labels = []; + for (var key in urlMap) { labels.push(key); } // Fill in the labels. + + function onSetupChosen(data) { + example.init(urlMap[data.value]); + } + + // if(!gui.setupChooser) { + // + // QuickSettings.useExtStyleSheet(); + // + // gui.setupChooser = QuickSettings.create( + // 7, 7, "Setup Chooser", dom.createDiv("_settingsLeft")) + // .setWidth(300) + // .addHTML("Switch between setups", "Choose either webcam or loaded picture.

    Make sure you opened the https:// URL. Otherwise the webcam may not start in Chrome.") + // .addDropDown("_setup", labels, onSetupChosen) + // .hideTitle("_setup"); + // } +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069630_program.js b/pool/shard011/JavaScript/0069630_program.js new file mode 100644 index 0000000000000000000000000000000000000000..7eecaef128fb7fdb84165b24e2f0f1eaf40ff376 --- /dev/null +++ b/pool/shard011/JavaScript/0069630_program.js @@ -0,0 +1,9 @@ +exports.run = function() { + var a = require('./a'); + var foo = a.foo; + + should(a.foo()).eql(a); + should(foo()).eql((function (){return this})()); + a.set(10); + should(a.get()).eql(10); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069632_colors.js b/pool/shard011/JavaScript/0069632_colors.js new file mode 100644 index 0000000000000000000000000000000000000000..224ae8c02e9467fa98b2878dd7210ed01792702c --- /dev/null +++ b/pool/shard011/JavaScript/0069632_colors.js @@ -0,0 +1,21 @@ +let colors = { + '__file__': '#db7100', + //'node_modules': '#599e59', + //'node_modules': '#215E21', + //'node_modules': '#326589', //#26587A', + '__default__': '#487ea4' +}; + + +export function getColor(obj) { + let name = obj.name; + let dotIndex = name.indexOf('.'); + + if (dotIndex !== -1 && dotIndex !== 0 && dotIndex !== name.length - 1) { + return colors.__file__; + } else if (obj.parent && obj.parent.name === 'node_modules') { + return '#599e59'; + } + + return colors[name] || colors.__default__; +} diff --git a/pool/shard011/JavaScript/0069635_server.js b/pool/shard011/JavaScript/0069635_server.js new file mode 100644 index 0000000000000000000000000000000000000000..68c25b1234de76ad3580b9d7345ca313da96f41a --- /dev/null +++ b/pool/shard011/JavaScript/0069635_server.js @@ -0,0 +1,53 @@ +const path = require('path'); +const webpack = require('webpack'); +const express = require('express'); +const config = require('./webpack.config'); +const connect = require('./src/backend/common/db-connect'); +const bodyParser = require('body-parser'); + + +const app = express(); + + +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({extended: false})); + +const compiler = webpack(config); + +app.use(require('webpack-dev-middleware')(compiler, { + publicPath: config.output.publicPath +})); + +app.use(require('webpack-hot-middleware')(compiler)); + +app.use(express.static(path.join(__dirname, 'public'))); + +app.use(require('./src/backend/routes/index')); +connect(); + + +app.get('/*', function (req, res) { + res.sendFile(path.join(__dirname, 'index.html')); +}); + + + +app.use(function (req, res, next) { + const err = new Error('Not found'); + err.status = 404; + next(err); +}); + +app.use(function (err, req, res) { + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + res.status(err.status || 500); +}); + +app.listen(3000, function (err) { + if (err) { + return console.error(err); + } + + console.log('Listening at http://localhost:3000/'); +}); diff --git a/pool/shard011/JavaScript/0069636_render.js b/pool/shard011/JavaScript/0069636_render.js new file mode 100644 index 0000000000000000000000000000000000000000..268a4cedc75048c7930f343789ce81e5a91cfca7 --- /dev/null +++ b/pool/shard011/JavaScript/0069636_render.js @@ -0,0 +1,69 @@ +var expect = require("chai").expect; +var Pagemaki = require("../pagemaki"); + +describe("render", function () { + + var testParsed = { + test: "a test string" + }; + + var testRenderer = function () { + return "

    <%= page.test %>

    "; + }; + + + it("should use underscore templates by default", function (done) { + + var maker = new Pagemaki({ + getTemplateString: testRenderer + }); + + maker.render(null, testParsed, function (err, rendered) { + + expect(rendered).to.equal("

    a test string

    "); + + done(); + + }); + + }); + + + + it("should be customizeable on creation", function (done) { + + var maker = new Pagemaki({ + getTemplateString: testRenderer, + templateCompile: function (string) { + return function () { + return "removed"; + }; + } + }); + + maker.render(null, testParsed, function (err, rendered) { + + expect(rendered).to.equal("removed"); + + done(); + + }); + + }); + +}); + + +// MOAR TESTS +// var fs = require("fs"); +// var Maker = require("./pagemaker"); + +// var maker = new Maker({ +// templateData: { site: { title: "Not Robotic Ok?" } } +// }); + +// maker.make(fs.readFileSync("./src/pages/index.html"), function (err, made) { + +// console.log(arguments); + +// }); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069637_BasemapLayerSpec.js b/pool/shard011/JavaScript/0069637_BasemapLayerSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..76214eec812ca6a673f1b794938824e4f6c0c29f --- /dev/null +++ b/pool/shard011/JavaScript/0069637_BasemapLayerSpec.js @@ -0,0 +1,129 @@ +/* eslint-env mocha */ +describe('L.esri.BasemapLayer', function () { + function createMap () { + // create container + var container = document.createElement('div'); + + // give container a width/height + container.setAttribute('style', 'width:500px; height: 500px;'); + + // add container to body + document.body.appendChild(container); + + return L.map(container).setView([37.75, -122.45], 5); + } + + var map; + var server; + var clock; + var mockAttributions = { + 'contributors': [ + { + 'attribution': 'SkyNet', + 'coverageAreas': [ + { + 'zoomMax': 19, + 'zoomMin': 0, + 'score': 50, + 'bbox': [-84.94, -179.66, 84.94, 179.66] + } + ] + }, + { + 'attribution': 'City & County of San Francisco', + 'coverageAreas': [ + { + 'zoomMax': 19, + 'zoomMin': 16, + 'score': 100, + 'bbox': [37.71, -122.51, 37.83, -122.36] + } + ] + } + ] + }; + + beforeEach(function () { + clock = sinon.useFakeTimers(); + server = sinon.fakeServer.create(); + server.respondWith('GET', new RegExp(/.*/), JSON.stringify(mockAttributions)); + map = createMap(); + }); + + afterEach(function () { + clock.restore(); + server.restore(); + map.remove(); + }); + + it('can return valid basemaps', function () { + var testmaps = ['Streets', 'Topographic', 'NationalGeographic', 'Oceans', 'OceansLabels', 'DarkGray', 'DarkGrayLabels', 'Gray', 'GrayLabels', 'Imagery', 'ImageryLabels', 'ImageryTransportation', 'ShadedRelief', 'ShadedReliefLabels', 'Terrain', 'TerrainLabels', 'USATopo']; + for (var i = 0, len = testmaps.length; i < len; i++) { + var name = testmaps[i]; + expect(L.esri.basemapLayer(name)).to.be.instanceof(L.esri.BasemapLayer); + expect(L.esri.basemapLayer(name)._url).to.equal(L.esri.BasemapLayer.TILES[name].urlTemplate); + } + }); + + it('can survive adding/removing basemaps w/ labels', function () { + var moremaps = ['Oceans', 'DarkGray', 'Gray', 'Imagery', 'ShadedRelief', 'Terrain']; + for (var i = 0, len = moremaps.length; i < len; i++) { + var layer = L.esri.basemapLayer(moremaps[i]).addTo(map); + var layerWithLabels = L.esri.basemapLayer(moremaps[i] + 'Labels').addTo(map); + expect(map.hasLayer(layer)).to.equal(true); + expect(map.hasLayer(layerWithLabels)).to.equal(true); + + map.removeLayer(layer); + map.removeLayer(layerWithLabels); + expect(map.hasLayer(layer)).to.equal(false); + expect(map.hasLayer(layerWithLabels)).to.equal(false); + } + }); + + it('can be added to the map as normal', function () { + var baseLayer = L.esri.basemapLayer('Streets'); + map.addLayer(baseLayer); + expect(map.hasLayer(baseLayer)).to.equal(true); + }); + + it('will append tokens when fetching tiles if necessary', function () { + var baseLayer = L.esri.basemapLayer('Streets', {token: 'bogus'}); + map.addLayer(baseLayer); + expect(baseLayer._url).to.contain('token=bogus'); + }); + + it('will throw an error given invalid basemap name', function () { + expect(function () { + L.esri.basemapLayer('junk'); + }).to.throw(/Invalid parameter/); + }); + + it('should have an L.esri.basemapLayer alias', function () { + expect(L.esri.basemapLayer('Topographic')).to.be.instanceof(L.esri.BasemapLayer); + }); + + // /* + // need to figure out how to wire up the mockAttributions to + // test display when map is panned beyond the dateline + // + // i dont understand how to spoof http responses for inner logic private function calls + // like the jsonp request made inside L.esri.Util._getAttributionData(); + // */ + // it('can display attribution when panned beyond the dateline', function () { + // var baseLayer = L.esri.basemapLayer('Streets'); + // map.addLayer(baseLayer); + // // L.esri.Util._getAttributionData(baseLayer.options.attributionUrl, map); + // // map.setView([ 37.30, 360], 10); + // clock.tick(151); + // + // var check = false; + // for(var prop in map.attributionControl._attributions) { + // // console.log(prop); + // if (prop.match(/SkyNet/i) != null) { + // test = true; + // }; + // } + // + // expect(check).to.equal(true); + // }); +}); diff --git a/pool/shard011/JavaScript/0069639_gulpfile.js b/pool/shard011/JavaScript/0069639_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..33680f4faa3c92d4622dd8833161b9e1dd9d9392 --- /dev/null +++ b/pool/shard011/JavaScript/0069639_gulpfile.js @@ -0,0 +1,19 @@ +var gulp = require('gulp'); +var minify = require('gulp-minify'); +var babel = require('gulp-babel'); +var jshint = require('gulp-jshint'); + +gulp.task('default', ['scripts'], function() { }); + +gulp.task('scripts', function () { + return gulp.src('./src/*.js') + .pipe(babel()) + .pipe(minify()) + .pipe(gulp.dest('./dist/')); +}); + +gulp.task('jshint', function() { + gulp.src('./src/*.js') + .pipe(jshint()) + .pipe(jshint.reporter('default')); +}); diff --git a/pool/shard011/JavaScript/0069640_AccessManager.js b/pool/shard011/JavaScript/0069640_AccessManager.js new file mode 100644 index 0000000000000000000000000000000000000000..eeb3fb67ba4c1c0d1fe7a65bc97310ba88fbd8da --- /dev/null +++ b/pool/shard011/JavaScript/0069640_AccessManager.js @@ -0,0 +1,68 @@ +import { + NativeModules, + NativeAppEventEmitter, + Platform +} from 'react-native'; + +const { TwilioAccessManager } = NativeModules; + +function parseManager(manager) { + if (manager) { + this.token = manager.token; + this.expires = new Date(manager.expirationDate); + } + return true; +} + +class AccessManager { + constructor(token) { + this.token = token; + + this.onTokenExpired = null; + this.onTokenWillExpire = null; + this.onTokenInvalid = null; + + this._accessManagerTokenInvalidSubscription = NativeAppEventEmitter.addListener( + 'accessManager:tokenInvalid', + (error) => { + if (this.onTokenInvalid) this.onTokenInvalid(error); + }, + ); + + this._accessManagerTokenWillExpireSubscription = NativeAppEventEmitter.addListener( + 'accessManager:tokenWillExpire', + (error) => { + if (this.onTokenWillExpire) this.onTokenWillExpire(error); + }, + ); + + this._accessManagerTokenExpiredSubscription = NativeAppEventEmitter.addListener( + 'accessManager:tokenExpired', + () => { + if (this.onTokenExpired) this.onTokenExpired(); + }, + ); + + TwilioAccessManager.accessManagerWithToken(this.token) + .then(parseManager.bind(this)); + } + + registerClient() { + if (Platform.OS === 'ios') { + TwilioAccessManager.registerClient(); + } + } + + updateToken(newToken) { + TwilioAccessManager.updateToken(newToken) + .then(parseManager.bind(this)); + } + + removeListeners() { + this._accessManagerTokenInvalidSubscription.remove(); + this._accessManagerTokenExpiredSubscription.remove(); + this._accessManagerTokenWillExpireSubscription.remove(); + } +} + +export default AccessManager; diff --git a/pool/shard011/JavaScript/0069641_CreditcardController.js b/pool/shard011/JavaScript/0069641_CreditcardController.js new file mode 100644 index 0000000000000000000000000000000000000000..811c549faf11f0383cf0f2f57114b889c23108c9 --- /dev/null +++ b/pool/shard011/JavaScript/0069641_CreditcardController.js @@ -0,0 +1,139 @@ +/** + * CreditcardController + * + * @description :: Server-side logic for managing creditcards + * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers + */ + + /* stripe test card*/ +var stripe = require('stripe')('sk_test_p6T6ZefABbqttGgXHkpKeedX'); + +/* +All credit card related transtions like tokenization, +get and delete card is handled in this controller +*/ + +module.exports = { + /*Get All saved Card on the basis for req.session.User.id */ + + get: function(req,res){ + /* + @ method: GET + @ url: /card/get(required) + */ + + //get stripe customer id + User.find({ select: ['customer_id'], uid: req.session.User.uid}).exec(function(err,results){ + var cust_id = results[0].customer_id; + if(err){ + sails.log.error(new Error(err)); + res.status(200).send({ success: false, message: 'Some Error has occured. Please try again.'}) + } else if(cust_id) { + // call stripe to get all cards. + stripe.customers.listCards(cust_id,function(err, cards){ + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Failed to retrive saved cards. Please try again.'}) + } + return res.status(200).send({ success: true, message: 'Saved cards retrived succssfully.', data: cards.data }); + }) + } else { + return res.status(200).send({ success: true, message: 'You dont have saved cards', data: [] }); + } + }) + }, + + /* Save a Card Information, for further transactions */ + + save: function(req,res){ + /* + @ method: POST + @ url: '/card/save' + @ data: {'id': token_id} + */ + if(req.body.id){ + + var createCard = function(cust_id,token){ + // stripe call to create new card. + stripe.customers.createSource(cust_id,{source: token},function(err,card){ + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Failed to save card. Please try again'}); + } else { + return res.status(200).send({ success: true, message: 'Card saved succssfully.'}) + } + }); + }; + + User.find({ select: ['customer_id'], uid: req.session.User.uid}).exec(function(err,results){ + var cust_id = results[0].customer_id; + var token = req.body.id; + + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Some Error has occured. Please try again.'}); + } + else if(cust_id){ + createCard(cust_id,token); + } else { + // stripe call to create customer + stripe.customers.create({ + source: token + },function(err,customer){ + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Failed to save card. Please try again'}); + } + User.update({uid: req.session.User.uid}, {customer_id: customer.id}).exec(function(err,results){ + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Some Error has occured. Please try again.'}); + } + createCard(customer.id,token); + }) + }) + } + }) + } else { + return res.status(200).send({ success: false, message: 'Required Fields Missing'}); + } + }, + /* Delete a card on the basis of req.session.User.id */ + + delete: function(req,res){ + /* + @ method: POST, + @ url: '/card/delete', + @ data: { + id: tokenization_id + } + */ + if(req.body.id){ + var id = req.body.id; + User.find({ select: ['customer_id'], uid: req.session.User.uid}).exec(function(err,results){ + var cust_id = results[0].customer_id; + var card_id = req.body.id; + if(err){ + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Some Error has occured. Please try again.'}); + } + else if(cust_id){ + // stripe call to delete customer. + stripe.customers.deleteCard(cust_id,card_id,function(err,confirmation){ + if(confirmation.deleted){ + return res.status(200).send({ success: true, message: 'Card deleted successfully.'}) + } + sails.log.error(new Error(err)); + return res.status(200).send({ success: false, message: 'Failed to delete card. Please try again'}); + }) + } else { + return res.status(200).send({ success: false, message: 'You dont have any saved cards to delete.'}); + } + }) + } else { + return res.status(200).send({ success: false, message: 'Required fields are missing. Please try again.'}); + } + } + +}; + diff --git a/pool/shard011/JavaScript/0069645_test.js b/pool/shard011/JavaScript/0069645_test.js new file mode 100644 index 0000000000000000000000000000000000000000..7c7a2d7ca28a503e4cbefde79b950328238aa1e2 --- /dev/null +++ b/pool/shard011/JavaScript/0069645_test.js @@ -0,0 +1,38 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var tape = require( 'tape' ); +var subscriptions = require( './../lib' ); + + +// TESTS // + +tape( 'main export is a function', function test( t ) { + t.ok( true, __filename ); + t.equal( typeof subscriptions, 'function', 'main export is a function' ); + t.end(); +}); + +tape( 'module exports a factory method', function test( t ) { + t.equal( typeof subscriptions.factory, 'function', 'export includes a factory method' ); + t.end(); +}); diff --git a/pool/shard011/JavaScript/0069646_myapp.js b/pool/shard011/JavaScript/0069646_myapp.js new file mode 100644 index 0000000000000000000000000000000000000000..e3732e489baf5203a21278829be2417dd1012aef --- /dev/null +++ b/pool/shard011/JavaScript/0069646_myapp.js @@ -0,0 +1,23 @@ +"use strict"; +var fx = require("framework"); +var Class = fx.import("framework.Class"); +var H5App = fx.import("framework.app.H5App"); +var View = fx.import("framework.h5.view.View"); + +Class.define("MyApp", H5App, { + onStart: function() { + this.view = new View(); + this.view.background = "#FF0000"; + this.view.left = 110; + this.view.top = 110; + this.view.width = 100; + this.view.height = 100; + this.view.addEventListener("touchend", this.onTouchEnd.bind(this)); + + this.window.addChild(this.view); + }, + + onTouchEnd: function() { + this.view.background = "#00FF00"; + } +}, module); diff --git a/pool/shard011/JavaScript/0069650_connect-logger.js b/pool/shard011/JavaScript/0069650_connect-logger.js new file mode 100644 index 0000000000000000000000000000000000000000..1f287c06a5b70770466195b0f239f4ec59f3ab63 --- /dev/null +++ b/pool/shard011/JavaScript/0069650_connect-logger.js @@ -0,0 +1,197 @@ +"use strict"; +var levels = require("./levels"); +var DEFAULT_FORMAT = ':remote-addr - -' + + ' ":method :url HTTP/:http-version"' + + ' :status :content-length ":referrer"' + + ' ":user-agent"'; +/** + * Log requests with the given `options` or a `format` string. + * + * Options: + * + * - `format` Format string, see below for tokens + * - `level` A log4js levels instance. Supports also 'auto' + * + * Tokens: + * + * - `:req[header]` ex: `:req[Accept]` + * - `:res[header]` ex: `:res[Content-Length]` + * - `:http-version` + * - `:response-time` + * - `:remote-addr` + * - `:date` + * - `:method` + * - `:url` + * - `:referrer` + * - `:user-agent` + * - `:status` + * + * @param {String|Function|Object} format or options + * @return {Function} + * @api public + */ + +function getLogger(logger4js, options) { + if ('object' == typeof options) { + options = options || {}; + } else if (options) { + options = { format: options }; + } else { + options = {}; + } + + var thislogger = logger4js + , level = levels.toLevel(options.level, levels.INFO) + , fmt = options.format || DEFAULT_FORMAT + , nolog = options.nolog ? createNoLogCondition(options.nolog) : null; + + return function (req, res, next) { + // mount safety + if (req._logging) return next(); + + // nologs + if (nolog && nolog.test(req.originalUrl)) return next(); + if (thislogger.isLevelEnabled(level) || options.level === 'auto') { + + var start = new Date() + , statusCode + , writeHead = res.writeHead + , url = req.originalUrl; + + // flag as logging + req._logging = true; + + // proxy for statusCode. + res.writeHead = function(code, headers){ + res.writeHead = writeHead; + res.writeHead(code, headers); + res.__statusCode = statusCode = code; + res.__headers = headers || {}; + + //status code response level handling + if(options.level === 'auto'){ + level = levels.INFO; + if(code >= 300) level = levels.WARN; + if(code >= 400) level = levels.ERROR; + } else { + level = levels.toLevel(options.level, levels.INFO); + } + }; + + //hook on end request to emit the log entry of the HTTP request. + res.on('finish', function() { + res.responseTime = new Date() - start; + //status code response level handling + if(res.statusCode && options.level === 'auto'){ + level = levels.INFO; + if(res.statusCode >= 300) level = levels.WARN; + if(res.statusCode >= 400) level = levels.ERROR; + } + if (thislogger.isLevelEnabled(level)) { + if (typeof fmt === 'function') { + var line = fmt(req, res, function(str){ return format(str, req, res); }); + if (line) thislogger.log(level, line); + } else { + thislogger.log(level, format(fmt, req, res)); + } + } + }); + } + + //ensure next gets always called + next(); + }; +} + +/** + * Return formatted log line. + * + * @param {String} str + * @param {IncomingMessage} req + * @param {ServerResponse} res + * @return {String} + * @api private + */ + +function format(str, req, res) { + return str + .replace(':url', req.originalUrl) + .replace(':method', req.method) + .replace(':status', res.__statusCode || res.statusCode) + .replace(':response-time', res.responseTime) + .replace(':date', new Date().toUTCString()) + .replace(':referrer', req.headers.referer || req.headers.referrer || '') + .replace(':http-version', req.httpVersionMajor + '.' + req.httpVersionMinor) + .replace( + ':remote-addr', req.ip || req._remoteAddress || ( + req.socket && + (req.socket.remoteAddress || (req.socket.socket && req.socket.socket.remoteAddress)) + )) + .replace(':user-agent', req.headers['user-agent'] || '') + .replace( + ':content-length', + (res._headers && res._headers['content-length']) || + (res.__headers && res.__headers['Content-Length']) || + '-' + ) + .replace(/:req\[([^\]]+)\]/g, function(_, field){ return req.headers[field.toLowerCase()]; }) + .replace(/:res\[([^\]]+)\]/g, function(_, field){ + return res._headers ? + (res._headers[field.toLowerCase()] || res.__headers[field]) + : (res.__headers && res.__headers[field]); + }); +} + +/** + * Return RegExp Object about nolog + * + * @param {String} nolog + * @return {RegExp} + * @api private + * + * syntax + * 1. String + * 1.1 "\\.gif" + * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga + * LOGGING http://example.com/hoge.agif + * 1.2 in "\\.gif|\\.jpg$" + * NOT LOGGING http://example.com/hoge.gif and + * http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga + * LOGGING http://example.com/hoge.agif, + * http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge + * 1.3 in "\\.(gif|jpe?g|png)$" + * NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg + * LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3 + * 2. RegExp + * 2.1 in /\.(gif|jpe?g|png)$/ + * SAME AS 1.3 + * 3. Array + * 3.1 ["\\.jpg$", "\\.png", "\\.gif"] + * SAME AS "\\.jpg|\\.png|\\.gif" + */ +function createNoLogCondition(nolog) { + var regexp = null; + + if (nolog) { + if (nolog instanceof RegExp) { + regexp = nolog; + } + + if (typeof nolog === 'string') { + regexp = new RegExp(nolog); + } + + if (Array.isArray(nolog)) { + var regexpsAsStrings = nolog.map( + function convertToStrings(o) { + return o.source ? o.source : o; + } + ); + regexp = new RegExp(regexpsAsStrings.join('|')); + } + } + + return regexp; +} + +exports.connectLogger = getLogger; diff --git a/pool/shard011/JavaScript/0069652_ci3-carousel.js b/pool/shard011/JavaScript/0069652_ci3-carousel.js new file mode 100644 index 0000000000000000000000000000000000000000..50a2ccc5df76308272922ebfde98de8fabeca60b --- /dev/null +++ b/pool/shard011/JavaScript/0069652_ci3-carousel.js @@ -0,0 +1,94 @@ +/* ======================================================================== + * cib_carousel.js v1.0 + * https://github.com/nhu313/cib_carousel + * ======================================================================== + * Copyright 2015 - Infinity and beyond Nhu Nguyen + * Licensed under MIT (https://github.com/nhu313/cib_carousel/blob/master/LICENSE) + * ======================================================================== */ +(function ($) { + "use strict"; + + var timer; + + function replaceClass(element, oldClass, newClass) { + element.removeClass(oldClass); + element.addClass(newClass); + } + + function clearRotatingFunc(element, className) { + element.unbind("click"); + element.removeClass(className); + } + + function nextItem(element) { + var next = element.next(); + if (next.length) { + return next; + } else { + return element.parent().find('.item:first'); + } + } + + function prevItem(element) { + var prev = element.prev(); + if (prev.length) { + return prev; + } else { + return element.parent().find('.item:last'); + } + } + + function addClickEvent(carousel, elementName, settings) { + var element = carousel.find('.' + elementName); + element.click(function() { + clearRotatingFunc(carousel.find('.next'), 'next'); + clearRotatingFunc(carousel.find('.prev'), 'prev'); + carousel.find('.active').removeClass('active'); + + setClasses($(this)); + clearInterval(timer); + setAutoRotate(carousel, settings); + + bindRotateEvent(carousel, settings); + }); + } + + function bindRotateEvent(carousel, settings) { + addClickEvent(carousel, 'prev', settings); + addClickEvent(carousel, 'next', settings); + } + + function setClasses(element) { + element.addClass('active'); + prevItem(element).addClass('prev'); + nextItem(element).addClass('next'); + } + + function bind(carousel, settings) { + setClasses(carousel.find('.item:first')); + + bindRotateEvent(carousel, settings); + setAutoRotate(carousel, settings); + } + + function setAutoRotate(carousel, settings) { + if (settings.auto) { + timer = setInterval(function () { + carousel.find('.next').click(); + }, (settings.duration * 1000)); + } + } + + $.fn.ci3 = function(options) { + var settings = $.extend( {}, $.fn.ci3.defaults, options ); + return this.each(function() { + bind($(this), settings); + }); + }; + + $.fn.ci3.defaults = { + duration: 4, + auto: true + }; + +}(jQuery)); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069653_migrate-db.js b/pool/shard011/JavaScript/0069653_migrate-db.js new file mode 100644 index 0000000000000000000000000000000000000000..66d529d7df6bc2250fdc6d98a7d3cd9801334b1a --- /dev/null +++ b/pool/shard011/JavaScript/0069653_migrate-db.js @@ -0,0 +1,53 @@ +const path = require('path') +const envPath = path.resolve(process.cwd(), '.env.local') + +console.log({ envPath }) + +require('dotenv').config({ path: envPath }) + +const mysql = require('serverless-mysql') + +const db = mysql({ + config: { + host: process.env.MYSQL_HOST, + database: process.env.MYSQL_DATABASE, + user: process.env.MYSQL_USERNAME, + password: process.env.MYSQL_PASSWORD, + port: process.env.MYSQL_PORT, + }, +}) + +async function query(q) { + try { + const results = await db.query(q) + await db.end() + return results + } catch (e) { + throw Error(e.message) + } +} + +// Create "entries" table if doesn't exist +async function migrate() { + try { + await query(` + CREATE TABLE IF NOT EXISTS entries ( + id INT AUTO_INCREMENT PRIMARY KEY, + title TEXT NOT NULL, + content TEXT NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at + TIMESTAMP + NOT NULL + DEFAULT CURRENT_TIMESTAMP + ON UPDATE CURRENT_TIMESTAMP + ) + `) + console.log('migration ran successfully') + } catch (e) { + console.error('could not run migration, double check your credentials.') + process.exit(1) + } +} + +migrate().then(() => process.exit()) diff --git a/pool/shard011/JavaScript/0069655_nsnjson.encoder.custom.js b/pool/shard011/JavaScript/0069655_nsnjson.encoder.custom.js new file mode 100644 index 0000000000000000000000000000000000000000..9f771155c8f4be2e0a359b8a5cd957de7be990b5 --- /dev/null +++ b/pool/shard011/JavaScript/0069655_nsnjson.encoder.custom.js @@ -0,0 +1,67 @@ +var Maybe = require('data.maybe'); + +var Types = require('../src/nsnjson.types'); + +var Encoder = require('../src/nsnjson.encoder'); + +var encoderOptions = {}; + +encoderOptions[Types.NULL] = function() { + return Maybe.Just([Types.NULL]); +} + +encoderOptions[Types.NUMBER] = function(value) { + return Maybe.Just([Types.NUMBER, value]); +} + +encoderOptions[Types.STRING] = function(value) { + return Maybe.Just([Types.STRING, value]); +} + +encoderOptions[Types.BOOLEAN] = function(value) { + return Maybe.Just([Types.BOOLEAN, ~~value]); +} + +encoderOptions[Types.ARRAY] = function(array) { + var itemsPresentation = []; + + for (var i = 0, size = array.length; i < size; i++) { + var itemPresentationMaybe = this.encode(array[i]); + + if (itemPresentationMaybe.isJust) { + var itemPresentation = itemPresentationMaybe.get(); + + itemsPresentation.push(itemPresentation); + } + } + + return Maybe.Just([Types.ARRAY, itemsPresentation]); +} + +encoderOptions[Types.OBJECT] = function(object) { + var fieldsPresentation = []; + + for (var name in object) { + if (object.hasOwnProperty(name)) { + var valuePresentationMaybe = this.encode(object[name]); + + if (valuePresentationMaybe.isJust) { + var valuePresentation = valuePresentationMaybe.get(); + + var fieldPresentation = valuePresentation.slice(); + + fieldPresentation.push(name); + + fieldsPresentation.push(fieldPresentation); + } + } + } + + return Maybe.Just([Types.OBJECT, fieldsPresentation]); +} + +module.exports = { + encode: function(data) { + return Encoder.encode(data, encoderOptions); + } +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069656_server.js b/pool/shard011/JavaScript/0069656_server.js new file mode 100644 index 0000000000000000000000000000000000000000..d6d1492fed7a6c225237c88b40998afc898bed6e --- /dev/null +++ b/pool/shard011/JavaScript/0069656_server.js @@ -0,0 +1,184 @@ +/********************************************************************************** + * CloudCV Boostrap - A starter template for Node.js with OpenCV bindings. + * This project lets you to quickly prototype a REST API + * in a Node.js for a image processing service written in C++. + * + * Author: Eugene Khvedchenya + * + * More information: + * - https://cloudcv.io + * - http://computer-vision-talks.com + * + **********************************************************************************/ + +var pmx = require('pmx'); pmx.init(); + +var express = require('express') + , http = require('http') + , path = require('path') + , fs = require('fs') + , cookieParser = require('cookie-parser') + , multer = require('multer') + , methodOverride = require('method-override') + , async = require('async') + , request = require('request') + , cv = require('./cloudcv.js') + , validator = require('validator') + , logger = require('./lib/logger.js') + , download = require('./lib/download.js') + , config = require('./lib/config.js') + , inspect = require('util').inspect + ; + +var app = express(); + +var multerOptions = { + inMemory:true, + limits: { + fileSize: config.maxFileSize, + files: 1 + } +} + +// Configuration +app.set('port', process.env.PORT || 3000); +app.set('title', 'cloudcv-bootstrap'); +app.set('views', __dirname + '/views'); +app.set('view engine', 'jade'); +app.set('view options', { pretty: true }); + +app.use(methodOverride()); +app.use(multer(multerOptions)); +app.use(cookieParser('optional secret string')); +app.use(pmx.expressErrorHandler()); +app.use(express.static(path.join(__dirname, 'public'))); + +// Static pages +app.get('/', function (req, res) { res.render('index'); }); + +function MapAnalyzeResult(analyzeResult) { + var returnRes = { + aspect: analyzeResult.aspectRatio, + size: { width:0, height:0}, + dominantColors: [] + }; + + for (var i = 0; i < analyzeResult.dominantColors.length; i++) + { + var c = analyzeResult.dominantColors[i]; + + returnRes.dominantColors.push(c); + } + + return returnRes; +} + +// Peace to everyone! + +app.use(function(req, res, next) { + res.header("Access-Control-Allow-Origin", "*"); + res.header("Access-Control-Allow-Headers", "X-Requested-With"); + + next(); +}); + +app.get('/api/v1/buildInformation', function (req, res) { + res.write(cv.buildInformation()); + res.end(); +}); + +app.get('/api/v1/image/analyze/dominantColors', function (req, res) { + + var sendErrorResponse = function (code, message) { + res.statusCode = code; + res.setHeader("Content-Type", "application/json"); + res.write(JSON.stringify({message:message})); + res.end(); + }; + + if (!req.query.image) { + return sendErrorResponse(404, 'Missing required parameter'); + } + + var externalImageURL = decodeURIComponent(req.query.image); + + if (!validator.isURL(externalImageURL)) { + logger.error('Given request is not an URL %s', externalImageURL); + return sendErrorResponse(404, 'Missing required parameter'); + } + + async.waterfall([ + function (callback) { + logger.info('Downloading external image from ' + externalImageURL); + download.plainDownloadViaHttpGet(externalImageURL, callback); + }, + function (image, callback) { + logger.info('Loaded file from %s of %d bytes', externalImageURL, image.length); + cv.analyzeImage(image, callback); + } + ], + function (failureOrNull, result) { + + if (failureOrNull) { + logger.error('Problem with a file %s: %s', externalImageURL, failureOrNull.message); + sendErrorResponse(500, failureOrNull.message); + } + else if (result) { + res.setHeader("Content-Type", "application/json"); + res.write(JSON.stringify(MapAnalyzeResult(result))); + res.end(); + } + else { + console.error("Neither error nor result are defined"); + res.end(); + } + } + ); +}); + +app.post('/api/v1/image/analyze/dominantColors/', function (req, res) { + + var sendErrorResponse = function (code, message) { + res.statusCode = code; + res.setHeader("Content-Type", "application/json"); + res.write(JSON.stringify({message:message})); + res.end(); + }; + + if (req.files && req.files.image) { + var uploadedImage = req.files.image.buffer; + } + else { + return sendErrorResponse(400, "Missing image data"); + } + + async.waterfall([ + function (callback) { + cv.analyzeImage(uploadedImage, callback); + } + ], + function (failureOrNull, result) { + + if (failureOrNull) { + logger.error('Problem with a file %s: %s', req.files.image.originalname, failureOrNull.message); + sendErrorResponse(500, failureOrNull.message); + } + else if (result) { + res.setHeader("Content-Type", "application/json"); + res.write(JSON.stringify(MapAnalyzeResult(result))); + res.end(); + } + else { + console.error("Neither error nor result are defined"); + res.end(); + } + } + ); + +}); + +logger.info("cloudcv-bootstrap server starting on port " + app.get('port')); + +http.createServer(app).listen(app.get('port'), function(){ + logger.info("cloudcv-bootstrap server listening on port " + app.get('port')); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069657_edit-test.js b/pool/shard011/JavaScript/0069657_edit-test.js new file mode 100644 index 0000000000000000000000000000000000000000..203940b5a6d54d720eeebf0c604f63b541ddb79f --- /dev/null +++ b/pool/shard011/JavaScript/0069657_edit-test.js @@ -0,0 +1,38 @@ +import { moduleFor } from 'ember-qunit'; +import test from 'ember-sinon-qunit/test-support/test'; +import wait from 'ember-test-helpers/wait'; +import Changeset from 'ember-changeset'; + +var controller; +moduleFor('controller:friends/edit', 'Unit | Controller | friends/edit', { + beforeEach() { + controller = this.subject(); + } +}); + +test('shows loading', function(assert) { + controller.send('showLoading'); + assert.equal(controller.get('isShowingLoading'), true); +}); + +test('hides loading', function(assert) { + controller.send('hideLoading'); + assert.equal(controller.get('isShowingLoading'), false); +}); + +test('shows modal', function(assert) { + controller.send('showSuccessModal'); + assert.equal(controller.get('isShowingSuccessModal'), true); +}); + +test('hides modal', function(assert) { + controller.send('hideSuccessModal'); + assert.equal(controller.get('isShowingSuccessModal'), false); +}); + +test('hide modal and go back to friends/list', function(assert) { + const stub = this.stub(controller, 'transitionToRoute'); + controller.send('goBack'); + assert.equal(controller.get('isShowingSuccessModal'), false); + assert.equal(stub.calledWith('friends.list'), true); +}); diff --git a/pool/shard011/JavaScript/0069658_page_keyevent.js b/pool/shard011/JavaScript/0069658_page_keyevent.js new file mode 100644 index 0000000000000000000000000000000000000000..5b6ae2d4000624036f62c5bb455bdcf4d0140e57 --- /dev/null +++ b/pool/shard011/JavaScript/0069658_page_keyevent.js @@ -0,0 +1,42 @@ +var page = require('webpage').create(); + +page.open("http://www.google.com") + .then(function() { + return page.injectJs("libs/keylogger.js"); + }) + .then(function() { + return page.evaluate(function(value) { + document.activeElement.value = value; + console.log("active element value:" + document.activeElement.value); + }, "foo"); + }) + .then(function() { + return page.sendEvent('keydown', 'a'); + }) + .then(function() { + return page.sendEvent('keypress', 'a'); + }) + .then(function() { + return page.sendEvent('keyup', 'a'); + }) + .then(function() { + return page.sendEvent('keydown', 'B', null, null, page.event.modifier.shift_down); + }) + .then(function() { + return page.sendEvent('keypress', 'B', null, null, page.event.modifier.shift_down); + }) + .then(function() { + return page.sendEvent('keyup', 'B', null, null, page.event.modifier.shift_down); + }) + .then(function() { + return page.sendEvent('keypress', "PhantomJS"); + }) + .then(function() { + return page.evaluate(function(value) { + console.log("active element value:" + document.activeElement.value); + console.assert(document.activeElement.value == value, "failed to simulate key event"); + }, "fooaBPhantomJS"); + }) + .then(function() { console.log("success!"); }, + function(error) { console.log("error! " + error + "\n" + error.stack); }) + .then(phantom.exit) diff --git a/pool/shard011/JavaScript/0069659_forms.js b/pool/shard011/JavaScript/0069659_forms.js new file mode 100644 index 0000000000000000000000000000000000000000..77fe72ecd4d04a09f50760c6fe75347f596fd12d --- /dev/null +++ b/pool/shard011/JavaScript/0069659_forms.js @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2013 peredur.net + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +function formhash(form, password) { + // Create a new element input, this will be our hashed password field. + var p = document.createElement("input"); + + // Add the new element to our form. + form.appendChild(p); + p.name = "p"; + p.type = "hidden"; + p.value = hex_sha512(password.value); + + // Make sure the plaintext password doesn't get sent. + password.value = ""; + + // Finally submit the form. + form.submit(); +} + +function regformhash(form, key, uid, email, password, conf) { + // Check each field has a value + if (uid.value == '' || email.value == '' || password.value == '' || conf.value == '' || form.key.value == '') { + alert('You must provide all the requested details. Please try again'); + return false; + } + + + // Check the username + re = /^\w+$/; + if(!re.test(form.username.value)) { + alert("Username must contain only letters, numbers and underscores. Please try again"); + form.username.focus(); + return false; + } + + + // Check that the password is sufficiently long (min 6 chars) + // The check is duplicated below, but this is included to give more + // specific guidance to the user + if (password.value.length < 6) { + alert('Passwords must be at least 6 characters long. Please try again'); + form.password.focus(); + return false; + } + + // At least one number, one lowercase and one uppercase letter + // At least six characters + var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,}/; + if (!re.test(password.value)) { + alert('Passwords must contain at least one number, one lowercase and one uppercase letter. Please try again'); + return false; + } + + // Check password and confirmation are the same + if (password.value != conf.value) { + alert('Your password and confirmation do not match. Please try again'); + form.password.focus(); + return false; + } + + // Create a new element input, this will be our hashed password field. + var p = document.createElement("input"); + + // Add the new element to our form. + form.appendChild(p); + p.name = "p"; + p.type = "hidden"; + p.value = hex_sha512(password.value); + + // Make sure the plaintext password doesn't get sent. + password.value = ""; + conf.value = ""; + + // Finally submit the form. + form.submit(); + return true; +} diff --git a/pool/shard011/JavaScript/0069661_StreamedOutgoingMessage.js b/pool/shard011/JavaScript/0069661_StreamedOutgoingMessage.js new file mode 100644 index 0000000000000000000000000000000000000000..ee99aa9242f4e0286db925437d5c07dbfaa99af9 --- /dev/null +++ b/pool/shard011/JavaScript/0069661_StreamedOutgoingMessage.js @@ -0,0 +1,98 @@ +const ByteBuffer = require('bytebuffer'); +const Stream = require('stream'); +const Util = require('util'); + +const WS13 = require('./index.js'); + +module.exports = StreamedOutgoingMessage; + +Util.inherits(StreamedOutgoingMessage, Stream.Writable); + +function StreamedOutgoingMessage(socket, type) { + this.started = false; + this.finished = false; + this.dataSent = false; + this.type = type; + this._socket = socket; + this._chunks = []; + + Stream.Writable.call(this); + + this.on('finish', () => { + this.finished = true; + this._emptyQueue(); + }); + + this.setDefaultEncoding("binary"); +} + +StreamedOutgoingMessage.prototype._start = function() { + if (this.started) { + return; + } + + this.started = true; + + for (let i = 0; i < this._chunks.length; i++) { + if (this._chunks[i].callback) { + this._chunks[i].callback(null); + this._chunks[i].callback = null; + } + } + + this._emptyQueue(); +}; + +StreamedOutgoingMessage.prototype._emptyQueue = function() { + if (!this.started || this._chunks.length == 0) { + return; + } + + let chunks = this._chunks.slice(0, this.finished ? this._chunks.length : this._chunks.length - 1); + if (chunks.length == 0) { + return; + } + + // No reason not to combine all those chunks into one + let buffer = Buffer.concat(chunks.map(chunk => chunk.payload)); + this._socket._sendFrame({ + "FIN": !!this.finished, + "RSV1": false, + "RSV2": false, + "RSV3": false, + "opcode": !this.dataSent ? this.type : WS13.FrameType.Continuation, + "payload": buffer + }, true); + + this.dataSent = true; + + chunks.filter(chunk => !!chunk.callback).forEach(chunk => chunk.callback(null)); + this._chunks.splice(0, chunks.length); + + this._socket._processQueue(); +}; + +StreamedOutgoingMessage.prototype._write = function(chunk, encoding, callback) { + if (this.type == WS13.FrameType.Data.Binary && typeof chunk === 'string') { + callback(new Error("Cannot send a string through a binary frame.")); + this.end(); + return; + } + + if (ByteBuffer.isByteBuffer(chunk)) { + chunk = chunk.toBuffer(); + } + + // We have to call the callback now or else remaining chunks don't make their way to us + if (this.started) { + callback(null); + } + + this._chunks.push({ + "payload": chunk, + "callback": !this.started ? callback : null + }); + + this._emptyQueue(); + this._socket._processQueue(); +}; diff --git a/pool/shard011/JavaScript/0069664_TimelineBuffEvents.js b/pool/shard011/JavaScript/0069664_TimelineBuffEvents.js new file mode 100644 index 0000000000000000000000000000000000000000..8100bd8e6c1acbff8b791fe42f8cc0d0da1768ee --- /dev/null +++ b/pool/shard011/JavaScript/0069664_TimelineBuffEvents.js @@ -0,0 +1,60 @@ +import Analyzer from 'parser/core/Analyzer'; +import Abilities from '../../core/modules/Abilities'; + +// add 500ms so buffs don't have a gap at the end of the timeline +const FILLER = 500; + +class TimelineBuffEvents extends Analyzer { + static dependencies = { + abilities: Abilities, + }; + + buffHistoryBySpellId = {}; + + _getAbility(spellId) { + // checking if there is any ability that cares about this buff + const ability = this.abilities.getSpellBuffAbility(spellId); + if (!ability) { + return null; + } + + if (!this.buffHistoryBySpellId[spellId]) { + this.buffHistoryBySpellId[spellId] = []; + } + return this.buffHistoryBySpellId[spellId]; + } + + _append(spellId, event) { + const history = this._getAbility(spellId); + if (history) { + history.push(event); + } + } + + on_byPlayer_changebuffstack(event) { + const spellId = event.ability.guid; + this._append(spellId, event); + } + + on_byPlayer_changedebuffstack(event) { + const spellId = event.ability.guid; + this._append(spellId, event); + } + + on_finished() { + // check if there are buffs which are still active on fight end, and add an end event + Object.keys(this.buffHistoryBySpellId) + .forEach((spellId) => { + const event = this.buffHistoryBySpellId[spellId][this.buffHistoryBySpellId[spellId].length -1]; + if (event.end === null) { + this.buffHistoryBySpellId[spellId].push({ + ...event, + end: this.owner.fight.end_time, + timestamp: this.owner.fight.end_time + FILLER, + }); + } + }); + } +} + +export default TimelineBuffEvents; diff --git a/pool/shard011/JavaScript/0069667_index.js b/pool/shard011/JavaScript/0069667_index.js new file mode 100644 index 0000000000000000000000000000000000000000..4869f4e56341122c4593fc9067004b1406de1e83 --- /dev/null +++ b/pool/shard011/JavaScript/0069667_index.js @@ -0,0 +1,43 @@ +(function () { + 'use strict'; + /* global window */ + var beautify = (typeof require === 'function' && require('js-beautify').html) || + (typeof window !== 'undefined' && window.html_beautify); + if (typeof beautify !== 'function') { + throw new Error('missing HTML beautify function'); + } + + if (typeof module === 'object') { + // node + module.exports = function () { + setConsoleHtml(); + }; + } + + function setConsoleHtml() { + if (typeof console === 'undefined') { + throw new Error('Weird, console object is undefined'); + } + if (typeof console.html === 'function') { + return; + } + + console.html = function () { + var args = Array.prototype.slice.call(arguments); + args.forEach(function (k) { + if (typeof k === 'string') { + return console.log(beautify(k)); + } + if (typeof k === 'object' && + typeof k.html === 'function') { + return console.log(beautify(k.html())); + } + if (typeof k.innerHTML === 'string') { + return console.log(beautify(k.innerHTML)); + } + }); + }; + } + + setConsoleHtml(); +}()); diff --git a/pool/shard011/JavaScript/0069670_uuid_service.js b/pool/shard011/JavaScript/0069670_uuid_service.js new file mode 100644 index 0000000000000000000000000000000000000000..7e84642a7d1d8537620a7c9a6d6cd832753e5672 --- /dev/null +++ b/pool/shard011/JavaScript/0069670_uuid_service.js @@ -0,0 +1,33 @@ +/** + * Created by T.Behrens on 06.06.14. + */ + +'use strict'; + +/* Services */ + +// Demonstrate how to register services +// In this case it is a simple value service. +var simulationApp = angular.module('simulationApp.services', []); + + +// This function is irrelevant for the simulator but without, the drag and drop would not work, +// because the directives need this id, which is returned in this function. +simulationApp.factory('uuid', function () { + var svc = { + new: function () { + function _p8(s) { + var p = (Math.random().toString(16) + "000000000").substr(2, 8); + return s ? "-" + p.substr(0, 4) + "-" + p.substr(4, 4) : p; + } + + return _p8() + _p8(true) + _p8(true) + _p8(); + }, + + empty: function () { + return '00000000-0000-0000-0000-000000000000'; + } + }; + + return svc; +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069671_FlintDevice.js b/pool/shard011/JavaScript/0069671_FlintDevice.js new file mode 100644 index 0000000000000000000000000000000000000000..7afc98d3ac0cd25cba94534b79b9025f7ff8a99e --- /dev/null +++ b/pool/shard011/JavaScript/0069671_FlintDevice.js @@ -0,0 +1,100 @@ +const { Class } = require('sdk/core/heritage'); +const { EventTarget } = require('sdk/event/target'); +const { emit } = require('sdk/event/core'); + +var timer = require('sdk/timers'); + +const FlintDevice = Class({ + extends: EventTarget, + + uniqueId_: null, + deviceType_: null, + friendlyName_: null, + manufacturer_: null, + modelName_: null, + + location_: null, + urlBase_: null, + + timerId_: null, + + initialize: function (device) { + this.uniqueId_ = device['uniqueId']; + this.deviceType_ = device['deviceType']; + this.friendlyName_ = device['friendlyName']; + this.manufacturer_ = device['manufacturer']; + this.modelName_ = device['modelName']; + + this.location_ = device['location']; + this.urlBase_ = device['urlBase']; + this.host_ = this.urlBase_.replace('http://', ''); + this.host_ = this.host_.replace(':9431', ''); + }, + + triggerTimer: function () { + var self = this; + this._clearTimer(); + this.timerId_ = timer.setTimeout(function () { + self._onTimeout(); + }, 30 * 1000); + }, + + _onTimeout: function () { + emit(this, 'devicegone', this.uniqueId_); + }, + + clear: function () { + this._clearTimer(); + }, + + _clearTimer: function () { + timer.clearTimeout(this.timerId_); + }, + + getUniqueId: function () { + return this.uniqueId_; + }, + + getDeviceType: function () { + return this.deviceType_; + }, + + getName: function () { + return this.friendlyName_; + }, + + getManufacture: function () { + return this.manufacturer_; + }, + + getModelName: function () { + return this.modelName_; + }, + + getLocation: function () { + return this.location_; + }, + + getUrlBase: function () { + return this.urlBase_; + }, + + getHost: function () { + return this.host_; + }, + + toJson: function () { + return { + uniqueId: this.uniqueId_, + location: this.location_, + urlBase: this.urlBase_, + host: this.host_, + deviceType: this.deviceType_, + deviceName: this.friendlyName_, + manufacture: this.manufacturer_, + modelName: this.modelName_ + }; + } +}); + +exports.FlintDevice = FlintDevice; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069672_gulpfile.js b/pool/shard011/JavaScript/0069672_gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..45dc916c670b17013f72899c8e4283deb41ce63b --- /dev/null +++ b/pool/shard011/JavaScript/0069672_gulpfile.js @@ -0,0 +1,42 @@ +'use strict'; + +var webpack_conf = require('./webpack.config'), + gulp = require('gulp'), + plugins = require('gulp-load-plugins')(), + webpack = require('webpack-stream'); + +gulp.task('start', function() { + require('dotenv').load(); + plugins.nodemon({ + watch: ["configurations", "lib", "config.js", "package.json", "app.js"], + script: 'bin/www' + }); +}); + +gulp.task('js', function () { + return gulp.src('./public/javascripts/**/*') + .pipe(plugins.eslint({ + extends: 'eslint:recommended', + ecmaFeatures: { + 'modules': true, + 'jsx': true + }, + rules: { + 'no-console': 1, + 'no-unused-vars': 1 + }, + globals: {}, + plugins: ["react"], + envs: ['browser', 'es6'] + })) + .pipe(plugins.eslint.format()) + //.pipe(plugins.eslint.failAfterError()) + .pipe(webpack(webpack_conf)) + .pipe(gulp.dest('./public/javascripts/')); +}); + +gulp.task('watch', function () { + return gulp.watch('./public/javascripts/src/**/*', ['js']); +}); + +gulp.task('default', ['start', 'js', 'watch']); diff --git a/pool/shard011/JavaScript/0069674_CodeListItems.js b/pool/shard011/JavaScript/0069674_CodeListItems.js new file mode 100644 index 0000000000000000000000000000000000000000..1b2e41caff56cfcbab3b314549fd9918e090ee60 --- /dev/null +++ b/pool/shard011/JavaScript/0069674_CodeListItems.js @@ -0,0 +1,53 @@ +import React from 'react'; +import { connect } from 'react-redux'; +// +import * as Basic from '../../components/basic'; +import CodeListItemTable from './CodeListItemTable'; +import { CodeListManager } from '../../redux'; + +const manager = new CodeListManager(); + +/** + * Codel list items. + * + * @author Radek Tomiška + * @since 9.4.0 + */ +class CodeListItems extends Basic.AbstractContent { + + getContentKey() { + return 'content.code-lists.items'; + } + + getNavigationKey() { + return 'code-list-items'; + } + + render() { + const { entity, showLoading } = this.props; + // + return ( + + { this.renderContentHeader({ style: { marginBottom: 0 }}) } + { + !entity || showLoading + ? + + : + + } + + ); + } +} + +function select(state, component) { + const { entityId } = component.match.params; + // + return { + entity: manager.getEntity(state, entityId), + showLoading: manager.isShowLoading(state, null, entityId) + }; +} + +export default connect(select)(CodeListItems); diff --git a/pool/shard011/JavaScript/0069675_bubble.js b/pool/shard011/JavaScript/0069675_bubble.js new file mode 100644 index 0000000000000000000000000000000000000000..5199856dfce89cbc73cb4e703dea2e778005f834 --- /dev/null +++ b/pool/shard011/JavaScript/0069675_bubble.js @@ -0,0 +1,79 @@ +'use strict'; + +const makeSort = require('./makeSort'); +const swap = require('./helpers/swap'); + +function downToUp(array, { lowerBound, upperBound, compare }) { + let newUpperBound = 0; + let newIsSorted = true; + + for (let i = lowerBound; i < upperBound; i++) { + if (compare(array[i], array[i + 1]) > 0) { + swap(array, i, i + 1); + + newUpperBound = i; + newIsSorted = false; + } + } + + return { + newUpperBound, + newIsSorted + }; +} + +function upToDown(array, { lowerBound, upperBound, compare }) { + let newLowerBound = array.length; + let newIsSorted = true; + + for (let i = upperBound; i > lowerBound; i--) { + if (compare(array[i], array[i - 1]) < 0) { + swap(array, i, i - 1); + + newLowerBound = i; + newIsSorted = false; + } + } + + return { + newLowerBound, + newIsSorted + }; +} + +function bubbleSort(array, { compare }) { + let isSorted = true; + let isDownToUp = true; + + let lowerBound = 0; + let upperBound = array.length - 1; + + const checkOpts = { + compare + }; + + do { + checkOpts.lowerBound = lowerBound; + checkOpts.upperBound = upperBound; + + if (isDownToUp) { + const { newIsSorted, newUpperBound } = downToUp(array, checkOpts); + + upperBound = newUpperBound; + isSorted = newIsSorted; + } else { + const { newIsSorted, newLowerBound } = upToDown(array, checkOpts); + + lowerBound = newLowerBound; + isSorted = newIsSorted; + } + + isDownToUp = !isDownToUp; + } while (!isSorted); + + return array; +} + +module.exports = (array, opts) => { + return makeSort(array, bubbleSort, opts); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069678_Ajax.js b/pool/shard011/JavaScript/0069678_Ajax.js new file mode 100644 index 0000000000000000000000000000000000000000..24676a7f5a7be72399d9872fb730223bc863915e --- /dev/null +++ b/pool/shard011/JavaScript/0069678_Ajax.js @@ -0,0 +1,51 @@ +function loadAjax() { + var xhr = null; + + if (window.XMLHttpRequest || window.ActiveXObject) + { + if (window.ActiveXObject) + { + try + { + xhr = new ActiveXObject("Msxml2.XMLHTTP"); + } + catch(e) + { + xhr = new ActiveXObject("Microsoft.XMLHTTP"); + } + } + else + { + xhr = new XMLHttpRequest(); + } + } + else + { + alert("Votre navigateur ne supporte pas l'objet XMLHttpRequest"); + return null; + } + + return xhr; +} + +function a(url) { + var xhr = loadAjax(); + xhr.onreadystatechange = function() + { + if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) + { + var regex = /^([\s\S]*)([\s\S]*)<\/body>([\s\S]*)$/; + var new_body = xhr.responseText.replace(regex, "$2"); + document.body.innerHTML = xhr.responseText; + if (!god_damn_ie) { + window.history.pushState(document.title, document.title, url); + } + var ajs = document.getElementsByTagName("ajaxscript"); + for (var i in ajs) { + eval(ajs[i].innerHTML); + } + } + }; + xhr.open("GET", url, true); + xhr.send(null); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069679_foot_mark_orgin.js b/pool/shard011/JavaScript/0069679_foot_mark_orgin.js new file mode 100644 index 0000000000000000000000000000000000000000..0ff08db8a7ce58cfc6eb85b47a6fa0a45d0a9fed --- /dev/null +++ b/pool/shard011/JavaScript/0069679_foot_mark_orgin.js @@ -0,0 +1,145 @@ +/** +* 淘足迹js部分 caiwen +*/ + +/** +* jquery 扩展等待方法 +*/ +$.fn.extend({ + wait: function(time, type) { + return this.queue(type || "fx", function() { + var $this = $(this); + setTimeout(function() { $this.dequeue(); }, time || 1000); + }); + } +}); +$(document).ready(function() { + $('.e_t_wrap li a').attr('href', 'javascript:void(0);'); //使连接失效 + //为关闭按钮注册事件和实现功能 + $('.e_t_b_title s').bind('click', function() { + //这里其实无需判断直接绑定功能即可 + if ($('.t_footmark,.t_goods,.t_news:visible').length >= 1) { + //关闭并还原样式 + $('.t_footmark,.t_goods,.t_news:visible').hide(); + $('.e_t_wrap li').removeClass('setall'); + $('.e_t_wrap li').removeClass('setthis'); + } + }); + //伸缩工具条 + $("li.e_toolbar_begin").click( + function() { + if ($(".e_t_wrap li:hidden").length > 0) { + $(this).unbind("mouseover").unbind('mouseout'); + $(".e_toolbar_begin span").removeClass("recovetb").addClass("switch-mini-tip"); + $(".switch-mini").remove(); + $(this).css("background-position", "-53px -165px"); + $(".e_t_wrap li").each( + function() { $(this).show(); } + ); + } else { + var _t = $(this); + $(this).css("background-position", "-72px -165px"); + $(this).addClass('hover'); setTimeout(function() { _t.removeClass('hover'); }, 2000); + $(".e_t_wrap li").not($(this)).each( + function() { + $(this).hide(); + } + ); + $('#e_mark .e_t_wrap li').removeClass('setall'); + $('#e_mark .e_t_wrap li').removeClass('setthis'); + $(".t_news,.t_footmark,.t_goods").each( + function() { + $(this).hide(); + } + ); + _t.attr('title', ''); + _t.mouseover( + function() { $(".e_toolbar_begin span").removeClass("switch-mini-tip").addClass("recovetb"); } + ).mouseout( + function() { + $(".e_toolbar_begin span").removeClass("recovetb").addClass("switch-mini-tip"); + } + ); + $(".e_t_wrap").prepend($("
  • ")); + } + } + ); +}); + +/** +* IE 下绑定展开 进货车 我的足迹 消息,会出现延迟现象 修复 直接添加事件 add by caiwen +*/ +function gettitlevalue() +{ + var linkusername= ""; + $.ajax({ + type: "GET", + async:false, + url: im_url+"/GetStoreSession.aspx?StoreID="+store_id, + dataType: "jsonp", + jsonp: "callback", + jsonpCallback: "im_storeId", + success:function(json) { + linkusername =json.storevalue; + var user_nick_name=json.nickname; + if(user_nick_name=='') {user_nick_name=json.username;} + $("#storecustonname").html(""); + $("#beforechecked").val(json.username); + $("#storecustonname").append('
  • '); + $("#storecustonname:first-child li").append(""); + $("#storecustonname:first-child span").append(''); + $("#storecustonname:first-child span").append('╳'); + } + }); +} + +var lisEvent = {}; +lisEvent.TempHide = '.t_footmark,.t_goods,.t_news,.webim-tool-con'; +lisEvent.exe = function(obj, str) { + $('#e_mark .e_t_wrap li').removeClass('setall'); + $('#e_mark .e_t_wrap li').removeClass('setthis'); + $('#e_mark .e_t_wrap li').addClass('setall'); + $(obj).addClass('setthis'); + if ($('#e_mark ' + str + ':hidden').length >= 1) { + $(lisEvent.TempHide).hide(); + $(str + ':hidden').show(); + var hide_clickSum = $("#clickSumId").attr("value"); + if(hide_clickSum =="0") + { + $("#clickSumId").attr("value",1); + var iframe_url = $('#shanshanwebim').attr('value');//$('#shanshanwebim').attr('src'); + //$('#shanshanwebim').attr("src", iframe_url); + var iframe = document.getElementById("shanshanwebim"); + iframe.src = iframe_url; + if (iframe.attachEvent){ + iframe.attachEvent("onload", function(){ + gettitlevalue(); + });} else { + iframe.onload = function(){ + gettitlevalue(); + }; + } + } + } else { + $('#e_mark ' + str + ':visible').hide(); + $('#e_mark .e_t_wrap li').removeClass('setall'); + $('#e_mark .e_t_wrap li').removeClass('setthis'); + }}; +lisEvent.t_my_news = function(obj) { + lisEvent.exe(obj, ".t_news"); + //ajax_request("index.php?app=foot_mark&act=ajax_new_inbox&num=5&t=mes&ajax=1", 't_n_c_news', 'html'); +}; +lisEvent.t_my_footmark = function(obj) { + lisEvent.exe(obj, ".t_footmark"); + //ajax_request("index.php?app=foot_mark&act=footmark_list", 'history_ft_list', 'html', function() { dir_marquee("all_vis", "t_left", "t_right", "history_ft_list", "history_list_con"); }); +}; +lisEvent.t_my_car = function(obj) { + lisEvent.exe(obj, ".t_goods"); +}; +lisEvent.open_web_im = function(obj) { + $(obj).removeClass('newtx'); + $(obj).find('label').text('联系客服'); + lisEvent.exe(obj, ".webim-tool-con"); +}; +//换一组 +lisEvent.next_g = function(t) {}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069682_lib_xml_to_json.js b/pool/shard011/JavaScript/0069682_lib_xml_to_json.js new file mode 100644 index 0000000000000000000000000000000000000000..96ec6edfca22df7ca7d9ad87cc9625d3035ce248 --- /dev/null +++ b/pool/shard011/JavaScript/0069682_lib_xml_to_json.js @@ -0,0 +1,106 @@ +// start of file + +// ------------------- +// XML to JSON +// ------------------- + + function convertXMLtoJSON(inputXML){ + var XMLdoc, XMLerror; + // debug('convertXMLtoJSON \t PASSED\n' + inputXML); + + // Ignore namespace designations, which may not be properly + // defined in pasted code snippets. We ignore namespace stuff + // anyway, so we don't want to hit errors unnecessarily. + inputXML = inputXML.replace(/:/g, '-'); + + if (typeof window.DOMParser !== 'undefined') { + XMLdoc = (new window.DOMParser()).parseFromString(inputXML, 'text/xml'); + } else if (typeof window.ActiveXObject !== 'undefined' && new window.ActiveXObject('Microsoft.XMLDOM')) { + XMLdoc = new window.ActiveXObject('Microsoft.XMLDOM'); + XMLdoc.async = 'false'; + XMLdoc.loadXML(inputXML); + } else { + console.warn('No XML document parser found.'); + XMLerror = new SyntaxError('No XML document parser found.'); + throw XMLerror; + } + + var parsererror = XMLdoc.getElementsByTagName('parsererror'); + if (parsererror.length) { + var msgcon = XMLdoc.getElementsByTagName('div')[0].innerHTML; + XMLerror = new SyntaxError(trim(msgcon)); + throw XMLerror; + } + + return { + 'name' : XMLdoc.documentElement.nodeName, + 'attributes' : tag_getAttributes(XMLdoc.documentElement.attributes), + 'content' : tag_getContent(XMLdoc.documentElement) + }; + + + function tag_getContent(parent) { + var kids = parent.childNodes; + // debug('\n tag_getContent - START'); + // debug('\nTAG: ' + parent.nodeName + '\t' + parent.childNodes.length); + + if(kids.length === 0) return trim(parent.nodeValue); + + var result = []; + var node, tagresult, tagcontent, tagattributes; + + for(var k=0; k>START kid ' + k + ' ' + node.nodeName); +/* + if(node.nodeName === '#comment') { + // debug('\t Found a #comment, breaking...'); + break; + } +*/ + // debug('\t tag content: '); + // debug(tagcontent); + + tagcontent = tag_getContent(node); + tagattributes = tag_getAttributes(node.attributes); + + if(node.nodeName === '#text' && JSON.stringify(tagattributes) === '{}'){ + tagresult = trim(tagcontent); + } else { + tagresult.name = node.nodeName; + tagresult.attributes = tagattributes; + tagresult.content = tagcontent; + } + + if(tagresult !== '') result.push(tagresult); + + // debug('\t>>END kid ' + k); + } + + // debug(' tag_getContent - END\n'); + return result; + } + + function tag_getAttributes(attributes) { + if(!attributes || !attributes.length) return {}; + + // debug('\t\t tag_getAttributes:'); + // debug(attributes); + + var result = {}; + var attr; + + for(var a=0; a
    ' ); + + widget.chart = $('#' + widget.name).epoch({ + type: 'time.area', + + data: [ + // The first layer + { + label: 'TXs per Sec', + values: [ { time: (new Date()).getTime() / 1000, y: 0 } ] + } + + ], + axes: ['left', 'right', 'bottom'] + }); + }, + + onData: function(data) { + if (!data) { + return; + } + + var b = { + time: data.timestamp, + y: data.value + }; + widget.chart.push([ b ]); + }, + }; + + + var widget = _.extend({}, widgetRoot, extended); + + // register presence with screen manager + Dashboard.addWidget(widget); +}; diff --git a/pool/shard011/JavaScript/0069688_get-styles.test.js b/pool/shard011/JavaScript/0069688_get-styles.test.js new file mode 100644 index 0000000000000000000000000000000000000000..a0833650aefcfed41a764923f47783ff753b8fe0 --- /dev/null +++ b/pool/shard011/JavaScript/0069688_get-styles.test.js @@ -0,0 +1,125 @@ +/* eslint-env mocha */ +import { expect } from 'chai'; +import getStyles from '../../src/input/get-styles'; +import styles from '../../src/input/styles'; + +describe('Input.getStyles', () => { + describe('root', () => { + it('should get styles', () => { + const style = getStyles.root(); + + expect(style).to.deep.equal(styles.root); + }); + + it('should combine styles', () => { + const style = getStyles.root(false, { color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + + it('should add disabled styles', () => { + const style = getStyles.root(true); + + expect(style).to.have.property('opacity', '0.5'); + }); + }); + + describe('label', () => { + it('should get styles', () => { + const style = getStyles.label(); + + expect(style).to.deep.equal(styles.label); + }); + + it('should combine styles', () => { + const style = getStyles.label({ color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + }); + + describe('input', () => { + it('should get styles', () => { + const style = getStyles.input(); + + expect(style).to.deep.equal(styles.input); + }); + + it('should get error styles', () => { + const style = getStyles.input(true); + + expect(style).to.have.property('border', '1px solid #FD2A43'); + expect(style).to.have.property('color', '#FD2A43'); + }); + + it('should combine styles', () => { + const style = getStyles.input(false, { color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + }); + + describe('textarea', () => { + it('should get styles', () => { + const style = getStyles.textarea(); + + expect(style).to.deep.equal({ ...styles.textarea, ...styles.input }); + }); + + it('should combine styles', () => { + const style = getStyles.textarea(false, { color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + + it('should add errorMessage styles', () => { + const style = getStyles.textarea(true); + + expect(style).to.have.property('border', '1px solid #FD2A43'); + expect(style).to.have.property('color', '#FD2A43'); + }); + }); + + describe('error', () => { + it('should get styles', () => { + const style = getStyles.error(); + + expect(style).to.deep.equal(styles.error); + }); + + it('should combine styles', () => { + const style = getStyles.error({ color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + }); + + describe('inputRoot', () => { + it('should get styles', () => { + const style = getStyles.inputRoot(); + + expect(style).to.deep.equal({ ...styles.inputRoot, ...{ height: 32 } }); + }); + + it('should add height', () => { + const height = Math.floor(Math.random() * 10); + const style = getStyles.inputRoot(height); + + expect(style).to.have.property('height', height); + }); + }); + + describe('placeholder', () => { + it('should get styles', () => { + const style = getStyles.placeholder(); + + expect(style).to.deep.equal(styles.placeholder); + }); + + it('should combine styles', () => { + const style = getStyles.placeholder({ color: 'red' }); + + expect(style).to.have.property('color', 'red'); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069689_gen_node.js b/pool/shard011/JavaScript/0069689_gen_node.js new file mode 100644 index 0000000000000000000000000000000000000000..08eaab2307f0685394f3991c8374ff015515d046 --- /dev/null +++ b/pool/shard011/JavaScript/0069689_gen_node.js @@ -0,0 +1,104 @@ +/** + * @license + * Copyright 2019 Google LLC. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============================================================================= + */ + +/** + * Use a trained next-character prediction model to generate some text. + */ + +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import * as argparse from 'argparse'; + +import * as tf from '@tensorflow/tfjs'; + +import {maybeDownload, TextData, TEXT_DATA_URLS} from './data'; +import {generateText} from './model'; + +function parseArgs() { + const parser = argparse.ArgumentParser({ + description: 'Train an lstm-text-generation model.' + }); + parser.addArgument('textDatasetName', { + type: 'string', + choices: Object.keys(TEXT_DATA_URLS), + help: 'Name of the text dataset' + }); + parser.addArgument('modelJSONPath', { + type: 'string', + help: 'Path to the trained next-char prediction model saved on disk ' + + '(e.g., ./my-model/model.json)' + }); + parser.addArgument('--genLength', { + type: 'int', + defaultValue: 200, + help: 'Length of the text to generate.' + }); + parser.addArgument('--temperature', { + type: 'float', + defaultValue: 0.5, + help: 'Temperature value to use for text generation. Higher values ' + + 'lead to more random-looking generation results.' + }); + parser.addArgument('--gpu', { + action: 'storeTrue', + help: 'Use CUDA GPU for training.' + }); + parser.addArgument('--sampleStep', { + type: 'int', + defaultValue: 3, + help: 'Step length: how many characters to skip between one example ' + + 'extracted from the text data to the next.' + }); + return parser.parseArgs(); +} + +async function main() { + const args = parseArgs(); + + if (args.gpu) { + console.log('Using GPU'); + require('@tensorflow/tfjs-node-gpu'); + } else { + console.log('Using CPU'); + require('@tensorflow/tfjs-node'); + } + + // Load the model. + const model = await tf.loadModel(`file://${args.modelJSONPath}`); + + const sampleLen = model.inputs[0].shape[1]; + + // Create the text data object. + const textDataURL = TEXT_DATA_URLS[args.textDatasetName].url; + const localTextDataPath = path.join(os.tmpdir(), path.basename(textDataURL)); + await maybeDownload(textDataURL, localTextDataPath); + const text = fs.readFileSync(localTextDataPath, {encoding: 'utf-8'}); + const textData = new TextData('text-data', text, sampleLen, args.sampleStep); + + // Get a seed text from the text data object. + const [seed, seedIndices] = textData.getRandomSlice(); + + console.log(`Seed text:\n"${seed}"\n`); + + const generated = await generateText( + model, textData, seedIndices, args.genLength, args.temperature); + + console.log(`Generated text:\n"${generated}"\n`); +} + +main(); diff --git a/pool/shard011/JavaScript/0069690_lazy_load_test.js b/pool/shard011/JavaScript/0069690_lazy_load_test.js new file mode 100644 index 0000000000000000000000000000000000000000..039bdaf47560e956491672b901f424199f74319c --- /dev/null +++ b/pool/shard011/JavaScript/0069690_lazy_load_test.js @@ -0,0 +1,79 @@ +import { run } from 'ember-metal'; +import { onLoad, runLoadHooks, _loaded } from '../../system/lazy_load'; +import { moduleFor, AbstractTestCase } from 'internal-test-helpers'; + +moduleFor( + 'Lazy Loading', + class extends AbstractTestCase { + afterEach() { + let keys = Object.keys(_loaded); + for (let i = 0; i < keys.length; i++) { + delete _loaded[keys[i]]; + } + } + + ['@test if a load hook is registered, it is executed when runLoadHooks are exected'](assert) { + let count = 0; + + run(function() { + onLoad('__test_hook__', function(object) { + count += object; + }); + }); + + run(function() { + runLoadHooks('__test_hook__', 1); + }); + + assert.equal(count, 1, 'the object was passed into the load hook'); + } + + ['@test if runLoadHooks was already run, it executes newly added hooks immediately'](assert) { + let count = 0; + run(() => { + onLoad('__test_hook__', object => (count += object)); + }); + + run(() => runLoadHooks('__test_hook__', 1)); + + count = 0; + run(() => { + onLoad('__test_hook__', object => (count += object)); + }); + + assert.equal(count, 1, 'the original object was passed into the load hook'); + } + + ["@test hooks in ENV.EMBER_LOAD_HOOKS['hookName'] get executed"](assert) { + // Note that the necessary code to perform this test is run before + // the Ember lib is loaded in tests/index.html + + run(() => { + runLoadHooks('__before_ember_test_hook__', 1); + }); + + assert.equal(window.ENV.__test_hook_count__, 1, 'the object was passed into the load hook'); + } + + ['@test load hooks trigger a custom event'](assert) { + if ( + typeof window === 'object' && + typeof window.dispatchEvent === 'function' && + typeof CustomEvent === 'function' + ) { + let eventObject = 'super duper awesome events'; + + window.addEventListener('__test_hook_for_events__', function(e) { + assert.ok(true, 'custom event was fired'); + assert.equal(e.detail, eventObject, 'event details are provided properly'); + }); + + run(() => { + runLoadHooks('__test_hook_for_events__', eventObject); + }); + } else { + assert.expect(0); + } + } + } +); diff --git a/pool/shard011/JavaScript/0069692_CaffeInPlaceLayers.js b/pool/shard011/JavaScript/0069692_CaffeInPlaceLayers.js new file mode 100644 index 0000000000000000000000000000000000000000..217d378e3652407a4b41fcce880d8514d06f776c --- /dev/null +++ b/pool/shard011/JavaScript/0069692_CaffeInPlaceLayers.js @@ -0,0 +1,20 @@ +// This file contains the layers that can be computed in place +// +// It is used by both the NetworkImporter and the CNNCreator +// TODO: See if we can automate the creation of this file from +// Caffe's docs or something +define([], function() { + var convertKeysToLowerCase = function(object) { + var result = {}, + keys = Object.keys(object); + for (var i = keys.length; i--;) { + result[keys[i].toLowerCase()] = object[keys[i]]; + } + return result; + }; + + return convertKeysToLowerCase({ + ReLU: true, + Dropout: true + }); +}); diff --git a/pool/shard011/JavaScript/0069695_download.js b/pool/shard011/JavaScript/0069695_download.js new file mode 100644 index 0000000000000000000000000000000000000000..3a619770e777a1fd190ca21ff07da0cec90b4f7c --- /dev/null +++ b/pool/shard011/JavaScript/0069695_download.js @@ -0,0 +1,102 @@ +// ファイルをダウンロード +var downloadFile = function (url) { + var xhr = new XMLHttpRequest(), + deferred = new $.Deferred(); + + // ダウンロードが完了したら実行されるよ + xhr.addEventListener('load', function() { + xhr.response; // ダウンロードしたデータ + deferred.resolve(xhr); + }); + + xhr.open('GET', url, true); + xhr.responseType = 'arraybuffer'; //ここでarraybufferを設定 + xhr.send(); + + return deferred.promise(); +} + +// 複数ファイルを一括ダウンロード +var batchDownload = function(urlList) { + // 初期化 + dispLoading("準備中..."); + $(".btn").attr('disabled', true); + + var zip = new JSZip(), + deferreds = []; + + for (var i = 0; i < urlList.length; i += 1) { + //拡張子取得 + var f = urlList[i].split('.'); + var ext = f[f.length-1].split(':')[0]; + let filename = i+"."+ext; + var deferred = downloadFile(urlList[i]).done(function(xhr) { + zip.file(filename, xhr.response); //zipに追加 + }) + deferreds.push(deferred); + } + + $.when.apply($, deferreds).done(function() { + // すべてのダウンロードが完了したら実行されるよ! + zip.generateAsync({type:"blob"}).then(function (content) { + saveAs(content, _formatDate(new Date(), "YYYYMMDD-hhmmss") + ".zip"); + }); + $(".btn").attr('disabled', false); + removeLoading(); + }); +}; + +/** + * ZIPファイルを生成する + */ +function DownloadZip() { + // 選択した画像分ループ + var $images = $("img"); + var list = []; + $images.each(function(i) { + var thumbUrl = $(this).data("original"); + var originalUrl = thumbUrl.replace(/:thumb/, ":orig"); + list.push(originalUrl); + }); + batchDownload(list); +} + +/** + * 日付をフォーマットする + */ +function _formatDate(date, format) { + if (!format) format = 'YYYY-MM-DD hh:mm:ss.SSS'; + format = format.replace(/YYYY/g, date.getFullYear()); + format = format.replace(/MM/g, ('0' + (date.getMonth() + 1)).slice(-2)); + format = format.replace(/DD/g, ('0' + date.getDate()).slice(-2)); + format = format.replace(/hh/g, ('0' + date.getHours()).slice(-2)); + format = format.replace(/mm/g, ('0' + date.getMinutes()).slice(-2)); + format = format.replace(/ss/g, ('0' + date.getSeconds()).slice(-2)); + if (format.match(/S/g)) { + var milliSeconds = ('00' + date.getMilliseconds()).slice(-3); + var length = format.match(/S/g).length; + for (var i = 0; i < length; i++) format = format.replace(/S/, milliSeconds.substring(i, i + 1)); + } + return format; +}; + + +// Loadingイメージ表示関数 +function dispLoading(msg){ + // 画面表示メッセージ + var dispMsg = ""; + + // 引数が空の場合は画像のみ + if( msg != "" ){ + dispMsg = "
    " + msg + "
    "; + } + // ローディング画像が表示されていない場合のみ表示 + if($("#loading").size() == 0){ + $("body").append("
    " + dispMsg + "
    "); + } +} + +// Loadingイメージ削除関数 +function removeLoading(){ + $("#loading").remove(); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069698_phantom_crawler.js b/pool/shard011/JavaScript/0069698_phantom_crawler.js new file mode 100644 index 0000000000000000000000000000000000000000..98abc3d85ebd48621816882dc2fc30ae6c09ac7c --- /dev/null +++ b/pool/shard011/JavaScript/0069698_phantom_crawler.js @@ -0,0 +1,64 @@ +/* + * grunt-phantom-crawler + * + * + * + */ + +'use strict'; + +var phantom = require('node-phantom'); +var _ = require('underscore'); +var page; +var document; +var paths = []; +var options; +var done; +var crawl; + +module.exports = function(grunt) { + grunt.registerMultiTask('phantom-crawler', 'crawl a webpage and return urls', function(){ + + options = this.options({ + baseUrl: 'http://localhost', + filePath: 'config/paths.js', + startingPath: '/', + depth: 5, + }); + + done = this.async(); + + crawl = function (path, depth) { + var url; + + if (0 === depth || -1 !== paths.indexOf(path)) { + done(grunt.file.write(options.filePath, JSON.stringify(_.uniq(paths)))); + } + + + page = phantom.create(function(err, ph){ + ph.createPage(function(err, page) { + url = options.baseUrl + path; + return page.open(url, function (err, status) { + setTimeout(function(){ + return page.evaluate(function() { + return [].map.call(document.querySelectorAll('a'), function(link) { + return link.getAttribute('href'); + }); + }, function(err,result) { + result.forEach(function(href) { + crawl(href, depth-1); + }); + ph.exit(); + }); + }, 1000); + }); + }); + }); + paths.push(path); + }; + setTimeout(function() { + crawl(options.startingPath, options.depth); + }, 1000); + }); +}; diff --git a/pool/shard011/JavaScript/0069699_logoutControllerSpec.js b/pool/shard011/JavaScript/0069699_logoutControllerSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..ecb17d056e32dc62719e7136ef32152f7c8d8a2e --- /dev/null +++ b/pool/shard011/JavaScript/0069699_logoutControllerSpec.js @@ -0,0 +1,47 @@ +/** + * @license TRIP - Trip Recording and Itinerary Planning application. + * (c) 2016, 2017 Frank Dean + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * 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 . + */ +'use strict'; + +describe('LogoutCtrl', function() { + + beforeEach(module('myApp')); + + var scope, ctrl, $httpBackend, $location, Storage; + + beforeEach(inject(function($rootScope, $controller, _$location_, _Storage_) { + scope = $rootScope.$new(); + scope.admin = true; + $location = _$location_; + Storage = _Storage_; + spyOn($location, 'path').and.stub(); + spyOn(Storage, 'removeItem').and.stub(); + ctrl = $controller('LogoutCtrl', {$scope: scope}); + })); + + it('should remove the authentication token', function() { + expect(Storage.removeItem).toHaveBeenCalled(); + expect(Storage.removeItem.calls.argsFor(0)).toEqual(['id_token']); + expect(scope.admin).toBeFalsy(); + }); + + it('should redirect to the login page', function() { + expect($location.path).toHaveBeenCalled(); + expect($location.path.calls.argsFor(0)).toEqual(['/login']); + }); + +}); diff --git a/pool/shard011/JavaScript/0069702_step3.js b/pool/shard011/JavaScript/0069702_step3.js new file mode 100644 index 0000000000000000000000000000000000000000..ba969356e96748d3b4bdbb61cb9a336bb32bdd1f --- /dev/null +++ b/pool/shard011/JavaScript/0069702_step3.js @@ -0,0 +1,22 @@ + +var Q = require("q/util"); +var FS = require("q-fs"); + +Q.step( + function () { + return FS.list(__dirname); + }, + function (fileNames) { + return fileNames.map(function (fileName) { + return [fileName, FS.read(fileName)]; + }); + }, + function (files) { + files.forEach(function (pair) { + var fileName = pair[0]; + var file = pair[1]; + console.log(fileName, file.length); + }); + } +); + diff --git a/pool/shard011/JavaScript/0069705_client.prod.js b/pool/shard011/JavaScript/0069705_client.prod.js new file mode 100644 index 0000000000000000000000000000000000000000..6634799de83c157401ad4d93169ca798e793ee54 --- /dev/null +++ b/pool/shard011/JavaScript/0069705_client.prod.js @@ -0,0 +1,28 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; +import { RouterProvider } from 'react-router5'; +import configureStore from '../store/configureStore'; +import { Provider } from 'react-redux'; +import createRouter from '../createRouter'; +import Root from '../Root'; + +/** + * Fire-up Router5. + */ +const reactRoot = window.document.getElementById('app'); +const router = createRouter(); +const store = configureStore(router); + +/** + * Fire-up Router5. + */ +router.start(() => { + ReactDOM.render( + + + + + , + reactRoot + ); +}); diff --git a/pool/shard011/JavaScript/0069708_collection.js b/pool/shard011/JavaScript/0069708_collection.js new file mode 100644 index 0000000000000000000000000000000000000000..8b5247d4c95d457d49aa0c310bd8456413f0bb1a --- /dev/null +++ b/pool/shard011/JavaScript/0069708_collection.js @@ -0,0 +1,181 @@ +/* globals describe, it, before, after */ +"use strict"; + +var _ = require('lodash'); +var should = require("chai").should(); +var Model = require("../../model"); +var Collection = require("../../collection"); +var Mongo = require("../../mongo"); + +// TODO FIX TESTS +describe.skip("Collections", function() { + + // Local variables + var savedId; + + // Before + // Connect to mongodb + + before(function(done) { + var db = new Mongo("mongodb://localhost:27017/test"); + db.connect(); + db.on("connect", function(url) { + Model.prototype.db = db; + Model.prototype.urlRoot = "tests"; + Collection.prototype.db = db; + Collection.prototype.db.eraseCollection("tests"); + done(); + }); + }); + + before(function(done) { + var modelOne = new Model({ + cid: 1, + name: "Pedro Sanchez" + }); + + modelOne.save(null, { + success: function(modelOne, resp, options) { + var modelTwo = new Model({ + cid: 2, + name: "Jack Dagnels" + }); + + modelTwo.save(null, { + success: function(modelTwo, resp, options) { + done(); + } + }); + } + }); + + + + }); + + // Fetch + + it("should fetch", function(done) { + var collection = new Collection(); + collection.fetch({ + success: function(collection, resp, options) { + collection.length.should.equal(2); + (collection.at(0) instanceof Model).should.be.true; + (collection.at(1) instanceof Model).should.be.true; + collection.at(0).get("name").should.equal("Pedro Sanchez"); + collection.at(1).get("name").should.equal("Jack Dagnels"); + + done(); + } + }); + }); + + it("should fetch with promise", function(done) { + var collection = new Collection(); + collection.fetch() + .then(function(resp) { + collection.length.should.equal(2); + (collection.at(0) instanceof Model).should.be.true; + (collection.at(1) instanceof Model).should.be.true; + collection.at(0).get("name").should.equal("Pedro Sanchez"); + collection.at(1).get("name").should.equal("Jack Dagnels"); + done(); + }) + .catch(function(err) { + done(); + }); + }); + + it("should fetch with limit and skip", function(done) { + var collection = new Collection(); + collection.fetch({ + limit: 1, + skip: 1, + success: function(collection, resp, options) { + collection.length.should.equal(1); + (collection.at(0) instanceof Model).should.be.true; + collection.at(0).get("name").should.equal("Jack Dagnels"); + + done(); + } + }); + }); + + it("should fetch with sort desc", function(done) { + var collection = new Collection(); + collection.fetch({ + sort: [ + ["cid", "desc"] + ], + success: function(collection, resp, options) { + collection.length.should.equal(2); + collection.at(0).get("name").should.equal("Jack Dagnels"); + + done(); + } + }); + }); + + it("should fetch with sort asc", function(done) { + var collection = new Collection(); + collection.fetch({ + sort: [ + ["cid", "asc"] + ], + success: function(collection, resp, options) { + collection.length.should.equal(2); + collection.at(0).get("name").should.equal("Pedro Sanchez"); + + done(); + } + }); + }); + + it("should fetch with query and regex", function(done) { + var collection = new Collection(); + collection.fetch({ + query: { + name: /pedro sanchez/i + }, + success: function(collection, resp, options) { + collection.length.should.equal(1); + (collection.at(0) instanceof Model).should.be.true; + + done(); + } + }); + }); + + // Count + + it("should count", function(done) { + var collection = new Collection(); + collection.count({ + success: function(resp) { + resp.should.equal(2); + done(); + } + }); + }); + + it("should count with promise", function(done) { + var collection = new Collection(); + collection.count() + .then(function(resp) { + resp.should.equal(2); + done(); + }) + .catch(function(err) { + done(); + }); + }); + + + + // After + + after(function(done) { + done(); + }); + +}); diff --git a/pool/shard011/JavaScript/0069711_playergetter.js b/pool/shard011/JavaScript/0069711_playergetter.js new file mode 100644 index 0000000000000000000000000000000000000000..1e675ddb04f089852fe4a7a5d6b9ef5cdbeb0987 --- /dev/null +++ b/pool/shard011/JavaScript/0069711_playergetter.js @@ -0,0 +1,20 @@ +// public/js/controllers/playergetter.js +angular.module('playerGetModule', ['playerFightService']).controller('playerGetController', function($scope, $http, $location, playerFightData) + { + + $scope.players; + $scope.status; + $scope.tagline = "This line generated by playergetter.js. In this page you select a player, and it matches them up against a random player from the database. It adds up their stats (Luck, Macro, etc) and compares the sum to the other player and selects the winner or declare a tie based on the higher sum."; + + $http.get('playerfetcher') + .success(function (response) { $scope.players = response; }) + .error(function (error) { $scope.status = 'Unable to retrieve player data: ' + error.message; }); + + $scope.playerSelect = function(selectedPlayer) + { + // alert("Selected player is " + selectedPlayer); + // playerFightData.setVar(selectedPlayer); + playerFightData.setProperty(selectedPlayer); + $location.path("/playerfight") + }; + }); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069712_FunctionProvider.js b/pool/shard011/JavaScript/0069712_FunctionProvider.js new file mode 100644 index 0000000000000000000000000000000000000000..6e7d0374783886f74f9c17f1535ae8d366a8e1d1 --- /dev/null +++ b/pool/shard011/JavaScript/0069712_FunctionProvider.js @@ -0,0 +1,28 @@ +goog.provide('slieb.injector.providers.FunctionProvider'); +goog.require('goog.Disposable'); +goog.require('slieb.injector.Provider'); + +/** + * @constructor + * @extends {goog.Disposable} + * @implements slieb.injector.Provider + * @template T + * + * @param {slieb.injector.Injector} injector + * @param {function():T|function(slieb.injector.Injector):T} method + */ +slieb.injector.providers.FunctionProvider = function(injector, method) { + slieb.injector.providers.FunctionProvider.base(this, 'constructor'); + this.injector = injector; + this.method = method; +}; +goog.inherits(slieb.injector.providers.FunctionProvider, goog.Disposable); + + +/** + * @override + * @return {T} + */ +slieb.injector.providers.FunctionProvider.prototype.get = function() { + return this.method.call(undefined, this.injector); +}; diff --git a/pool/shard011/JavaScript/0069715_left-nav.js b/pool/shard011/JavaScript/0069715_left-nav.js new file mode 100644 index 0000000000000000000000000000000000000000..f1f6f330ca46d95b7e75336b914b4c99f5509ace --- /dev/null +++ b/pool/shard011/JavaScript/0069715_left-nav.js @@ -0,0 +1,12 @@ +//左导航栏 + $(function(){ + var curindex=0; + $('.sec_attr li').filter('.list').hover(function(){ + curindex = $(this).index(); + $(this).addClass('active'); + $('.sec_attr .nav_list').fadeOut(0).eq(curindex).fadeIn(0); + },function(){ + $('.sec_attr .nav_list').fadeOut(0); + $(this).removeClass('active'); + }); + }); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069717_baseEditor.js b/pool/shard011/JavaScript/0069717_baseEditor.js new file mode 100644 index 0000000000000000000000000000000000000000..fe29dd92ca9d5dcbb6b722fc94dac99baef217e1 --- /dev/null +++ b/pool/shard011/JavaScript/0069717_baseEditor.js @@ -0,0 +1,268 @@ +import Handsontable from './../browser'; +import {stringify} from './../helpers/mixed'; +import {WalkontableCellCoords} from './../3rdparty/walkontable/src/cell/coords'; + +export {BaseEditor}; + +Handsontable.editors = Handsontable.editors || {}; +Handsontable.editors.BaseEditor = BaseEditor; + +Handsontable.EditorState = { + VIRGIN: 'STATE_VIRGIN', //before editing + EDITING: 'STATE_EDITING', + WAITING: 'STATE_WAITING', //waiting for async validation + FINISHED: 'STATE_FINISHED' +}; + +function BaseEditor(instance) { + this.instance = instance; + this.state = Handsontable.EditorState.VIRGIN; + + this._opened = false; + this._fullEditMode = false; + this._closeCallback = null; + + this.init(); +} + +BaseEditor.prototype._fireCallbacks = function(result) { + if (this._closeCallback) { + this._closeCallback(result); + this._closeCallback = null; + } +}; + +BaseEditor.prototype.init = function() {}; + +BaseEditor.prototype.getValue = function() { + throw Error('Editor getValue() method unimplemented'); +}; + +BaseEditor.prototype.setValue = function(newValue) { + throw Error('Editor setValue() method unimplemented'); +}; + +BaseEditor.prototype.open = function() { + throw Error('Editor open() method unimplemented'); +}; + +BaseEditor.prototype.close = function() { + throw Error('Editor close() method unimplemented'); +}; + +BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties) { + this.TD = td; + this.row = row; + this.col = col; + this.prop = prop; + this.originalValue = originalValue; + this.cellProperties = cellProperties; + + if (this.instance.view.isMouseDown() && document.activeElement && document.activeElement !== document.body) { + document.activeElement.blur(); + } else if (!document.activeElement) { //IE + document.body.focus(); + } + + this.state = Handsontable.EditorState.VIRGIN; +}; + +BaseEditor.prototype.extend = function() { + var baseClass = this.constructor; + + function Editor() { + baseClass.apply(this, arguments); + } + + function inherit(Child, Parent) { + function Bridge() {} + Bridge.prototype = Parent.prototype; + Child.prototype = new Bridge(); + Child.prototype.constructor = Child; + + return Child; + } + + return inherit(Editor, baseClass); +}; + +BaseEditor.prototype.saveValue = function(val, ctrlDown) { + var sel, tmp; + + // if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) + if (ctrlDown) { + sel = this.instance.getSelected(); + + if (sel[0] > sel[2]) { + tmp = sel[0]; + sel[0] = sel[2]; + sel[2] = tmp; + } + if (sel[1] > sel[3]) { + tmp = sel[1]; + sel[1] = sel[3]; + sel[3] = tmp; + } + + this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit'); + } else { + this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit'); + } +}; + +BaseEditor.prototype.beginEditing = function(initialValue, event) { + if (this.state != Handsontable.EditorState.VIRGIN) { + return; + } + this.instance.view.scrollViewport(new WalkontableCellCoords(this.row, this.col)); + this.instance.view.render(); + this.state = Handsontable.EditorState.EDITING; + + initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue; + this.setValue(stringify(initialValue)); + + this.open(event); + this._opened = true; + this.focus(); + + // only rerender the selections (FillHandle should disappear when beginediting is triggered) + this.instance.view.render(); +}; + +BaseEditor.prototype.finishEditing = function(restoreOriginalValue, ctrlDown, callback) { + var _this = this, + val; + + if (callback) { + var previousCloseCallback = this._closeCallback; + + this._closeCallback = function(result) { + if (previousCloseCallback) { + previousCloseCallback(result); + } + callback(result); + }; + } + + if (this.isWaiting()) { + return; + } + + if (this.state == Handsontable.EditorState.VIRGIN) { + this.instance._registerTimeout(setTimeout(function() { + _this._fireCallbacks(true); + }, 0)); + + return; + } + + if (this.state == Handsontable.EditorState.EDITING) { + if (restoreOriginalValue) { + this.cancelChanges(); + this.instance.view.render(); + + return; + } + + let value = this.getValue(); + + if (this.instance.getSettings().trimWhitespace) { + // We trim only string values + val = [ + [typeof value === 'string' ? String.prototype.trim.call(value || '') : value] + ]; + } else { + val = [ + [value] + ]; + } + + this.state = Handsontable.EditorState.WAITING; + this.saveValue(val, ctrlDown); + + if (this.instance.getCellValidator(this.cellProperties)) { + this.instance.addHookOnce('postAfterValidate', function(result) { + _this.state = Handsontable.EditorState.FINISHED; + _this.discardEditor(result); + }); + } else { + this.state = Handsontable.EditorState.FINISHED; + this.discardEditor(true); + } + } +}; + +BaseEditor.prototype.cancelChanges = function() { + this.state = Handsontable.EditorState.FINISHED; + this.discardEditor(); +}; + +BaseEditor.prototype.discardEditor = function(result) { + if (this.state !== Handsontable.EditorState.FINISHED) { + return; + } + // validator was defined and failed + if (result === false && this.cellProperties.allowInvalid !== true) { + this.instance.selectCell(this.row, this.col); + this.focus(); + this.state = Handsontable.EditorState.EDITING; + this._fireCallbacks(false); + + } else { + this.close(); + this._opened = false; + this._fullEditMode = false; + this.state = Handsontable.EditorState.VIRGIN; + this._fireCallbacks(true); + } +}; + +/** + * Switch editor into full edit mode. In this state navigation keys don't close editor. This mode is activated + * automatically after hit ENTER or F2 key on the cell or while editing cell press F2 key. + */ +BaseEditor.prototype.enableFullEditMode = function() { + this._fullEditMode = true; +}; + +/** + * Checks if editor is in full edit mode. + * + * @returns {Boolean} + */ +BaseEditor.prototype.isInFullEditMode = function() { + return this._fullEditMode; +}; + +BaseEditor.prototype.isOpened = function() { + return this._opened; +}; + +BaseEditor.prototype.isWaiting = function() { + return this.state === Handsontable.EditorState.WAITING; +}; + +BaseEditor.prototype.checkEditorSection = function() { + var totalRows = this.instance.countRows(); + var section = ''; + + if (this.row < this.instance.getSettings().fixedRowsTop) { + if (this.col < this.instance.getSettings().fixedColumnsLeft) { + section = 'top-left-corner'; + } else { + section = 'top'; + } + } else if (this.instance.getSettings().fixedRowsBottom && this.row >= totalRows - this.instance.getSettings().fixedRowsBottom) { + if (this.col < this.instance.getSettings().fixedColumnsLeft) { + section = 'bottom-left-corner'; + } else { + section = 'bottom'; + } + } else { + if (this.col < this.instance.getSettings().fixedColumnsLeft) { + section = 'left'; + } + } + + return section; +}; diff --git a/pool/shard011/JavaScript/0069721_leaflet-legend.js b/pool/shard011/JavaScript/0069721_leaflet-legend.js new file mode 100644 index 0000000000000000000000000000000000000000..3ce0d9e37f59388145007d8884882420f9223998 --- /dev/null +++ b/pool/shard011/JavaScript/0069721_leaflet-legend.js @@ -0,0 +1,98 @@ +/** + * Created by meyerjd on 8/5/2014. + */ + +L.Control.LegendToggle = L.Control.extend({ + options: { + position: 'topright' + }, + + _currentLegends: [], + _legendControl: undefined, + _legendEnabled: true, + + + _toggleClass: function(el, name) { + 'use strict'; + + if (L.DomUtil.hasClass(el, name)) { + L.DomUtil.removeClass(el, name); + } else { + L.DomUtil.addClass(el, name); + } + }, + + _toggleLegend: function (e) { + 'use strict'; + + L.DomEvent.stopPropagation(e); + L.DomEvent.preventDefault(e); + + this._legendEnabled = !this._legendEnabled; + this._toggleClass(e.currentTarget, 'leaflet-control-legend-toggle-active'); + + this.updateLegend(); + }, + + updateLegend: function(layers) { + 'use strict'; + + var self = this; + if (layers) { + this._currentLegends = layers; + } + + + if (this._map && this._legendControl) { + this._map.removeControl(this._legendControl); + } + + if (this._legendEnabled) { + if (!this._legendControl) { + this._legendControl = L.control({position: 'bottomright'}); + } + + this._legendControl.onAdd = function () { + var div = L.DomUtil.create('div', 'leaflet-control-legend'); + + div.innerHTML += 'Layer Legend
    '; + + if (self._currentLegends.length > 0) { + angular.forEach(self._currentLegends, function (legend) { + + div.innerHTML += 'legend
    '; + }); + } else { + div.innerHTML += 'No selected layers'; + } + + return div; + }; + + if (this._map) { + this._legendControl.addTo(this._map); + } + } + else { + this._legendControl = undefined; + } + }, + + onAdd: function (map) { + 'use strict'; + + this._map = map; + var controlDiv = L.DomUtil.create('div', 'leaflet-control-legend-toggle leaflet-control-legend-toggle-active'); + controlDiv.setAttribute('title','Toggle Layer Legend'); + L.DomEvent.on(controlDiv, 'click', this._toggleLegend, this); + return controlDiv; + }, + + updateLayers: this.updateLegend +}); + +L.control.layerLegend = function (options) { + 'use strict'; + + return new L.Control.LegendToggle(options); +}; diff --git a/pool/shard011/JavaScript/0069726_karma.conf.js b/pool/shard011/JavaScript/0069726_karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..55a935f49e5b202d80923b6ba6ff88dfed51a620 --- /dev/null +++ b/pool/shard011/JavaScript/0069726_karma.conf.js @@ -0,0 +1,52 @@ +'use strict'; + +/** + * Module dependencies. + */ +var applicationConfiguration = require('./config/config'); + +// Karma configuration +module.exports = function(config) { + config.set({ + // Frameworks to use + frameworks: ['jasmine'], + + // List of files / patterns to load in the browser + files: applicationConfiguration.assets.lib.js.concat(applicationConfiguration.assets.js, applicationConfiguration.assets.tests), + + // Test results reporter to use + // Possible values: 'dots', 'progress', 'junit', 'growl', 'coverage' + //reporters: ['progress'], + reporters: ['progress'], + + // Web server port + port: 9876, + + // Enable / disable colors in the output (reporters and logs) + colors: true, + + // Level of logging + // Possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + // Enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + // Start these browsers, currently available: + // - Chrome + // - ChromeCanary + // - Firefox + // - Opera + // - Safari (only Mac) + // - PhantomJS + // - IE (only Windows) + browsers: ['PhantomJS', 'Chrome'], + + // If browser does not capture in given timeout [ms], kill it + captureTimeout: 60000, + + // Continuous Integration mode + // If true, it capture browsers, run tests and exit + singleRun: true + }); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069729_child-process-wrapper.js b/pool/shard011/JavaScript/0069729_child-process-wrapper.js new file mode 100644 index 0000000000000000000000000000000000000000..55e6733d1802480d34b25528166d86431943b5b1 --- /dev/null +++ b/pool/shard011/JavaScript/0069729_child-process-wrapper.js @@ -0,0 +1,46 @@ +var childProcess = require('child_process'); + +// Exit the process if the command failed and only call the callback if the +// command succeed, output of the command would also be piped. +exports.safeExec = function(command, options, callback) { + if (!callback) { + callback = options; + options = {}; + } + if (!options) + options = {}; + + // This needed to be increased for `apm test` runs that generate many failures + // The default is 200KB. + options.maxBuffer = 1024 * 1024; + + var child = childProcess.exec(command, options, function(error, stdout, stderr) { + if (error) + process.exit(error.code || 1); + else if (callback) + callback(null); + }); + child.stderr.pipe(process.stderr); + if (!options.ignoreStdout) + child.stdout.pipe(process.stdout); +} + +// Same with safeExec but call child_process.spawn instead. +exports.safeSpawn = function(command, args, options, callback) { + if (!callback) { + callback = options; + options = {}; + } + var child = childProcess.spawn(command, args, options); + child.stderr.pipe(process.stderr); + child.stdout.pipe(process.stdout); + child.on('error', function(error) { + console.error('Command \'' + command + '\' failed: ' + error.message); + }); + child.on('exit', function(code) { + if (code != 0) + process.exit(code); + else + callback(null); + }); +} diff --git a/pool/shard011/JavaScript/0069735_configurable_report.js b/pool/shard011/JavaScript/0069735_configurable_report.js new file mode 100644 index 0000000000000000000000000000000000000000..05de55303ff4d420320e03015f3310a1aa29d8d6 --- /dev/null +++ b/pool/shard011/JavaScript/0069735_configurable_report.js @@ -0,0 +1,111 @@ +hqDefine("userreports/js/configurable_report", function () { + var initial_page_data = hqImport("hqwebapp/js/initial_page_data").get; + + if (typeof define === 'function' && define.amd || window.USE_REQUIREJS) { + throw new Error("This part of UCR is not yet migrated to RequireJS. Update the UCR logic in reports/js/standard_hq_report before removing this error."); + } + + var getStandardHQReport = function (isFirstLoad) { + if (!initial_page_data("standardHQReport")) { + return undefined; + } + + var $editReportButton = $("#edit-report-link"); + + if (initial_page_data("created_by_builder") && !isFirstLoad) { + var $applyFiltersButton = $("#apply-filters"), + builder_type = initial_page_data("builder_report_type"), + report_type = initial_page_data("type"); + $applyFiltersButton.click(function () { + var label = hqImport('hqwebapp/js/main').capitalize(builder_type) + '-' + hqImport('hqwebapp/js/main').capitalize(report_type); + hqImport('userreports/js/report_analytix').track.event("View Report Builder Report", label); + }); + hqImport('userreports/js/report_analytix').track.event("Loaded Report Builder Report"); + $editReportButton.click(function () { + hqImport('analytix/js/kissmetrix').track.event("RBv2 - Click Edit Report"); + }); + } + + _.each(initial_page_data("report_builder_events"), function (e) { + hqImport('userreports/js/report_analytix').track.event.apply(this, e); + }); + + var urlSerialize = hqImport('reports/js/reports.util').urlSerialize; + var reportOptions = { + domain: initial_page_data('domain'), + urlRoot: initial_page_data('url_root'), + slug: initial_page_data('slug'), + subReportSlug: initial_page_data('sub_slug'), + type: initial_page_data('type'), + filterSet: initial_page_data('filter_set'), + needsFilters: initial_page_data('needs_filters'), + isExportable: initial_page_data('is_exportable'), + isExportAll: initial_page_data('is_export_all'), + isEmailable: initial_page_data('is_emailable'), + emailDefaultSubject: initial_page_data('title'), + emailSuccessMessage: gettext('Report successfully emailed'), + emailErrorMessage: gettext('An error occurred emailing you report. Please try again.'), + getReportRenderUrl: function (renderType) { + var params = urlSerialize($('#paramSelectorForm'), ['format']); + return window.location.pathname + "?format=" + renderType + "&" + params; + }, + }; + if (initial_page_data('startdate')) { + reportOptions.datespan = { + startdate: initial_page_data('startdate'), + enddate: initial_page_data('enddate'), + }; + } + var standardHQReport = hqImport("reports/js/hq_report").hqReport(reportOptions); + standardHQReport.init(); + return standardHQReport; + }; + + $(function () { + getStandardHQReport(true); + + // Bind the ReportConfigsViewModel to the save button. + var defaultConfig = initial_page_data("default_config"); + if (initial_page_data("has_datespan")) { + if (!defaultConfig.date_range) { + defaultConfig.date_range = 'last7'; + } + defaultConfig.has_ucr_datespan = true; + defaultConfig.datespan_filters = initial_page_data("datespan_filters"); + } else { + defaultConfig.date_range = null; + defaultConfig.has_ucr_datespan = false; + defaultConfig.datespan_filters = []; + } + if (!defaultConfig.datespan_slug) { + defaultConfig.datespan_slug = null; + } + + var reportConfigModels = hqImport("reports/js/report_config_models"), + reportConfigsView = reportConfigModels.reportConfigsViewModel({ + filterForm: $("#paramSelectorForm"), + items: initial_page_data("report_configs"), + defaultItem: defaultConfig, + saveUrl: hqImport("hqwebapp/js/initial_page_data").reverse("add_report_config"), + }); + $("#savedReports").koApplyBindings(reportConfigsView); + reportConfigsView.setUserConfigurableConfigBeingViewed(reportConfigModels.reportConfig(defaultConfig)); + + $('#email-enabled').tooltip({ + placement: 'right', + html: true, + title: gettext("You can email a saved version
    of this report."), + }); + + if (initial_page_data("created_by_builder")) { + hqImport('userreports/js/report_analytix').track.event( + initial_page_data("builder_report_type"), + 'Load a report that was built in report builder' + ); + } + }); + + return { + getStandardHQReport: getStandardHQReport, + }; +}); diff --git a/pool/shard011/JavaScript/0069736_index.js b/pool/shard011/JavaScript/0069736_index.js new file mode 100644 index 0000000000000000000000000000000000000000..a01e74edabc44344e8035954bb1d1695ff543f3b --- /dev/null +++ b/pool/shard011/JavaScript/0069736_index.js @@ -0,0 +1,47 @@ +/** + * shuji (周氏) + * https://github.com/paazmaya/shuji + * + * Reverse engineering JavaScript and CSS sources from sourcemaps + * + * Copyright (c) Juga Paazmaya (https://paazmaya.fi) + * Licensed under the MIT license + */ + +const readSources = require('./lib/read-sources'), + findMap = require('./lib/find-map'); + +/** + * @param {string} inputFilepath Contents of the sourceMap file + * @param {object} options Options object + * @param {boolean} options.verbose Shall there be more output + * @param {boolean} options.preserve Preserve original folder structure + * + * @returns {Array} Source contents mapped to file names + */ +const handleInput = async (inputFilepath, options) => { + if (options.verbose) { + console.log(`Processing file "${inputFilepath}"`); + } + + const input = findMap(inputFilepath); + + const output = await readSources(input, { + verbose: typeof options.verbose === 'boolean' ? + options.verbose : + false, + preserve: typeof options.preserve === 'boolean' ? + options.preserve : + false + }); + + const sourceFiles = Object.entries(output); + + if (!sourceFiles.length) { + console.error(`Could not get any sources for "${inputFilepath}"`); + } + + return sourceFiles; +}; + +module.exports = handleInput; diff --git a/pool/shard011/JavaScript/0069737_StageTopScore.js b/pool/shard011/JavaScript/0069737_StageTopScore.js new file mode 100644 index 0000000000000000000000000000000000000000..92db4a02157b381ef1d6105d7a2236267b570d32 --- /dev/null +++ b/pool/shard011/JavaScript/0069737_StageTopScore.js @@ -0,0 +1,106 @@ +import KeyListener from '../common/KeyListener'; + +export default class StageTopScore extends PIXI.Container { + + constructor(stages, topScore, settings) { + super(); + + this.stages = stages; + this.topScore = topScore; + this.settings = settings; + + this.myScore = -1; + } + + addScore(score) { + this.topScore.addScore(score); + this.myScore = this.topScore.getTop(StageTopScore.TOP_COUNT).indexOf(score); + } + + load() { + this.background = new PIXI.Graphics(); + this.background.cacheAsBitmap = true; + this.background.beginFill(StageTopScore.BACKGROUND_COLOR); + this.background.drawRect(0, 0, this.settings.width, this.settings.height); + + this.scores = new PIXI.Container(); + var i = 0; + this.topScore.getTop(StageTopScore.TOP_COUNT).forEach(score => { + + var x = i % 10; + var y = Math.floor(i / 10); + + var color = '#E1303C'; + if(this.myScore === i) { + color = '#9FBC12'; + } + + var scoreText = new PIXI.Text(score, new PIXI.TextStyle({fontSize: 14, fill: color})); + scoreText.x = (x+1) * (this.settings.width / (10 + 1)); + scoreText.y = (y+1) * (this.settings.height / (5 + 1)); + scoreText.anchor.x = 0.5; + scoreText.anchor.y = 0.5; + + this.scores.addChild(scoreText); + i++; + }); + + this.crashedTextGuide = new PIXI.Text("Press space to continue", new PIXI.TextStyle({fontSize: 14, fill: '#9FBC12'})); + this.crashedTextGuide.x = this.settings.width / 2; + this.crashedTextGuide.y = this.settings.height - 16; + this.crashedTextGuide.anchor.x = 0.5; + this.crashedTextGuide.anchor.y = 1; + + this.gameByText = new PIXI.Text("Game by Ienze (Dominik Gmiterko)", new PIXI.TextStyle({fontSize: 10, fill: '#9FBC12'})); + this.gameByText.x = 16; + this.gameByText.y = this.settings.height - 16; + this.gameByText.anchor.x = 0.0; + this.gameByText.anchor.y = 1.0; + this.gameByText.interactive = true; + this.gameByText.click = () => { + var win = window.open("http://ienze.me", '_blank'); + win.focus(); + } + + this.gameAtText = new PIXI.Text("play at ienze.me/trainwreck", new PIXI.TextStyle({fontSize: 10, fill: '#9FBC12'})); + this.gameAtText.x = this.settings.width - 16; + this.gameAtText.y = this.settings.height - 16; + this.gameAtText.anchor.x = 1.0; + this.gameAtText.anchor.y = 1.0; + + this.addChild(this.background); + this.addChild(this.scores); + this.addChild(this.crashedTextGuide); + this.addChild(this.gameByText); + this.addChild(this.gameAtText); + + this.keySpace = new KeyListener(32); + } + + tick() { + if(this.keySpace.isDown) { + this.stages.changeStage("play"); + } + } + + unload() { + this.removeChild(this.background); + this.removeChild(this.scores); + this.removeChild(this.crashedTextGuide); + this.removeChild(this.gameByText); + this.removeChild(this.gameAtText); + + this.keySpace.close(); + + this.keySpace = undefined; + + this.background = undefined; + this.scores = undefined; + this.crashedTextGuide = undefined; + this.gameByText = undefined; + this.gameAtText = undefined; + } +} + +StageTopScore.BACKGROUND_COLOR = 0xFFFFFF; +StageTopScore.TOP_COUNT = 40; diff --git a/pool/shard011/JavaScript/0069738_index.js b/pool/shard011/JavaScript/0069738_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d0adebbf16b5b6c99703442151ecd70c8fa4a4b0 --- /dev/null +++ b/pool/shard011/JavaScript/0069738_index.js @@ -0,0 +1,31 @@ +var app = require('express')(); +var server = require('http').Server(app); +var io = require('socket.io')(server); +var players = []; + +server.listen(8080, function(){ + console.log("Server is now running..."); +}); + +io.on('connection', function(socket){ + console.log("Player Connected!"); + socket.emit('socketID', { id: socket.id }); + socket.emit('getPlayers', players); + socket.broadcast.emit('newPlayer', { id: socket.id }); + socket.on('disconnect', function(){ + console.log("Player Disconnected"); + socket.broadcast.emit('playerDisconnected', { id: socket.id }); + for(var i = 0; i < players.length; i++){ + if(players[i].id == socket.id){ + players.splice(i, 1); + } + } + }); + players.push(new player(socket.id, 0, 0)); +}); + +function player(id, x, y){ + this.id = id; + this.x = x; + this.y = y; +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069739_generateDungeon.js b/pool/shard011/JavaScript/0069739_generateDungeon.js new file mode 100644 index 0000000000000000000000000000000000000000..1b0c3b122a62cc13ef755f24da2f64abf1f74a45 --- /dev/null +++ b/pool/shard011/JavaScript/0069739_generateDungeon.js @@ -0,0 +1,49 @@ +import {createDungeon} from './emptyDungeon' +import thingsToDungeon from './thingsToDungeon' + +const addHp = (hp, obj) => Object.assign({hp, originalHP: hp}, obj) +const addAttack = (attack, obj) => Object.assign({attack}, obj) + +export default function(size, nrrooms, nrtunnels, nrenemies, nrpotions, nrweapons, maplevel=1, nrexit=1, nrboss=0) { + const weaponList = [ + {level: 1, name: 'dagger', attack: 10}, + {level: 1, name: 'axe', attack: 14}, + {level: 1, name: 'sword', attack: 18}, + {level: 2, name: 'pistol', attack: 22}, + {level: 2, name: 'rifle', attack: 26}, + {level: 2, name: 'shotgun', attack: 30}, + {level: 3, name: 'machinegun', attack: 34}, + {level: 3, name: 'hand granade', attack: 38}, + {level: 3, name: 'bazooka', attack: 42}, + {level: 4, name: 'laser gun', attack: 46}, + {level: 4, name: 'plasma gun', attack: 50}, + {level: 4, name: 'antimatter gun', attack: 54} + ].filter(w => w.level === maplevel) + + const enemyHP = [0, 45, 75, 110, 150] + + const emptyDungeon = createDungeon(size, nrrooms, nrtunnels) + const enemyMap = thingsToDungeon(emptyDungeon, 3, nrenemies) + const potionMap = thingsToDungeon(enemyMap.dungeon, 4, nrpotions) + const weaponMap = thingsToDungeon(potionMap.dungeon, 8, nrweapons) + const player = thingsToDungeon(weaponMap.dungeon, 5, 1) + const exit = thingsToDungeon(player.dungeon, 6, nrexit) + const bossMap = thingsToDungeon(exit.dungeon, 7, nrboss) + + const enemies_hp = enemyMap.list.map(addHp.bind(this, enemyHP[maplevel])) + const enemies = enemies_hp.map(addAttack.bind(this, 5+6*maplevel)) + const potions = potionMap.list.map(addHp.bind(this, 10+10*maplevel)) + const weapons = weaponMap.list.map((obj, i) => Object.assign(weaponList[i], obj)) + const boss_hp = bossMap.list.map(addHp.bind(this, 600)) + const boss = boss_hp.map(addAttack.bind(this, 50)) + + return { + dungeon: emptyDungeon, + enemies, + potions, + weapons, + playerPosition: player.list[0], + exitPosition: exit.list[0], + boss: boss[0] + } +} diff --git a/pool/shard011/JavaScript/0069742_schedule-cron-jobs.js b/pool/shard011/JavaScript/0069742_schedule-cron-jobs.js new file mode 100644 index 0000000000000000000000000000000000000000..1b52056b43e0fd9d259374be6cb7cf19a04fa217 --- /dev/null +++ b/pool/shard011/JavaScript/0069742_schedule-cron-jobs.js @@ -0,0 +1,141 @@ +'use strict'; + +const test = require('tape'); +const sinon = require('sinon'); +const schedule = require('..'); +const { runAtDate } = require('./utils/timerUtils') + +test(".scheduleJob(cron_expr, fn)", function (t) { + let clock + t.test("Setup", function (t) { + clock = sinon.useFakeTimers() + t.end() + }) + + t.test("Runs job every second", function (t) { + t.plan(3); + + const timeout = 3 * 1000 + 150; + + const job = schedule.scheduleJob('* * * * * *', function () { + t.ok(true); + }); + + setTimeout(function () { + job.cancel(); + t.end(); + }, timeout); + + clock.tick(timeout); + }) + + t.test("Runs job every minute", function (t) { + t.plan(3); + + const timeout = 3 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 * * * * *', function () { + t.ok(true); + }); + + setTimeout(function () { + job.cancel(); + t.end(); + }, timeout); + + clock.tick(timeout); + }) + + t.test("Runs job every hour", function (t) { + t.plan(3); + + const timeout = 3 * 60 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 0 * * * *', function () { + t.ok(true); + }); + + setTimeout(function () { + job.cancel(); + t.end(); + }, timeout); + + clock.tick(timeout); + }) + + t.test("Runs job every day", function (t) { + t.plan(3); + + const timeout = 3 * 24 * 60 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 0 0 * * *', function () { + t.ok(true); + }); + + setTimeout(function () { + job.cancel(); + t.end(); + }, timeout); + + clock.tick(timeout); + }) + + t.test("Runs job every week", function (t) { + t.plan(3); + + const timeout = 3 * 7 * 24 * 60 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 0 0 * * 1', function () { + t.ok(true); + }); + + setTimeout(function () { + job.cancel(); + t.end(); + }, timeout); + + clock.tick(timeout); + }) + + t.test("Runs job every month", function (t) { + t.plan(48); + const clock = sinon.useFakeTimers() + + const timeout = 4 * 365.25 * 24 * 60 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 0 0 1 * *', function () { + t.ok(true); + }); + + runAtDate(new Date(timeout), function () { + job.cancel(); + t.end(); + }) + + clock.tick(timeout); + }) + + t.test("Runs job every year", function (t) { + t.plan(4); + const clock = sinon.useFakeTimers() + + const timeout = 4 * 365.25 * 24 * 60 * 60 * 1000 + 150; + + const job = schedule.scheduleJob('0 0 0 1 1 *', function () { + t.ok(true); + }); + + runAtDate(new Date(timeout), function () { + job.cancel(); + t.end(); + }) + + clock.tick(timeout); + }) + + t.test("Restore", function (t) { + clock.restore(); + t.end() + }) +}) + diff --git a/pool/shard011/JavaScript/0069743_systemRouter.js b/pool/shard011/JavaScript/0069743_systemRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..01186f78304129454e2d266cf63eb8233b935fc4 --- /dev/null +++ b/pool/shard011/JavaScript/0069743_systemRouter.js @@ -0,0 +1,21 @@ +/** + * @file hiproxy system router + * @author zdying + */ +'use strict'; + +var routers = require('../../routers'); + +module.exports = function (ctx, next) { + var req = ctx.req; + var res = ctx.res; + var url = req.url.split('?')[0]; + var render = routers.getRender(url); + var hiproxy = this; + + if (render) { + render.call(hiproxy, req, res); + } else { + next(); + } +}; diff --git a/pool/shard011/JavaScript/0069746_shareSpec.js b/pool/shard011/JavaScript/0069746_shareSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..5c76ea600b8188a800711b48b6f00fcecd624f80 --- /dev/null +++ b/pool/shard011/JavaScript/0069746_shareSpec.js @@ -0,0 +1,243 @@ +/** +* ownCloud +* +* @author Vincent Petry +* @copyright 2014 Vincent Petry +* +* This library is free software; you can redistribute it and/or +* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE +* License as published by the Free Software Foundation; either +* version 3 of the License, or 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 AFFERO GENERAL PUBLIC LICENSE for more details. +* +* You should have received a copy of the GNU Affero General Public +* License along with this library. If not, see . +* +*/ + +/* global oc_appconfig */ +describe('OC.Share tests', function() { + describe('markFileAsShared', function() { + var $file; + var tipsyStub; + + beforeEach(function() { + tipsyStub = sinon.stub($.fn, 'tipsy'); + $file = $('
    File name'); + $file.find('.filename').append( + '' + + '' + + ' Share' + + '' + + '' + ); + }); + afterEach(function() { + $file = null; + tipsyStub.restore(); + }); + describe('displaying the share owner', function() { + function checkOwner(input, output, title) { + var $action; + + $file.attr('data-share-owner', input); + OC.Share.markFileAsShared($file); + + $action = $file.find('.action-share>span'); + expect($action.text().trim()).toEqual(output); + if (_.isString(title)) { + expect($action.find('.remoteAddress').attr('title')).toEqual(title); + } else { + expect($action.find('.remoteAddress').attr('title')).not.toBeDefined(); + } + expect(tipsyStub.calledOnce).toEqual(true); + tipsyStub.reset(); + } + + it('displays the local share owner as is', function() { + checkOwner('User One', 'User One', null); + }); + it('displays the user name part of a remote share owner', function() { + checkOwner( + 'User One@someserver.com', + 'User One@…', + 'User One@someserver.com' + ); + checkOwner( + 'User One@someserver.com/', + 'User One@…', + 'User One@someserver.com' + ); + checkOwner( + 'User One@someserver.com/root/of/owncloud', + 'User One@…', + 'User One@someserver.com' + ); + }); + it('displays the user name part with domain of a remote share owner', function() { + checkOwner( + 'User One@example.com@someserver.com', + 'User One@example.com', + 'User One@example.com@someserver.com' + ); + checkOwner( + 'User One@example.com@someserver.com/', + 'User One@example.com', + 'User One@example.com@someserver.com' + ); + checkOwner( + 'User One@example.com@someserver.com/root/of/owncloud', + 'User One@example.com', + 'User One@example.com@someserver.com' + ); + }); + }); + + describe('displaying the folder icon', function() { + function checkIcon(expectedImage) { + var imageUrl = OC.TestUtil.getImageUrl($file.find('.filename .thumbnail')); + expectedIcon = OC.imagePath('core', expectedImage); + expect(imageUrl).toEqual(expectedIcon); + } + + it('shows a plain folder icon for non-shared folders', function() { + $file.attr('data-type', 'dir'); + OC.Share.markFileAsShared($file); + + checkIcon('filetypes/folder'); + }); + it('shows a shared folder icon for folders shared with another user', function() { + $file.attr('data-type', 'dir'); + OC.Share.markFileAsShared($file, true); + + checkIcon('filetypes/folder-shared'); + }); + it('shows a shared folder icon for folders shared with the current user', function() { + $file.attr('data-type', 'dir'); + $file.attr('data-share-owner', 'someoneelse'); + OC.Share.markFileAsShared($file); + + checkIcon('filetypes/folder-shared'); + }); + it('shows a link folder icon for folders shared with link', function() { + $file.attr('data-type', 'dir'); + OC.Share.markFileAsShared($file, false, true); + + checkIcon('filetypes/folder-public'); + }); + it('shows a link folder icon for folders shared with both link and another user', function() { + $file.attr('data-type', 'dir'); + OC.Share.markFileAsShared($file, true, true); + + checkIcon('filetypes/folder-public'); + }); + it('shows a link folder icon for folders reshared with link', function() { + $file.attr('data-type', 'dir'); + $file.attr('data-share-owner', 'someoneelse'); + OC.Share.markFileAsShared($file, false, true); + + checkIcon('filetypes/folder-public'); + }); + it('shows external storage icon if external mount point', function() { + $file.attr('data-type', 'dir'); + $file.attr('data-mountType', 'external'); + OC.Share.markFileAsShared($file, false, false); + + checkIcon('filetypes/folder-external'); + }); + }); + + describe('displaying the recipoients', function() { + function checkRecipients(input, output, title) { + var $action; + + $file.attr('data-share-recipients', input); + OC.Share.markFileAsShared($file, true); + + $action = $file.find('.action-share>span'); + expect($action.text().trim()).toEqual(output); + if (_.isString(title)) { + expect($action.find('.remoteAddress').attr('title')).toEqual(title); + } else if (_.isArray(title)) { + var tooltips = $action.find('.remoteAddress'); + expect(tooltips.length).toEqual(title.length); + + tooltips.each(function(i) { + expect($(this).attr('title')).toEqual(title[i]); + }); + } else { + expect($action.find('.remoteAddress').attr('title')).not.toBeDefined(); + } + expect(tipsyStub.calledOnce).toEqual(true); + tipsyStub.reset(); + } + + it('displays the local share owner as is', function() { + checkRecipients('User One', 'Shared with User One', null); + }); + it('displays the user name part of a remote recipient', function() { + checkRecipients( + 'User One@someserver.com', + 'Shared with User One@…', + 'User One@someserver.com' + ); + checkRecipients( + 'User One@someserver.com/', + 'Shared with User One@…', + 'User One@someserver.com' + ); + checkRecipients( + 'User One@someserver.com/root/of/owncloud', + 'Shared with User One@…', + 'User One@someserver.com' + ); + }); + it('displays the user name part with domain of a remote share owner', function() { + checkRecipients( + 'User One@example.com@someserver.com', + 'Shared with User One@example.com', + 'User One@example.com@someserver.com' + ); + checkRecipients( + 'User One@example.com@someserver.com/', + 'Shared with User One@example.com', + 'User One@example.com@someserver.com' + ); + checkRecipients( + 'User One@example.com@someserver.com/root/of/owncloud', + 'Shared with User One@example.com', + 'User One@example.com@someserver.com' + ); + }); + it('display multiple remote recipients', function() { + checkRecipients( + 'One@someserver.com, two@otherserver.com', + 'Shared with One@…, two@…', + ['One@someserver.com', 'two@otherserver.com'] + ); + checkRecipients( + 'One@someserver.com/, two@otherserver.com', + 'Shared with One@…, two@…', + ['One@someserver.com', 'two@otherserver.com'] + ); + checkRecipients( + 'One@someserver.com/root/of/owncloud, two@otherserver.com', + 'Shared with One@…, two@…', + ['One@someserver.com', 'two@otherserver.com'] + ); + }); + it('display mixed recipients', function() { + checkRecipients( + 'One, two@otherserver.com', + 'Shared with One, two@…', + ['two@otherserver.com'] + ); + }); + }); + }); +}); + diff --git a/pool/shard011/JavaScript/0069747_gani_data.js b/pool/shard011/JavaScript/0069747_gani_data.js new file mode 100644 index 0000000000000000000000000000000000000000..a249f24f355a55f6dd3d36fe5c181749841071a6 --- /dev/null +++ b/pool/shard011/JavaScript/0069747_gani_data.js @@ -0,0 +1,37 @@ +// Filename: data.js +// Timestamp: 2018.05.05-00:28:54 (last modified) +// Author(s): bumblehead + +const ocon = require('ocon'), + spectraph = require('spectraph'), + + gani_token = require('./gani_token'), + gani_ui = require('./gani_ui'); + +module.exports = ocon([ + gani_ui +], o => { + const { + ISDATA + } = gani_token.tokens; + + o.type = 'data'; + + o.initnode = node => + spectraph.node.assign(node, { + [ISDATA]: true + }); + + o.resetnode = node => + node; + + // consider moving onsubj calls to be blocking + o.onsubj = (sess, cfg, graph, node, prev, subj) => { + o.postevactionopt(sess, cfg, graph, node, 'onsubj', { + prev, + subj + }); + }; + + return o; +}); diff --git a/pool/shard011/JavaScript/0069748_Users.js b/pool/shard011/JavaScript/0069748_Users.js new file mode 100644 index 0000000000000000000000000000000000000000..cb7b7071030411a9b5eb028dc403978f3c51a4b5 --- /dev/null +++ b/pool/shard011/JavaScript/0069748_Users.js @@ -0,0 +1,76 @@ +Ext.define('Slims.controller.Users', { + extend: 'Ext.app.Controller', + + models: ['User'], + stores: ['Users'], + views: ['users.Grid', 'users.Window'], + + refs: [{ + ref: 'usersGrid', + selector: 'usersgrid' + }], + + init: function() { + this.control({ + 'usersgrid button[name=addUser]': { + click: this.openAddUserWindow + }, + 'usersgrid button[name=reloadGrid]': { + click: this.reloadGrid + }, + 'usersgrid': { + 'editrecord': this.openEditUserWindow + }, + 'userwindow': { + save: this.saveUser + } + }); + }, + + openAddUserWindow: function() { + var addUserWindow = Ext.create('Slims.view.users.Window'); + + addUserWindow.show(); + }, + + openEditUserWindow: function(user) { + var editUserWindow = Ext.create('Slims.view.users.Window', { + record: user + }); + + editUserWindow.show(); + }, + + saveUser: function(user, dialog) { + dialog.setLoading('Saving. Please wait.'); + + var url; + if (user.getId()) { + url = Slims.Url.getRoute('setuser', [user.getId()]); + } else { + url = Slims.Url.getRoute('createuser'); + } + + var userData = user.getData(); + delete userData.id; + + Ext.Ajax.request({ + url: url, + method: 'POST', + jsonData: userData, + scope: this, + success: function() { + this.getUsersGrid().getStore().load(); + dialog.setLoading(false); + dialog.close(); + }, + failure: function() { + dialog.setLoading(false); + } + }); + }, + + reloadGrid: function() { + this.getUsersGrid().getStore().reload(); + } +}); diff --git a/pool/shard011/JavaScript/0069749_manageCategoriesCtrl.js b/pool/shard011/JavaScript/0069749_manageCategoriesCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..c2a262066a14e70e0a0d75713b4c18a50b4a4a0c --- /dev/null +++ b/pool/shard011/JavaScript/0069749_manageCategoriesCtrl.js @@ -0,0 +1,62 @@ +'use strict'; + +angular.module('webClientApp') + .controller('ManageCategoriesCtrl', ['$scope', '$routeParams', '$window', 'Category', '$analytics', + function ($scope, $routeParams, $window, Category, $analytics) { + + // Holder for creating new categories. + $scope.category = {}; + $scope.categories = Category.query(); + $scope.error = null; + $scope.errorMessages = {}; + + $scope.saveCategory = function(category) { + if (category.id) { + Category.update({'categoryId': category.id}, {'category': category}, updateSuccess, updateError); + } else { + Category.save({'category': category}, createSuccess, updateError); + } + }; + + $scope.deleteCategory = function(category) { + if ($window.confirm('هل أنت متأكد من حذف الفئة؟')) { + Category.delete({'categoryId': category.id}, function () { + var index = $scope.categories.indexOf(category); + $scope.categories.splice(index, 1); + }); + } + }; + + var updateSuccess = function() { + $analytics.eventTrack('Update Success', { + category: 'Category' + }); + }; + + var updateError = function(response) { + $analytics.eventTrack('Update Error', { + category: 'Category', + label: angular.toJson(response.errors) + }); + $scope.error = 'حدث خطأ ما.'; + $scope.errorMessages = response.errors; + }; + + var createSuccess = function(resource) { + $scope.categories.push(resource); + $scope.category = {}; + $analytics.eventTrack('Create Success', { + category: 'Category' + }); + }; + + var createError = function(response) { + $analytics.eventTrack('Create Error', { + category: 'Category', + label: angular.toJson(response.errors) + }); + $scope.error = 'حدث خطأ ما.'; + $scope.errorMessages = response.errors; + }; + + }]); diff --git a/pool/shard011/JavaScript/0069752_Component.js b/pool/shard011/JavaScript/0069752_Component.js new file mode 100644 index 0000000000000000000000000000000000000000..47b9c93ac39980f115bde05ee0ab695017b69cbb --- /dev/null +++ b/pool/shard011/JavaScript/0069752_Component.js @@ -0,0 +1,182 @@ +import {Validate} from '~/src/util/Validate' +import {Dispatcher} from '~/src/tickator/Dispatcher' +import {InstanceDefinition} from '~/src/tickator/definition/InstanceDefinition' +import {Property} from '~/src/tickator/instance/Property' + +export class Component { + constructor(dispatcher, instanceDefinition, parent) { + Validate.isA(dispatcher, Dispatcher) + Validate.isA(instanceDefinition, InstanceDefinition) + Validate.valid(instanceDefinition.component()!==undefined, 'Component expected, got ticklet!') + + if (parent) { + Validate.isA(parent, Component) + } + + this._dispatcher = dispatcher + this._instanceDefinition = instanceDefinition + this._parent = parent + } + + definition() { + return this._instanceDefinition.definition() + } + + instanceDefinition() { + return this._instanceDefinition + } + + properties() { + return this._properties + } + + propertiesMap() { + let res = {} + + Object.keys(this._properties).forEach(name=>res[name] = this._properties[name]()) + + return res + } + + propertyInstances() { + return this._propertyInstances + } + + build() { + this._buildProperties() + this._buildInstances() + } + + wireUp() { + console.log("In ############################# "+this._instanceDefinition.definition().name()); + this._instanceDefinition.component().connections().forEach(connection=>{ + + if (connection.fromInstance()) { + const instanceFrom = this._findInstance(connection.fromInstance()) + + if (instanceFrom.instanceDefinition().definition().type()==='ticklet') { + const output = instanceFrom.out()[connection.fromOutput()]() + + const probes = [] + + const inputs = this._findOppositeInputs(connection, probes) + + if (inputs.length>0) { + console.log(inputs.length+" opposite inputs found, wiring"); + + inputs.forEach(input=>{ + output.addDepending(input) + + probes.forEach(probe=>output.addProbe(probe)) + + input.bind(output) + }) + } else { + console.log("Opposite ticklet not found, ignoring"); + } + } + } + }) + + this._instances.forEach(instance=>{ + if (instance.instanceDefinition().definition().type()==='component') { + instance.wireUp() + } + }) + } + + _findOppositeInputs(connection, probes) { + + if (connection.hasProbe()) { + probes.push(connection.probeName()) + } + + //connected to something inside of this component + if (connection.toInstance()) { + const instanceTo = this._findInstance(connection.toInstance()) + + //connected to ticklet, return it + if (instanceTo.instanceDefinition().definition().type()==='ticklet') { + return [instanceTo.in()[connection.toInput()]()] + //connected to component, dive to i + } else { + const res = [] + + instanceTo._findConnectionsFromInputPort(connection.toInput()).forEach(subConnection=>{ + res.push(...instanceTo._findOppositeInputs(subConnection, probes)) + }) + + return res + } + //connected to output port of *this* component, dive outside + } else { + const res = [] + + //if there is parent that can be checked + if (this._parent) { + this._parent._findConnectionsToFromInstance(this._instanceDefinition.name(), connection.toInput()) + .forEach(subConnection=>{ + res.push(...this._parent._findOppositeInputs(subConnection, probes)) + }) + } + + return res + } + } + + _findConnectionsFromInputPort(inputName) { + return this._instanceDefinition.component().connections().filter(connection=>{ + return connection.fromInstance()===null && connection.fromOutput()===inputName + }) + } + + _findConnectionsToFromInstance(instanceName, outputName) { + return this._instanceDefinition.component().connections().filter(connection=>{ + return connection.fromInstance()===instanceName && connection.fromOutput()===outputName + }) + } + + _buildInstances() { + this._instances = this._instanceDefinition.component().instances().map(instance=>{ + if (instance.component()) { + const component = new Component(this._dispatcher, instance, this) + component.build() + return component + } else if (instance.ticklet()) { + const klass = instance.ticklet().klass() + const ticklet = new klass(this._dispatcher, instance, this) + ticklet.initialize() + + if (instance.ticklet().autostart()) { + this._dispatcher.schedule(ticklet) + } + + return ticklet + } else { + throw `Unknown instance type ${instance.type()}` + } + }) + } + + _findInstance(name) { + Validate.notBlank(name) + + const res = this._instances.filter(instance=>instance.instanceDefinition().name()===name) + + Validate.ofSize(res, 1, `Found ${res.length} instances with name ${name}, expected exactly one`) + + return res[0] + } + + _buildProperties() { + this._properties = {} + + const parentProperties = this._parent ? this._parent.propertiesMap() : {} + + this._propertyInstances = this._instanceDefinition.properties().map(instanceProperty=>{ + const property = new Property(instanceProperty, parentProperties) + this._properties[instanceProperty.definition().name()] = ()=>property.value() + return property + }) + } +} diff --git a/pool/shard011/JavaScript/0069753_service-list.js b/pool/shard011/JavaScript/0069753_service-list.js new file mode 100644 index 0000000000000000000000000000000000000000..abd509346db48484b2b5f5c0494602ecc78c26e1 --- /dev/null +++ b/pool/shard011/JavaScript/0069753_service-list.js @@ -0,0 +1,31 @@ +import React from 'react'; +import styled from 'styled-components'; +import ServiceCard from './service-card'; +import { Flex } from 'rebass'; +import { width, space } from 'styled-system'; + +const CardWrapper = ({children, className}) => (
    {children}
    ) +const StyledCardWrapper = styled(CardWrapper)` + ${ width }; + ${ space }; + display:flex; +` + +const ServiceList = ({className, services}) => { + var result = services.map( (service) => ( + + + )); + + return ( + { result } + ) +}; + +const StyledServiceList = styled(ServiceList)` + > * { + margin: 10px; + } +` + +export default StyledServiceList; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069754_actions.js b/pool/shard011/JavaScript/0069754_actions.js new file mode 100644 index 0000000000000000000000000000000000000000..a7eee414921db931babd83da2288517eeff0f1a2 --- /dev/null +++ b/pool/shard011/JavaScript/0069754_actions.js @@ -0,0 +1,38 @@ +function pinClickAction(x, y) { + if (anchor) { + iconPinSetting.l = pathList; + levelEngine.startSlideTo(anchor.x, anchor.y, anchor.z); + anchor = null; + levelEngine.clearGroupDetails(document.getElementById('controls')); + levelEngine.tileFromModel(); + } else { + console.log('slide to pin'); + var back = { + x: levelEngine.translateX, + y: levelEngine.translateY, + z: levelEngine.translateZ + }; + var y = 0; + if (selectedTrack > -1) { + //if (selectedTrack < currentSong.tracks.length) { + y = settingTracksTop + selectedTrack * 10; + //} else { + // y = settingTracksTop +( currentSong.tracks.length + selectedTrack) * 10; + //} + } + //console.log(y, y * levelEngine.tapSize); + levelEngine.startSlideTo(0 * levelEngine.tapSize, -y * levelEngine.tapSize, 7, function () { + console.log('pin'); + anchor = back; + iconPinSetting.l = pathPin; + levelEngine.clearGroupDetails(document.getElementById('controls')); + levelEngine.tileFromModel(); + }); + } +} +function promptClickAction(x, y) { + document.getElementById('chooseFileInput').click(); +} +function playClickAction(x, y) { + console.log(levelEngine.translateX, levelEngine.translateY, levelEngine.translateZ); +} diff --git a/pool/shard011/JavaScript/0069760_user.server.model.js b/pool/shard011/JavaScript/0069760_user.server.model.js new file mode 100644 index 0000000000000000000000000000000000000000..6429ff601d32db1b57f2a5d3cefc48052860330d --- /dev/null +++ b/pool/shard011/JavaScript/0069760_user.server.model.js @@ -0,0 +1,113 @@ +'use strict'; + +/** + * Module dependencies. + */ +var xskillzNeo4J = require('../models/xskillz.neo4j'), + _ = require('lodash'); + +exports.findOne = function (id) { + return xskillzNeo4J.findXebianById(id).then( + function (user) { + try { + var userData = user[0][0].data; + userData.roles = []; + if (user[0][1]) { + _.forEach(user[0][1], function (role) { + userData.roles.push(role); + }); + } + + return userData; + } catch (err) { + return null; + } + }); +}; + +exports.importUserWithDomainDirectoryData = function (gData, next) { + + var userData = { + displayName: gData.firstName + ' ' + gData.lastName, + firstName: gData.firstName, + lastName: gData.lastName, + email: gData.email, + picture: gData.picture || 'http://blog.xebia.fr/wp-content/glc_cache/fd4df8067d57ff096523f2c2f2981a52-60.jpg' + }; + + xskillzNeo4J.findXebianByEmail(userData.email) + .then(function (xebian) { + if (!xebian || _.isEmpty(xebian)) { + xskillzNeo4J.createXebian(userData) + .then(function () { + next(); + }) + .fail(function (error) { + next(error); + }); + } else { + var mergedUserData = _.extend(xebian[0][0].data, userData); + xskillzNeo4J.updateXebian(mergedUserData) + .then(function () { + next(); + }) + .fail(function (error) { + next(error); + }); + } + }) + .fail(function (error) { + next(error); + }); +}; + +exports.importUserWithGoogleAuthData = function (authData, next) { + + var userData = { + _id: authData.providerData.id, + displayName: authData.displayName, + firstName: authData.firstName, + lastName: authData.lastName, + email: authData.email, + accessToken: authData.providerData.accessToken, + gender: authData.providerData.gender, + link: authData.providerData.link + }; + + xskillzNeo4J.findXebianByEmail(userData.email) + .then(function (xebian) { + if (!xebian || _.isEmpty(xebian)) { + xskillzNeo4J.createXebian(userData) + .then(function () { + next(); + }) + .fail(function (error) { + next(error); + }); + } else { + var mergedUserData = _.extend(xebian[0][0].data, userData); + xskillzNeo4J.updateXebian(mergedUserData) + .then(function () { + next(); + }) + .fail(function (error) { + next(error); + }); + } + }) + .fail(function (error) { + next(error); + }); +}; + +exports.remove = function (next, done) { + var self = this; + + xskillzNeo4J.deleteNode(self.nodeUrl) + .then(function (status) { + next(); + }) + .fail(function (error) { + next(error); + }); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069762_authentication.js b/pool/shard011/JavaScript/0069762_authentication.js new file mode 100644 index 0000000000000000000000000000000000000000..bc4b08825c9e0fc826bc528985b29508c8caf129 --- /dev/null +++ b/pool/shard011/JavaScript/0069762_authentication.js @@ -0,0 +1,209 @@ +// Generated by CoffeeScript 1.9.3 +var Instance, User, helpers, localization, passport, passwordKeys, randomstring, request; + +passport = require('passport'); + +randomstring = require('randomstring'); + +request = require('request-json'); + +User = require('../models/user'); + +Instance = require('../models/instance'); + +helpers = require('../lib/helpers'); + +localization = require('../lib/localization_manager'); + +passwordKeys = require('../lib/password_keys'); + +module.exports.registerIndex = function(req, res) { + return User.first(function(err, user) { + if (user != null) { + return res.redirect('/login'); + } else { + localization.setLocale(req.headers['accept-language']); + return res.render("index"); + } + }); +}; + +module.exports.register = function(req, res, next) { + var error, hash, instanceData, passwdValidationError, userData, validationErrors; + hash = helpers.cryptPassword(req.body.password); + userData = { + email: req.body.email, + owner: true, + password: hash.hash, + salt: hash.salt, + public_name: req.body.public_name, + timezone: req.body.timezone, + activated: true, + allow_stats: req.body.allow_stats, + docType: "User" + }; + instanceData = { + locale: req.body.locale + }; + passwdValidationError = User.validatePassword(req.body.password); + validationErrors = User.validate(userData, passwdValidationError); + if (!Object.keys(validationErrors).length) { + return User.all(function(err, users) { + var error; + if (err != null) { + return next(new Error(err)); + } else if (users.length !== 0) { + error = new Error("User already registered."); + error.status = 409; + return next(error); + } else { + return Instance.createOrUpdate(instanceData, function(err) { + if (err) { + return next(new Error(err)); + } + return User.createNew(userData, function(err) { + if (err) { + return next(new Error(err)); + } + localization.setLocale(req.body.locale); + return next(); + }); + }); + } + }); + } else { + error = new Error('Errors in validation'); + error.errors = validationErrors; + error.status = 400; + return next(error); + } +}; + +module.exports.loginIndex = function(req, res) { + return User.first(function(err, user) { + var name, ref, words; + if (user == null) { + return res.redirect('/register'); + } + if (((ref = user.public_name) != null ? ref.length : void 0) > 0) { + name = user.public_name; + } else { + name = helpers.hideEmail(user.email); + words = name.split(' '); + name = words.map(function(word) { + return word.charAt(0).toUpperCase() + word.slice(1); + }).join(' '); + } + return res.render("index", { + name: name + }); + }); +}; + +module.exports.forgotPassword = function(req, res, next) { + return User.first(function(err, user) { + var key; + if (err != null) { + return next(new Error(err)); + } else if (user == null) { + err = new Error("No user registered."); + err.status = 400; + err.headers = { + 'Location': '/register/' + }; + return next(err); + } else { + key = randomstring.generate(); + Instance.setResetKey(key); + return Instance.first(function(err, instance) { + if (err != null) { + next(new Error(err)); + } else if (instance == null) { + instance = { + domain: "domain.not.set" + }; + } + return helpers.sendResetEmail(instance, user, key, function(err, result) { + if (err != null) { + return next(new Error("Email cannot be sent")); + } else { + return res.send(204); + } + }); + }); + } + }); +}; + +module.exports.resetPasswordIndex = function(req, res) { + if (Instance.getResetKey() === req.params.key) { + return res.render("index", { + resetKey: req.params.key + }); + } else { + return res.redirect('/'); + } +}; + +module.exports.resetPassword = function(req, res, next) { + var key, newPassword; + key = req.params.key; + newPassword = req.body.password; + return User.first(function(err, user) { + var data, error, validationErrors; + if (err != null) { + return next(new Error(err)); + } else if (user == null) { + err = new Error(localization.t("reset error no user")); + err.status = 400; + err.headers = { + 'Location': '/register/' + }; + return next(err); + } else { + if (Instance.getResetKey() === req.params.key) { + validationErrors = User.validatePassword(newPassword); + if (!Object.keys(validationErrors).length) { + data = { + password: helpers.cryptPassword(newPassword).hash + }; + return user.merge(data, function(err) { + if (err != null) { + return next(new Error(err)); + } else { + Instance.resetKey = null; + return passwordKeys.resetKeys(function(err) { + if (err != null) { + return next(new Error(err)); + } else { + passport.currentUser = null; + return res.send(204); + } + }); + } + }); + } else { + error = new Error('Errors in validation'); + error.errors = validationErrors; + error.status = 400; + return next(error); + } + } else { + error = new Error(localization.t("reset error invalid key")); + error.status = 400; + return next(error); + } + } + }); +}; + +module.exports.logout = function(req, res) { + req.logout(); + return res.send(204); +}; + +module.exports.authenticated = function(req, res) { + return res.send(200, { + isAuthenticated: req.isAuthenticated() + }); +}; diff --git a/pool/shard011/JavaScript/0069763_benchmark.rev_sorted_few_uniques.ndarray.native.js b/pool/shard011/JavaScript/0069763_benchmark.rev_sorted_few_uniques.ndarray.native.js new file mode 100644 index 0000000000000000000000000000000000000000..387c8885ef380f8e1aea507d5c78529b59cd5c55 --- /dev/null +++ b/pool/shard011/JavaScript/0069763_benchmark.rev_sorted_few_uniques.ndarray.native.js @@ -0,0 +1,132 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var resolve = require( 'path' ).resolve; +var bench = require( '@stdlib/bench' ); +var discreteUniform = require( '@stdlib/random/base/discrete-uniform' ).factory; +var isnan = require( '@stdlib/math/base/assert/is-nan' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var floor = require( '@stdlib/math/base/special/floor' ); +var Float64Array = require( '@stdlib/array/float64' ); +var dcopy = require( '@stdlib/blas/base/dcopy' ); +var tryRequire = require( '@stdlib/utils/try-require' ); +var pkg = require( './../package.json' ).name; + + +// VARIABLES // + +var dsorthp = tryRequire( resolve( __dirname, './../lib/ndarray.native.js' ) ); +var opts = { + 'skip': ( dsorthp instanceof Error ) +}; + + +// FUNCTIONS // + +/** +* Create a benchmark function. +* +* @private +* @param {PositiveInteger} iter - number of iterations +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( iter, len ) { + var randi; + var tmp; + var x; + var v; + var M; + var i; + var j; + + randi = discreteUniform( 1, 10 ); + M = floor( len*0.333 ); + + x = []; + for ( i = 0; i < iter; i++ ) { + tmp = new Float64Array( len ); + v = randi(); + for ( j = 0; j < len; j++ ) { + if ( i % M === 0 ) { + v -= randi(); + } + tmp[ j ] = v; + } + x.push( tmp ); + } + return benchmark; + + function benchmark( b ) { + var xc; + var y; + var i; + + xc = x.slice(); + for ( i = 0; i < iter; i++ ) { + xc[ i ] = dcopy( len, x[ i ], 1, new Float64Array( len ), 1 ); + } + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + y = dsorthp( len, 1, xc[ i ], 1, 0 ); + if ( isnan( y[ i%len ] ) ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( isnan( y[ i%len ] ) ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +function main() { + var bopts; + var iter; + var len; + var min; + var max; + var f; + var i; + + iter = 1e6; + min = 1; // 10^min + max = 4; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( iter, len ); + bopts = { + 'skip': opts.skip, + 'iterations': iter + }; + bench( pkg+'::native,reverse_sorted,few_uniques:ndarray:len='+len, bopts, f ); + iter = floor( pow( iter, 3.0/4.0 ) ); + } +} + +main(); diff --git a/pool/shard011/JavaScript/0069767_http.js b/pool/shard011/JavaScript/0069767_http.js new file mode 100644 index 0000000000000000000000000000000000000000..84eec5d9b13a2b6c79798d201976c50533d8d796 --- /dev/null +++ b/pool/shard011/JavaScript/0069767_http.js @@ -0,0 +1,197 @@ +import Vue from 'vue'; + +describe('Vue.http', function () { + + it('get("data/text.txt")', done => { + + Vue.http.get('data/text.txt').then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(res.body).toBe('text'); + expect(res.headers.get('Content-Type')).toBe('text/plain'); + expect(res.headers.get('Content-Length')).toBe('4'); + + done(); + }); + + }); + + it('get("data/valid.json")', done => { + + Vue.http.get('data/valid.json').then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(typeof res.body).toBe('object'); + expect(res.body.foo).toBe('bar'); + + done(); + }); + + }); + + it('get("data/invalid.json")', done => { + + Vue.http.get('data/invalid.json').then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(res.body).toBeNull(); + + done(); + }); + + }); + + it('get("github.com/avatar")', done => { + + Vue.http.get('https://avatars1.githubusercontent.com/u/6128107').then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(res.body instanceof Blob).toBe(true); + expect(res.body.type).toBe('image/png'); + + done(); + }); + + }); + + it('get("cors-api.appspot.com")', done => { + + Vue.http.get('http://server.cors-api.appspot.com/server?id=1&enable=true').then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(typeof res.body).toBe('object'); + expect(res.body.shift().requestType).toBe('cors'); + expect(res.headers.get('Content-Type')).toBe('application/json'); + + done(); + }); + + }); + + it('jsonp("jsfiddle.net/jsonp")', done => { + + Vue.http.jsonp('http://jsfiddle.net/echo/jsonp/', {params: {foo: 'bar'}}).then(res => { + + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(typeof res.body).toBe('object'); + expect(res.body.foo).toBe('bar'); + + done(); + }); + + }); + +}); + +describe('this.$http', function () { + + it('get("data/valid.json")', done => { + + var vm = new Vue({ + + created() { + + this.$http.get('data/valid.json').then(res => { + + expect(this).toBe(vm); + expect(res.ok).toBe(true); + expect(res.status).toBe(200); + expect(typeof res.body).toBe('object'); + expect(res.body.foo).toBe('bar'); + + done(); + + }); + + } + + }); + + }); + + it('get("data/valid.json") with timeout', done => { + + var vm = new Vue({ + + created() { + + var random = Math.random().toString(36).substr(2); + + this.$http.get(`data/valid.json?${random}`, {timeout: 1}).then(res => { + + fail('Callback has been called'); + + }, res => { + + expect(res.ok).toBe(false); + expect(res.status).toBe(0); + + done(); + + }); + + } + + }); + + }); + + it('get("data/valid.json") with abort()', done => { + + var vm = new Vue({ + + created() { + + var random = Math.random().toString(36).substr(2); + + this.$http.get(`data/valid.json?${random}`, { + + before(req) { + setTimeout(() => { + + expect(typeof req.abort).toBe('function'); + + req.abort(); + + }, 0); + } + + }).then(res => { + fail('Callback has been called'); + }, res => { + done(); + }); + } + + }); + + }); + + it('get("data/notfound.json") using catch()', done => { + + var vm = new Vue({ + + created() { + + this.$http.get('data/notfound.json').catch(res => { + + expect(this).toBe(vm); + expect(res.ok).toBe(false); + expect(res.status).toBe(404); + + done(); + }); + + } + + }); + + }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069770_ShareKitPlugin.js b/pool/shard011/JavaScript/0069770_ShareKitPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..1f72053067ab72197c576c4077ea25bd7a6a7388 --- /dev/null +++ b/pool/shard011/JavaScript/0069770_ShareKitPlugin.js @@ -0,0 +1,92 @@ +// +// ShareKitPlugin.js +// +// +// Created by Erick Camacho on 28/07/11. +// MIT Licensed +// + +function ShareKitPlugin() +{ + console.log('creating plugin'); +}; + +ShareKitPlugin.prototype.share = function(message, url) +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "share", [message, url]); + +}; + + +ShareKitPlugin.prototype.isLoggedToTwitter = function( callback ) +{ + + PhoneGap.exec(callback, null, "ShareKitPlugin", "isLoggedToTwitter", [] ); +}; + +ShareKitPlugin.prototype.isLoggedToFacebook = function( callback ) +{ + + PhoneGap.exec(callback, null, "ShareKitPlugin", "isLoggedToFacebook", [] ); + +}; + +ShareKitPlugin.prototype.logoutFromTwitter = function() +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "logoutFromTwitter", [] ); + +}; + +ShareKitPlugin.prototype.logoutFromFacebook = function() +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "logoutFromFacebook", [] ); + +}; + + +ShareKitPlugin.prototype.facebookConnect = function() +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "facebookConnect", [] ); + +}; + +ShareKitPlugin.prototype.shareToFacebook = function( message, url) +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "shareToFacebook", [message, url] ); + +}; + +ShareKitPlugin.prototype.shareToTwitter = function( message, url) +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "shareToTwitter", [message, url] ); + +}; + +ShareKitPlugin.prototype.shareToMail = function( subject, message) +{ + + PhoneGap.exec(null, null, "ShareKitPlugin", "shareToMail", [subject, message] ); + +}; + + + + +ShareKitPlugin.install = function() +{ + if(!window.plugins) + { + window.plugins = {}; + } + + window.plugins.shareKit = new ShareKitPlugin(); + return window.plugins.shareKit; +}; + +PhoneGap.addConstructor(ShareKitPlugin.install); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069778_Controller.js b/pool/shard011/JavaScript/0069778_Controller.js new file mode 100644 index 0000000000000000000000000000000000000000..c295e9a55b2d4c32ce45f2d1b61f168e185f9836 --- /dev/null +++ b/pool/shard011/JavaScript/0069778_Controller.js @@ -0,0 +1,40 @@ +import {funcMeta} from "./utils"; +import {app} from "./app"; + +/** +@function Controller +@param {String} [name] - The name of the controller. + +@example +[@]Controller() +class MyController {} + +*/ +export function Controller(name, options) { + if (typeof name === "function") { + let constructor = name; name = null; + return register(constructor, options); + } + + return register; + function register(constructor, opts){ + registerLock(constructor); + let meta = funcMeta(constructor); + + name = (name || (opts && opts.name) || meta.name); + meta.controller.name = name; + + app.controller(name, constructor); + } +} + +function registerLock(constructor) { + let meta = funcMeta(constructor); + var lock = meta.controller; + + if (lock) { + throw "@Controller() can only be used once!"; + } + + meta.controller = {}; +} diff --git a/pool/shard011/JavaScript/0069779_keyquest.js b/pool/shard011/JavaScript/0069779_keyquest.js new file mode 100644 index 0000000000000000000000000000000000000000..0f5de244dca134575615d2b292feba42560450b8 --- /dev/null +++ b/pool/shard011/JavaScript/0069779_keyquest.js @@ -0,0 +1,81 @@ +function report(elementId, message) { + var element = document.createElement('p'); + var parent = document.getElementById(elementId); + parent.appendChild(element); + element.innerHTML = message; +}; + +function gameOver(message) { + var element = document.createElement('div'); + element.className = "game-over"; + document.body.appendChild(element); + element.innerHTML = "

    GAME OVER!

    " + message; +} + +function victory(message) { + var element = document.createElement('div'); + element.className = "victory"; + document.body.appendChild(element); + element.innerHTML = "

    YOU HAVE WON!

    " + message; +} + +function questify(url, elementId) { + return (function (item) { + var promise = new Promise(function (resolve, reject) { + var request = new XMLHttpRequest(); + //Send the proper header information along with the request + request.open('POST', url); + request.setRequestHeader("Content-type", "application/json"); + request.setRequestHeader("Accept", "application/json"); + request.onload = function () { + if (request.status == 200) { + var result = JSON.parse(request.response); + report(elementId, result.text); + resolve(result.item); // we got data here, so resolve the Promise + } else { + reject(Error(request.statusText)); // status is not 200 OK, so reject + } + }; + + request.onerror = function () { + reject(Error('Error fetching data.')); // error occurred, reject the Promise + }; + request.send(JSON.stringify(item)); //send the request + }); + return (promise); + }); +} + +function runQuest() { + //TODO: extend this runQuest method to complete all three quests and retrieve all three keys. + var talkToTheKnight = questify("/knight", "ctrl-div"); + var talkToTheWizard = questify("/wizard", "ctrl-div"); + var talkToTheWeaver = questify("/weaver", "ctrl-div"); + var talkToTheCleric = questify("/cleric", "alt-div"); + var talkToTheKeysmith = questify("/keysmith", "alt-div"); + var talkToTheEarl = questify("/earl", "delete-div"); + var bagOfGold = { name: "Bag of Gold" }; + var quests = new Array(); + + var controlKeyQuest = talkToTheWeaver() + .then(talkToTheKnight) + .then(talkToTheWizard); + var altKeyQuest = talkToTheKeysmith({ name: "Bag Of Gold" }) + .then(talkToTheCleric); + var deleteKeyQuest = talkToTheEarl({ name: "Diamond of Multiple Inheritance" }); + + quests.push(controlKeyQuest, altKeyQuest, deleteKeyQuest); + + Promise.all(quests) + .then(function (values) { + if (values.length === 3 && values.every(function (e) { + return (/key/i.test(e.name)); + })) { + victory("You have saved the kingdom!"); + } else { + gameOver("You need to collect all three keys."); + } + }) + .catch(gameOver); + +} diff --git a/pool/shard011/JavaScript/0069781_tab-scroller-menu.js b/pool/shard011/JavaScript/0069781_tab-scroller-menu.js new file mode 100644 index 0000000000000000000000000000000000000000..5d75a182ec3a7fb4aa1cd5b828a3374c5ef8e1bf --- /dev/null +++ b/pool/shard011/JavaScript/0069781_tab-scroller-menu.js @@ -0,0 +1,51 @@ +/*! + * Ext JS Library 3.4.0 + * Copyright(c) 2006-2011 Sencha Inc. + * licensing@sencha.com + * http://www.sencha.com/license + */ + +Ext.onReady(function() { + Ext.QuickTips.init(); + // Create our instance of tabScrollerMenu + var scrollerMenu = new Ext.ux.TabScrollerMenu({ + maxText : 15, + pageSize : 5 + }); + new Ext.Window({ + height : 200, + width : 400, + layout : 'fit', + title : 'Exercising scrollable tabs with a tabscroller menu', + items : { + xtype : 'tabpanel', + activeTab : 0, + id : 'myTPanel', + enableTabScroll : true, + resizeTabs : true, + minTabWidth : 75, + border : false, + plugins : [ scrollerMenu ], + items : [ + { + title : 'our first tab' + } + ] + } + }).show(); + + // Add a bunch of tabs dynamically + var tabLimit = 22; + (function (num) { + for (var i = 1; i <= tabLimit; i++) { + var title = 'Tab # ' + i; + Ext.getCmp('myTPanel').add({ + title : title, + html : 'Hi, i am tab ' + i, + tabTip : title, + closable : true + }); + } + }).defer(1000); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069782_classTypeParametersInStatics.js b/pool/shard011/JavaScript/0069782_classTypeParametersInStatics.js new file mode 100644 index 0000000000000000000000000000000000000000..3a12162f6441375bc7095978c5beb4e3a317d6be --- /dev/null +++ b/pool/shard011/JavaScript/0069782_classTypeParametersInStatics.js @@ -0,0 +1,31 @@ +var Editor; +(function (Editor) { + var List = (function () { + function List(isHead, data) { + this.isHead = isHead; + this.data = data; + } + List.MakeHead = function () { + var entry = new List(true, null); + entry.prev = entry; + entry.next = entry; + return entry; + }; + + List.MakeHead2 = function () { + var entry = new List(true, null); + entry.prev = entry; + entry.next = entry; + return entry; + }; + + List.MakeHead3 = function () { + var entry = new List(true, null); + entry.prev = entry; + entry.next = entry; + return entry; + }; + return List; + })(); + Editor.List = List; +})(Editor || (Editor = {})); diff --git a/pool/shard011/JavaScript/0069783_info-window-manager.js b/pool/shard011/JavaScript/0069783_info-window-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..a0173bc10858dfe3d609b1ddaf3681fb69572fee --- /dev/null +++ b/pool/shard011/JavaScript/0069783_info-window-manager.js @@ -0,0 +1,86 @@ +/** + * angular2-google-maps - Angular 2 components for Google Maps + * @version v0.14.0 + * @link https://github.com/SebastianM/angular2-google-maps#readme + * @license MIT + */ +"use strict"; +var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +}; +var __metadata = (this && this.__metadata) || function (k, v) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); +}; +var core_1 = require('@angular/core'); +var google_maps_api_wrapper_1 = require('../google-maps-api-wrapper'); +var marker_manager_1 = require('./marker-manager'); +var InfoWindowManager = (function () { + function InfoWindowManager(_mapsWrapper, _zone, _markerManager) { + this._mapsWrapper = _mapsWrapper; + this._zone = _zone; + this._markerManager = _markerManager; + this._infoWindows = new Map(); + } + InfoWindowManager.prototype.deleteInfoWindow = function (infoWindow) { + var _this = this; + var iWindow = this._infoWindows.get(infoWindow); + if (iWindow == null) { + // info window already deleted + return Promise.resolve(); + } + return iWindow.then(function (i) { + return _this._zone.run(function () { + i.close(); + _this._infoWindows.delete(infoWindow); + }); + }); + }; + InfoWindowManager.prototype.setPosition = function (infoWindow) { + return this._infoWindows.get(infoWindow).then(function (i) { return i.setPosition({ + lat: infoWindow.latitude, + lng: infoWindow.longitude + }); }); + }; + InfoWindowManager.prototype.setZIndex = function (infoWindow) { + return this._infoWindows.get(infoWindow) + .then(function (i) { return i.setZIndex(infoWindow.zIndex); }); + }; + InfoWindowManager.prototype.open = function (infoWindow) { + var _this = this; + return this._infoWindows.get(infoWindow).then(function (w) { + if (infoWindow.hostMarker != null) { + return _this._markerManager.getNativeMarker(infoWindow.hostMarker).then(function (marker) { + return _this._mapsWrapper.getNativeMap().then(function (map) { return w.open(map, marker); }); + }); + } + return _this._mapsWrapper.getNativeMap().then(function (map) { return w.open(map); }); + }); + }; + InfoWindowManager.prototype.close = function (infoWindow) { + return this._infoWindows.get(infoWindow).then(function (w) { return w.close(); }); + }; + InfoWindowManager.prototype.setOptions = function (infoWindow, options) { + return this._infoWindows.get(infoWindow).then(function (i) { return i.setOptions(options); }); + }; + InfoWindowManager.prototype.addInfoWindow = function (infoWindow) { + var options = { + content: infoWindow.content, + }; + if (typeof infoWindow.latitude === 'number' && typeof infoWindow.longitude === 'number') { + options.position = { lat: infoWindow.latitude, lng: infoWindow.longitude }; + } + var infoWindowPromise = this._mapsWrapper.createInfoWindow(options); + this._infoWindows.set(infoWindow, infoWindowPromise); + }; + InfoWindowManager = __decorate([ + core_1.Injectable(), + __metadata('design:paramtypes', [google_maps_api_wrapper_1.GoogleMapsAPIWrapper, core_1.NgZone, marker_manager_1.MarkerManager]) + ], InfoWindowManager); + return InfoWindowManager; +}()); +exports.InfoWindowManager = InfoWindowManager; + +//# sourceMappingURL=info-window-manager.js.map diff --git a/pool/shard011/JavaScript/0069788_index.js b/pool/shard011/JavaScript/0069788_index.js new file mode 100644 index 0000000000000000000000000000000000000000..d24ae8e753b68dba7162487997fc1c82ffeb001d --- /dev/null +++ b/pool/shard011/JavaScript/0069788_index.js @@ -0,0 +1,99 @@ +import React, { Component } from 'react'; +import { Link } from 'react-router'; +import {Glyphicon} from 'react-bootstrap'; + +import LogNotificationCard from './../LogNotificationCard'; +import LogActivityCard from './../LogActivityCard'; +import LogProjectCard from './../LogProjectCard'; + +import {Authorization, Authorization2} from './../../Core/Authorization'; + +import styles from './style.css'; +//import Authorization from "../../../utils/Authorization"; + +class NotificationCards extends Component{ + constructor(props){ + super(props); + this.state = { + partialLogs : 0, + totalHours:0, + missingLogs: new Date().getDate() + } + } + + componentWillReceiveProps(nextProps){ + let totalDays ; + if(nextProps.month < new Date().getMonth()){ + totalDays = nextProps.days; + }else if(nextProps.month === new Date().getMonth()){ + totalDays = new Date().getDate(); + }else{ + totalDays =0; + } + + let totalHoursForDay = 0,totalMins = 0,localTotalHours= 0 + let localPartial = 0, localMissing = totalDays; + + + if(nextProps.activity && nextProps.activity.activities.length >0){ + //calculate total hours completed on a day + nextProps.activity.activities.map((activitites)=>{ + activitites.activities.map((data)=>{ + totalHoursForDay=totalHoursForDay+data.hh; + totalMins=totalMins+data.mm; + while(totalMins > 60){ + totalHoursForDay=totalHoursForDay+1; + totalMins = totalMins-60 + } + }); + if( totalHoursForDay>=8 ){ + localMissing = localMissing-1; + } + else if( totalHoursForDay > 0 && totalHoursForDay <8 ){ + localMissing = localMissing-1; + localPartial = localPartial+1 + } + localTotalHours = localTotalHours + totalHoursForDay; + totalHoursForDay = 0,totalMins = 0; + }); + + this.setState({ + missingLogs:localMissing, + partialLogs:localPartial, + totalHours : localTotalHours + }); + } + else{ + this.setState({ + missingLogs:nextProps.days, + partialLogs:0, + totalHours : 0 + }); + } + + } + render(){ + + let LogNotificationCardHOC = Authorization(LogNotificationCard, 'admin'); + let LogActivityCardHOC = Authorization(LogActivityCard, 'user'); + return( +
    + {LogNotificationCardHOC && } +
    + + + + + + +
    + +
    + ); + } +} + +export default NotificationCards; + +// +// diff --git a/pool/shard011/JavaScript/0069791_ready.js b/pool/shard011/JavaScript/0069791_ready.js new file mode 100644 index 0000000000000000000000000000000000000000..0dbca0a87c652e9990de763664a75fd1eb2adde4 --- /dev/null +++ b/pool/shard011/JavaScript/0069791_ready.js @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2015-2016 Fraunhofer FOKUS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +define([ + "../core", + "init", + "../deferred" +], function( jQuery ) { + +// The deferred used on DOM ready +var readyList; + +jQuery.fn.ready = function( fn ) { + // Add the callback + jQuery.ready.promise().done( fn ); + + return this; +}; + +jQuery.extend({ + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Hold (or release) the ready event + holdReady: function( hold ) { + if ( hold ) { + jQuery.readyWait++; + } else { + jQuery.ready( true ); + } + }, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + + // Trigger any bound ready events + if ( jQuery.fn.triggerHandler ) { + jQuery( document ).triggerHandler( "ready" ); + jQuery( document ).off( "ready" ); + } + } +}); + +/** + * The ready event handler and self cleanup method + */ +function completed() { + document.removeEventListener( "DOMContentLoaded", completed, false ); + window.removeEventListener( "load", completed, false ); + jQuery.ready(); +} + +jQuery.ready.promise = function( obj ) { + if ( !readyList ) { + + readyList = jQuery.Deferred(); + + // Catch cases where $(document).ready() is called after the browser event has already occurred. + // We once tried to use readyState "interactive" here, but it caused issues like the one + // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 + if ( document.readyState === "complete" ) { + // Handle it asynchronously to allow scripts the opportunity to delay ready + setTimeout( jQuery.ready ); + + } else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed, false ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed, false ); + } + } + return readyList.promise( obj ); +}; + +// Kick off the DOM ready check even if the user does not +jQuery.ready.promise(); + +}); diff --git a/pool/shard011/JavaScript/0069795_services.js b/pool/shard011/JavaScript/0069795_services.js new file mode 100644 index 0000000000000000000000000000000000000000..84c3e3f13853d5b6d499753a058798d5955e2b51 --- /dev/null +++ b/pool/shard011/JavaScript/0069795_services.js @@ -0,0 +1,110 @@ +'use strict'; + +describe('uikit.services.TT', function() { + var TT, + $q, + $rootScope, + tt_deferred, + window_mock; + + beforeEach(module('uikit.services')); + + beforeEach(function() { + window_mock = { + TT: { + native: { + init: function() { + return { + done: function(callback) { + tt_deferred = $q.defer(); + return tt_deferred.promise.then(callback); + } + }; + }, + loaded: jasmine.createSpy(), + showStatus: jasmine.createSpy(), + accessToken: undefined + } + } + }; + tt_deferred = undefined; + + module(function($provide) { + $provide.value('$window', window_mock); + }); + + inject(function($injector) { + $q = $injector.get('$q'); + $rootScope = $injector.get('$rootScope'); + TT = $injector.get('TT'); + }); + }); + + describe('in general', function() { + it('should exist', function() { + expect(TT).toBeDefined(); + }); + + it('should be a promise', function() { + // Is it possible to check that it's actually a promise? + expect(TT.then).toBeDefined(); + }); + + it('should (only) call TT.native.loaded() when done', function() { + expect(window_mock.TT.native.loaded).not.toHaveBeenCalled(); + tt_deferred.resolve(); + $rootScope.$apply(); + expect(window_mock.TT.native.loaded).toHaveBeenCalled(); + }); + }); + + describe('when unauthorized', function() { + beforeEach(function() { + window_mock.TT.native.accessToken = undefined; + }); + + it('should not expose an accessToken', function() { + var accessToken = undefined; + + TT.then(function(resp) { accessToken = resp.accessToken; }); + tt_deferred.resolve(); + $rootScope.$apply(); + + expect(accessToken).not.toBeDefined(); + }); + + it('should call TT.native.showStatus', function() { + expect(window_mock.TT.native.showStatus).not.toHaveBeenCalled(); + + tt_deferred.resolve(); + $rootScope.$apply(); + + expect(window_mock.TT.native.showStatus).toHaveBeenCalled(); + }); + + it('should return Unauthorized error message', function() { + var error; + + TT.then(undefined, function(resp) { error = resp.error; }); + tt_deferred.resolve(); + $rootScope.$apply(); + + expect(error).toEqual('Unauthorized'); + }); + }); + + describe('when authorized', function() { + beforeEach(function() { + window_mock.TT.native.accessToken = 'ACCESS_TOKEN'; + }); + + it('should expose a valid accessToken', function() { + var accessToken; + TT.then(function(resp) { accessToken = resp.accessToken; }); + tt_deferred.resolve(); + $rootScope.$apply(); + + expect(accessToken).toEqual(window_mock.TT.native.accessToken); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069796_AboutApplyingWhatWeHaveLearnt.js b/pool/shard011/JavaScript/0069796_AboutApplyingWhatWeHaveLearnt.js new file mode 100644 index 0000000000000000000000000000000000000000..357efe373a3c305984550f313f57bd9e53252cc8 --- /dev/null +++ b/pool/shard011/JavaScript/0069796_AboutApplyingWhatWeHaveLearnt.js @@ -0,0 +1,114 @@ +var _; //globals + +describe("About Applying What We Have Learnt", function() { + + var products; + + beforeEach(function () { + products = [ + { name: "Sonoma", ingredients: ["artichoke", "sundried tomatoes", "mushrooms"], containsNuts: false }, + { name: "Pizza Primavera", ingredients: ["roma", "sundried tomatoes", "goats cheese", "rosemary"], containsNuts: false }, + { name: "South Of The Border", ingredients: ["black beans", "jalapenos", "mushrooms"], containsNuts: false }, + { name: "Blue Moon", ingredients: ["blue cheese", "garlic", "walnuts"], containsNuts: true }, + { name: "Taste Of Athens", ingredients: ["spinach", "kalamata olives", "sesame seeds"], containsNuts: true } + ]; + }); + + /*********************************************************************************/ + + it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (imperative)", function () { + + var i,j,hasMushrooms, productsICanEat = []; + + for (i = 0; i < products.length; i+=1) { + if (products[i].containsNuts === false) { + hasMushrooms = false; + for (j = 0; j < products[i].ingredients.length; j+=1) { + if (products[i].ingredients[j] === "mushrooms") { + hasMushrooms = true; + } + } + if (!hasMushrooms) productsICanEat.push(products[i]); + } + } + + expect(productsICanEat.length).toBe(1); + }); + + it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () { + + var productsICanEat = []; + + /* solve using filter() & all() / any() */ + + expect(productsICanEat.length).toBe(0); + }); + + /*********************************************************************************/ + + it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (imperative)", function () { + + var sum = 0; + for(var i=1; i<1000; i+=1) { + if (i % 3 === 0 || i % 5 === 0) { + sum += i; + } + } + + expect(sum).toBe(233168); + }); + + it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () { + + var sum = _.range(0, 1000).reduce(function(a,b){sum = a + b; return sum;}); /* try chaining range() and reduce() */ + + expect(233168).toBe(sum); + }); + + /*********************************************************************************/ + it("should count the ingredient occurrence (imperative)", function () { + var ingredientCount = { "{ingredient name}": 0 }; + + for (i = 0; i < products.length; i+=1) { + for (j = 0; j < products[i].ingredients.length; j+=1) { + ingredientCount[products[i].ingredients[j]] = (ingredientCount[products[i].ingredients[j]] || 0) + 1; + } + } + + expect(ingredientCount['mushrooms']).toBe(2); + }); + + it("should count the ingredient occurrence (functional)", function () { + var ingredientCount = { "{ingredient name}": 0 }; + + /* chain() together map(), flatten() and reduce() */ + _.chain().map(products, function(){return products.ingredients}).flatten(); + + expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN); + }); + + /*********************************************************************************/ + /* UNCOMMENT FOR EXTRA CREDIT */ + /* + it("should find the largest prime factor of a composite number", function () { + + }); + + it("should find the largest palindrome made from the product of two 3 digit numbers", function () { + + }); + + it("should find the smallest number divisible by each of the numbers 1 to 20", function () { + + + }); + + it("should find the difference between the sum of the squares and the square of the sums", function () { + + }); + + it("should find the 10001st prime", function () { + + }); + */ +}); diff --git a/pool/shard011/JavaScript/0069797_109.border.js b/pool/shard011/JavaScript/0069797_109.border.js new file mode 100644 index 0000000000000000000000000000000000000000..7e318fff4928712d9ad45368fa38d47f50f1ea54 --- /dev/null +++ b/pool/shard011/JavaScript/0069797_109.border.js @@ -0,0 +1,82 @@ +var join = require('path').join, + assert = require('assert'), + mkdirp = require('mkdirp'), + lwip = require('../../'), + imgs = require('../imgs'); + +var tmpDir = join(__dirname, '../results'), + basename = 'border', + current; + +describe('lwip.border', function() { + + var image; + + before(function(done) { + mkdirp(tmpDir, done); + }); + + beforeEach(function(){ + current = [basename]; + }); + + beforeEach(function(done) { + lwip.open(imgs.png.trans, function(err, img) { + image = img; + done(err); + }); + }); + + afterEach(function(done) { + image.writeFile(join(tmpDir, current.join('_') + '.gif'), 'gif', { + colors: 256 + }, done); + }); + + describe('19 pixels, green', function() { + var width = 500 + 19 * 2, + height = 333 + 19 * 2; + it('image should have the correct size', function(done) { + current.push('19px_green'); + image.border(19, 'green', function(err, im) { + if (err) return done(err); + assert(im.width() === width); + assert(im.height() === height); + done(); + }); + }); + }); + + describe('9 pixels, [100,200,25]', function() { + var width = 500 + 9 * 2, + height = 333 + 9 * 2; + it('image should have the correct size', function(done) { + current.push('9px_[100,200,25]'); + image.border(9, [100, 200, 25], function(err, im) { + if (err) return done(err); + assert(im.width() === width); + assert(im.height() === height); + done(); + }); + }); + }); + + describe('4 pixels, {r:100,g:200,b:25}', function() { + var width = 500 + 4 * 2, + height = 333 + 4 * 2; + it('image should have the correct size', function(done) { + current.push('4px_r100,g200,b25'); + image.border(4, { + r: 100, + g: 200, + b: 25 + }, function(err, im) { + if (err) return done(err); + assert(im.width() === width); + assert(im.height() === height); + done(); + }); + }); + }); + +}); diff --git a/pool/shard011/JavaScript/0069801_wegas-nodeformatter.js b/pool/shard011/JavaScript/0069801_wegas-nodeformatter.js new file mode 100644 index 0000000000000000000000000000000000000000..4b144b54da0ac8a9956f125df09c2c267b86611d --- /dev/null +++ b/pool/shard011/JavaScript/0069801_wegas-nodeformatter.js @@ -0,0 +1,158 @@ +/* + * Wegas + * http://wegas.albasim.ch + * + * Copyright (c) 2013 School of Business and Engineering Vaud, Comem + * Licensed under the MIT License + */ +/** + * @fileoverview + * @author Benjamin Gerber + */ +YUI.add('wegas-nodeformatter', function(Y) { + "use strict"; + + /** + * @name Y.Wegas.NodeFormatter + * @extends Y.Widget + * @borrows Y.Wegas.Widget + * @class return value in specifique node. + * @constructor + * @description returm value in specifique node. Available type: + * Text node, image node, value box node, and position node. + */ + var NodeFormatter = Y.Base.create("wegas-nodeformatter", Y.Base, [], { + /** @lends Y.Wegas.NodeFormatter# */ + + // ** Lifecycle Methods ** // + /** + * @function + * @private + * @param value + * @param label + * @param className + * @return node + * @description return a div node containing a node value and a node + * label corresponding with the given parameters. + * Returned node have the given class name. + */ + makeNodeText: function(value, label, className) { + var node = Y.Node.create('
    '); + value = (value !== null) ? value : 'undefine'; + if (className) { + node.addClass(className); + } + if (label) { + node.append('' + label + ''); + } + node.append('' + value + ''); + return node; + }, + /** + * @function + * @private + * @param attrs + * @param className + * @return node + * @description return a div node containing an image node. This image + * will have the given attrs parameters as attribute. + * Returned node have the given class name. + */ + makeNodeImage: function(attrs, className) { + var k, node = new Y.Node.create('
    '); + if (className) { + node.one('img').addClass(className); + } + if (typeof attrs !== 'object') { + return node; + } + for (k in attrs) { + node.one('img').setAttribute(k, attrs[k]); + } + return node; + }, + /** + * @function + * @private + * @param value + * @param maxVal + * @param label + * @param className + * @return node + * @description return a div node containing a node label, a node + * containing as many nodes as shown in value and a node shown the + * value and the max value. + * Returned node have the given class name. + */ + makeNodeValueBox: function(value, maxVal, label, className) { + var i, acc = [], node = new Y.Node.create('
    '); + value = (typeof parseInt(value) === 'number') ? parseInt(value) : 0; + maxVal = (maxVal || 'undefine'); + label = (label || 'undefine'); + if (className) { + node.addClass(className); + } + for (i = 0; i < value; i += 1) { + acc.push('
    '); + } + node.append('
    ' + label + '
    '); + node.append('' + acc.join('') + ''); + node.append('(' + value + '/' + maxVal + ')'); + return node; + }, + /** + * @function + * @private + * @param html + * @param selector + * @param value + * @param minVal + * @param invert + * @param className + * @return node + * @description return a div node containing the given html and + * highlight a nodes according to the given values (a number). + * To highlight a node this function count same type node as the + * "selector" parameter (like 'li', 'div', 'p', 'img', etc...). + * The first value depending of the given 'minVal' + * The 'invert' parameter allow to count reversely. + * Returned node have the given class name. + */ + makeNodePosition: function(html, selector, value, minVal, invert, className) { + var node = new Y.Node.create('
    '); + minVal = (typeof parseInt(minVal) === 'number') ? parseInt(minVal) : 0; + value = (typeof parseInt(value) === 'number') ? parseInt(value) - minVal : -1 - minVal; // if value isn't a number, value egal minVal - 1 (and thus never selected) + invert = (invert === 'true' || invert === true) ? true : false; + if (className) { + node.addClass(className); + } + node.append(html); + node.all(selector).each(function(n, i, q) { //n = node, i = iteration, q = number of iterations. + i = (invert) ? (q.size() - 1 - i) : i; + n.setAttribute('data-position', i + minVal); //keep a reference to real number position + if (i < value) { + n.addClass('previous'); + } else if (i === value) { + n.addClass('current'); + } else { + n.addClass('next'); + } + }); + return node; + }, + makeNodeLongText: function(cb, variable, value, className) { + Y.Wegas.Facade.Variable.cache.getWithView(variable, "Extended", {// Retrieve the object from the server in Export view + on: Y.Wegas.superbind({ + success: function(e) { + cb.one("." + className).setContent(e.response.entity.get(value) || "No " + value); + }, + failure: function(e) { + cb.one("." + className).setContent("No " + value); + } + }, this) + }); + } + }); + Y.Wegas.NodeFormatter = NodeFormatter; + +}); diff --git a/pool/shard011/JavaScript/0069803_authSpec.js b/pool/shard011/JavaScript/0069803_authSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..9757f9ebe9765e4a07d88cd98edf9ad6da59cf75 --- /dev/null +++ b/pool/shard011/JavaScript/0069803_authSpec.js @@ -0,0 +1,87 @@ +'use strict' + +var locator = require('node-service-locator'); +var request = require('supertest'); +var q = require('q'); +var app = require('../../../app.js'); +var UserModel = require('../../../models/user'); + +describe('/v1/auth route', function () { + var config; + + beforeEach(function () { + config = locator.get('config'); + locator.register('logger', { + log: function () {}, + trace: function () {}, + debug: function () {}, + info: function () {}, + warn: function () {}, + error: function () {}, + }); + }); + + it('validates email', function (done) { + request(app) + .post('/v1/auth/validate') + .send({ _field: 'email', email: 'foo' }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(function (res) { + expect(res.body.success).toBe(false); + }) + .expect(200, done); + }); + + it('validates password', function (done) { + request(app) + .post('/v1/auth/validate') + .send({ _field: 'password', password: 'foo' }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(function (res) { + expect(res.body.success).toBe(false); + }) + .expect(200, done); + }); + + it('creates token', function (done) { + var searchedEmail, searchedPassword, savedToken; + var foundUser = new UserModel({ id: 42 }); + foundUser.checkPassword = function (password) { + searchedPassword = password; + return true; + }; + + locator.register('user-repository', { + findByEmail: function (email) { + searchedEmail = email; + var defer = q.defer(); + defer.resolve([ foundUser ]); + return defer.promise; + }, + }); + locator.register('token-repository', { + save: function (token) { + savedToken = token; + var defer = q.defer(); + defer.resolve(1); + return defer.promise; + }, + }); + + request(app) + .post('/v1/auth/token') + .send({ email: 'root@example.com', password: 'foobar' }) + .set('Accept', 'application/json') + .expect('Content-Type', /json/) + .expect(function (res) { + expect(searchedEmail).toBe('root@example.com'); + expect(searchedPassword).toBe('foobar'); + expect(res.body.success).toBeTruthy(); + expect(res.body.token.split('.').length).toBe(3); + expect(savedToken.getUserId()).toBe(42); + }) + .expect(200, done); + }); +}); diff --git a/pool/shard011/JavaScript/0069807_panelizer-entity-bundle.js b/pool/shard011/JavaScript/0069807_panelizer-entity-bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..d99df36dd702923bfd35dbee69b2f17325a749de --- /dev/null +++ b/pool/shard011/JavaScript/0069807_panelizer-entity-bundle.js @@ -0,0 +1,34 @@ +/** + * @file + * This JavaScript provides Vertical Tabs integration with Panelizer so that the + * tab displays a summary of what is enabled. + */ +(function ($) { + 'use strict'; + +Drupal.behaviors.panelizerFieldsetSummary = { + attach: function (context) { + $('fieldset.panelizer-entity-bundle', context).drupalSetSummary(function (context) { + // Identify whether Panelizer is enabled. + if ($('input#panelizer-status:checked', context).length === 0) { + return Drupal.t('Not panelized'); + } + + // Indicate which view modes are panelized. + var vals = []; + $('input[name*="view modes"][name*=status]:checked', context).each(function () { + vals.push(Drupal.t("@name: enabled", {'@name' : $(this).attr('title')})); + }); + + // The view modes might not actually be enabled. + if (vals.length === 0) { + return Drupal.t('No view modes enabled'); + } + else { + return vals.join('
    '); + } + }); + } +}; + +})(jQuery); diff --git a/pool/shard011/JavaScript/0069808_search_test.js b/pool/shard011/JavaScript/0069808_search_test.js new file mode 100644 index 0000000000000000000000000000000000000000..faf74e160d39d1f7158fee50940351904ea95710 --- /dev/null +++ b/pool/shard011/JavaScript/0069808_search_test.js @@ -0,0 +1,24 @@ +describe('toLatLngObjects', function() { + + // Arrange + var scope, controller, serviceInstanceService; + + beforeEach(angular.mock.module("mcp.search.services")); + beforeEach(angular.mock.module("mcp.dataservices")); + beforeEach(angular.mock.module("mcp.mapservices")); + beforeEach(angular.mock.module("leaflet-directive")); + + beforeEach(angular.mock.inject(function($rootScope, ServiceInstanceService) { + scope = $rootScope.$new(); + serviceInstanceService = ServiceInstanceService; + })); + + beforeEach(angular.mock.inject(function($controller) { + controller = $controller("SearchServiceMapController", {$scope: scope}); + })); + + it('should have a list of services', function() { + expect(scope.services).to.have.length(serviceInstanceService.query().length); + }); + +}); diff --git a/pool/shard011/JavaScript/0069810_maps_lib.js b/pool/shard011/JavaScript/0069810_maps_lib.js new file mode 100644 index 0000000000000000000000000000000000000000..7e5756df4d6e25ca664ce5ae6003a47d48616123 --- /dev/null +++ b/pool/shard011/JavaScript/0069810_maps_lib.js @@ -0,0 +1,341 @@ +/*! + * TEMPLATE INSTRUCTIONS: Look for sections below marked MODIFY and adjust to fit your data and index.html page + * Learn more at + * Data Visualization book-in-progress by Jack Dougherty at Trinity College CT + * http://epress.trincoll.edu/dataviz + * and + * Searchable Map Template with Google Fusion Tables + * http://derekeder.com/searchable_map_template/ + * + * Copyright 2012, Derek Eder + * Licensed under the MIT license. + * https://github.com/derekeder/FusionTable-Map-Template/wiki/License + * + * Date: 17/03/2014 template modified by Derek Eder and Jack Dougherty + * + */ + +// Enable the visual refresh +google.maps.visualRefresh = true; + +var MapsLib = MapsLib || {}; +var MapsLib = { + + //Setup section - put your Fusion Table details here + //Using the v1 Fusion Tables API. See https://developers.google.com/fusiontables/docs/v1/migration_guide for more info + + //MODIFY the encrypted Table IDs of your Fusion Tables (found under File => About) + //NOTE: numeric IDs will be depricated soon + fusionTableId: "1p3HtGOMZpCYHwwbZPLPGo6rMZ7TO8w_TYA-3wjzg", //Point data layer + + polygon1TableID: "1ceippR4giBiF-pT9PE1YAUvebFp6_NKvYriccYo", //Outline map layer of CT town boundaries + polygon2TableID: "1VopQGBhRKyyk25EIA5ptScvULxR68d43RhZ1ycM", //Thematic map layer of selected CT school districts + + //*MODIFY Fusion Tables Requirement* API key. found at https://code.google.com/apis/console/ + //*Important* this key is for demonstration purposes. please register your own. + googleApiKey: "AIzaSyDIevSvpV-ONb4Pf15VUtwyr_zZa7ccwq4", + + //MODIFY name of the location column in your Fusion Table. + //NOTE: if your location column name has spaces in it, surround it with single quotes + //example: locationColumn: "'my location'", + //if your Fusion Table has two-column lat/lng data, see https://support.google.com/fusiontables/answer/175922 + locationColumn: "Lat", + + map_centroid: new google.maps.LatLng(41.7682,-72.684), //center that your map defaults to + locationScope: "connecticut", //geographical area appended to all address searches + recordName: "result", //for showing number of results + recordNamePlural: "results", + + searchRadius: 805, //in meters ~ 1/2 mile + defaultZoom: 12, //zoom level when map is loaded (bigger is more zoomed in) + addrMarkerImage: 'images/red-pushpin.png', + currentPinpoint: null, + + initialize: function() { + $( "#result_count" ).html(""); + + geocoder = new google.maps.Geocoder(); + var myOptions = { + zoom: MapsLib.defaultZoom, + center: MapsLib.map_centroid, + mapTypeId: google.maps.MapTypeId.ROADMAP, + styles: [ + { + stylers: [ + { saturation: -100 }, // MODIFY Saturation and Lightness if needed + { lightness: 40 } // Current values make thematic polygon shading stand out over base map + ] + } + ] + }; + map = new google.maps.Map($("#map_canvas")[0],myOptions); + + // maintains map centerpoint for responsive design + google.maps.event.addDomListener(map, 'idle', function() { + MapsLib.calculateCenter(); + }); + + google.maps.event.addDomListener(window, 'resize', function() { + map.setCenter(MapsLib.map_centroid); + }); + + MapsLib.searchrecords = null; + + // MODIFY if needed: defines background polygon1 and polygon2 layers + MapsLib.polygon1 = new google.maps.FusionTablesLayer({ + query: { + from: MapsLib.polygon1TableID, + select: "geometry" + }, + styleId: 2, + templateId: 2 + }); + + MapsLib.polygon2 = new google.maps.FusionTablesLayer({ + query: { + from: MapsLib.polygon2TableID, + select: "geometry" + }, + styleId: 2, + templateId: 2 + }); + + //reset filters + $("#search_address").val(MapsLib.convertToPlainString($.address.parameter('address'))); + var loadRadius = MapsLib.convertToPlainString($.address.parameter('radius')); + if (loadRadius != "") $("#search_radius").val(loadRadius); + else $("#search_radius").val(MapsLib.searchRadius); + $(":checkbox").prop("checked", "checked"); + $("#result_box").hide(); + + //-----custom initializers -- default setting to display Polygon1 layer + + $("#rbPolygon1").attr("checked", "checked"); + + //-----end of custom initializers------- + + //run the default search + MapsLib.doSearch(); + }, + + doSearch: function(location) { + MapsLib.clearSearch(); + + // MODIFY if needed: shows background polygon layer depending on which checkbox is selected + if ($("#rbPolygon1").is(':checked')) { + MapsLib.polygon1.setMap(map); + } + else if ($("#rbPolygon2").is(':checked')) { + MapsLib.polygon2.setMap(map); + } + + var address = $("#search_address").val(); + MapsLib.searchRadius = $("#search_radius").val(); + + var whereClause = MapsLib.locationColumn + " not equal to ''"; + + //-----custom filters for point data layer + //---MODIFY column header and values below to match your Google Fusion Table AND index.html + //-- TEXTUAL OPTION to display legend and filter by non-numerical data in your table + var type_column = "'Program Type'"; // -- note use of single & double quotes for two-word column header + var tempWhereClause = []; + if ( $("#cbType1").is(':checked')) tempWhereClause.push("Interdistrict"); + if ( $("#cbType2").is(':checked')) tempWhereClause.push("District"); + if ( $("#cbType3").is(':checked')) tempWhereClause.push("MorePreK"); + whereClause += " AND " + type_column + " IN ('" + tempWhereClause.join("','") + "')"; + + //-- NUMERICAL OPTION - to display and filter a column of numerical data in your table, use this instead + /* var type_column = "'TypeNum'"; + var searchType = type_column + " IN (-1,"; + if ( $("#cbType1").is(':checked')) searchType += "1,"; + if ( $("#cbType2").is(':checked')) searchType += "2,"; + if ( $("#cbType3").is(':checked')) searchType += "3,"; + if ( $("#cbType4").is(':checked')) searchType += "4,"; + if ( $("#cbType5").is(':checked')) searchType += "5,"; + whereClause += " AND " + searchType.slice(0, searchType.length - 1) + ")";*/ + //-------end of custom filters-------- + + if (address != "") { + if (address.toLowerCase().indexOf(MapsLib.locationScope) == -1) + address = address + " " + MapsLib.locationScope; + + geocoder.geocode( { 'address': address}, function(results, status) { + if (status == google.maps.GeocoderStatus.OK) { + MapsLib.currentPinpoint = results[0].geometry.location; + + $.address.parameter('address', encodeURIComponent(address)); + $.address.parameter('radius', encodeURIComponent(MapsLib.searchRadius)); + map.setCenter(MapsLib.currentPinpoint); + map.setZoom(14); + + MapsLib.addrMarker = new google.maps.Marker({ + position: MapsLib.currentPinpoint, + map: map, + icon: MapsLib.addrMarkerImage, + animation: google.maps.Animation.DROP, + title:address + }); + + whereClause += " AND ST_INTERSECTS(" + MapsLib.locationColumn + ", CIRCLE(LATLNG" + MapsLib.currentPinpoint.toString() + "," + MapsLib.searchRadius + "))"; + + MapsLib.drawSearchRadiusCircle(MapsLib.currentPinpoint); + MapsLib.submitSearch(whereClause, map, MapsLib.currentPinpoint); + } + else { + alert("We could not find your address: " + status); + } + }); + } + else { //search without geocoding callback + MapsLib.submitSearch(whereClause, map); + } + }, + + submitSearch: function(whereClause, map, location) { + //get using all filters + //NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows + //you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables + //for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles + + MapsLib.searchrecords = new google.maps.FusionTablesLayer({ + query: { + from: MapsLib.fusionTableId, + select: MapsLib.locationColumn, + where: whereClause + }, + styleId: 2, + templateId: 2 + }); + MapsLib.searchrecords.setMap(map); + MapsLib.getCount(whereClause); + }, + // MODIFY if you change the number of Polygon layers + clearSearch: function() { + if (MapsLib.searchrecords != null) + MapsLib.searchrecords.setMap(null); + if (MapsLib.polygon1 != null) + MapsLib.polygon1.setMap(null); + if (MapsLib.polygon2 != null) + MapsLib.polygon2.setMap(null); + if (MapsLib.addrMarker != null) + MapsLib.addrMarker.setMap(null); + if (MapsLib.searchRadiusCircle != null) + MapsLib.searchRadiusCircle.setMap(null); + }, + + findMe: function() { + // Try W3C Geolocation (Preferred) + var foundLocation; + + if(navigator.geolocation) { + navigator.geolocation.getCurrentPosition(function(position) { + foundLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude); + MapsLib.addrFromLatLng(foundLocation); + }, null); + } + else { + alert("Sorry, we could not find your location."); + } + }, + + addrFromLatLng: function(latLngPoint) { + geocoder.geocode({'latLng': latLngPoint}, function(results, status) { + if (status == google.maps.GeocoderStatus.OK) { + if (results[1]) { + $('#search_address').val(results[1].formatted_address); + $('.hint').focus(); + MapsLib.doSearch(); + } + } else { + alert("Geocoder failed due to: " + status); + } + }); + }, + + drawSearchRadiusCircle: function(point) { + var circleOptions = { + strokeColor: "#4b58a6", + strokeOpacity: 0.3, + strokeWeight: 1, + fillColor: "#4b58a6", + fillOpacity: 0.05, + map: map, + center: point, + clickable: false, + zIndex: -1, + radius: parseInt(MapsLib.searchRadius) + }; + MapsLib.searchRadiusCircle = new google.maps.Circle(circleOptions); + }, + + query: function(selectColumns, whereClause, callback) { + var queryStr = []; + queryStr.push("SELECT " + selectColumns); + queryStr.push(" FROM " + MapsLib.fusionTableId); + queryStr.push(" WHERE " + whereClause); + + var sql = encodeURIComponent(queryStr.join(" ")); + $.ajax({url: "https://www.googleapis.com/fusiontables/v1/query?sql="+sql+"&callback="+callback+"&key="+MapsLib.googleApiKey, dataType: "jsonp"}); + }, + + handleError: function(json) { + if (json["error"] != undefined) { + var error = json["error"]["errors"] + console.log("Error in Fusion Table call!"); + for (var row in error) { + console.log(" Domain: " + error[row]["domain"]); + console.log(" Reason: " + error[row]["reason"]); + console.log(" Message: " + error[row]["message"]); + } + } + }, + + getCount: function(whereClause) { + var selectColumns = "Count()"; + MapsLib.query(selectColumns, whereClause,"MapsLib.displaySearchCount"); + }, + + displaySearchCount: function(json) { + MapsLib.handleError(json); + var numRows = 0; + if (json["rows"] != null) + numRows = json["rows"][0]; + + var name = MapsLib.recordNamePlural; + if (numRows == 1) + name = MapsLib.recordName; + $( "#result_box" ).fadeOut(function() { + $( "#result_count" ).html(MapsLib.addCommas(numRows) + " " + name + " found"); + }); + $( "#result_box" ).fadeIn(); + }, + + addCommas: function(nStr) { + nStr += ''; + x = nStr.split('.'); + x1 = x[0]; + x2 = x.length > 1 ? '.' + x[1] : ''; + var rgx = /(\d+)(\d{3})/; + while (rgx.test(x1)) { + x1 = x1.replace(rgx, '$1' + ',' + '$2'); + } + return x1 + x2; + }, + + // maintains map centerpoint for responsive design + calculateCenter: function() { + center = map.getCenter(); + }, + + //converts a slug or query string in to readable text + convertToPlainString: function(text) { + if (text == undefined) return ''; + return decodeURIComponent(text); + } + + //-----custom functions------- + // NOTE: if you add custom functions, make sure to append each one with a comma, except for the last one. + // This also applies to the convertToPlainString function above + + //-----end of custom functions------- +} diff --git a/pool/shard011/JavaScript/0069811_event_almacen_traslado.js b/pool/shard011/JavaScript/0069811_event_almacen_traslado.js new file mode 100644 index 0000000000000000000000000000000000000000..4fa23ada5ff21ae2b431c3054742777eeb6bd24e --- /dev/null +++ b/pool/shard011/JavaScript/0069811_event_almacen_traslado.js @@ -0,0 +1,250 @@ +var win; + +Ext.onReady(function(){ +$("input[name='totalizar_monto_efectivo'], input[name='totalizar_monto_cheque'], input[name='totalizar_nro_cheque'], input[name='totalizar_monto_tarjeta'], input[name='totalizar_nro_tarjeta'],input[name='totalizar_monto_deposito'], input[name='totalizar_nro_deposito'],input[name='totalizar_nro_otrodocumento'],input[name='totalizar_monto_otrodocumento']").numeric(); + +$.setValoresInput = function(nombreObjetoDestino,nombreObjetoActual){ + $(nombreObjetoDestino).attr("value", $(nombreObjetoActual).val()); +} + +$.inputHidden = function(Input,Value,ID){ + return ''; +} + + +$("img.eliminar").live("click",function(){ + $(this).parents("tr").fadeOut("normal",function(){ + $(this).remove(); + eventos_form.CargarDisplayMontos(); + }); +}); + +$("#items").change(function(){ + //LabelCantidadExistente + codAlmacen = $("select[name='almacen_salida']").val(); + alert(codAlmacen) + alert($(this).val()) + if($(this).val()!=''){ + $.ajax({ + + type: "GET", + url: "../../libs/php/ajax/ajax.php", + data: "opt=verificarExistenciaItemByAlmacen&v1="+codAlmacen+"&v2="+$(this).val(), + beforeSend: function(){ + // $("#descripcion_item").html(MensajeEspera("Veficando Cod. item..")); + }, + success: function(data){ + resultado = eval(data) + if(resultado[0].id=="-1"){ + alert("Verifique existencia de producto seleccionado") + }else{ + $("#cantidad_existente").val(resultado[0].cantidad); + } + } + + }); + } + + }); + + +$(".info_detalle").live("click", function(){ + cod = $(this).parent('tr').find("a[rel*=facebox]").text(); + var mask = new Ext.LoadMask(Ext.get("Contenido"), {msg:'Cargando..',removeMask:false}); + $.ajax({ + type: 'GET', + data: 'cod='+cod, + url: 'info_servicio_item.php', + beforeSend: function(){ + mask.show(); + }, + success: function(data){ + var win_tmp = new Ext.Window({ + title:'Detalle del Producto', + height: 400, + width: 350, + frame:true, + autoScroll:true, + modal:true, + html: data, + buttons:[{ + text:'Cerrar', + handler:function(){ + win_tmp.hide(); + } + }] + }); + + win_tmp.show(this); + mask.hide(); + } + }); +}); + + win = new Ext.Window({ + title:'Seleccionar Producto', + height:360, + width:459, + autoScroll:true, + tbar:[ + { + text:'Actualizar lista de Productos', + icon: '../../libs/imagenes/ico_search.gif', + handler: function(){ + eventos_form.cargarProducto(); + } + }, + { + text:'Actualizar lista de Almacenes', + icon: '../../libs/imagenes/ico_search.gif', + handler: function(){ + eventos_form.cargarAlmacenes(); + eventos_form.cargarAlmacenesEntrada(); + } + }, + { + text:'Limpiar', + icon: '../../libs/imagenes/back.gif', + handler: function(){ + eventos_form.Limpiar(); + } + } + ], + modal:true, + bodyStyle:'padding-right:10px;padding-left:10px;padding-top:5px;', + closeAction:'hide', + contentEl:'incluirproducto', + buttons:[ + { + text:'Incluir', + icon: '../../libs/imagenes/drop-add.gif', + handler:function(){ + + if($("#items").val()==""||$("#almacen_salida").val()==""||$("#almacen_entrada").val()==""||$("#cantidadunitaria").val()==""){ + Ext.Msg.alert("Alerta","Debe especificar todos los campos."); + return false; + } + //alert($("#cantidadunitaria").val()) + //alert($("#cantidad_existente").val()) + if(($("#cantidadunitaria").val())>($("#cantidad_existente").val())){ + Ext.Msg.alert("Alerta","XLa cantidad a descargar no puede ser mayor a la existente"); + return false; + } + + eventos_form.IncluirRegistros({ + id_item: $("#items").val(), + descripcion: $("#items :selected").text(), + id_almacen: $("#almacen").val(), + cantidad: $("#cantidadunitaria").val(), + }); + + } + }, + { + text:'Cerrar', + icon: '../../libs/imagenes/cancel.gif', + handler:function(){ + win.hide(); + } + }, + ] + }); + + + var formpanel = new Ext.Panel({ + title:'Datos del Proveedor', + autoHeight: 300, + width: '100%', + + collapsible: true, + titleCollapse: true , + contentEl:'dp', + frame:true + }); + + + formpanel_dcompra = new Ext.Panel({ + title:'Información del Cargo', + autoHeight: 300, + width: '100%', + collapsible: true, + titleCollapse: true , + contentEl:'dcompra', + frame:true + }); + + var tab = new Ext.TabPanel({ + frame:true, + contentEl:'PanelGeneralCompra', + activeTab:0, + height:300, + items:[ + { + title:'Productos', + contentEl:'tabproducto', + + autoScroll:true, + tbar: [ + { + text:'Agregar Producto', + icon: '../../libs/imagenes/add.gif', + handler: function(){ + eventos_form.init() + win.show(); + } + }, + { + xtype:'label', + contentEl: 'displaytotal', + fn: eventos_form.CargarDisplayMontos() + } + + ] + + }, + { + title:'Registrar Movimiento', + contentEl:'tabpago', + + autoScroll:true, + + tbar: [ + { + text:'Registrar Descarga', + icon: '../../libs/imagenes/back.gif', + iconAlign: 'left', + height: 20, + handler: function(){ + eventos_form.GenerarCompraX(); + } + }, + { + xtype:'label', + contentEl: 'displaytotal2', + fn: eventos_form.CargarDisplayMontos() + } + + ] + + } + ] + }); + + + + formpanel.render("formulario"); + formpanel_dcompra.render("formulario"); + tab.render("formulario"); + + + + + + + + + +}); + + + diff --git a/pool/shard011/JavaScript/0069814_DetailPage.js b/pool/shard011/JavaScript/0069814_DetailPage.js new file mode 100644 index 0000000000000000000000000000000000000000..886a91860845b843de3212f5166d47722595fdb0 --- /dev/null +++ b/pool/shard011/JavaScript/0069814_DetailPage.js @@ -0,0 +1,154 @@ + +import React, { Component } from 'react'; +import { + StyleSheet,ScrollView,Text, Image, + DrawerLayoutAndroid,ToolbarAndroid,ToastAndroid,TouchableNativeFeedback, + Dimensions, Platform, View +} from 'react-native'; + +var DataSource = require('./DataSource'); +var source=new DataSource(); + +export default class DetailPage extends Component { + constructor(props) { + super(props); + this.state = { + isLoading: false, + movie: this.props.movie, + detail:null + }; + this.onBackButton=this.onBackButton.bind(this); + } + + componentDidMount() { + this.setState({ + isLoading: true, + }); + this.loadMovieData(this.state.movie.id); + } + + loadMovieData(movieId){ + source.getMovieDetail(movieId).then( + (responseData)=>{ + this.setState({ + detail:responseData, + isLoading: false + }); + } + ); + } + + render() { + return ( + this.renderDetail() + ); + } + + renderDetail(){ + return( + + + + + + + + + + + + + {this.props.movie.title} + {this.props.movie.rating.average}分 + ({this.props.movie.rating.stars}人评分) + 类型:{this.props.movie.genres.join(" ")} + 演员:{this.arrayToString(this.props.movie.casts)} + + + 简介 + {this.state.detail?this.state.detail.summary:"loading"} + + + ); + } + + arrayToString(obj) { + let actors =[]; + for(var i in obj){ + actors.push(obj[i]['name']); + } + return actors.join(' '); + } + + onBackButton() { + if (this.props.navigator) { + this.props.navigator.pop(); + } + } +} + +const styles = StyleSheet.create({ + detailContainer: { + flex: 1, + backgroundColor: 'white', + }, + detailImageBox: { + flex: 1, + flexDirection: 'row', + backgroundColor: '#30925C', + }, + detailImage: { + height: 160, + width: 112, + marginLeft:20, + marginTop: 15, + marginBottom: 15, + }, + detailTitleBox:{ + flex:1, + marginLeft: 15, + marginRight: 20, + }, + detailTitle: { + fontSize: 16, + marginTop: 15, + color:'#fff' + }, + detailList:{ + color: '#ddd', + fontSize: 12, + marginTop:10, + }, + detailSummaryTitle: { + color: '#333', + fontSize: 14, + marginTop: 10, + marginLeft: 20, + }, + detailSummaryContent: { + color: '#666', + fontSize: 12, + marginTop: 10, + marginLeft: 20, + marginRight: 20, + }, + container: { + flex: 1, + backgroundColor: '#FAFAFA', + }, + toolbar: { + backgroundColor: '#30925C', + height: 36, + }, + backButton: { + width: 32, + height: 32, + marginLeft: 10, + marginTop:2, + }, + +}); diff --git a/pool/shard011/JavaScript/0069815_SerGarlanTyrell.js b/pool/shard011/JavaScript/0069815_SerGarlanTyrell.js new file mode 100644 index 0000000000000000000000000000000000000000..8d03cbd82db2bb7f67c3a8bbd84679d083f469bf --- /dev/null +++ b/pool/shard011/JavaScript/0069815_SerGarlanTyrell.js @@ -0,0 +1,30 @@ +const DrawCard = require('../../drawcard.js'); + +class SerGarlanTyrell extends DrawCard { + setupCardAbilities(ability) { + this.persistentEffect({ + match: this, + effect: ability.effects.dynamicStrength(() => this.tokens['gold']) + }); + + this.action({ + title: 'Give character +2 STR', + cost: ability.costs.discardGold(), + target: { + cardCondition: card => card.location === 'play area' && card.isFaction('tyrell') && card.getType() === 'character' + }, + handler: context => { + this.untilEndOfPhase(ability => ({ + match: context.target, + effect: ability.effects.modifyStrength(2) + })); + this.game.addMessage('{0} discards 1 gold from {1} to give {2} +2 STR until the end of the phase', + this.controller, this, context.target); + } + }); + } +} + +SerGarlanTyrell.code = '06083'; + +module.exports = SerGarlanTyrell; diff --git a/pool/shard011/JavaScript/0069821_responses.js b/pool/shard011/JavaScript/0069821_responses.js new file mode 100644 index 0000000000000000000000000000000000000000..ad800a1a049ad56475a39a552c38c2921ee96500 --- /dev/null +++ b/pool/shard011/JavaScript/0069821_responses.js @@ -0,0 +1,10 @@ +module.exports.sendBadRequest = function sendBadRequest(res, msg) { + res.status(400); + res.end(msg); +}; + +module.exports.sendError = function sendError(res, msg) { + res.status(500); + res.set('Content-Type', 'text/html'); + res.end(msg); +}; diff --git a/pool/shard011/JavaScript/0069827_map.js b/pool/shard011/JavaScript/0069827_map.js new file mode 100644 index 0000000000000000000000000000000000000000..8e200dfaa4fb3e0111e860ddc49633824b6cdf7d --- /dev/null +++ b/pool/shard011/JavaScript/0069827_map.js @@ -0,0 +1,239 @@ +var size = 500; + +var mapProjection; + +var map, ocean, graticule, countries; + +var isGlobe = true; + +var rotateX = 0; + +var path; +var rotation; + +window.onresize = function () { + size = window.innerWidth / 2; + var scale = size / 500; + d3.select("svg").attr("width", size * 2).attr("height", size + 10).style("width", size * 2 + "px").style("height", size * 2 + "px"); + d3.select("#map").attr("transform","scale(" + scale + ")"); +}; + +var mapFeatures, chapterFeatures;; +d3.json( "countries.json", function( json ) +{ + d3.json( "chapters.json", function( chapters ){ + chapterFeatures = chapters.features; + mapFeatures = topojson.feature(json,json.objects.countries).features; + build_map(); + }) +}); + +var colorScale = d3.scale.linear() + .domain([-180, -120, -60, 0, 60, 120, 180]) + .range(['#1b9e77', '#d95f02', '#7570b3', '#e7298a', '#66a61e', '#e6ab02', '#1b9e77']); + +var pastelScale = d3.scale.linear() + .domain([-180, -120, -60, 0, 60, 120, 180]) + .range(['#fbb4ae', '#b3cde3', '#ccebc5', '#decbe4', '#fed9a6', '#ffffcc', '#fbb4ae']); + +function build_map() +{ + mapProjection = d3.geo.orthographic() + .scale( size / 2 ) + .translate( [ size, size / 1.5] ) + .clipAngle( 90 ) + .rotate([0,-15]); + + map = d3.select( "body" ) + .append( "svg:svg" ) + .attr( "width", size*2 + "px" ) + .attr( "height", size * 2 + "px" ) + .style("width", size * 2 + "px").style("height", size * 2 + "px") + .append( "g" ) + .attr( "id", "map" ); + + path = d3.geo.path() + .projection( mapProjection ); + + var filter = map.append( "svg:defs" ) + .append( "svg:filter" ).attr( "id", "blur" ) + .append( "svg:feGaussianBlur" ).attr( "stdDeviation", 3 ); + + var gradient = map.select("defs") + .append( "svg:radialGradient" ).attr( "id", "gradient" ); + gradient.append( "stop" ).attr( { "offset" : "0%", "stop-color" : "black", "stop-opacity" : 0 } ); + gradient.append( "stop" ).attr( { "offset" : "50%", "stop-color" : "black", "stop-opacity" : 0 } ); + gradient.append( "stop" ).attr( { "offset" : "60%", "stop-color" : "black", "stop-opacity" : 0.05 } ); + gradient.append( "stop" ).attr( { "offset" : "70%", "stop-color" : "black", "stop-opacity" : 0.15 } ); + gradient.append( "stop" ).attr( { "offset" : "100%", "stop-color" : "black", "stop-opacity" : 1 } ); + + map.append( "svg:ellipse" ).attr({ + "cx" : size, + "cy" : size / 1.5, + "rx" : size / 2, + "ry" : size / 2, + "fill" : "#bdd7e7", + "stroke" : "black", + "stroke-width" : "1px", + "filter" : "url(#blur)", + "id" : "map-bg" + }); + + ocean = map.append("svg:g") + .attr("id","ocean") + .attr("class","layer"); + + graticule = map.append("svg:g") + .attr("id","graticule") + .attr("class","layer"); + + countries = map.append( "svg:g" ) + .attr( "id", "countries" ) + .attr("class","layer"); + + chapters = map.append( "svg:g" ) + .attr( "id", "chapters" ) + .attr("class","layer"); + + + var oceanData = []; + + for ( var lat = -90; lat < 90; lat+= 45 ){ + for ( var lon = -180; lon < 180; lon += 45 ){ + var coords = [[[lon,lat],[lon+45,lat],[lon+45,lat+45],[lon,lat+45],[lon,lat]]]; + oceanData.push( {"type":"Feature",area:["ocean"],"properties":{area:["ocean"]},"geometry":{"type":"Polygon","coordinates":coords}} ) + } + } + + ocean.selectAll("path") + .data(oceanData) + .enter() + .append("path") + .attr("vector-effect","non-scaling-stroke") + .attr("class","ocean") + .attr("d",path); + + graticule.selectAll("path") + .data( d3.geo.graticule().step([20,20]).lines() ) + .enter() + .append("path") + .attr("vector-effect","non-scaling-stroke") + .attr("d",path) + .attr("pointer-events","none"); + + countries.selectAll( "path" ) + .data( mapFeatures ) + .enter() + .append( "svg:path" ) + .attr("vector-effect","non-scaling-stroke") + .attr("fill", function(){ + return pastelScale( Math.random() * 360 - 180 ); + }) + .attr( "d", path ); + + chapters.selectAll( "image" ) + .data( chapterFeatures ) + .enter() + .append( "svg:image" ) + .attr("xlink:href","rainbowrat.png") + .attr( "x", function(d){ + return mapProjection( d.geometry.coordinates )[0] - 30; + }) + .attr( "y", function(d){ + return mapProjection( d.geometry.coordinates )[1] - 25; + }) + .attr("width",60) + .attr("height",50) + .style("display",function(d){ + return path(d) ? "block" : "none"; + }); + + map.append( "svg:circle" ).attr({ + "cx" : size, + "cy" : size / 1.5, + "r" : size / 2, + "fill" : "url(#gradient)", + "fill-opacity" : 0.2, + "id" : "shadow", + "pointer-events": "none" + }); + + map.append( "svg:path" ).attr({ + "d" : "M801,333 a302,302 0 1,1 0,-1", + "id" : "title-path", + "pointer-events": "none" + }); + + map.append( "text" ) + .attr( "id","title-text" ) + .append( "textPath" ) + .attr( "xlink:href", "#title-path" ) + .text( "#ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap #ratmap" ); + + window.onresize(); + + startRotation(); + + return countries; +} + +function pauseRotation(){ + clearInterval(rotation); +} +function startRotation(){ + rotation = setInterval(function(){ + rotateX += .5; + if ( rotateX >= 180 ) rotateX -= 360; + var y = mapProjection.rotate()[1]; + move_globe( [rotateX,rotateX*2] ); + map.select( "#title-path" ).attr( "transform", "rotate(" + rotateX + ",500,333.33333)" ); + map.select( "#title-text" ).attr( "fill", colorScale(rotateX) ); + countries.selectAll("path") + .attr( "fill", pastelScale(rotateX) ); + },50); +} + +function move_globe( coords, animate, end ) +{ + if( animate ) + { + coords[ 1 ] = coords[ 1 ] > 30 ? 30 : + coords[ 1 ] < -30 ? -30 : + coords[ 1 ]; + + d3.transition() + .duration( 500 ) + .tween( "rotate", function() + { + var r = d3.interpolate( mapProjection.rotate(), coords ); + return function( t ) + { + mapProjection.rotate( r( t ) ); + d3.selectAll( "#map .layer path" ).attr("d", function(d) { return path(d) || "M0 0"; }); + chapters.selectAll("image") + .attr( "x", function(d){ + return mapProjection( d.geometry.coordinates )[0] - 30; + }) + .attr( "y", function(d){ + return mapProjection( d.geometry.coordinates )[1] - 25; + }) + }; + }) + .each( "end", end || function(){} ); // Function to run at the end of the animation + } + else + { + mapProjection.rotate( coords ); + d3.selectAll( "#map .layer path" ).attr("d", function(d) { return path(d) || "M0 0"; }); + chapters.selectAll("image") + .attr( "x", function(d){ + return mapProjection( d.geometry.coordinates )[0] - 30; + }) + .attr( "y", function(d){ + return mapProjection( d.geometry.coordinates )[1] - 25; + }) + .style("display",function(d){ + return path(d) ? "block" : "none"; + }); + } +} diff --git a/pool/shard011/JavaScript/0069830_cfg.js b/pool/shard011/JavaScript/0069830_cfg.js new file mode 100644 index 0000000000000000000000000000000000000000..bf0e795da2db33419230dd659cc7d72d5ae43b03 --- /dev/null +++ b/pool/shard011/JavaScript/0069830_cfg.js @@ -0,0 +1,47 @@ +const { existsSync, readFileSync } = require('fs'); +const { dirname, resolve } = require('path'); + +const resolveMain = require('./resolve-main'); + +const defaultConfig = { + clear: false, + debounce: 10, + dedupe: false, + deps: 1, + extensions: { + coffee: 'coffeescript/register', + ls: 'LiveScript', + ts: 'ts-node/register' + }, + fork: true, + graceful_ipc: '', + ignore: [], + interval: 1000, + notify: true, + poll: false, + respawn: false, + timestamp: 'HH:MM:ss', + vm: true +}; + +function read(dir) { + const f = resolve(dir, '.node-dev.json'); + return existsSync(f) ? JSON.parse(readFileSync(f)) : {}; +} + +function getConfig(script) { + const main = resolveMain(script); + const dir = main ? dirname(main) : '.'; + + return Object.assign( + defaultConfig, + read(process.env.HOME || process.env.USERPROFILE), + read(process.cwd()), + read(dir) + ); +} + +module.exports = { + defaultConfig, + getConfig +}; diff --git a/pool/shard011/JavaScript/0069832_passport.js b/pool/shard011/JavaScript/0069832_passport.js new file mode 100644 index 0000000000000000000000000000000000000000..9f8617795a4bf9a7b170222a5452341d71f46c87 --- /dev/null +++ b/pool/shard011/JavaScript/0069832_passport.js @@ -0,0 +1,95 @@ +var FacebookTokenStrategy = require('passport-facebook-token'); +var authConfig = require('./authkeys.js'); +//=== bring in teacher and Teacher dbs === +var Student = require('../students/studentsModel.js'); +var Teacher = require('../teachers/teachersModel.js'); +var Q = require('q'); + + + +module.exports = function(passport) { + console.log("**** INSIDE OF PASSPORT ***") + + passport.use(new FacebookTokenStrategy({ + clientID : process.env.ClientID || authConfig.facebookAuth.clientID, + clientSecret : process.env.ClientSecret || authConfig.facebookAuth.clientSecret, + passReqToCallback: true + }, function(req, accessToken, refereshToken, profile, done) { + /* + USER ROLE IS PASSED IN FROM THE FRONTEND INSIDE THE HEADER + req.headers.user_role = 'teacher' or 'student' + ------- + we grabe basic user information from their facebook profile, which is passed in + in the passport callback + */ + var name = profile.displayName; + var fbPicture = profile.photos[0].value; + var email = profile.emails[0].value; + + console.log("----------- USER DATA : -----------------"); + console.log('USER EMAIL ' + email); + console.log('USER ROLE ' + req.headers.user_role); + console.log('USER NAME ' + name); + console.log("----------------------------------------"); + + if(req.headers.user_role === "student"){ + /* + will refactor to not use Q + */ + console.log("-----------------------CREATING STUDENT ---------------------------"); + var findOne = Q.nbind(Student.findOne, Student); + findOne({email: email}) + .then(function(user) { + if (user) { + return user; + } else { + console.log("---------------- NO STUDENT FOUND, CREATING STUDENT -------------"); + var create = Q.nbind(Student.create, Student); + var newStudent = { + name: name, + fbToken: accessToken, + email: email, + fbPicture : fbPicture + }; + return create(newStudent); + } + }) + .then(function (user) { + console.log("----- CREATED NEW STUDENT , THE STUDENT IS" + user); + return done(null, user); + }) + .fail(function (error) { + console.log("******* ERROR ******"); + }); + }else if(req.headers.user_role === "teacher"){ + console.log("-----------------------CREATING TEACHER ---------------------------"); + console.log(email); + var findOne = Q.nbind(Teacher.findOne, Teacher); + findOne({email: email}) + .then(function(user) { + if (user) { + return user; + } else { + // create a Teacher + console.log("---------------- NO TEACHER FOUND, CREATING TEACHER -------------"); + var create = Q.nbind(Teacher.create, Teacher); + var newTeacher = { + name: name, + fbToken: accessToken, + email: email, + fbPicture : fbPicture + }; + return create(newTeacher); + } + }) + .then(function (user) { + console.log("----- CREATED NEW TEACHER , THE TEACHER IS" + user); + return done(null, user); + }) + .fail(function (error) { + console.log("******* ERROR ******"); + }); + } + } + )); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069833_benchmark.ndarray.native.js b/pool/shard011/JavaScript/0069833_benchmark.ndarray.native.js new file mode 100644 index 0000000000000000000000000000000000000000..ce49406bdd4d0c05c7315867093bee165c324efb --- /dev/null +++ b/pool/shard011/JavaScript/0069833_benchmark.ndarray.native.js @@ -0,0 +1,114 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +'use strict'; + +// MODULES // + +var resolve = require( 'path' ).resolve; +var bench = require( '@stdlib/bench' ); +var uniform = require( '@stdlib/random/base/uniform' ).factory; +var isnanf = require( '@stdlib/math/base/assert/is-nanf' ); +var pow = require( '@stdlib/math/base/special/pow' ); +var Float32Array = require( '@stdlib/array/float32' ); +var tryRequire = require( '@stdlib/utils/try-require' ); +var pkg = require( './../package.json' ).name; + + +// VARIABLES // + +var sdeg2rad = tryRequire( resolve( __dirname, './../lib/ndarray.native.js' ) ); +var opts = { + 'skip': ( sdeg2rad instanceof Error ) +}; +var rand = uniform( -180.0, 180.0 ); + + +// FUNCTIONS // + +/** +* Creates a benchmark function. +* +* @private +* @param {PositiveInteger} len - array length +* @returns {Function} benchmark function +*/ +function createBenchmark( len ) { + var x; + var y; + var i; + + x = new Float32Array( len ); + y = new Float32Array( len ); + for ( i = 0; i < x.length; i++ ) { + x[ i ] = rand(); + } + return benchmark; + + /** + * Benchmark function. + * + * @private + * @param {Benchmark} b - benchmark instance + */ + function benchmark( b ) { + var z; + var i; + + b.tic(); + for ( i = 0; i < b.iterations; i++ ) { + z = sdeg2rad( x.length, x, 1, 0, y, 1, 0 ); + if ( isnanf( z[ i%len ] ) ) { + b.fail( 'should not return NaN' ); + } + } + b.toc(); + if ( isnanf( z[ i%len ] ) ) { + b.fail( 'should not return NaN' ); + } + b.pass( 'benchmark finished' ); + b.end(); + } +} + + +// MAIN // + +/** +* Main execution sequence. +* +* @private +*/ +function main() { + var len; + var min; + var max; + var f; + var i; + + min = 1; // 10^min + max = 6; // 10^max + + for ( i = min; i <= max; i++ ) { + len = pow( 10, i ); + f = createBenchmark( len ); + bench( pkg+'::native:ndarray:len='+len, opts, f ); + } +} + +main(); diff --git a/pool/shard011/JavaScript/0069840_message.server.model.js b/pool/shard011/JavaScript/0069840_message.server.model.js new file mode 100644 index 0000000000000000000000000000000000000000..20422dca206d47cf9f312106a79f7acf18a0275f --- /dev/null +++ b/pool/shard011/JavaScript/0069840_message.server.model.js @@ -0,0 +1,45 @@ +'use strict'; + +/** + * Module dependencies. + */ +var mongoose = require('mongoose'), + //User = mongoose.model('User'), + Schema = mongoose.Schema; + +/** + * Message Schema + */ +var MessageSchema = new Schema({ + netid: { + type: String, + trim: true, + required: true + }, + message: { + type: String, + required: true + }, + urgency: { + type: String, + enum: ['Information', 'Notification', 'Requirement'], + required: true + }, + created:{ + type: Date, + default: Date.now() + } +}); + +MessageSchema.pre('save', function(next) { + this.netid = this.netid.toLowerCase(); + next(); +}); + +//MessageSchema.post('save', function(message){ +// User.findOne({username : message.netid}, function(err, user){ +// if(!err && message) user.messages.push(message._id); +// }) +//}); + +mongoose.model('Message', MessageSchema); diff --git a/pool/shard011/JavaScript/0069841_webform.form.tabs.js b/pool/shard011/JavaScript/0069841_webform.form.tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..63b34fd20da867d31c1c51c22dfb441ed329b763 --- /dev/null +++ b/pool/shard011/JavaScript/0069841_webform.form.tabs.js @@ -0,0 +1,54 @@ +/** + * @file + * JavaScript behaviors for form tabs using jQuery UI. + */ + +(function ($, Drupal) { + + 'use strict'; + + // @see http://api.jqueryui.com/tabs/ + Drupal.webform = Drupal.webform || {}; + Drupal.webform.formTabs = Drupal.webform.formTabs || {}; + Drupal.webform.formTabs.options = Drupal.webform.formTabs.options || { + hide: true, + show: true + }; + + /** + * Initialize webform tabs. + * + * @type {Drupal~behavior} + * + * @prop {Drupal~behaviorAttach} attach + * Attaches the behavior for form tabs using jQuery UI. + * + * @see \Drupal\webform\Utility\WebformFormHelper::buildTabs + */ + Drupal.behaviors.webformFormTabs = { + attach: function (context) { + // Set active tab and clear the location hash once it is set. + if (location.hash) { + var active = $('a[href="' + location.hash + '"]').data('tab-index'); + if (active !== undefined) { + Drupal.webform.formTabs.options.active = active; + location.hash = ''; + } + } + + $(context).find('div.webform-tabs').once('webform-tabs').each(function() { + var $tabs = $(this); + var options = jQuery.extend({}, Drupal.webform.formTabs.options); + + // Set active tab from data-tab-active attribute. + var tab_name = $tabs.attr('data-tab-active'); + if (tab_name) { + options.active = $('a[href="#' + tab_name + '"]').data('tab-index'); + } + + $tabs.tabs(options); + }) + } + }; + +})(jQuery, Drupal); diff --git a/pool/shard011/JavaScript/0069842_PosAnimation.js b/pool/shard011/JavaScript/0069842_PosAnimation.js new file mode 100644 index 0000000000000000000000000000000000000000..a3ee932ce55843edc8468add992e53315b4ab78a --- /dev/null +++ b/pool/shard011/JavaScript/0069842_PosAnimation.js @@ -0,0 +1,98 @@ +/* + * L.PosAnimation is used by Leaflet internally for pan animations. + */ + +L.PosAnimation = L.Evented.extend({ + + run: function (el, newPos, duration, easeLinearity) { // (HTMLElement, Point[, Number, Number]) + this.stop(); + + this._el = el; + this._inProgress = true; + this._newPos = newPos; + + this.fire('start'); + + el.style[L.DomUtil.TRANSITION] = 'all ' + (duration || 0.25) + + 's cubic-bezier(0,0,' + (easeLinearity || 0.5) + ',1)'; + + L.DomEvent.on(el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); + L.DomUtil.setPosition(el, newPos); + + // toggle reflow, Chrome flickers for some reason if you don't do this + L.Util.falseFn(el.offsetWidth); + + // there's no native way to track value updates of transitioned properties, so we imitate this + this._stepTimer = setInterval(L.bind(this._onStep, this), 50); + }, + + stop: function () { + if (!this._inProgress) { return; } + + // if we just removed the transition property, the element would jump to its final position, + // so we need to make it stay at the current position + + // Only setPosition if _getPos actually returns a valid position. + this._newPos = this._getPos(); + if (this._newPos) { + L.DomUtil.setPosition(this._el, this._newPos); + } + + this._onTransitionEnd(); + L.Util.falseFn(this._el.offsetWidth); // force reflow in case we are about to start a new animation + }, + + _onStep: function () { + var stepPos = this._getPos(); + if (!stepPos) { + this._onTransitionEnd(); + return; + } + // jshint camelcase: false + // make L.DomUtil.getPosition return intermediate position value during animation + this._el._leaflet_pos = stepPos; + + this.fire('step'); + }, + + // you can't easily get intermediate values of properties animated with CSS3 Transitions, + // we need to parse computed style (in case of transform it returns matrix string) + + _transformRe: /([-+]?(?:\d*\.)?\d+)\D*, ([-+]?(?:\d*\.)?\d+)\D*\)/, + + _getPos: function () { + var left, top, matches, + el = this._el, + style = window.getComputedStyle(el); + + if (L.Browser.any3d) { + matches = style[L.DomUtil.TRANSFORM].match(this._transformRe); + if (!matches) { return; } + left = parseFloat(matches[1]); + top = parseFloat(matches[2]); + } else { + left = parseFloat(style.left); + top = parseFloat(style.top); + } + + return new L.Point(left, top, true); + }, + + _onTransitionEnd: function () { + L.DomEvent.off(this._el, L.DomUtil.TRANSITION_END, this._onTransitionEnd, this); + + if (!this._inProgress) { return; } + this._inProgress = false; + + this._el.style[L.DomUtil.TRANSITION] = ''; + + // jshint camelcase: false + // make sure L.DomUtil.getPosition returns the final position value after animation + this._el._leaflet_pos = this._newPos; + + clearInterval(this._stepTimer); + + this.fire('step').fire('end'); + } + +}); diff --git a/pool/shard011/JavaScript/0069843_script.js b/pool/shard011/JavaScript/0069843_script.js new file mode 100644 index 0000000000000000000000000000000000000000..4daf6ebc5c5b69ae292560d723c077b8bc0cd6b9 --- /dev/null +++ b/pool/shard011/JavaScript/0069843_script.js @@ -0,0 +1,121 @@ +d3.json('js/data/forecast.json', function(d) { + + var temperatures = [], + dates = [], + margin = { top: 0, right: 0, bottom: 30, left: 20 } + height = 400 - margin.top - margin.bottom, + width = 600 - margin.left - margin.right; + + var tempColor, + yScale, + yAxisValues, + yAxisTicks, + yGuide, + xScale, + xAxisValues, + xAxisTicks, + xGuide, + colors, + tooltip, + myChart; + + for (var i = 0; i' + + d + '°
    ' + ) + .style('left', (d3.event.pageX -35) + 'px') + .style('top', (d3.event.pageY -30) + 'px') + tempColor = this.style.fill; + d3.select(this) + .style('fill', 'yellow') + }) + + .on('mouseout', function(d) { + tooltip.html('') + d3.select(this) + .style('fill', tempColor) + }); + + yGuide = d3.select('#viz svg').append('g') + .attr('transform', 'translate(20,0)') + .call(yAxisTicks) + + xGuide = d3.select('#viz svg').append('g') + .attr('transform', 'translate(20,'+ height + ')') + .call(xAxisTicks) + + myChart.transition() + .attr('height', function(d) { + return yScale(d); + }) + .attr('y', function(d) { + return height - yScale(d); + }) + .delay(function(d, i) { + return i * 20; + }) + .duration(1000) + .ease(d3.easeBounceOut) + +}); // json import diff --git a/pool/shard011/JavaScript/0069844_server.js b/pool/shard011/JavaScript/0069844_server.js new file mode 100644 index 0000000000000000000000000000000000000000..921fc6c2765e76b9a7586115dcfd35d90197aaf3 --- /dev/null +++ b/pool/shard011/JavaScript/0069844_server.js @@ -0,0 +1,43 @@ +var express = require('express'); +var app = express(); + +// Exports +module.exports = { + coverage: coverage +}; + +function listen(port, launchWindow, cb) { + return app.listen(port, function () { + if (cb) { + cb(); + } + if (launchWindow) { + require('child_process').exec('open http://localhost:' + port); + } + }); +} + +function coverage(port, launchWindow) { + app.use(express.static('coverage/lcov-report')); + return listen(port, launchWindow); +} + +// Run if main +if (require.main === module) { + var port = process.argv[2] || 8080; + var run = process.argv[3]; + switch (run) { + case 'examples': + app.use(express.static('.')); + app.get('/500', function(req, res) { + res.send(500); + }); + listen(port, true); + break; + case 'coverage': + default: + coverage(port, true); + break; + } +} + diff --git a/pool/shard011/JavaScript/0069846_template_modal.js b/pool/shard011/JavaScript/0069846_template_modal.js new file mode 100644 index 0000000000000000000000000000000000000000..d90abdae8c148a9f372d5654afe1941df308fa99 --- /dev/null +++ b/pool/shard011/JavaScript/0069846_template_modal.js @@ -0,0 +1,47 @@ +//Copyright 2014-2015 Alex Benfaremo, Alessandro Chelli, Lorenzo Di Berardino, Matteo Di Sabatino + +/********************************** LICENSE ********************************* + * * + * This file is part of ApioOS. * + * * + * ApioOS is free software released under the GPLv2 license: you can * + * redistribute it and/or modify it under the terms of the GNU General * + * Public License version 2 as published by the Free Software Foundation. * + * * + * ApioOS is distributed in the hope that it will be useful, but * + * WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License version 2 for more details. * + * * + * To read the license either open the file COPYING.txt or * + * visit * + * * + ****************************************************************************/ + +angular.module("ApioApplication").controller("modald2-01-0b", ["$scope", "$http", "$mdDialog", "socket", function ($scope, $http, $mdDialog, socket) { + socket.on("close_autoInstall_modal", function () { + $mdDialog.hide(); + }); + + $scope.cancel = function () { + socket.emit("close_autoInstall_modal", Apio.currentBoard.get()); + $mdDialog.hide(); + }; + + $scope.confirm = function () { + if ($scope.objectName) { + $scope.modalData.apioId = Apio.currentBoard.get(); + $scope.modalData.name = $scope.objectName; + $scope.modalData.category = "Smart Plug"; + socket.emit("close_autoInstall_modal", $scope.modalData.apioId); + socket.emit("send_to_service", { + service: "autoInstall", + message: "apio_install_new_object_final", + data: $scope.modalData + }); + $mdDialog.hide(); + } else { + alert("Please, choose a name to continue"); + } + }; +}]); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069848_index-shell.js b/pool/shard011/JavaScript/0069848_index-shell.js new file mode 100644 index 0000000000000000000000000000000000000000..c731e469d54a5c66a2cf73e9c0221e7d39e8064a --- /dev/null +++ b/pool/shard011/JavaScript/0069848_index-shell.js @@ -0,0 +1,255 @@ +var atom = require('app'); +var path = require('path'); +var spawn = require('child_process').spawn; +var BrowserWindow = require('browser-window'); +var Menu = require('menu'); +var shell = require('shell'); +var versionCheck = require('./lib/version-check'); +var log = require('./lib/log'); +var node = path.resolve(path.join(__dirname, 'vendor', 'node')); +var script = path.resolve(path.join(__dirname, 'index-server.js')); +var logger = require('fastlog')('', 'debug', '<${timestamp}>'); +var serverPort = null; +var mainWindow = null; + +if (process.platform === 'win32') { + // HOME is undefined on windows + process.env.HOME = process.env.USERPROFILE; + // skill shell.log setup + shellsetup(); +} else { + var shellLog = path.join(process.env.HOME, '.mapbox-studio', 'shell.log'); + // set up shell.log and log rotation + log(shellLog, 10e6, shellsetup); +} + +function shellsetup(err){ + process.on('exit', function(code) { + logger.debug('Mapbox Studio exited with', code + '.'); + }); + + // Start the server child process. + var server = spawn(node, [script, '--shell=true']); + server.on('exit', process.exit); + server.stdout.once('data', function(data) { + var matches = data.toString().match(/Mapbox Studio @ http:\/\/localhost:([0-9]+)\//); + if (!matches) { + console.warn('Server port not found'); + process.exit(1); + } + serverPort = matches[1]; + logger.debug('Mapbox Studio @ http://localhost:'+serverPort+'/'); + loadURL(); + }); + + // Report crashes to our server. + require('crash-reporter').start(); + + atom.on('window-all-closed', exit); + atom.on('will-quit', exit); + + function exit() { + if (server) server.kill(); + process.exit(); + }; + + atom.on('ready', makeWindow); +}; + +function makeWindow() { + // Create the browser window. + mainWindow = new BrowserWindow({ + width: 960, + height: 600, + 'min-width': 720, + 'min-height': 480, + title: 'Mapbox Studio', + 'node-integration': 'all', + 'web-preferences': { + webgl: true, + java: false, + webaudio: false + } + }); + mainWindow.loadUrl('file://' + path.join(__dirname, 'app', 'loading.html')); + // Restore OS X fullscreen state. + restoreFullScreen(); + // Emitted when the window is closed. + mainWindow.on('closed', function() { + // Dereference the window object, usually you would store windows + // in an array if your app supports multi windows, this is the time + // when you should delete the corresponding element. + mainWindow = null; + }); + // Prevent page changes from updating the window title (typically to 'Untitled'). + mainWindow.on('page-title-updated', function(e) { + e.preventDefault(); + }); + mainWindow.on('enter-full-screen', function(e) { + persistFullScreen(); + }); + mainWindow.on('leave-full-screen', function(e) { + persistFullScreen(); + }); + createMenu(); + loadURL(); + + // Restore OS X fullscreen state. + function restoreFullScreen() { + if (process.platform !== 'darwin') return; + var cp = require("child_process"); + if (cp.execSync("defaults read com.mapbox.mapbox-studio FullScreen 2>/dev/null || echo 0") == 1) { + setTimeout(function(){ + mainWindow.setFullScreen(true); + }, 100); + } + } + + // Persist OS X fullscreen state. + function persistFullScreen() { + if (process.platform !== 'darwin') return; + var cp = require("child_process"); + cp.execSync("defaults write com.mapbox.mapbox-studio FullScreen -bool " + mainWindow.isFullScreen()); + } +} + +function loadURL() { + if (!mainWindow) return; + if (!serverPort) return; + versionCheck({ + host: 'mapbox.s3.amazonaws.com', + path: '/mapbox-studio/latest', + pckge: require('./package.json') + }, function(update, current, latest){ + update = update ? '/update?current='+current+'&latest='+latest : ''; + mainWindow.loadUrl('http://localhost:'+serverPort + update); + }); +} + +function createMenu() { + var template; + + if (process.platform == 'darwin') { + template = [ + { + label: 'Mapbox Studio', + submenu: [ + { + label: 'About Mapbox Studio', + selector: 'orderFrontStandardAboutPanel:' + }, + { + type: 'separator' + }, + { + label: 'Hide Mapbox Studio', + accelerator: 'Command+H', + selector: 'hide:' + }, + { + label: 'Hide Others', + accelerator: 'Command+Shift+H', + selector: 'hideOtherApplications:' + }, + { + label: 'Show All', + selector: 'unhideAllApplications:' + }, + { + type: 'separator' + }, + { + label: 'Quit Mapbox Studio', + accelerator: 'Command+Q', + selector: 'performClose:' + } + ] + }, + { + label: 'Edit', + submenu: [ + { + label: 'Cut', + accelerator: 'Command+X', + selector: 'cut:' + }, + { + label: 'Copy', + accelerator: 'Command+C', + selector: 'copy:' + }, + { + label: 'Paste', + accelerator: 'Command+V', + selector: 'paste:' + }, + { + label: 'Select All', + accelerator: 'Command+A', + selector: 'selectAll:' + } + ] + }, + { + label: 'View', + submenu: [ + { + label: 'Reload', + accelerator: 'Command+R', + click: function() { mainWindow.restart(); } + }, + { + label: 'Toggle Developer Tools', + accelerator: 'Alt+Command+I', + click: function() { mainWindow.toggleDevTools(); } + }, + { + type: 'separator' + }, + { + label: 'Toggle Full Screen', + accelerator: 'Ctrl+Command+F', + click: function() { mainWindow.setFullScreen(!mainWindow.isFullScreen()); } + } + ] + }, + { + label: 'Window', + submenu: [ + { + label: 'Minimize', + accelerator: 'Command+M', + selector: 'performMiniaturize:' + } + ] + }, + { + label: 'Help', + submenu: [ + { + label: 'Online Resources', + click: function() { shell.openExternal('https://www.mapbox.com/mapbox-studio/'); } + }, + { + label: 'Application Log', + click: function() { + var cp = require("child_process"); + cp.exec("open -a /Applications/Utilities/Console.app ~/.mapbox-studio/app.log"); + } + }, + { + label: 'Shell Log', + click: function() { + var cp = require("child_process"); + cp.exec("open -a /Applications/Utilities/Console.app ~/.mapbox-studio/shell.log"); + } + } + ] + } + ]; + + menu = Menu.buildFromTemplate(template); + Menu.setApplicationMenu(menu); + } +} + diff --git a/pool/shard011/JavaScript/0069850_touch.js b/pool/shard011/JavaScript/0069850_touch.js new file mode 100644 index 0000000000000000000000000000000000000000..fa54d5e558aaaa2c938ebda742c797c95278da2d --- /dev/null +++ b/pool/shard011/JavaScript/0069850_touch.js @@ -0,0 +1,132 @@ +$(document).ready(function(){ + //设置变量 + open_write_twitter=$("#open_write_twitter"); + open_menu=$("#open_menu"); + close_menu=$("#close_menu"); + open_post_twitter=$("#open_post_twitter"); + open_zf_twitter=$("#open_zf_twitter"); + close_post_twitter=$("#close_post_twitter"); + close_zf_twitter=$("#close_zf_twitter"); + post_twitter_input=$("#post_twitter_input"); + zf_twitter=$("#zf_twitter"); + menu=$("#menu"); + post_twitter=$("#post_twitter"); + no=$("#no"); + default_menu_box_option=$("#default_menu_box_option"); + more_menu_box_option=$("#more_menu_box_option"); + open_more=$("#open_more"); + back2_default_menu_box_option=$("#back2_default_menu_box_option"); + post_tip=$("#post_tip"); + menu_box=$("#menu_box"); + c=$(".c"); + var i=0; + var start_x=0; + var start_y=0; + //设置头部图片宽度 + function resize_logo(){ + logo_width=$(window).width(); + logo_height=logo_width/720*300; + $("#header_logo").attr({ + "width":logo_width, + "height":logo_height + }); + $("#content").css("margin-top",logo_height); + } + resize_logo(); + $(window).resize(function(){ + resize_logo(); + // window.location.reload(); + }); + function x_click(x,box){ + dw2=$(window).width()/2; + dh2=$(window).height()/2; + box_w=box.width(); + box_h=box.height(); + x.click(function(e){ + to_top=$(document).scrollTop(); + page_x=e.pageX-box_w/2*0.1; + page_y=e.pageY-box_h/2*0.1-to_top; + if(i==0){ + start_x=page_x; + start_y=page_y; + box.show(); + box.css({ + "top":page_y+"px", + "left":page_x+"px", + // "top":"50%", + // "left":"50%", + "margin-top":"-" + box_h/2 + "px", + "margin-left":"-25%" + }); + box.removeClass("menu_ani_hide"); + box.addClass("menu_ani_show"); + box.animate({ + opacity:1, + top:dh2 +"px", + left:dw2+"px" + },300); + i=1; + $(this).addClass("c_mousedown"); + }else{ + // box.fadeOut(500); + box.removeClass("menu_ani_show"); + box.addClass("menu_ani_hide"); + box.animate({ + top:start_y+"px", + left:start_x+"px", + opacity:0 + },500,function(){ + $(this).hide(); + }); + i=0; + more_menu_box_option.hide(); + default_menu_box_option.show(); + x.removeClass("c_mousedown"); + } + }); + }//end of function x_click() + function open_box(x,openbox,hidebox){ + x.click(function(){ + hidebox.slideUp(300); + openbox.slideDown(300); + i=0; + c.removeClass("c_mousedown"); + }); + } + //修正i数值 + function click4i(x,x_i){ + x.click(function(){ + i=x_i; + }); + }; + //输入框提示 + function p_tip(x){ + post_tip.text(x); + } + //点开选项菜单 + x_click(c,menu_box); + //打开主菜单 + open_box(open_menu,menu,menu_box); + open_box(close_menu,no,menu); + //写微博 + open_box(open_write_twitter,post_twitter,menu_box); + open_write_twitter.click(function(){ + post_twitter_input.focus(); + p_tip("发表微博:"); + }); + //回复 + open_box(open_post_twitter,post_twitter,menu_box); + open_post_twitter.click(function(){ + post_twitter_input.focus(); + p_tip("回复微博:"); + }); + open_box(close_post_twitter,no,post_twitter); + //转发 + open_box(open_zf_twitter,zf_twitter,menu_box); + open_zf_twitter.click(function(){ + zf_twitter_input.focus(); + }); + open_box(close_zf_twitter,no,zf_twitter); + open_box(open_more,more_menu_box_option,default_menu_box_option); + open_box(back2_default_menu_box_option,default_menu_box_option,more_menu_box_option); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069852_node-test.js b/pool/shard011/JavaScript/0069852_node-test.js new file mode 100644 index 0000000000000000000000000000000000000000..0fa2d454dc83d2ba152e7895fd491b19aeac2fb8 --- /dev/null +++ b/pool/shard011/JavaScript/0069852_node-test.js @@ -0,0 +1,178 @@ +/** + * Copyright (c) 2014-present, Facebook, Inc. All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + * + * @emails oncall+jsinfra + */ +'use strict'; + +jest.unmock('../../constants') + .unmock('../node'); + +jest.mock('child_process', () => ({ + spawn: jest.fn((cmd, args) => { + let closeCallback; + return { + stdout: { + on: jest.fn().mockImplementation((event, callback) => { + if (event === 'data') { + setTimeout(() => { + callback(mockResponse); + setTimeout(closeCallback, 0); + }, 0); + } else if (event === 'close') { + closeCallback = callback; + } + }), + setEncoding: jest.fn(), + }, + }; + }), +})); + +jest.mock('fs', () => { + let mtime = 32; + const stat = (path, callback) => { + setTimeout(() => callback(null, { + isDirectory() { + return path.endsWith('/directory'); + }, + isSymbolicLink() { + return false; + }, + mtime: { + getTime() { + return mtime++; + }, + }, + }), 0); + }; + return { + readdir: jest.fn((dir, callback) => { + if (dir === '/fruits') { + setTimeout(() => callback(null, ['directory', 'tomato.js']), 0); + } else if (dir === '/fruits/directory') { + setTimeout(() => callback(null, ['strawberry.js']), 0); + } + }), + lstat: jest.fn(stat), + stat: jest.fn(stat), + }; +}); + +const pearMatcher = path => /pear/.test(path); + +let mockResponse; +let nodeCrawl; +let childProcess; + +describe('node crawler', () => { + + beforeEach(() => { + mockResponse = [ + '/fruits/pear.js', + '/fruits/strawberry.js', + '/fruits/tomato.js', + ].join('\n'); + }); + + it('crawls for files based on patterns', () => { + process.platform = 'linux'; + + childProcess = require('child_process'); + nodeCrawl = require('../node'); + + mockResponse = [ + '/fruits/pear.js', + '/fruits/strawberry.js', + '/fruits/tomato.js', + '/vegetables/melon.json', + ].join('\n'); + + const promise = nodeCrawl( + ['/fruits', '/vegtables'], + ['js', 'json'], + pearMatcher, + { + files: Object.create(null), + } + ).then(data => { + expect(childProcess.spawn).lastCalledWith('find', [ + '/fruits', + '/vegtables', + '-type', + 'f', + '\(', + '-iname', + '*.js', + '-o', + '-iname', + '*.json', + '\)', + ]); + + expect(data.files).not.toBe(null); + + expect(data.files).toEqual({ + '/fruits/strawberry.js': ['', 32, 0, []], + '/fruits/tomato.js': ['', 33, 0, []], + '/vegetables/melon.json': ['', 34, 0, []], + }); + }); + + jest.runAllTimers(); + + return promise; + }); + + it('updates only changed files', () => { + process.platform = 'linux'; + + nodeCrawl = require('../node'); + + const files = Object.create(null); + + // In this test sample, strawberry is changed and tomato is unchanged + const tomato = ['', 33, 1, []]; + files['/fruits/strawberry.js'] = ['', 30, 1, []]; + files['/fruits/tomato.js'] = tomato; + + const promise = nodeCrawl(['/fruits'], ['js'], pearMatcher, {files}) + .then(data => { + expect(data.files).toEqual({ + '/fruits/strawberry.js': ['', 32, 0, []], + '/fruits/tomato.js': tomato, + }); + + // Make sure it is the *same* unchanged object. + expect(data.files['/fruits/tomato.js']).toBe(tomato); + }); + + jest.runAllTimers(); + + return promise; + }); + + it('uses node fs APIs on windows', () => { + process.platform = 'win32'; + + nodeCrawl = require('../node'); + + const files = Object.create(null); + const promise = nodeCrawl(['/fruits'], ['js'], pearMatcher, {files}) + .then(data => { + expect(data.files).toEqual({ + '/fruits/tomato.js': ['', 32, 0, []], + '/fruits/directory/strawberry.js': ['', 33, 0, []], + }); + }); + + jest.runAllTimers(); + + return promise; + }); + +}); diff --git a/pool/shard011/JavaScript/0069855_chart.js b/pool/shard011/JavaScript/0069855_chart.js new file mode 100644 index 0000000000000000000000000000000000000000..d828b1786f3de001431af68fc7ce26f1a655e347 --- /dev/null +++ b/pool/shard011/JavaScript/0069855_chart.js @@ -0,0 +1,67 @@ +var midaas = midaas || {}; + +midaas.chart = { + + addGrayBars: function(chart) { + $(".ct-series .ct-bar").each(function() { + var x = $(this).attr("x1"), + y = $(this).attr("y1"), + y2 = 10; + + chart.svg.querySelector(".ct-series").elem("line", { + x1: x, + x2: x, + y1: y, + y2: y2 + }, "gray-line", true); + }); + }, + + addStrokeWidth: function(data) { + if(data.type === "bar") { + data.element.attr({ + style: "stroke-width: 15px" + }); + } + }, + + createChart: function(labels, data) { + var chart = new Chartist.Bar("#chart", { + labels: labels, + series: data + }, { + axisX: { showLabel: true, showGrid: false }, + axisY: { + showLabel: true, + showGrid: false, + labelInterpolationFnc: function(value) { + return midaas.formatMoney.toDollars(value); + } + }, + chartPadding: { left: 15, top: 10, right: -10 }, + fullWidth: true, + height: "350px", + low: 0, + }); + + chart.on("draw", function(context) { + midaas.chart.addStrokeWidth(context); + }); + + chart.on("created", function(createdChart) { + midaas.chart.addGrayBars(createdChart); + midaas.chart.removeLoadingIcon(); + }); + + return chart; + }, + + removeLoadingIcon: function() { + $("#loading-icon").fadeOut("fast"); + }, + + returnError: function(error) { + $("#loading-icon").fadeOut("fast"); + $("#chart-error").fadeIn("fast"); + }, +}; diff --git a/pool/shard011/JavaScript/0069856_main.js b/pool/shard011/JavaScript/0069856_main.js new file mode 100644 index 0000000000000000000000000000000000000000..1615862609dae70d408d3ff78d8f9efeca2d9fff --- /dev/null +++ b/pool/shard011/JavaScript/0069856_main.js @@ -0,0 +1,44 @@ +(function () { + 'use strict'; + + const ipcRenderer = require('electron').ipcRenderer; + const splash = document.getElementById('splash'); + const opening = document.getElementById('opening'); + const openingUrl = document.getElementById('opening-url'); + const webview = document.createElement('webview'); + + let revealTimeout; + webview.addEventListener('dom-ready', () => { + clearTimeout(revealTimeout); + revealTimeout = setTimeout(() => { + opening.classList.add('hidden'); + webview.style.opacity = 1; + }, 500); + }); + webview.setAttribute('allowpopups', 'true'); + document.body.appendChild(webview); + + ipcRenderer.send('loadMostRecentUrl'); + + const showSplashTimeout = setTimeout(() => { + splash.classList.remove('hidden'); + }, 250); + + let loadedUrl; + ipcRenderer.on('loadUrl', (event, url) => { + if (loadedUrl === url) { + console.log('not loading url into webview, already loaded:', url); + return; + } + + console.log('loading new url into webview:', url); + clearTimeout(showSplashTimeout); + splash.classList.add('hidden'); + webview.style.opacity = 0; + opening.classList.remove('hidden'); + openingUrl.innerText = url; + webview.src = url; + loadedUrl = url; + document.title = `NodeCG Dashboard - ${url}`; + }); +})(); diff --git a/pool/shard011/JavaScript/0069857_users.js b/pool/shard011/JavaScript/0069857_users.js new file mode 100644 index 0000000000000000000000000000000000000000..936ffa0055e193ff1ad14750b42da1be164cebb0 --- /dev/null +++ b/pool/shard011/JavaScript/0069857_users.js @@ -0,0 +1,448 @@ +/* + Copyright 2017 Carmilla Mina Jankovic + + 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. + */ + +'use strict'; + +const express = require('express'); +const objectValidator = require('../../utils/objectValidator'); +const userManager = require('../../managers/users'); +const roomManager = require('../../managers/rooms'); +const aliasManager = require('../../managers/aliases'); +const restErrorChecker = require('../../helpers/restErrorChecker'); +const errorCreator = require('../../error/errorCreator'); +const { dbConfig } = require('../../config/defaults/config'); + +const router = new express.Router(); + +/** + * @param {Object} io Socket.io + * @returns {Object} Router + */ +function handle(io) { + /** + * @api {get} /users Get users. + * @apiVersion 8.0.0 + * @apiName GetUsers + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Get users. + * + * @apiParam {boolean} [Query] [includeInactive] Should banned and unverified users be in the result? + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.users Found users. + */ + router.get('/', (request, response) => { + const { authorization: token } = request.headers; + const { includeInactive } = request.query; + + userManager.getUsersByUser({ + token, + includeInactive, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {post} /users/:userId/password Update a user's password. + * @apiVersion 8.0.0 + * @apiName ChangePassword + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Update a user's password. + * + * @apiParam {string} userId Id of the user that will get a new password. + * + * @apiParam {Object} data + * @apiParam {string} data.password New password. + * + * @apiSuccess {Object} data + * @apiSuccess {Object[]} data.success Was the password properly changed? + */ + router.post('/:userId/password', (request, response) => { + const sentData = request.body.data; + + if (!objectValidator.isValidData(request.params, { userId: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId }' }) }); + + return; + } + + const { authorization: token } = request.headers; + const { password } = request.body.data; + const { userId } = request.params; + + userManager.changePassword({ + password, + userId, + token, + callback: ({ error, data }) => { + if (error) { + sentData.password = typeof sentData.password !== 'undefined'; + + restErrorChecker.checkAndSendError({ response, error, sentData }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {post} /users Create a user. + * @apiVersion 8.0.0 + * @apiName CreateUser + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Create a user. + * + * @apiParam {Object} data + * @apiParam {Object} data.user User to create. + * @apiParam {string} [data.options] Update options. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.user Created user. + */ + router.post('/', (request, response) => { + const sentData = request.body.data; + + if (!objectValidator.isValidData(request.body, { data: { user: { username: true, password: true } } })) { + sentData.user.password = typeof sentData.user.password !== 'undefined'; + + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ data: { user: { username, password } } }' }), sentData }); + + return; + } + + const { authorization: token } = request.headers; + const { user, options } = request.body.data; + user.registerDevice = dbConfig.DeviceTypes.RESTAPI; + + userManager.createUser({ + user, + token, + io, + options, + callback: ({ error, data }) => { + if (error) { + sentData.user.password = typeof sentData.user.password !== 'undefined'; + + restErrorChecker.checkAndSendError({ response, error, sentData }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {put} /users/:userId Update a user. + * @apiVersion 8.0.0 + * @apiName UpdateUser + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Update a user. + * + * @apiParam {string} userIdToUpdate [Url] Id of the user to update. + * + * @apiParam {string} data Body parameters. + * @apiParam {string} data.user User parameters to update. + * @apiParam {string} [data.options] Update options. + * + * @apiSuccess {Object} data + * @apiSuccess {User} data.user Updated user. + */ + router.put('/:userId', (request, response) => { + if (!objectValidator.isValidData(request.params, { userId: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId }' }) }); + + return; + } + + if (!objectValidator.isValidData(request.body, { data: { user: true } })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ data: { user } }' }), sentData: request.body.data }); + + return; + } + + const { + user, + options, + } = request.body.data; + const { userId } = request.params; + const { authorization: token } = request.headers; + + userManager.updateUser({ + user, + options, + io, + userId, + token, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {get} /users/:userId Get a user. + * @apiVersion 8.0.0 + * @apiName GetUser + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Get a user. + * + * @apiParam {string} userId [Url] Id of the user to get. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.user Found user. + */ + router.get('/:userId', (request, response) => { + if (!objectValidator.isValidData(request.params, { userId: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId }' }) }); + + return; + } + + const { authorization: token } = request.headers; + const { userId } = request.params; + + userManager.getUserById({ + token, + userId, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {put} /users/:userId/rooms/:roomId/follow Follow a room. + * @apiVersion 8.0.0 + * @apiName FollowRoom + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token. + * + * @apiDescription Follow a room. + * + * @apiParam {Object} data + * @apiParam {string} [data.password] Password for the room. + * @apiParam {string} [data.aliasId] Id of the alias used to follow the room. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.room Followed room. + */ + router.put('/:userId/rooms/:roomId/follow', (request, response) => { + const sentData = request.body.data; + + if (!objectValidator.isValidData(request.params, { userId: true, roomId: true })) { + sentData.password = typeof sentData.password !== 'undefined'; + + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId, roomId }' }), sentData }); + + return; + } + + const { password, aliasId } = request.body.data; + const { roomId } = request.params; + const { authorization: token } = request.headers; + + roomManager.followRoom({ + io, + token, + roomId, + password, + aliasId, + callback: ({ error, data }) => { + if (error) { + sentData.password = typeof sentData.password !== 'undefined'; + + restErrorChecker.checkAndSendError({ response, error, sentData }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {put} /users/:userId/rooms/:roomId/unfollow Unfollow a room. + * @apiVersion 8.0.0 + * @apiName UnfollowRoom + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token + * + * @apiDescription Unfollow a room. + * + * @apiParam {Object} userId [Url] Id of the user that will unfollow the room. + * @apiParam {Object} roomId [Url] Id of the room to unfollow. + * + * @apiParam {Object} data. + * @apiParam {Object} [data.aliasId] Id of the alias that will unfollow a room. It overrides userId. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.room Room that was unfollowed. + */ + router.put('/:userId/rooms/:roomId/unfollow', (request, response) => { + if (!objectValidator.isValidData(request.params, { userId: true, roomId: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: 'params: { userId, roomId }' }), sentData: request.body.data }); + + return; + } + + const { roomId, userId } = request.params; + const { authorization: token } = request.headers; + const { aliasId } = request.body.data; + + roomManager.unfollowRoom({ + io, + token, + userId, + roomId, + aliasId, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {get} /users/:userId/aliases Get aliases from a user. + * @apiVersion 8.0.0 + * @apiName GetUserAliases + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token + * + * @apiDescription Get aliases from a user. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.aliases Found aliases. + */ + router.get('/:userId/aliases', (request, response) => { + if (!objectValidator.isValidData(request.params, { userId: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId }' }), sentData: request.body.data }); + + return; + } + + const { userId } = request.params; + const { authorization: token } = request.headers; + + aliasManager.getAliasesByUser({ + userId, + token, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); + + return; + } + + response.json({ data }); + }, + }); + }); + + /** + * @api {put} /users/:userIdToVerify/verify Verify a user. + * @apiVersion 8.0.0 + * @apiName VerifyUser + * @apiGroup Users + * + * @apiHeader {string} Authorization Your JSON Web Token + * + * @apiDescription Verify a user and allow it to log in. + * + * @apiParam {string} userId Id of the user to verify. + * + * @apiSuccess {Object} data + * @apiSuccess {Object} data.user Verified user. + */ + router.put('/:userIdToVerify/verify', (request, response) => { + if (!objectValidator.isValidData(request.params, { userIdToVerify: true })) { + restErrorChecker.checkAndSendError({ response, error: new errorCreator.InvalidData({ expected: '{ userId }' }), sentData: request.body.data }); + + return; + } + + const { userIdToVerify } = request.params; + const { authorization: token } = request.headers; + + userManager.verifyUser({ + userIdToVerify, + token, + io, + callback: ({ error, data }) => { + if (error) { + restErrorChecker.checkAndSendError({ response, error, sentData: request.body.data }); + + return; + } + + response.json({ data }); + }, + }); + }); + + return router; +} + +module.exports = handle; diff --git a/pool/shard011/JavaScript/0069858_MenuItem.js b/pool/shard011/JavaScript/0069858_MenuItem.js new file mode 100644 index 0000000000000000000000000000000000000000..2735ee518e13e5176b8c418af3bdeb3e4a34ddac --- /dev/null +++ b/pool/shard011/JavaScript/0069858_MenuItem.js @@ -0,0 +1,95 @@ +import React from 'react'; +import classnames from 'classnames'; +import CustomPropTypes from './utils/CustomPropTypes'; +import SafeAnchor from './SafeAnchor'; + +export default class MenuItem extends React.Component { + constructor(props) { + super(props); + + this.handleClick = this.handleClick.bind(this); + } + + handleClick(event) { + if (!this.props.href || this.props.disabled) { + event.preventDefault(); + } + + if (this.props.disabled) { + return; + } + + if (this.props.onSelect) { + this.props.onSelect(event, this.props.eventKey); + } + } + + render() { + if (this.props.divider) { + return
  • ; + } + + if (this.props.header) { + return ( +
  • {this.props.children}
  • + ); + } + + const classes = { + disabled: this.props.disabled, + active: this.props.active + }; + + return ( +
  • + + {this.props.children} + +
  • + ); + } +} + +MenuItem.propTypes = { + disabled: React.PropTypes.bool, + active: React.PropTypes.bool, + divider: CustomPropTypes.all([ + React.PropTypes.bool, + props => { + if (props.divider && props.children) { + return new Error('Children will not be rendered for dividers'); + } + } + ]), + eventKey: React.PropTypes.oneOfType([ + React.PropTypes.number, + React.PropTypes.string + ]), + header: React.PropTypes.bool, + href: React.PropTypes.string, + target: React.PropTypes.string, + title: React.PropTypes.string, + onKeyDown: React.PropTypes.func, + onSelect: React.PropTypes.func, + id: React.PropTypes.oneOfType([ + React.PropTypes.string, + React.PropTypes.number + ]) +}; + +MenuItem.defaultProps = { + divider: false, + disabled: false, + header: false +}; diff --git a/pool/shard011/JavaScript/0069859_shell.js b/pool/shard011/JavaScript/0069859_shell.js new file mode 100644 index 0000000000000000000000000000000000000000..70c1b79b7f27050526a9a65585b17786fb6296dc --- /dev/null +++ b/pool/shard011/JavaScript/0069859_shell.js @@ -0,0 +1,189 @@ + +/* + * (c) Sindre Sorhus + * sindresorhus.com + * MIT License + */ +module.exports = function( grunt ) { + 'use strict'; + + var _ = grunt.util._; + var log = grunt.log; + + // Keep track of killable and killed processes. + var killable = {}; + var killed = {}; + + grunt.registerMultiTask( 'shell', 'Run shell commands', function() { + var cp = require('child_process'); + var proc; + + var options = this.options({stdout: true, stderr: true, failOnError: true, canKill: true, stopIfStarted: false}); + + var data = this.data; + var done = options.async ? function() {} : this.async(); + var target = this.target; + var file, args, opts; + var cmd = data.command; + + if (cmd === undefined) { + throw new Error('`command` required'); + } + + cmd = grunt.template.process(typeof cmd === 'function' ? cmd.apply(grunt, arguments) : cmd); + + grunt.verbose.writeflags(options, 'Options'); + + // On Unix, set detached option to make it possible to kill the entire process group later + opts = _.defaults({}, options.execOptions, { detached: (process.platform !== 'win32') }); + + // Tests to see if user is trying to kill a running process + var shouldKill = options.canKill && this.args.length === 1 && this.args[0] === 'kill'; + if (shouldKill) { + proc = killable[target]; + if (!proc) { + grunt.log.writeln('No running process for target:' + target); + return; + } + grunt.verbose.writeln('Killing process for target: ' + target + ' (pid = ' + proc.pid + ')'); + + // Mark that we're killing this process. This is required because a killed process will + // have a null or a non-zero exit code, which would result in an error if the + // failOnError option is set. It is assumed that if the user wants to kill a task, that + // shouldn't cause an error (they meant to do it) and we should continue processing tasks. + killed[target] = proc; + + killPid(proc.pid); + + delete killable[target]; + done(); + return; + } + + if (process.platform === 'win32') { + file = 'cmd.exe'; + args = ['/s', '/c', cmd ]; + opts.windowsVerbatimArguments = true; + } else { + file = '/bin/sh'; + args = ['-c', cmd]; + } + + grunt.verbose.writeln('Command: ' + file); + grunt.verbose.writeflags(args, 'Args'); + + var BUFF_LENGTH = 200*1024, + stdOutPos = 0, + stdErrPos = 0, + stdOutBuf, stdErrBuf; + + var stdBuffering = _.isFunction( options.callback ); + + if (stdBuffering) { + stdOutBuf = new Buffer(BUFF_LENGTH); + stdErrBuf = new Buffer(BUFF_LENGTH); + } + + proc = cp.spawn(file, args, opts); + + // Store proc to be killed! + if (options.canKill) { + if (killable[target]) { + if (options.stopIfStarted) { + var oldProc = killable[target]; + oldProc.removeAllListeners('close'); + oldProc.on('close', function() { + log.ok('restarted :' + target); + }); + + killPid(oldProc.pid); + } else { + grunt.fatal('Process :' + target + ' already started.'); + } + } + killable[target] = proc; + } + + // proc.stdout and proc.stderr don't exist when stdio: 'inherit' is + // passed to spawn. + if (proc.stdout) { + proc.stdout.setEncoding('utf8'); + proc.stdout.on('data', function(data) { + if (stdBuffering) { + stdOutPos += stdOutBuf.write(data, stdOutPos); + } + + if( _.isFunction( options.stdout ) ) { + options.stdout(data); + } else if(options.stdout === true || grunt.option('verbose')) { + log.write(data); + } + }); + } + + if (proc.stderr) { + proc.stderr.setEncoding('utf8'); + proc.stderr.on('data', function(data) { + if (stdBuffering) { + stdErrPos += stdErrBuf.write(data, stdErrPos); + } + + if( _.isFunction( options.stderr ) ) { + options.stderr(data); + } else if(options.stderr === true || grunt.option('verbose')) { + log.error(data); + } + }); + } + + proc.on('close', function (code) { + delete killable[target]; + if ( _.isFunction( options.callback ) ) { + var stdOutString = stdOutBuf.toString('utf8', 0, stdOutPos), + stdErrString = stdErrBuf.toString('utf8', 0, stdErrPos); + + options.callback.call(this, code, stdOutString, stdErrString, done); + } else if (code !== 0 && options.failOnError && !killed[target]){ + grunt.warn('Done, with errors: command "' + data.command + '" (target "' + target + + '") exited with code ' + code + '.'); + done(); + } else { + done(); + } + }); + + }); + + process.on('exit', function () { + _.forEach(killable, function (proc, key, collection) { + killPid(proc.pid); + delete collection[key]; + }); + }); + + process.on('SIGINT', function () { + process.exit(); + }); + + function killPid(pid) { + var execSync = require('sync-exec'); + + // Kill the process group. Note that the proc.pid represents the PID of the parent shell + // process (/bin/sh or cmd.exe). If we simply kill the parent process, the child + // processes will remain running (they will become orphaned). Methods for killing the + // entire process group vary by platform. + if (process.platform === 'win32') { + // On windows, we can run taskkill.exe with the /T parameter to do a tree kill. This + // needs to be run synchronously in case the :kill task is the last task in the + // list, as otherwise grunt will exit first and the process will keep running. + execSync('taskkill /f /t /pid ' + pid); + } else { + // On Unix, we can kill the entire process group by passing in a negative PID. Note + // this requires passing in a signal, and it also required us to launch the process + // with the option { detached: true }. + process.kill(-pid, 'SIGKILL'); + } + } + + +}; diff --git a/pool/shard011/JavaScript/0069861_IosCompose.js b/pool/shard011/JavaScript/0069861_IosCompose.js new file mode 100644 index 0000000000000000000000000000000000000000..dd5e178bbed627c19e83e29ddce4be3f7baf4ee3 --- /dev/null +++ b/pool/shard011/JavaScript/0069861_IosCompose.js @@ -0,0 +1,22 @@ +'use strict'; + +var React = require('react'); +var IconBase = require(__dirname + 'components/IconBase/IconBase'); + +var IosCompose = React.createClass({ + displayName: 'IosCompose', + + render: function render() { + return React.createElement( + IconBase, + null, + React.createElement( + 'g', + null, + React.createElement('polygon', { points: '256,320 192,320 192,256 320,128 64,128 64,432 384,432 384,192 \t' }), + React.createElement('polygon', { points: '387.927,91.74 208,271.651 208,304 240.216,304 420.261,124.016 \t' }), + React.createElement('path', { d: 'M444.213,80.312l-12.465-12.466C429.084,65.467,425.556,64,421.746,64c-3.812,0-7.304,1.468-9.929,3.85L399.666,80 l0.08,0.08l11.293,11.293l21.02,21.02l12.15-12.15c2.383-2.625,3.791-6.117,3.791-9.929C448,86.504,446.592,82.975,444.213,80.312z ' }) + ) + ); + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069862_AuthenticationService.js b/pool/shard011/JavaScript/0069862_AuthenticationService.js new file mode 100644 index 0000000000000000000000000000000000000000..7dc15f0240068303d425e88860b1c08951754494 --- /dev/null +++ b/pool/shard011/JavaScript/0069862_AuthenticationService.js @@ -0,0 +1,53 @@ +'use strict'; +define([ + 'app' +], function (app) { + + var srv = function ($http, $q, $cookies, $base64, $rootScope, CoreConfig) { + + var result = {}; + + result.isLoggedIn = function(){ + return true; + }; + + result.login = function (rootScope, scope) { + var delay = $q.defer(); + $http.post(scope.rootUrl + CoreConfig.url.security.login, {username: scope.user.username, password: scope.user.password}) + .success(function (response) { + delay.resolve(response); + }) + .error(function (data, status, headers, config) { + delay.reject(new Error(status, config)); + }); + return delay.promise; + }; + + result.setCredentials = function (rootScope, scope, data) { + var authdata = $base64.encode(scope.user.username + ':' + scope.user.password); + + rootScope.globals.security = { + currentUser: { + username: scope.user.username, + authdata: authdata + } + }; + + $http.defaults.headers.common['Authorization'] = 'Basic ' + authdata; // jshint ignore:line + $cookies.globalSecurity = rootScope.globals.security; + }; + + result.clearCredentials = function (rootScope) { + rootScope.globals = { + security : {} + }; + $cookies.globalSecurity = undefined; + $http.defaults.headers.common.Authorization = 'Basic '; + }; + + return result; + }; + + app.factory('AuthenticationService', ['$http', '$q', '$cookies', '$base64', '$rootScope', 'CoreConfig', srv]); + +}); diff --git a/pool/shard011/JavaScript/0069863_datetimepicker.js b/pool/shard011/JavaScript/0069863_datetimepicker.js new file mode 100644 index 0000000000000000000000000000000000000000..07c5d0ef7a5cd8fc3ece0aefc35121919e7bf238 --- /dev/null +++ b/pool/shard011/JavaScript/0069863_datetimepicker.js @@ -0,0 +1,50 @@ +import test from 'ava'; +import snapshot from '../../helpers/snapshot'; +import Vue from 'vue/dist/vue.common.js'; +import datetimepicker from '../../../src/lib/components/datetimepicker/index.vue'; +import commonTest from '../../common/unit'; + +const uiid = 12; +const testOptions = { + test, + Vue, + snapshot, + component : window.morning._origin.Form.extend(datetimepicker), + name : 'datetimepicker', + formValue1 : '2018-03-23 12:15:30', + formValue2 : '2017-02-12 15:12:20', + formValueInvalid1 : undefined, + formValueInvalid2 : undefined, + attrs : ``, + uiid, + // cause : ui-calendar will highlight today. + // but ui-datetimepicker no config can disabled this config.for test eveyday snapshot is different. + delVmEl : true, + _baseTestHookCustomMount : async vm => { + + // fixed date + vm.date = +new Date('2018-03-23'); + + await new Promise(resolve => { + + vm.Vue.nextTick(() => { + + vm.$mount(); + + }); + + resolve(); + + }); + + return vm; + + }, + // this component allow emit event more than once. + _formValueChangeSkipInvalidValueEmitTest : true, + _formValueChangeSkipValueFilterEmitTest : true +}; + +commonTest.componentBase(testOptions); +commonTest.formBase(testOptions); +commonTest.formValueChange(testOptions); diff --git a/pool/shard011/JavaScript/0069865_sprites.js b/pool/shard011/JavaScript/0069865_sprites.js new file mode 100644 index 0000000000000000000000000000000000000000..c143a187d1085b5c0df3fc4d25802e7f3c0da6a0 --- /dev/null +++ b/pool/shard011/JavaScript/0069865_sprites.js @@ -0,0 +1,100 @@ +const { promisify } = require('util'); +const path = require('path'); +const { writeFile } = require('fs'); +const mkdirp = require('mkdirp'); +const ansi = require('ansi-colors'); + +const writeFileAsync = promisify(writeFile); +const { log } = require('./log'); +const { pluginOptions } = require('./plugin-options'); + +/** + * Map properties for every image. + * + * @param {Array} images - An array of image objects. + * @param {Array} sprites - Array of sprite file object data. + * @returns {Array} + */ +function mapSpritesProperties(images, sprites) { + const spriteProperties = sprites.map((sprite) => { + const imagePaths = Object.keys(sprite.coordinates); + + return imagePaths.map((imagePath) => { + // Retrieve the existing image object with the same image path. + const matchingImage = images.find( + (element) => element.path === imagePath + ); + + // Add the sprite information to the image object and return a copy + // of the object. + return Object.assign(matchingImage, { + coordinates: sprite.coordinates[imagePath], + spritePath: sprite.path, + properties: sprite.properties, + }); + }); + }); + + return [images, spriteProperties]; +} + +/** + * Write the actual sprite image file. + * + * @async + * @param {object} spriteElement - The sprite element that will be saved. + * @returns {Promise} + */ +async function saveSpriteFile(spriteElement) { + const opts = pluginOptions.getOptions(); + const sprite = spriteElement; + + // Build the full path the sprite file should be saved to. + sprite.path = path.resolve(opts.spritePath, `${sprite.groups}.png`); + + // If the sprite is being pulled from the cache, don't save a new version. + if (sprite.isFromCache) { + log('Easysprites:', ansi.green(sprite.path), 'unchanged.'); + return sprite; + } + + // Save new version of the sprite image file. + await writeFileAsync(sprite.path, Buffer.from(sprite.image, 'binary')); + + log('Easysprites:', ansi.yellow(sprite.path), 'generated.'); + + return sprite; +} + +/** + * Save the sprite images. + * + * @async + * @param {Array} images - An array of image objects. + * @param {Array} sprites - Array of sprite file object data. + * @returns {Array} + */ +async function saveSprites(images, sprites) { + const opts = pluginOptions.getOptions(); + + try { + await mkdirp(opts.spritePath); + } catch (error) { + throw new Error( + `The directory ${opts.spritePath} could not be created. ${error}` + ); + } + + try { + const allSavedSprites = await Promise.all( + sprites.map((sprite) => saveSpriteFile(sprite)) + ); + + return [images, allSavedSprites]; + } catch (error) { + throw new Error(`Sprite file failed to save. ${error}`); + } +} + +module.exports.mapSpritesProperties = mapSpritesProperties; +module.exports.saveSprites = saveSprites; diff --git a/pool/shard011/JavaScript/0069867_register.js b/pool/shard011/JavaScript/0069867_register.js new file mode 100644 index 0000000000000000000000000000000000000000..583d206e8a9b865e5ac8a96caa329d6bdbb8a093 --- /dev/null +++ b/pool/shard011/JavaScript/0069867_register.js @@ -0,0 +1,75 @@ + + var bcrypt = require('bcrypt'); + + +function validateEmail(email) { + var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; + return re.test(email); +} + +exports.registerGet = function(req, res) { + + if (typeof req.user !== 'undefined') { + // User is logged in. + res.redirect('/partials/account'); + return; + } + else { + req.user = false; + } + var message = req.flash('error'); + if (message.length < 1) { + message = false; + } + res.render('starter/register', { title: 'Register', message: message, user: req.user }); + +}; + +exports.registerPost = function(req, res) { + if (typeof req.user !== 'undefined') { + // User is logged in. + res.redirect('/partials/account'); + return; + } + if (!validateEmail(req.param('email'))) { + // Probably not a good email address. + req.flash('error', 'Not a valid email address!'); + res.redirect('/register'); + return; + } + if (req.param('password') !== req.param('password2')) { + // 2 different passwords! + req.flash('error', 'Passwords does not match!'); + res.redirect('/register'); + return; + } + + console.log("role" + req.param('role')); + // Saving the new user to DB + req.db.saveUser({ + username: req.param('username'), + mail: req.param('email'), + role: req.param('role'), + password: bcrypt.hashSync(req.param('password'), 8) + }, + function(err, saved) { + console.log("[DEBUG][/register][saveUser] %s", saved); + if(err) { + req.flash('error', 'There was an error creating the account. Please try again later'); + res.redirect('/register'); + return; + } + if(saved) { + console.log("[DEBUG][/register][saveUser] /invoice"); + res.redirect('/login'); + } + else { + req.flash('error', 'The account wasn\'t created'); + res.redirect('/register'); + console.log("[DEBUG][/register][saveUser] /register"); + } + return; + } + ); +}; + diff --git a/pool/shard011/JavaScript/0069868_indexSpec.js b/pool/shard011/JavaScript/0069868_indexSpec.js new file mode 100644 index 0000000000000000000000000000000000000000..8c2bd7670134eafb3d0943528975c923f831069e --- /dev/null +++ b/pool/shard011/JavaScript/0069868_indexSpec.js @@ -0,0 +1,63 @@ +var ne = require('../index.js') + +const key = 'f66de9e326b4a7defaa0b1e0f015a140' +const hashSalt = '77e701df2dc630eb141d3e24ff81f0d9' +const fooCipher = 'zXAkwFWwTUqxLEscQhnyDQ==--H9eRMjuw1bMZ/k+ki08jjg==' +const fooHash = '2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae' +const fooSaltHash = 'ee643c115a7062742e9a65b1f485469cd8e1b5ec99a20f37f4eca670d7878b88' + +describe ('Encryption / Decryption', () => { + + describe ('encrypt', () => { + it ('encrypts foo with key specified', () => { + ne.encrypt ({ text: 'foo', key: key }, (err, ciphertext) => { + expect (err).toBe(null) + }) + }) + it ('returns missing key error if key is missing', () => { + ne.encrypt ({ text: 'foo' }, (err, ciphertext) => { + expect (err.toString().slice(0, 29)).toBe('Error: Missing encryption key') + }) + }) + it ('encrypts with key not specified but environment var available', () => { + process.env.ENCRYPTION_KEY = key + ne.encrypt ( { text: 'foo' }, (err, ciphertext) => { + expect (err).toBe(null) + }) + }) + }) + + describe ('decrypt', () => { + it ('decrypts foo with key specified', () => { + ne.decrypt ({ cipher: fooCipher, key: key }, (err, plaintext) => { + expect (plaintext).toBe('foo') + }) + }) + it ('decrypt fails with bad key specified', () => { + ne.decrypt ( { cipher: fooCipher, key: 'f66de9e326b4a7defaa0b1xxxxxxxxxx' }, (err, plaintext) => { + expect (err.toString()).toBe('Error: Bad encryption key!') + }) + }) + }) + + describe ('hash', () => { + it ('creates a hash with a salt', () => { + ne.hash ({ text: 'foo', salt: hashSalt }, (err, hash) => { + expect (hash).toBe(fooSaltHash) + }) + }) + it ('creates a hash without a salt', () => { + process.env.HASH_SALT = '' + ne.hash ( { text: 'foo' }, (err, hash) => { + expect (hash).toBe(fooHash) + }) + }) + it ('creates a hash with a salt from env var HASH_SALT', () => { + process.env.HASH_SALT = hashSalt + ne.hash ( { text: 'foo' }, (err, hash) => { + expect (hash).toBe(fooSaltHash) + }) + }) + }) +}) + diff --git a/pool/shard011/JavaScript/0069870_year-test.js b/pool/shard011/JavaScript/0069870_year-test.js new file mode 100644 index 0000000000000000000000000000000000000000..e73831cf6dbb4aed44593840b7cc7a1eb3921d51 --- /dev/null +++ b/pool/shard011/JavaScript/0069870_year-test.js @@ -0,0 +1,137 @@ +require("../env"); + +var vows = require("vows"), + assert = require("assert"); + +var suite = vows.describe("d3.time.year"); + +suite.addBatch({ + "year": { + topic: function() { + return d3.time.year; + }, + "defaults to floor": function(interval) { + assert.strictEqual(interval, interval.floor); + }, + "floor": { + topic: function(interval) { + return interval.floor; + }, + "returns years": function(floor) { + assert.deepEqual(floor(local(2010, 11, 31, 23, 59, 59)), local(2010, 00, 01)); + assert.deepEqual(floor(local(2011, 00, 01, 00, 00, 00)), local(2011, 00, 01)); + assert.deepEqual(floor(local(2011, 00, 01, 00, 00, 01)), local(2011, 00, 01)); + } + }, + "ceil": { + topic: function(interval) { + return interval.ceil; + }, + "returns years": function(ceil) { + assert.deepEqual(ceil(local(2010, 11, 31, 23, 59, 59)), local(2011, 00, 01)); + assert.deepEqual(ceil(local(2011, 00, 01, 00, 00, 00)), local(2011, 00, 01)); + assert.deepEqual(ceil(local(2011, 00, 01, 00, 00, 01)), local(2012, 00, 01)); + } + }, + "offset": { + topic: function(interval) { + return interval.offset; + }, + "does not modify the passed-in date": function(offset) { + var date = local(2010, 11, 31, 23, 59, 59, 999); + offset(date, +1); + assert.deepEqual(date, local(2010, 11, 31, 23, 59, 59, 999)); + }, + "does not round the passed-in-date": function(offset) { + assert.deepEqual(offset(local(2010, 11, 31, 23, 59, 59, 999), +1), local(2011, 11, 31, 23, 59, 59, 999)); + assert.deepEqual(offset(local(2010, 11, 31, 23, 59, 59, 456), -2), local(2008, 11, 31, 23, 59, 59, 456)); + }, + "allows negative offsets": function(offset) { + assert.deepEqual(offset(local(2010, 11, 01), -1), local(2009, 11, 01)); + assert.deepEqual(offset(local(2011, 00, 01), -2), local(2009, 00, 01)); + assert.deepEqual(offset(local(2011, 00, 01), -1), local(2010, 00, 01)); + }, + "allows positive offsets": function(offset) { + assert.deepEqual(offset(local(2009, 11, 01), +1), local(2010, 11, 01)); + assert.deepEqual(offset(local(2009, 00, 01), +2), local(2011, 00, 01)); + assert.deepEqual(offset(local(2010, 00, 01), +1), local(2011, 00, 01)); + }, + "allows zero offset": function(offset) { + assert.deepEqual(offset(local(2010, 11, 31, 23, 59, 59, 999), 0), local(2010, 11, 31, 23, 59, 59, 999)); + assert.deepEqual(offset(local(2010, 11, 31, 23, 59, 58, 000), 0), local(2010, 11, 31, 23, 59, 58, 000)); + } + }, + "UTC": { + topic: function(interval) { + return interval.utc; + }, + "defaults to floor": function(interval) { + assert.strictEqual(interval, interval.floor); + }, + "floor": { + topic: function(interval) { + return interval.floor; + }, + "returns years": function(floor) { + assert.deepEqual(floor(utc(2010, 11, 31, 23, 59, 59)), utc(2010, 00, 01)); + assert.deepEqual(floor(utc(2011, 00, 01, 00, 00, 00)), utc(2011, 00, 01)); + assert.deepEqual(floor(utc(2011, 00, 01, 00, 00, 01)), utc(2011, 00, 01)); + } + }, + "ceil": { + topic: function(interval) { + return interval.ceil; + }, + "returns years": function(ceil) { + assert.deepEqual(ceil(utc(2010, 11, 31, 23, 59, 59)), utc(2011, 00, 01)); + assert.deepEqual(ceil(utc(2011, 00, 01, 00, 00, 00)), utc(2011, 00, 01)); + assert.deepEqual(ceil(utc(2011, 00, 01, 00, 00, 01)), utc(2012, 00, 01)); + } + }, + "offset": { + topic: function(interval) { + return interval.offset; + }, + "does not modify the passed-in date": function(offset) { + var date = utc(2010, 11, 31, 23, 59, 59, 999); + offset(date, +1); + assert.deepEqual(date, utc(2010, 11, 31, 23, 59, 59, 999)); + }, + "does not round the passed-in-date": function(offset) { + assert.deepEqual(offset(utc(2010, 11, 31, 23, 59, 59, 999), +1), utc(2011, 11, 31, 23, 59, 59, 999)); + assert.deepEqual(offset(utc(2010, 11, 31, 23, 59, 59, 456), -2), utc(2008, 11, 31, 23, 59, 59, 456)); + }, + "allows negative offsets": function(offset) { + assert.deepEqual(offset(utc(2010, 11, 01), -1), utc(2009, 11, 01)); + assert.deepEqual(offset(utc(2011, 00, 01), -2), utc(2009, 00, 01)); + assert.deepEqual(offset(utc(2011, 00, 01), -1), utc(2010, 00, 01)); + }, + "allows positive offsets": function(offset) { + assert.deepEqual(offset(utc(2009, 11, 01), +1), utc(2010, 11, 01)); + assert.deepEqual(offset(utc(2009, 00, 01), +2), utc(2011, 00, 01)); + assert.deepEqual(offset(utc(2010, 00, 01), +1), utc(2011, 00, 01)); + }, + "allows zero offset": function(offset) { + assert.deepEqual(offset(utc(2010, 11, 31, 23, 59, 59, 999), 0), utc(2010, 11, 31, 23, 59, 59, 999)); + assert.deepEqual(offset(utc(2010, 11, 31, 23, 59, 58, 000), 0), utc(2010, 11, 31, 23, 59, 58, 000)); + } + } + } + } +}); + +function local(year, month, day, hours, minutes, seconds, milliseconds) { + var date = new Date(); + date.setFullYear(year, month, day); + date.setHours(hours || 0, minutes || 0, seconds || 0, milliseconds || 0); + return date; +} + +function utc(year, month, day, hours, minutes, seconds, milliseconds) { + var date = new Date(); + date.setUTCFullYear(year, month, day); + date.setUTCHours(hours || 0, minutes || 0, seconds || 0, milliseconds || 0); + return date; +} + +suite.export(module); diff --git a/pool/shard011/JavaScript/0069874_connector.js b/pool/shard011/JavaScript/0069874_connector.js new file mode 100644 index 0000000000000000000000000000000000000000..e3dade5afffebd690d9a5a137ac067f497d28a78 --- /dev/null +++ b/pool/shard011/JavaScript/0069874_connector.js @@ -0,0 +1,51 @@ +import { connect } from 'react-redux'; +import { + hasProductVariants, + isProductOrderable, +} from '@shopgate/pwa-common-commerce/product/selectors/product'; +import { isProductPageLoading } from '@shopgate/pwa-common-commerce/product/selectors/page'; +import { addProductToCart } from './actions'; + +/** + * @param {Object} state The current application state. + * @param {Object} props The component props. + * @return {Object} The extended component props. + */ +const mapStateToProps = (state, props) => ({ + /** + * 1. Product has no variants and not orderable + * 2. Parent product can be not orderable but having orderable variants + */ + disabled: !isProductOrderable(state, props) && !hasProductVariants(state, props), + loading: isProductPageLoading(state, props), +}); + +/** + * @param {Function} dispatch The redux dispatch function. + * @param {Function} props The component props. + * @return {Object} The extended component props. + */ +const mapDispatchToProps = dispatch => ({ + addToCart: (product) => { + dispatch(addProductToCart(product)); + }, +}); + +/** + * @param {Object} next The next component props. + * @param {Object} prev The previous component props. + * @return {boolean} + */ +const areStatePropsEqual = (next, prev) => { + if (prev.disabled !== next.disabled) { + return false; + } + + if (prev.loading !== next.loading) { + return false; + } + + return true; +}; + +export default connect(mapStateToProps, mapDispatchToProps, null, { areStatePropsEqual }); diff --git a/pool/shard011/JavaScript/0069875_taskmill-editor-atom.js b/pool/shard011/JavaScript/0069875_taskmill-editor-atom.js new file mode 100644 index 0000000000000000000000000000000000000000..6b3e260b83e21b84f1b12a8d2b763fc21e02f9d3 --- /dev/null +++ b/pool/shard011/JavaScript/0069875_taskmill-editor-atom.js @@ -0,0 +1,94 @@ +var CompositeDisposable = require('atom').CompositeDisposable; + +var MySelectListView = require('./select-list-view'); +var _ = require('lodash'); +var taskmill_cli = require('taskmill-cli'); + +module.exports = { + subscriptions: null, + activate: function(state) { + this.subscriptions = new CompositeDisposable; + return this.subscriptions.add(atom.commands.add('atom-workspace', { + 'taskmill-editor-atom:chose': (function(_this) { + return function() { + return _this.chose(); + }; + })(this) + })); + }, + deactivate: function() { + this.subscriptions.dispose(); + }, + chose: function() { + var editor = atom.workspace.getActiveTextEditor(); + + MySelectListView + .show(taskmill_cli.search().then(function(result){ + return _.map(result, function(item){ + var label = item.title || '' + , detail = item.html_url || '' + , description = item.description || '' + ; + + return _.extend(item, { + description : description + , detail : detail + , label : label + , fuzzy : label + '\n' + description + '\n' + detail + }); + }); + })) + .then(function(chosen) { + if (chosen) { + var text = undefined; + if (editor) { + text = editor.getSelectedText(); + } + + taskmill_cli + .run(chosen.run_url, text) + .then(function(result){ + if (result.encoding != 'binary' && editor) { + return result + .readFile() + .then(function(text){ + var sel = editor.getLastSelection(); + var range = sel.getScreenRange(); + + if (range.isEmpty()) { + sel.insertText(text); + } else { + var pragma = result.pragma; + var re = /^editor\s+(\w+)$/; + var directive = _.chain(pragma) + .map(function(pragma) { + var m = undefined; + if (m = re.exec(pragma)) { + return m[1]; + } + }) + .compact() + .first() + .value(); + + if (directive === 'replace') { + sel.insertText(text, { select : true }); + } else { + var cur = editor.getCursorBufferPosition() + editor.setCursorBufferPosition([range.end.row, range.end.column]) + editor.insertText('\n' + text); + editor.setCursorBufferPosition(cur) + } + } + }); + } else { + return result.open(); + } + }); + } + }) + .catch(function(err) { + console.error(err); + }); + } +}; diff --git a/pool/shard011/JavaScript/0069876_chart-loader.js b/pool/shard011/JavaScript/0069876_chart-loader.js new file mode 100644 index 0000000000000000000000000000000000000000..abb5c1c34607db901fa13a2373a49fc688eb9870 --- /dev/null +++ b/pool/shard011/JavaScript/0069876_chart-loader.js @@ -0,0 +1,86 @@ +var dataDisplay; +var taxPercentage; + +function loadCharts(parsedData) { + Chart.defaults.global.responsive = true; + Chart.defaults.global.maintainAspectRatio = false; + dataDisplay = new DataDisplay(parsedData.loads, parsedData.rides); + taxPercentage = 0; + + loadMonthlyPassAnalysis() +} + +function barChartOptions() { + return { + //Boolean - Whether grid lines are shown across the chart + scaleShowGridLines : false, + //Boolean - If there is a stroke on each bar + barShowStroke : false, + scaleFontFamily: "'Montserrat', sans-serif", + } +} + +function loadMonthlyPassAnalysis() { + //Calculate pass cost when accounting for percentage of taxes. + var monthlyPassDollars = 100; + var incomePercentage = 100 - taxPercentage; + var multiplier = incomePercentage / 100; + var passDollarsAdjustedForTaxPercentage = monthlyPassDollars * multiplier; + + var labels = dataDisplay.allMonthLabels(); + var cost = dataDisplay.costByMonth(); + + var monthlyData = { + labels: labels, + datasets: [ + { + label: "My First dataset", + fillColor: "rgba(41,165,165,1)", +// strokeColor: "rgba(220,220,220,0.8)", + highlightFill: "rgba(41,165,165,0.75)", +// highlightStroke: "rgba(220,220,220,1)", + data: cost + }, + ] + }; + + renderBar(monthlyData, "monthly-pass-chart", 800, 400); + // Get context with jQuery - using jQuery's .get() method. +/* + var ctx = $("#monthly-pass-chart").get(0).getContext('2d'); + + var chartInstance = new Chart(ctx); + + // This will get the first returned node in the jQuery collection. + new chartInstance.Bar(monthlyData, barChartOptions()); +*/ + + +} + +/** + * Renders the charts in specified Divs + * @param data + * @param idOfCanvas + */ +function renderBar(data, idOfCanvas, width, height) { + var $canvas = $('#' + idOfCanvas); + var $parent = $canvas.parent(); + /** + * Canvas needs to be removed and re-rendered before we draw the chart + * Reason: When Chart is rendered and Window is Zoomed Out, On hovering the chart produces + * glitch in the chart + */ + $canvas.remove(); + $parent.prepend(""); + + var ctx = $parent.find('#' + idOfCanvas).get(0).getContext("2d"); + var chart = new Chart(ctx).Bar(data, barChartOptions()); + var legend = chart.generateLegend(); + $('#' + idOfCanvas + '-legend').html(legend); +} + +function adjustTaxPercentage(percentage) { + taxPercentage = parseFloat(percentage); + loadMonthlyPassAnalysis() +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069878_pageRender.js b/pool/shard011/JavaScript/0069878_pageRender.js new file mode 100644 index 0000000000000000000000000000000000000000..af216652f270b4b21dc061dc6bbf48008e4c2a71 --- /dev/null +++ b/pool/shard011/JavaScript/0069878_pageRender.js @@ -0,0 +1,114 @@ +import React from 'react'; +import ReactDOMServer from 'react-dom/server'; + +//TODO use config file +const PUBLIC_PATH = '/build/'; + +/** + * + * + * @param domainName + * @param pageName + * @returns {{scriptSrcList: *, styleSrcList: *, svgSpritePath: *}} + */ +function getPageResources(domainName, pageName) { + let scriptSrcList; + let styleSrcList; + let headerScriptSrcList; + + scriptSrcList = [ + `${PUBLIC_PATH}vendor.js`, + `${PUBLIC_PATH}${domainName}.${pageName}.js` + ]; + + styleSrcList = [ + `${PUBLIC_PATH}vendor.css`, + `${PUBLIC_PATH}${domainName}.${pageName}.css` + ]; + + //TODO remove headerScript + headerScriptSrcList = [ + `${PUBLIC_PATH}jquery-2.2.4.min.js`, + `${PUBLIC_PATH}bootstrap.3.3.7.min.js` + ]; + + return { + scriptSrcList: scriptSrcList.filter( src => !!src ), + styleSrcList: styleSrcList.filter( src => !!src ), + headerScriptSrcList + }; +} + + +/** + * Render React component to string + * + * @param {React.Component} Component - target React component + * @param {Object} [componentProps] - component props + * + * @returns {string} html - rendered component to string + */ +function renderReactComponent(Component, componentProps) { + return ReactDOMServer.renderToString(); +} + + +/** + * renderHTML - render HTML based on parameters + * + * @param {string} title - page title + * @param {array} styleSrcList - list of src strings to styles + * @param {array} scriptSrcList - list of src strings to scripts + * @param {string} html - html string to be rendered as a part of body + * @param headerScriptSrcList + * @returns {string} + */ +function renderHTML( { + title, + styleSrcList, + headerScriptSrcList, + scriptSrcList, + html +}) { + + const generateScripts = (scripts) => + scripts.filter(src => !!src).map(src => ``).join(''); + + + return ` + + + + ${title} + ${styleSrcList.map(src => ``).join('')} + + +
    ${html}
    + ${generateScripts(scriptSrcList)} + + + `; +} + + +export function renderApp (AppComponent, { + domainName, + pageName, + pageTitle +}) { + const { + scriptSrcList, + styleSrcList, + headerScriptSrcList + } = getPageResources(domainName, pageName); + + const html = renderHTML({ + title: pageTitle || `${pageName} | ${domainName}`, + html: renderReactComponent(AppComponent), + scriptSrcList, + styleSrcList, + headerScriptSrcList + }); + + return html; +}; diff --git a/pool/shard011/JavaScript/0069880_traceability_provider.js b/pool/shard011/JavaScript/0069880_traceability_provider.js new file mode 100644 index 0000000000000000000000000000000000000000..459bfdbeccd4a5f56ec9b56fed94fc2eab28d1ef --- /dev/null +++ b/pool/shard011/JavaScript/0069880_traceability_provider.js @@ -0,0 +1,41 @@ +"use strict"; + +var ENABLE_TRACEBLE_PROVIDER = false; +var http = require('http'); + +class TraceabilityProvider { + constructor() { + this.count = 0; + } + + // public methods + start() { + if (ENABLE_TRACEBLE_PROVIDER) { + console.log('Starting TraceabilityProvider'); + this._checkEvents(); + } + } + + // private methods + _checkEvents() { + var self = this; + setTimeout(function() { + self._fetchCompletedEvents(self._submitEvents); + self._checkEvents(); + }, 1000); + } + + _fetchCompletedEvents(callback) { + this.count += 1; + callback(null, this.count); + } + + _submitEvents(err, events) { + if (err) + return; + + console.log("Submitting event:", events); + } +} + +module.exports = new TraceabilityProvider(); diff --git a/pool/shard011/JavaScript/0069882_tutorial1-wdio.js b/pool/shard011/JavaScript/0069882_tutorial1-wdio.js new file mode 100644 index 0000000000000000000000000000000000000000..506fa4424abe2e04ece98682adf1bd21f4bd9fac --- /dev/null +++ b/pool/shard011/JavaScript/0069882_tutorial1-wdio.js @@ -0,0 +1,42 @@ +// tutorial1-wdio.js +// +// This is a simple test script that does the following tests: +// open a website +// validate title +// + +// To Run: +// $ wdio wdio.conf-tutorial1.js + +// Updated to support version 4 of webdriverio + +// required libraries +var webdriverio = require('webdriverio'), + should = require('should'); + +// a test script block or suite +describe('Title Test for Web Driver IO - Tutorial Test Page Website', function() { + + // set timeout to 10 seconds + this.timeout(10000); + var driver = {}; + + // hook to run before tests + before( function() { + // wdio will load the browser driver + driver = browser; + }); + + // a test spec - "specification" + it('should be load correct page and title', function () { + // load page, then call function() + driver.url('http://www.tlkeith.com/WebDriverIOTutorialTest.html'); + // get title, then pass title to function() + var title = driver.getTitle(); + // verify title + (title).should.be.equal("Web Driver IO - Tutorial Test Page"); + // uncomment for console debug + // console.log('Current Page Title: ' + title); + }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069887_main.js b/pool/shard011/JavaScript/0069887_main.js new file mode 100644 index 0000000000000000000000000000000000000000..4ad0dbcc08e1f7ed48c21eb46332a0c081eacf62 --- /dev/null +++ b/pool/shard011/JavaScript/0069887_main.js @@ -0,0 +1,109 @@ +$(document).ready(function() { + // Move the site information block below the other blocks + $("#site-info-block").insertAfter("#map-block"); + + // Read the resource in order to generate the user interface + readResource(startingResource, schemas["http://resources.usgin.org/uri-gin/usgin/schema/json-metadata/"]); + + // Setup the contact dialog + $("#add-contact-dialog").dialog({ + autoOpen: false, + modal: true, + resizable: false, + width: 500, + buttons: { + "Add Contact": function() { + $.get("/contact/" + $("#new-selected-contact").val(), function(response) { + writeToArray( + response, + schemas["http://resources.usgin.org/uri-gin/usgin/schema/json-metadata-contact/"], + $("#add-contact-dialog").dialog("option", "context") + ); + }); + $(this).dialog("close"); + }, + Cancel: function() { + $(this).dialog("close"); + } + } + }); + refreshContactOptions(); + + // Setup the collections dialog + $("#add-collection-dialog").dialog({ + autoOpen: false, + modal: true, + resizeable: false, + width: 500, + buttons: { + "Add to selected collection": function() { + id = $("#new-selected-collection").val(); + title = $("#new-collection-selector").val(); + $("#collections-current-list").prepend("
  • " + title + "
  • "); + $("#nil-collection").remove(); + writeToArray(id, schemas["http://resources.usgin.org/uri-gin/usgin/schema/json-metadata/"].properties.Collections.items, $("#theResource-Collections")); + $(this).dialog("close"); + }, + Cancel: function() { + $(this).dialog("close"); + } + } + }); + + $.post("/collection-names", { ids: "all" }, function(response) { + collections = []; + for (var r in response) { collections.push({ id: response[r].id, value: response[r].value.title }); } + $("#new-collection-selector").autocomplete({ + source: collections, + select: function(event, ui) { + $("#new-selected-collection").val(ui.item.id); + $(this).val(ui.item.value); + return false; + } + }); + }); + + // Setup the response for saving a new contact + $("#saved-contact-dialog").dialog({ + autoOpen: false, + modal: true, + resizable: false, + buttons: { + "OK": function() { + $(this).dialog("close"); + } + } + }); + + // Setup the validation dialog + $("#validation-dialog").dialog({ + autoOpen: false, + modal: true, + resizable: true, + width: 850, + buttons: { + "OK": function() { + $(this).dialog("close"); + } + } + }); + + // Setup the deletion dialog + $("#deletion-dialog").dialog({ + autoOpen: false, + modal: true, + resizable: true, + width: 850, + buttons: { + "OK": function() { + $.get("/delete-resource/" + $(this).dialog("option", "theid"), function(response) { + window.location = "/search/"; + }); + $(this).dialog("close"); + }, + Cancel: function() { + $(this).dialog("close"); + } + } + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069888_app.js b/pool/shard011/JavaScript/0069888_app.js new file mode 100644 index 0000000000000000000000000000000000000000..032dd6dfad65d4235f717f9a1137a6dd2ab47a74 --- /dev/null +++ b/pool/shard011/JavaScript/0069888_app.js @@ -0,0 +1,48 @@ +var express = require('express'); +var session = require('cookie-session'); // Charge le middleware de sessions +var bodyParser = require('body-parser'); // Charge le middleware de gestion des paramètres +var urlencodedParser = bodyParser.urlencoded({ extended: false }); + +var app = express(); + + +/* On utilise les sessions */ +app.use(session({secret: 'todotopsecret'})) + + +/* S'il n'y a pas de todolist dans la session, +on en crée une vide sous forme d'array avant la suite */ +.use(function(req, res, next){ + if (typeof(req.session.todolist) == 'undefined') { + req.session.todolist = []; + } + next(); +}) + +/* On affiche la todolist et le formulaire */ +.get('/todo', function(req, res) { + res.render('todo.ejs', {todolist: req.session.todolist}); +}) + +/* On ajoute un élément à la todolist */ +.post('/todo/ajouter/', urlencodedParser, function(req, res) { + if (req.body.newtodo != '') { + req.session.todolist.push(req.body.newtodo); + } + res.redirect('/todo'); +}) + +/* Supprime un élément de la todolist */ +.get('/todo/supprimer/:id', function(req, res) { + if (req.params.id != '') { + req.session.todolist.splice(req.params.id, 1); + } + res.redirect('/todo'); +}) + +/* On redirige vers la todolist si la page demandée n'est pas trouvée */ +.use(function(req, res, next){ + res.redirect('/todo'); +}) + +.listen(8080); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069889_getTypeFromName.js b/pool/shard011/JavaScript/0069889_getTypeFromName.js new file mode 100644 index 0000000000000000000000000000000000000000..f53abaf31604426c567dd399619b2dadf1417e02 --- /dev/null +++ b/pool/shard011/JavaScript/0069889_getTypeFromName.js @@ -0,0 +1,19 @@ +import getTypeFromName from '../../lib/helpers/getTypeFromName'; + +it('accept empty configs', () => { + expect(getTypeFromName()).toBe(null); + expect(getTypeFromName({})).toBe(null); + expect(getTypeFromName({ types: [] })).toBe(null); +}); + +it('cannot find name', () => { + const config = { types: [{ type: 'find' }] }; + + expect(getTypeFromName(config, 'findme')).toBe(null); +}); + +it('find name', () => { + const config = { types: [{ type: 'findme' }] }; + + expect(getTypeFromName(config, 'findme')).toEqual({ type: 'findme' }); +}); diff --git a/pool/shard011/JavaScript/0069894_extendableCalculatorTest.js b/pool/shard011/JavaScript/0069894_extendableCalculatorTest.js new file mode 100644 index 0000000000000000000000000000000000000000..31e07cf091d510f6cb8d8cfff2e90713355eae3b --- /dev/null +++ b/pool/shard011/JavaScript/0069894_extendableCalculatorTest.js @@ -0,0 +1,47 @@ +/** + * @file extendableCalculatorTest.js + * @author Vladimir Deminenko + * @date 16.08.2017 + */ + +'use strict'; + +describe('extendable calculator', function () { + let calculator; + + before(function () { + calculator = new ExtendableCalculator(); + }); + + after(function () { + calculator = null; + }); + + it('calculate(12 + 34) = 46', function () { + assert.equal(calculator.calculate('12 + 34'), 46); + }); + + it('calculate(34 - 12) = 22', function () { + assert.equal(calculator.calculate('34 - 12'), 22); + }); + + it('добавили умножение: calculate(2 * 3) = 6', function () { + calculator.addMethod('*', function (a, b) { + return a * b; + }); + + assert.equal(calculator.calculate('2 * 3'), 6); + }); + + it('добавили возведение в степень: calculate(2 ** 3) = 8', function () { + calculator.addMethod('**', function (a, b) { + return Math.pow(a, b); + }); + + assert.equal(calculator.calculate('2 ** 3'), 8); + }); + + it('calculate() throws an TypeError exception', function () { + assert.throws(calculator.calculate, TypeError, 'Incorrect use of a method'); + }); +}); diff --git a/pool/shard011/JavaScript/0069897_contextual.toolbar.js b/pool/shard011/JavaScript/0069897_contextual.toolbar.js new file mode 100644 index 0000000000000000000000000000000000000000..b5a9053490c0bd195ea15f6ecab07afaa5ac5d66 --- /dev/null +++ b/pool/shard011/JavaScript/0069897_contextual.toolbar.js @@ -0,0 +1,77 @@ +/** + * @file + * Attaches behaviors for the Contextual module's edit toolbar tab. + */ + +(function ($, Drupal, Backbone) { + + 'use strict'; + + var strings = { + tabbingReleased: Drupal.t('Tabbing is no longer constrained by the Contextual module.'), + tabbingConstrained: Drupal.t('Tabbing is constrained to a set of @contextualsCount and the edit mode toggle.'), + pressEsc: Drupal.t('Press the esc key to exit.') + }; + + /** + * Initializes a contextual link: updates its DOM, sets up model and views. + * + * @param {HTMLElement} context + * A contextual links DOM element as rendered by the server. + */ + function initContextualToolbar(context) { + if (!Drupal.contextual || !Drupal.contextual.collection) { + return; + } + + var contextualToolbar = Drupal.contextualToolbar; + var model = contextualToolbar.model = new contextualToolbar.StateModel({ + // Checks whether localStorage indicates we should start in edit mode + // rather than view mode. + // @see Drupal.contextualToolbar.VisualView.persist + isViewing: localStorage.getItem('Drupal.contextualToolbar.isViewing') !== 'false' + }, { + contextualCollection: Drupal.contextual.collection + }); + + var viewOptions = { + el: $('.toolbar .toolbar-bar .contextual-toolbar-tab'), + model: model, + strings: strings + }; + new contextualToolbar.VisualView(viewOptions); + new contextualToolbar.AuralView(viewOptions); + } + + /** + * Attaches contextual's edit toolbar tab behavior. + * + * @type {Drupal~behavior} + * + * @prop {Drupal~behaviorAttach} attach + * Attaches contextual toolbar behavior on a contextualToolbar-init event. + */ + Drupal.behaviors.contextualToolbar = { + attach: function (context) { + if ($('body').once('contextualToolbar-init').length) { + initContextualToolbar(context); + } + } + }; + + /** + * Namespace for the contextual toolbar. + * + * @namespace + */ + Drupal.contextualToolbar = { + + /** + * The {@link Drupal.contextualToolbar.StateModel} instance. + * + * @type {?Drupal.contextualToolbar.StateModel} + */ + model: null + }; + +})(jQuery, Drupal, Backbone); diff --git a/pool/shard011/JavaScript/0069903_soluznodes.server.routes.js b/pool/shard011/JavaScript/0069903_soluznodes.server.routes.js new file mode 100644 index 0000000000000000000000000000000000000000..6bdb3eb3d34e2081a16327b7af78ad50e9ed6181 --- /dev/null +++ b/pool/shard011/JavaScript/0069903_soluznodes.server.routes.js @@ -0,0 +1,19 @@ +'use strict'; + +module.exports = function(app) { + var users = require('../../app/controllers/users'); + var soluznodes = require('../../app/controllers/soluznodes'); + + // Soluznodes Routes + app.route('/soluznodes') + .get(soluznodes.list) + .post(users.requiresLogin, soluznodes.create); + + app.route('/soluznodes/:soluznodeId') + .get(soluznodes.read) + .put(users.requiresLogin, soluznodes.hasAuthorization, soluznodes.update) + .delete(users.requiresLogin, soluznodes.hasAuthorization, soluznodes.delete); + + // Finish by binding the Soluznode middleware + app.param('soluznodeId', soluznodes.soluznodeByID); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069904_instant-report-field-options-controller.js b/pool/shard011/JavaScript/0069904_instant-report-field-options-controller.js new file mode 100644 index 0000000000000000000000000000000000000000..7bebcfa17ab9cf8c70be1928a97708df1e0f149f --- /dev/null +++ b/pool/shard011/JavaScript/0069904_instant-report-field-options-controller.js @@ -0,0 +1,257 @@ +/** +* Instant report field options controller +*/ +angular +.module('izendaInstantReport') +.controller('InstantReportFieldOptionsController', [ + '$rootScope', + '$scope', + '$window', + '$timeout', + '$q', + '$sce', + '$log', + '$izendaInstantReportQuery', + '$izendaInstantReportStorage', + InstantReportFieldOptionsController +]); + +function InstantReportFieldOptionsController( + $rootScope, + $scope, + $window, + $timeout, + $q, + $sce, + $log, + $izendaInstantReportQuery, + $izendaInstantReportStorage) { + 'use strict'; + var vm = this; + var primaryButtonClass = "btn-izenda-dark", + activeButtonClass = "btn-izenda-dark active"; + + + $scope.$izendaInstantReportStorage = $izendaInstantReportStorage; + vm.field = null; + vm.currentSortFunction = 'asc'; + vm.isSubtotalsEnabled = false; + + vm.drillDownStyles = $izendaInstantReportStorage.getDrillDownStyles(); + vm.subreports = $izendaInstantReportStorage.getSubreports(); + vm.expanded = false; + vm.ddkValuesMaxAmount = -1; + + /** + * Get class + */ + vm.getPanelClass = function () { + if (!angular.isObject(vm.field) || !$scope.irController.isLeftPanelBodyActive(0)) + return 'collapsed'; + if (vm.expanded) + return 'expanded'; + return ''; + }; + + /** + * Get classes for validate messages icon + */ + vm.getValidateMessageIconClass = function (message) { + return message; + }; + + /** + * Fires when description was set manually. + */ + vm.onDescriptionWasSet = function () { + vm.field.isDescriptionSetManually = vm.field.description !== ''; + }; + + /** + * Fires when group was selected + */ + vm.onFunctionSelected = function () { + if (vm.field.groupByFunction === null) + return; + $izendaInstantReportStorage.onFieldFunctionApplyed(vm.field); + }; + + /** + * Fires when typegroup was selected + */ + vm.onTypeGroupSelected = function() { + $izendaInstantReportStorage.onExpressionTypeGroupApplyed(vm.field); + }; + + /** + * Update preview + */ + vm.applyChanges = function () { + $izendaInstantReportStorage.getReportPreviewHtml(); + }; + + /** + * Get sort button class + */ + vm.getSortButtonClass = function () { + if (vm.field === null) + return primaryButtonClass; + var cls = ''; + cls += ' ' + (vm.field.sort !== null ? activeButtonClass : primaryButtonClass); + return cls.trim(); + } + + /** + * Get sort button icon class + */ + vm.getSortButtonGlyphClass = function () { + return vm.currentSortFunction === 'desc' ? 'glyphicon-sort-by-alphabet-alt' : 'glyphicon-sort-by-alphabet'; + } + + /** + * Apply field sort. Parameter should be 'asc', 'desc' or null + */ + vm.applyFieldSort = function (sortFunction) { + if (!angular.isDefined(sortFunction)) { + if (vm.field.sort === null) { + // enable selected sort + $izendaInstantReportStorage.applyFieldSort(vm.field, vm.currentSortFunction); + } else { + // disable selected sort + $izendaInstantReportStorage.applyFieldSort(vm.field, null); + } + } else { + // set and enable selected sort + vm.currentSortFunction = sortFunction; + $izendaInstantReportStorage.applyFieldSort(vm.field, vm.currentSortFunction); + } + }; + + /** + * Get italic button class + */ + vm.getItalicButtonClass = function () { + if (vm.field === null) + return primaryButtonClass; + return vm.field.italic ? activeButtonClass : primaryButtonClass; + }; + + /** + * Apply field italic. + */ + vm.applyFieldItalic = function () { + $izendaInstantReportStorage.applyFieldItalic(vm.field, !vm.field.italic); + }; + + /** + * Get visible button class + */ + vm.getVisibleButtonClass = function() { + if (vm.field === null) + return primaryButtonClass; + return vm.field.visible ? primaryButtonClass : activeButtonClass; + }; + + /** + * Apply field italic. + */ + vm.applyFieldVisible = function () { + $izendaInstantReportStorage.applyFieldVisible(vm.field, !vm.field.visible); + }; + + /** + * Get bold button class + */ + vm.getBoldButtonClass = function () { + if (vm.field === null) + return primaryButtonClass; + return vm.field.bold ? activeButtonClass : primaryButtonClass; + }; + + /** + * Apply field bold. + */ + vm.applyFieldBold = function () { + $izendaInstantReportStorage.applyFieldBold(vm.field, !vm.field.bold); + }; + + /** + * Get visual group button class + */ + vm.getVgButtonClass = function () { + if (vm.field === null) + return primaryButtonClass; + return vm.field.isVgUsed ? activeButtonClass : primaryButtonClass; + }; + + /** + * If user selects non-default subtotal function, we need to turn on subtotals. + */ + vm.onSubtotalFunctionSelect = function () { + var subtotalFunction = vm.field.groupBySubtotalFunction; + if (subtotalFunction !== 'DEFAULT') + $izendaInstantReportStorage.getOptions().isSubtotalsEnabled = true; + }; + + /** + * Apply visual group changed + */ + vm.applyVg = function () { + $izendaInstantReportStorage.applyVisualGroup(vm.field, !vm.field.isVgUsed); + }; + + /** + * Check is subtotal group function === expression + */ + vm.isSubtotalExpressionDisabled = function () { + if (!angular.isObject(vm.field)) + return true; + if (!vm.isSubtotalsEnabled) + return true; + if (!angular.isObject(vm.field.groupBySubtotalFunction)) + return true; + return vm.field.groupBySubtotalFunction.value !== 'EXPRESSION'; + }; + + /** + * Close panel + */ + vm.closePanel = function () { + $izendaInstantReportStorage.setCurrentActiveField(null); + }; + + /** + * Initialize watchers + */ + vm.initWatchers = function () { + $scope.$watch('$izendaInstantReportStorage.getCurrentActiveField()', function (field) { + vm.field = field; + vm.expanded = false; + }); + + $scope.$watch('$izendaInstantReportStorage.getDrillDownStyles()', function (ddStyles) { + vm.drillDownStyles = ddStyles; + }); + + $scope.$watch('$izendaInstantReportStorage.getExpressionTypes()', function (types) { + vm.expressionTypes = types; + }); + + $scope.$watch('$izendaInstantReportStorage.getSubreports()', function(subreports) { + vm.subreports = subreports; + }); + + $scope.$watch('$izendaInstantReportStorage.getOptions().isSubtotalsEnabled', function (isSubtotalsEnabled) { + vm.isSubtotalsEnabled = isSubtotalsEnabled; + }); + }; + + /** + * Initialize controller + */ + vm.init = function () { + }; + + // initialize with controller + vm.initWatchers(); +} diff --git a/pool/shard011/JavaScript/0069905_conversion-struct.js b/pool/shard011/JavaScript/0069905_conversion-struct.js new file mode 100644 index 0000000000000000000000000000000000000000..f5e43ffa563b1c3dd03dd609a21421e85649a8e3 --- /dev/null +++ b/pool/shard011/JavaScript/0069905_conversion-struct.js @@ -0,0 +1,36 @@ +// Type conversion error should report its type. + +load(libdir + 'asserts.js'); + +function test() { + let test_struct = ctypes.StructType("test_struct", [{ "x": ctypes.int32_t }, + { "bar": ctypes.int32_t }]); + + // constructor + assertTypeErrorMessage(() => { new test_struct("foo"); }, + "can't convert the string \"foo\" to the type test_struct"); + assertTypeErrorMessage(() => { new test_struct("foo", "x"); }, + "can't convert the string \"foo\" to the 'x' field (int32_t) of test_struct"); + assertTypeErrorMessage(() => { new test_struct({ "x": "foo", "bar": 1 }); }, + "can't convert the string \"foo\" to the 'x' field (int32_t) of test_struct"); + assertTypeErrorMessage(() => { new test_struct({ 0: 1, "bar": 1 }); }, + "property name the number 0 of the object ({0:1, bar:1}) is not a string"); + + // field setter + let struct_val = test_struct(); + assertTypeErrorMessage(() => { struct_val.x = "foo"; }, + "can't convert the string \"foo\" to the 'x' field (int32_t) of test_struct"); + assertTypeErrorMessage(() => { struct_val.bar = "foo"; }, + "can't convert the string \"foo\" to the 'bar' field (int32_t) of test_struct"); + + // value setter + assertTypeErrorMessage(() => { struct_val.value = { "x": "foo" }; }, + "property count of the object ({x:\"foo\"}) does not match to field count of the type test_struct (expected 2, got 1)"); + assertTypeErrorMessage(() => { struct_val.value = { "x": "foo", "bar": 1 }; }, + "can't convert the string \"foo\" to the 'x' field (int32_t) of test_struct"); + assertTypeErrorMessage(() => { struct_val.value = "foo"; }, + "can't convert the string \"foo\" to the type test_struct"); +} + +if (typeof ctypes === "object") + test(); diff --git a/pool/shard011/JavaScript/0069906_style.js b/pool/shard011/JavaScript/0069906_style.js new file mode 100644 index 0000000000000000000000000000000000000000..a0286223b17a29ef062b202e21a2c6a57ef08d3a --- /dev/null +++ b/pool/shard011/JavaScript/0069906_style.js @@ -0,0 +1,21 @@ +'use strict'; + +var gulp = require('gulp'), + config = require('../config'), + paths = config.paths; + +gulp.task('styles', function() { + var sass = require('gulp-sass'), + cssnano = require('gulp-cssnano'), + prefix = require('gulp-autoprefixer'), + path = require('path'), + sourcemaps = require('gulp-sourcemaps'); + + return gulp.src(paths.source.styles, {base : path.join(process.cwd(), paths.source.root)}) + .pipe(sourcemaps.init()) + .pipe(sass({includePaths: ['./' + paths.source.root + ' css']})) + .pipe(cssnano()) + .pipe(prefix('last 1 version', '> 1%')) + .pipe(sourcemaps.write('./')) + .pipe(gulp.dest(paths.dest)); +}); diff --git a/pool/shard011/JavaScript/0069911_Function.js b/pool/shard011/JavaScript/0069911_Function.js new file mode 100644 index 0000000000000000000000000000000000000000..bcdb55302bac947c622edfa7b02bcef800c563ba --- /dev/null +++ b/pool/shard011/JavaScript/0069911_Function.js @@ -0,0 +1,510 @@ +/* +This file is part of Ext JS 4.2 + +Copyright (c) 2011-2013 Sencha Inc + +Contact: http://www.sencha.com/contact + +GNU General Public License Usage +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 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 http://www.sencha.com/contact. + +Build date: 2013-05-16 14:36:50 (f9be68accb407158ba2b1be2c226a6ce1f649314) +*/ +// @tag foundation,core +// @require Array.js +// @define Ext.Function + +/** + * @class Ext.Function + * + * A collection of useful static methods to deal with function callbacks + * @singleton + * @alternateClassName Ext.util.Functions + */ +Ext.Function = { + + /** + * A very commonly used method throughout the framework. It acts as a wrapper around another method + * which originally accepts 2 arguments for `name` and `value`. + * The wrapped function then allows "flexible" value setting of either: + * + * - `name` and `value` as 2 arguments + * - one single object argument with multiple key - value pairs + * + * For example: + * + * var setValue = Ext.Function.flexSetter(function(name, value) { + * this[name] = value; + * }); + * + * // Afterwards + * // Setting a single name - value + * setValue('name1', 'value1'); + * + * // Settings multiple name - value pairs + * setValue({ + * name1: 'value1', + * name2: 'value2', + * name3: 'value3' + * }); + * + * @param {Function} setter + * @returns {Function} flexSetter + */ + flexSetter: function(fn) { + return function(a, b) { + var k, i; + + if (a === null) { + return this; + } + + if (typeof a !== 'string') { + for (k in a) { + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + + if (Ext.enumerables) { + for (i = Ext.enumerables.length; i--;) { + k = Ext.enumerables[i]; + if (a.hasOwnProperty(k)) { + fn.call(this, k, a[k]); + } + } + } + } else { + fn.call(this, a, b); + } + + return this; + }; + }, + + /** + * Create a new function from the provided `fn`, change `this` to the provided scope, optionally + * overrides arguments for the call. (Defaults to the arguments passed by the caller) + * + * {@link Ext#bind Ext.bind} is alias for {@link Ext.Function#bind Ext.Function.bind} + * + * @param {Function} fn The function to delegate. + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. + * **If omitted, defaults to the default global environment object (usually the browser window).** + * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) + * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, + * if a number the args are inserted at the specified position + * @return {Function} The new function + */ + bind: function(fn, scope, args, appendArgs) { + if (arguments.length === 2) { + return function() { + return fn.apply(scope, arguments); + }; + } + + var method = fn, + slice = Array.prototype.slice; + + return function() { + var callArgs = args || arguments; + + if (appendArgs === true) { + callArgs = slice.call(arguments, 0); + callArgs = callArgs.concat(args); + } + else if (typeof appendArgs == 'number') { + callArgs = slice.call(arguments, 0); // copy arguments first + Ext.Array.insert(callArgs, appendArgs, args); + } + + return method.apply(scope || Ext.global, callArgs); + }; + }, + + /** + * Create a new function from the provided `fn`, the arguments of which are pre-set to `args`. + * New arguments passed to the newly created callback when it's invoked are appended after the pre-set ones. + * This is especially useful when creating callbacks. + * + * For example: + * + * var originalFunction = function(){ + * alert(Ext.Array.from(arguments).join(' ')); + * }; + * + * var callback = Ext.Function.pass(originalFunction, ['Hello', 'World']); + * + * callback(); // alerts 'Hello World' + * callback('by Me'); // alerts 'Hello World by Me' + * + * {@link Ext#pass Ext.pass} is alias for {@link Ext.Function#pass Ext.Function.pass} + * + * @param {Function} fn The original function + * @param {Array} args The arguments to pass to new callback + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. + * @return {Function} The new callback function + */ + pass: function(fn, args, scope) { + if (!Ext.isArray(args)) { + if (Ext.isIterable(args)) { + args = Ext.Array.clone(args); + } else { + args = args !== undefined ? [args] : []; + } + } + + return function() { + var fnArgs = [].concat(args); + fnArgs.push.apply(fnArgs, arguments); + return fn.apply(scope || this, fnArgs); + }; + }, + + /** + * Create an alias to the provided method property with name `methodName` of `object`. + * Note that the execution scope will still be bound to the provided `object` itself. + * + * @param {Object/Function} object + * @param {String} methodName + * @return {Function} aliasFn + */ + alias: function(object, methodName) { + return function() { + return object[methodName].apply(object, arguments); + }; + }, + + /** + * Create a "clone" of the provided method. The returned method will call the given + * method passing along all arguments and the "this" pointer and return its result. + * + * @param {Function} method + * @return {Function} cloneFn + */ + clone: function(method) { + return function() { + return method.apply(this, arguments); + }; + }, + + /** + * Creates an interceptor function. The passed function is called before the original one. If it returns false, + * the original one is not called. The resulting function returns the results of the original function. + * The passed function is called with the parameters of the original function. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * // create a new function that validates input without + * // directly modifying the original function: + * var sayHiToFriend = Ext.Function.createInterceptor(sayHi, function(name){ + * return name == 'Brian'; + * }); + * + * sayHiToFriend('Fred'); // no alert + * sayHiToFriend('Brian'); // alerts "Hi, Brian" + * + * @param {Function} origFn The original function. + * @param {Function} newFn The function to call before the original + * @param {Object} [scope] The scope (`this` reference) in which the passed function is executed. + * **If omitted, defaults to the scope in which the original function is called or the browser window.** + * @param {Object} [returnValue=null] The value to return if the passed function return false. + * @return {Function} The new function + */ + createInterceptor: function(origFn, newFn, scope, returnValue) { + var method = origFn; + if (!Ext.isFunction(newFn)) { + return origFn; + } else { + returnValue = Ext.isDefined(returnValue) ? returnValue : null; + return function() { + var me = this, + args = arguments; + + newFn.target = me; + newFn.method = origFn; + return (newFn.apply(scope || me || Ext.global, args) !== false) ? origFn.apply(me || Ext.global, args) : returnValue; + }; + } + }, + + /** + * Creates a delegate (callback) which, when called, executes after a specific delay. + * + * @param {Function} fn The function which will be called on a delay when the returned function is called. + * Optionally, a replacement (or additional) argument list may be specified. + * @param {Number} delay The number of milliseconds to defer execution by whenever called. + * @param {Object} scope (optional) The scope (`this` reference) used by the function at execution time. + * @param {Array} args (optional) Override arguments for the call. (Defaults to the arguments passed by the caller) + * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, + * if a number the args are inserted at the specified position. + * @return {Function} A function which, when called, executes the original function after the specified delay. + */ + createDelayed: function(fn, delay, scope, args, appendArgs) { + if (scope || args) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + } + + return function() { + var me = this, + args = Array.prototype.slice.call(arguments); + + setTimeout(function() { + fn.apply(me, args); + }, delay); + }; + }, + + /** + * Calls this function after the number of millseconds specified, optionally in a specific scope. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * // executes immediately: + * sayHi('Fred'); + * + * // executes after 2 seconds: + * Ext.Function.defer(sayHi, 2000, this, ['Fred']); + * + * // this syntax is sometimes useful for deferring + * // execution of an anonymous function: + * Ext.Function.defer(function(){ + * alert('Anonymous'); + * }, 100); + * + * {@link Ext#defer Ext.defer} is alias for {@link Ext.Function#defer Ext.Function.defer} + * + * @param {Function} fn The function to defer. + * @param {Number} millis The number of milliseconds for the setTimeout call + * (if less than or equal to 0 the function is executed immediately) + * @param {Object} scope (optional) The scope (`this` reference) in which the function is executed. + * **If omitted, defaults to the browser window.** + * @param {Array} args (optional) Overrides arguments for the call. (Defaults to the arguments passed by the caller) + * @param {Boolean/Number} appendArgs (optional) if True args are appended to call args instead of overriding, + * if a number the args are inserted at the specified position + * @return {Number} The timeout id that can be used with clearTimeout + */ + defer: function(fn, millis, scope, args, appendArgs) { + fn = Ext.Function.bind(fn, scope, args, appendArgs); + if (millis > 0) { + return setTimeout(Ext.supports.TimeoutActualLateness ? function () { + fn(); + } : fn, millis); + } + fn(); + return 0; + }, + + /** + * Create a combined function call sequence of the original function + the passed function. + * The resulting function returns the results of the original function. + * The passed function is called with the parameters of the original function. Example usage: + * + * var sayHi = function(name){ + * alert('Hi, ' + name); + * } + * + * sayHi('Fred'); // alerts "Hi, Fred" + * + * var sayGoodbye = Ext.Function.createSequence(sayHi, function(name){ + * alert('Bye, ' + name); + * }); + * + * sayGoodbye('Fred'); // both alerts show + * + * @param {Function} originalFn The original function. + * @param {Function} newFn The function to sequence + * @param {Object} scope (optional) The scope (`this` reference) in which the passed function is executed. + * If omitted, defaults to the scope in which the original function is called or the default global environment object (usually the browser window). + * @return {Function} The new function + */ + createSequence: function(originalFn, newFn, scope) { + if (!newFn) { + return originalFn; + } + else { + return function() { + var result = originalFn.apply(this, arguments); + newFn.apply(scope || this, arguments); + return result; + }; + } + }, + + /** + * Creates a delegate function, optionally with a bound scope which, when called, buffers + * the execution of the passed function for the configured number of milliseconds. + * If called again within that period, the impending invocation will be canceled, and the + * timeout period will begin again. + * + * @param {Function} fn The function to invoke on a buffered timer. + * @param {Number} buffer The number of milliseconds by which to buffer the invocation of the + * function. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @param {Array} args (optional) Override arguments for the call. Defaults to the arguments + * passed by the caller. + * @return {Function} A function which invokes the passed function after buffering for the specified time. + */ + createBuffered: function(fn, buffer, scope, args) { + var timerId; + + return function() { + var callArgs = args || Array.prototype.slice.call(arguments, 0), + me = scope || this; + + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(function(){ + fn.apply(me, callArgs); + }, buffer); + }; + }, + + /** + * Creates a throttled version of the passed function which, when called repeatedly and + * rapidly, invokes the passed function only after a certain interval has elapsed since the + * previous invocation. + * + * This is useful for wrapping functions which may be called repeatedly, such as + * a handler of a mouse move event when the processing is expensive. + * + * @param {Function} fn The function to execute at a regular time interval. + * @param {Number} interval The interval **in milliseconds** on which the passed function is executed. + * @param {Object} scope (optional) The scope (`this` reference) in which + * the passed function is executed. If omitted, defaults to the scope specified by the caller. + * @returns {Function} A function which invokes the passed function at the specified interval. + */ + createThrottled: function(fn, interval, scope) { + var lastCallTime, elapsed, lastArgs, timer, execute = function() { + fn.apply(scope || this, lastArgs); + lastCallTime = Ext.Date.now(); + }; + + return function() { + elapsed = Ext.Date.now() - lastCallTime; + lastArgs = arguments; + + clearTimeout(timer); + if (!lastCallTime || (elapsed >= interval)) { + execute(); + } else { + timer = setTimeout(execute, interval - elapsed); + } + }; + }, + + + /** + * Adds behavior to an existing method that is executed before the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptBefore(soup, "add", function(ingredient){ + * if (!this.contents.length && ingredient !== "water") { + * // Always add water to start with + * this.contents.push("water"); + * } + * }); + * soup.add("onions"); + * soup.add("salt"); + * soup.contents; // will contain: water, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptBefore: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + var ret = fn.apply(scope || this, arguments); + method.apply(this, arguments); + + return ret; + }); + }, + + /** + * Adds behavior to an existing method that is executed after the + * original behavior of the function. For example: + * + * var soup = { + * contents: [], + * add: function(ingredient) { + * this.contents.push(ingredient); + * } + * }; + * Ext.Function.interceptAfter(soup, "add", function(ingredient){ + * // Always add a bit of extra salt + * this.contents.push("salt"); + * }); + * soup.add("water"); + * soup.add("onions"); + * soup.contents; // will contain: water, salt, onions, salt + * + * @param {Object} object The target object + * @param {String} methodName Name of the method to override + * @param {Function} fn Function with the new behavior. It will + * be called with the same arguments as the original method. The + * return value of this function will be the return value of the + * new method. + * @param {Object} [scope] The scope to execute the interceptor function. Defaults to the object. + * @return {Function} The new function just created. + */ + interceptAfter: function(object, methodName, fn, scope) { + var method = object[methodName] || Ext.emptyFn; + + return (object[methodName] = function() { + method.apply(this, arguments); + return fn.apply(scope || this, arguments); + }); + } +}; + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#defer + */ +Ext.defer = Ext.Function.alias(Ext.Function, 'defer'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#pass + */ +Ext.pass = Ext.Function.alias(Ext.Function, 'pass'); + +/** + * @method + * @member Ext + * @inheritdoc Ext.Function#bind + */ +Ext.bind = Ext.Function.alias(Ext.Function, 'bind'); diff --git a/pool/shard011/JavaScript/0069913_bundle.js b/pool/shard011/JavaScript/0069913_bundle.js new file mode 100644 index 0000000000000000000000000000000000000000..30834713912e1f8342d3fba77a5ae523f1c408a3 --- /dev/null +++ b/pool/shard011/JavaScript/0069913_bundle.js @@ -0,0 +1,61 @@ +/* begin_generated_IBM_copyright_prolog */ +/* */ +/* This is an automatically generated copyright prolog. */ +/* After initializing, DO NOT MODIFY OR MOVE */ +/* **************************************************************** */ +/* (C) Copyright IBM Corp. 2016, 2016 */ +/* All Rights Reserved. */ +/* **************************************************************** */ +/* end_generated_IBM_copyright_prolog */ +var Webpack = require('webpack'); +var WebpackDevServer = require('webpack-dev-server'); +var path = require('path'); +var fs = require('fs'); + +var webpackConfig = require.main.require('./webpack.config.js'); + +module.exports = function() { + + // First we fire up Webpack an pass in the configuration we + // created + var bundleStart = null; + var compiler = Webpack(webpackConfig); + + // We give notice in the terminal when it starts bundling and + // set the time it started + compiler.plugin('compile', function() { + console.log('Bundling...'); + bundleStart = Date.now(); + }); + + // We also give notice when it is done compiling, including the + // time it took. Nice to have + compiler.plugin('done', function() { + console.log('Bundled in ' + (Date.now() - bundleStart) + 'ms!'); + }); + + var bundler = new WebpackDevServer(compiler, { + + // We need to tell Webpack to serve our bundled application + // from the build path. When proxying: + // http://localhost:3000/build -> http://localhost:8080/build + publicPath: '/build/', + + // Configure hot replacement + hot: true, + + // The rest is terminal configurations + quiet: false, + noInfo: true, + stats: { + colors: true + } + }); + + // We fire up the development server and give notice in the terminal + // that we are starting the initial bundle + bundler.listen(8080, 'localhost', function() { + console.log('Bundling project, please wait...'); + }); + +}; diff --git a/pool/shard011/JavaScript/0069916_email_log.js b/pool/shard011/JavaScript/0069916_email_log.js new file mode 100644 index 0000000000000000000000000000000000000000..d5e9ac6aec58352b0e69022aa6e448544d30c14b --- /dev/null +++ b/pool/shard011/JavaScript/0069916_email_log.js @@ -0,0 +1,47 @@ +"use strict"; + +$(() => { + // This code will be executed when the user visits /emails in + // development mode and email_log.html is rendered. + $("#toggle").on("change", () => { + if ($(".email-text").css("display") === "none") { + $(".email-text").each(function () { + $(this).css("display", "block"); + }); + $(".email-html").each(function () { + $(this).css("display", "none"); + }); + } else { + $(".email-text").each(function () { + $(this).css("display", "none"); + }); + $(".email-html").each(function () { + $(this).css("display", "block"); + }); + } + }); + $("input[type=radio][name=forward]").on("change", function () { + if ($(this).val() === "enabled") { + $("#forward_address_sections").show(); + } else { + $("#forward_address_sections").hide(); + } + }); + $("#save_smptp_details").on("click", () => { + const address = + $("input[name=forward]:checked").val() === "enabled" ? $("#address").val() : ""; + const csrf_token = $('input[name="csrfmiddlewaretoken"]').attr("value"); + const data = {forward_address: address, csrfmiddlewaretoken: csrf_token}; + + channel.post({ + url: "/emails/", + data, + success() { + $("#smtp_form_status").show(); + setTimeout(() => { + $("#smtp_form_status").hide(); + }, 3000); + }, + }); + }); +}); diff --git a/pool/shard011/JavaScript/0069917_create.js b/pool/shard011/JavaScript/0069917_create.js new file mode 100644 index 0000000000000000000000000000000000000000..2758f79033192fedfdd97e05d8dbf8ff042e5d7a --- /dev/null +++ b/pool/shard011/JavaScript/0069917_create.js @@ -0,0 +1,16 @@ +module.exports = function(req, res) { + async.waterfall([ + function(cb) { + commonController.create(req, res, cb); + }, + function(cart, cb) { + var me = req.user; + me.addCart(cart, function(err) { + cb(err, cart); + }); + } + ], function(err, cart) { + if (err) { sendError(res, err); } + res.json(cart); + }); +} diff --git a/pool/shard011/JavaScript/0069918_AxiosESTransport.js b/pool/shard011/JavaScript/0069918_AxiosESTransport.js new file mode 100644 index 0000000000000000000000000000000000000000..0325567a7a95bb54dbc1b69d8df677c303ae5ac5 --- /dev/null +++ b/pool/shard011/JavaScript/0069918_AxiosESTransport.js @@ -0,0 +1,40 @@ +"use strict"; +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var axios = require("axios"); +var ESTransport_1 = require("./ESTransport"); +var defaults = require("lodash/defaults"); +var AxiosESTransport = (function (_super) { + __extends(AxiosESTransport, _super); + function AxiosESTransport(host, options) { + if (options === void 0) { options = {}; } + _super.call(this); + this.host = host; + this.options = defaults(options, { + headers: {}, + searchUrlPath: "/_search" + }); + if (this.options.basicAuth) { + this.options.headers["Authorization"] = ("Basic " + btoa(this.options.basicAuth)); + } + this.axios = axios.create({ + baseURL: this.host, + timeout: AxiosESTransport.timeout, + headers: this.options.headers + }); + } + AxiosESTransport.prototype.search = function (query) { + return this.axios.post(this.options.searchUrlPath, query) + .then(this.getData); + }; + AxiosESTransport.prototype.getData = function (response) { + return response.data; + }; + AxiosESTransport.timeout = 5000; + return AxiosESTransport; +}(ESTransport_1.ESTransport)); +exports.AxiosESTransport = AxiosESTransport; +//# sourceMappingURL=AxiosESTransport.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069919_index.js b/pool/shard011/JavaScript/0069919_index.js new file mode 100644 index 0000000000000000000000000000000000000000..c8a9d75f19a80861e90a0504b46cff7a56c19147 --- /dev/null +++ b/pool/shard011/JavaScript/0069919_index.js @@ -0,0 +1,66 @@ +/** + * Author: krasu + * Date: 8/5/13 + * Time: 11:37 AM + This is example config file, + for saving actual settings place config..js + in this folder on your server + */ +var _ = require('lodash'), + fs = require('fs'), + path = require('path'), + nodemailer = require("nodemailer") + +var config = {}; +//config.env used to quickly get environment app wide +config.env = process.env.NODE_ENV || 'development'; +config.isDev = config.env === 'development'; + +//config.logsDir absolute path for directory with logs, be sure it is writable +config.logsDir = '/var/log/iloveopensource'; +//config.hostname used to create site links +config.hostname = 'www.iloveopensource.io'; +//config.isHttps used to create site links +config.isHttps = false; +//config.usePort used to create site links +config.usePort = false; +//config.mongodb connection Uri string +config.mongodbUri = 'mongodb://localhost/ilos' +//config.github app settings +config.github = { + clientId: '', + clientSecret: '' +} +//config.emails.from - name of sender +//config.emails.to - email of support +//config.emails.transport - nodemailer email transport +config.emails = { + from: 'robo@' + config.hostname, + to: 'support@codio.com', + transport: nodemailer.createTransport('sendmail', { + path: '/usr/sbin/sendmail', + args: ['-i', '-t'] + }) +} +//config.sessionSecret to hash sessions +config.sessionSecret = 's,dfjsklfj3k45j34k5kjLKj87093476ukvj jlk'; +//config.port on which app should run +config.port = '5000'; +//config.port on which app should run +config.jsPath = '/js/' + +config.fullUrl = function () { + return 'http' + + (this.isHttps ? 's' : '') + + '://' + + this.hostname + + (this.usePort ? ':' + this.port : '') +} + +config.path = path.join(__dirname, 'config.' + config.env + '.js') + +if (fs.existsSync(config.path)) { + config = _.extend({}, config, require(config.path)) +} + +module.exports = config \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069921_courseindex.js b/pool/shard011/JavaScript/0069921_courseindex.js new file mode 100644 index 0000000000000000000000000000000000000000..9cc270c0e6574ad75c9782cd55ac0acc7d88eb05 --- /dev/null +++ b/pool/shard011/JavaScript/0069921_courseindex.js @@ -0,0 +1,366 @@ +// This file is part of Moodle - http://moodle.org/ +// +// Moodle 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. +// +// Moodle 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 Moodle. If not, see . + +/** + * Course index main component. + * + * @module core_courseformat/local/courseindex/courseindex + * @class core_courseformat/local/courseindex/courseindex + * @copyright 2021 Ferran Recio + * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later + */ + +import {BaseComponent} from 'core/reactive'; +import {getCurrentCourseEditor} from 'core_courseformat/courseeditor'; +import jQuery from 'jquery'; +import ContentTree from 'core_courseformat/local/courseeditor/contenttree'; + +export default class Component extends BaseComponent { + + /** + * Constructor hook. + */ + create() { + // Optional component name for debugging. + this.name = 'courseindex'; + // Default query selectors. + this.selectors = { + SECTION: `[data-for='section']`, + SECTION_CMLIST: `[data-for='cmlist']`, + CM: `[data-for='cm']`, + TOGGLER: `[data-action="togglecourseindexsection"]`, + COLLAPSE: `[data-toggle="collapse"]`, + DRAWER: `.drawer`, + }; + // Default classes to toggle on refresh. + this.classes = { + SECTIONHIDDEN: 'dimmed', + CMHIDDEN: 'dimmed', + SECTIONCURRENT: 'current', + COLLAPSED: `collapsed`, + SHOW: `show`, + }; + // Arrays to keep cms and sections elements. + this.sections = {}; + this.cms = {}; + } + + /** + * Static method to create a component instance form the mustache template. + * + * @param {element|string} target the DOM main element or its ID + * @param {object} selectors optional css selector overrides + * @return {Component} + */ + static init(target, selectors) { + return new Component({ + element: document.getElementById(target), + reactive: getCurrentCourseEditor(), + selectors, + }); + } + + /** + * Initial state ready method. + * + * @param {Object} state the state data + */ + stateReady(state) { + // Activate section togglers. + this.addEventListener(this.element, 'click', this._sectionTogglers); + + // Get cms and sections elements. + const sections = this.getElements(this.selectors.SECTION); + sections.forEach((section) => { + this.sections[section.dataset.id] = section; + }); + const cms = this.getElements(this.selectors.CM); + cms.forEach((cm) => { + this.cms[cm.dataset.id] = cm; + }); + + // Set the page item if any. + this._refreshPageItem({element: state.course, state}); + + // Configure Aria Tree. + this.contentTree = new ContentTree(this.element, this.selectors, this.reactive.isEditing); + } + + getWatchers() { + return [ + {watch: `section.indexcollapsed:updated`, handler: this._refreshSectionCollapsed}, + {watch: `cm:created`, handler: this._createCm}, + {watch: `cm:deleted`, handler: this._deleteCm}, + {watch: `section:created`, handler: this._createSection}, + {watch: `section:deleted`, handler: this._deleteSection}, + {watch: `course.pageItem:created`, handler: this._refreshPageItem}, + {watch: `course.pageItem:updated`, handler: this._refreshPageItem}, + // Sections and cm sorting. + {watch: `course.sectionlist:updated`, handler: this._refreshCourseSectionlist}, + {watch: `section.cmlist:updated`, handler: this._refreshSectionCmlist}, + ]; + } + + /** + * Setup sections toggler. + * + * Toggler click is delegated to the main course index element because new sections can + * appear at any moment and this way we prevent accidental double bindings. + * + * @param {Event} event the triggered event + */ + _sectionTogglers(event) { + const sectionlink = event.target.closest(this.selectors.TOGGLER); + const isChevron = event.target.closest(this.selectors.COLLAPSE); + + if (sectionlink || isChevron) { + + const section = event.target.closest(this.selectors.SECTION); + const toggler = section.querySelector(this.selectors.COLLAPSE); + const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false; + + if (isChevron || isCollapsed) { + // Update the state. + const sectionId = section.getAttribute('data-id'); + this.reactive.dispatch( + 'sectionPreferences', + [sectionId], + { + indexcollapsed: !isCollapsed, + }, + ); + } + } + } + + /** + * Update section collapsed. + * + * @param {object} args + * @param {object} args.element The leement to be expanded + */ + _refreshSectionCollapsed({element}) { + const target = this.getElement(this.selectors.SECTION, element.id); + if (!target) { + throw new Error(`Unkown section with ID ${element.id}`); + } + // Check if it is already done. + const toggler = target.querySelector(this.selectors.COLLAPSE); + const isCollapsed = toggler?.classList.contains(this.classes.COLLAPSED) ?? false; + + if (element.indexcollapsed !== isCollapsed) { + this._expandSectionNode(element); + } + } + + /** + * Expand a section node. + * + * By default the method will use element.indexcollapsed to decide if the + * section is opened or closed. However, using forceValue it is possible + * to open or close a section independant from the indexcollapsed attribute. + * + * @param {Object} element the course module state element + * @param {boolean} forceValue optional forced expanded value + */ + _expandSectionNode(element, forceValue) { + const target = this.getElement(this.selectors.SECTION, element.id); + const toggler = target.querySelector(this.selectors.COLLAPSE); + let collapsibleId = toggler.dataset.target ?? toggler.getAttribute("href"); + if (!collapsibleId) { + return; + } + collapsibleId = collapsibleId.replace('#', ''); + const collapsible = document.getElementById(collapsibleId); + if (!collapsible) { + return; + } + + if (forceValue === undefined) { + forceValue = (element.indexcollapsed) ? false : true; + } + + // Course index is based on Bootstrap 4 collapsibles. To collapse them we need jQuery to + // interact with collapsibles methods. Hopefully, this will change in Bootstrap 5 because + // it does not require jQuery anymore (when MDL-79179 is integrated). + const togglerValue = (forceValue) ? 'show' : 'hide'; + jQuery(collapsible).collapse(togglerValue); + } + + /** + * Handle a page item update. + * + * @param {Object} details the update details + * @param {Object} details.state the state data. + * @param {Object} details.element the course state data. + */ + _refreshPageItem({element, state}) { + if (!element?.pageItem?.isStatic || element.pageItem.type != 'cm') { + return; + } + // Check if we need to uncollapse the section and scroll to the element. + const section = state.section.get(element.pageItem.sectionId); + if (section.indexcollapsed) { + this._expandSectionNode(section, true); + setTimeout( + () => this.cms[element.pageItem.id]?.scrollIntoView({block: "nearest"}), + 250 + ); + } + } + + /** + * Create a newcm instance. + * + * @param {object} param + * @param {Object} param.state + * @param {Object} param.element + */ + async _createCm({state, element}) { + // Create a fake node while the component is loading. + const fakeelement = document.createElement('li'); + fakeelement.classList.add('bg-pulse-grey', 'w-100'); + fakeelement.innerHTML = ' '; + this.cms[element.id] = fakeelement; + // Place the fake node on the correct position. + this._refreshSectionCmlist({ + state, + element: state.section.get(element.sectionid), + }); + // Collect render data. + const exporter = this.reactive.getExporter(); + const data = exporter.cm(state, element); + // Create the new content. + const newcomponent = await this.renderComponent(fakeelement, 'core_courseformat/local/courseindex/cm', data); + // Replace the fake node with the real content. + const newelement = newcomponent.getElement(); + this.cms[element.id] = newelement; + fakeelement.parentNode.replaceChild(newelement, fakeelement); + } + + /** + * Create a new section instance. + * + * @param {Object} details the update details. + * @param {Object} details.state the state data. + * @param {Object} details.element the element data. + */ + async _createSection({state, element}) { + // Create a fake node while the component is loading. + const fakeelement = document.createElement('div'); + fakeelement.classList.add('bg-pulse-grey', 'w-100'); + fakeelement.innerHTML = ' '; + this.sections[element.id] = fakeelement; + // Place the fake node on the correct position. + this._refreshCourseSectionlist({ + state, + element: state.course, + }); + // Collect render data. + const exporter = this.reactive.getExporter(); + const data = exporter.section(state, element); + // Create the new content. + const newcomponent = await this.renderComponent(fakeelement, 'core_courseformat/local/courseindex/section', data); + // Replace the fake node with the real content. + const newelement = newcomponent.getElement(); + this.sections[element.id] = newelement; + fakeelement.parentNode.replaceChild(newelement, fakeelement); + } + + /** + * Refresh a section cm list. + * + * @param {object} param + * @param {Object} param.element + */ + _refreshSectionCmlist({element}) { + const cmlist = element.cmlist ?? []; + const listparent = this.getElement(this.selectors.SECTION_CMLIST, element.id); + this._fixOrder(listparent, cmlist, this.cms); + } + + /** + * Refresh the section list. + * + * @param {object} param + * @param {Object} param.element + */ + _refreshCourseSectionlist({element}) { + const sectionlist = element.sectionlist ?? []; + this._fixOrder(this.element, sectionlist, this.sections); + } + + /** + * Fix/reorder the section or cms order. + * + * @param {Element} container the HTML element to reorder. + * @param {Array} neworder an array with the ids order + * @param {Array} allitems the list of html elements that can be placed in the container + */ + _fixOrder(container, neworder, allitems) { + + // Empty lists should not be visible. + if (!neworder.length) { + container.classList.add('hidden'); + container.innerHTML = ''; + return; + } + + // Grant the list is visible (in case it was empty). + container.classList.remove('hidden'); + + // Move the elements in order at the beginning of the list. + neworder.forEach((itemid, index) => { + const item = allitems[itemid]; + // Get the current element at that position. + const currentitem = container.children[index]; + if (currentitem === undefined) { + container.append(item); + return; + } + if (currentitem !== item) { + container.insertBefore(item, currentitem); + } + }); + // Remove the remaining elements. + while (container.children.length > neworder.length) { + container.removeChild(container.lastChild); + } + } + + /** + * Remove a cm from the list. + * + * The actual DOM element removal is delegated to the cm component. + * + * @param {object} param + * @param {Object} param.element + */ + _deleteCm({element}) { + delete this.cms[element.id]; + } + + /** + * Remove a section from the list. + * + * The actual DOM element removal is delegated to the section component. + * + * @param {Object} details the update details. + * @param {Object} details.element the element data. + */ + _deleteSection({element}) { + delete this.sections[element.id]; + } +} diff --git a/pool/shard011/JavaScript/0069923_ListFile.js b/pool/shard011/JavaScript/0069923_ListFile.js new file mode 100644 index 0000000000000000000000000000000000000000..8ff41fe5d2b9242e4b6a541a15ea1d5a80da27a7 --- /dev/null +++ b/pool/shard011/JavaScript/0069923_ListFile.js @@ -0,0 +1,126 @@ +var util = require("util"), + File = require("./File"); + +function getIgnoreIterator(ignore) { + if (typeof ignore === "string") { + return function (line) { + return line.slice(0, ignore.length) !== ignore; + }; + } else if (ignore instanceof RegExp) { + return function (line) { + return !ignore.test(line); + }; + } else if (typeof ignore === "function") { + return function (line) { + return !ignore(line); + }; + } else { + return function (line) { + return !!line; + } + } +} + +/** + * Create an API for manipulating a list of entries (each on it's own line) + * + * @augments File + */ +function ListFile() { + File.apply(this, arguments); +} + +// inherit directly from File +util.inherits(ListFile, File); + +// split each line into it's own entry in an array +ListFile.prototype.parse = function (input) { + var filter = getIgnoreIterator(this.ignore); + + return input.trim().split(/[\r\n]+/gm).filter(function (line) { + line = line.trim(); + return !!line ? filter(line) : false; + }); +}; + +// put each item on it's own line +ListFile.prototype.stringify = function (input) { + return input.join("\n"); +}; + +/** + * Retrieve the line number (0-indexed) for a particular item + * + * @param {String} item + * @param {Function} callback + */ +ListFile.prototype.indexOf = function (item, callback) { + callback = callback.bind(this); + + this.read(function (err, list) { + if (err) return callback(err); + + callback(null, list.indexOf(item), list); + }) +}; + +/** + * Determine whether or not a particular item exists in the collection + * + * @param {String} item + * @param {Function} callback + */ +ListFile.prototype.contains = function (item, callback) { + callback = callback.bind(this); + + this.indexOf(item, function (err, index, list) { + if (err) return callback(err); + + callback(null, index !== -1, list); + }); +}; + +/** + * Add an item to the collection + * + * @param {String} item + * @param {Function} callback + */ +// TODO: optimize with fs.appendFile ...? +ListFile.prototype.add = function (item, callback) { + callback = callback.bind(this); + + this.read(function (err, list) { + if (err) return callback(err); + + this.write(list.concat(item), callback); + }); +}; + +/** + * Remove an item from the collection + * + * @param {String|Number} item String item, or Numbered index + * @param {Function} callback + */ +ListFile.prototype.remove = function (item, callback) { + callback = callback.bind(this); + + if (typeof item === "string") { + this.indexOf(item, function (err, index, list) { + if (err) return callback(err); + + list.splice(index, 1); + this.write(list, callback); + }); + } else { + this.read(function (err, list) { + if (err) return callback(err); + + list.splice(item, 1); + this.write(list, callback); + }); + } +}; + +module.exports = ListFile; diff --git a/pool/shard011/JavaScript/0069924_Persona.EditarPersonaJuridica.RepresentanteController.js b/pool/shard011/JavaScript/0069924_Persona.EditarPersonaJuridica.RepresentanteController.js new file mode 100644 index 0000000000000000000000000000000000000000..285f54e3ff3e28ad5b09ae84828279624eb5d867 --- /dev/null +++ b/pool/shard011/JavaScript/0069924_Persona.EditarPersonaJuridica.RepresentanteController.js @@ -0,0 +1,32 @@ +'use strict'; + +/* jshint -W098 */ +angular.module('mean.persona').controller('Persona.EditarPersonaJuridica.RepresentanteController', function( + $scope, $state, SGTipoDocumento, SGPersonaNatural, toastr){ + + $scope.representante = { + tipoDocumento: undefined, + numeroDocumento: undefined + }; + + $scope.combo = { + tipoDocumento: SGTipoDocumento.$search({tipoPersona: 'natural'}).$object + }; + $scope.combo.selected = { + tipoDocumento: undefined + }; + + $scope.setRepresentante = function($event){ + if(!angular.isUndefined($event)) + $event.preventDefault(); + if(angular.isDefined($scope.combo.selected.tipoDocumento) && angular.isDefined($scope.representante.numeroDocumento)){ + SGPersonaNatural.$findByTipoNumeroDocumento($scope.combo.selected.tipoDocumento.abreviatura, $scope.representante.numeroDocumento).then(function(response){ + if(response) + $scope.view.persona.representanteLegal = response; + else + toastr.warning('Persona no encontrada'); + }); + } + }; + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069925_Search.js b/pool/shard011/JavaScript/0069925_Search.js new file mode 100644 index 0000000000000000000000000000000000000000..587244479cdf88a6a04afa67baefe73d018d31db --- /dev/null +++ b/pool/shard011/JavaScript/0069925_Search.js @@ -0,0 +1,59 @@ +'use strict' + +function toArrayObj(array) { + for (var i = 0; i < array.length; ++i) + array[i] = {url: array[i], extract: {}}; + return array; +} + +angular.module('gistOfItApp').controller('SearchCtrl', ['$scope', 'GistofitService', 'embedlyService', + function ($scope, Gistofit, Embedly) { + + $scope.setUrlExtract = function(result) { + var url = result.url; + + Gistofit.getExtract(url).then(function (response) { + if (response.data == undefined || response.data == '') { + Embedly.extract(url,536,536) + .then(function(e){ + Gistofit.setExtract(url, e.data); + result.extract = e.data; + }, + function(error) { + console.log(error); + }); + } else { + result.extract = response.data; + } + }); + } + + $scope.$watch('search', function (value) { + Gistofit.searchTopUrls(value).then(function (response) { + $scope.results = toArrayObj(response.data); + var promises = []; + + angular.forEach($scope.results,function(result){ + $scope.setUrlExtract(result); + }); + + console.log(response.data); + }); + + Gistofit.searchTopUrls(value).then(function (response) { + $scope.results = toArrayObj(response.data); + var promises = []; + + angular.forEach($scope.results,function(result){ + $scope.setUrlExtract(result); + }); + + console.log(response.data); + }); + }); + + window.addEventListener("message", $scope.setAddData); + steroids.view.navigationBar.show("Search"); + +} +]); diff --git a/pool/shard011/JavaScript/0069928_Collider.js b/pool/shard011/JavaScript/0069928_Collider.js new file mode 100644 index 0000000000000000000000000000000000000000..ce1e231b30a1891ceb2f0f19805c5639c60fcaff --- /dev/null +++ b/pool/shard011/JavaScript/0069928_Collider.js @@ -0,0 +1,53 @@ +(function(exports) { + 'use strict'; + + function Collider(subject) { + this.subject = subject; + this.objects = []; + + this.threshold = 50; + this.timeSinceLastCheck = 0; + } + + Collider.prototype.addObject = function(obj) { + this.objects.push(obj); + }; + + Collider.prototype.update = function(delta) { + var then = Date.now(); + while (Date.now() - then < 54) { + // YOU FOUND ME :D + } + this.timeSinceLastCheck += delta; + if (this.timeSinceLastCheck > this.threshold) { + this.timeSinceLastCheck -= this.threshold; + + this.subject.y2 = this.subject.y; + this.subject.x2 = this.subject.x + this.subject.width; + + var sub = this.subject; + for (var i = 0; i < this.objects.length; i++) { + var obj = this.objects[i]; + var objX = obj.getX(); + var objX2 = objX + obj.width; + if (objX < sub.x2 && objX2 > sub.x) { + var objY = obj.getY(); + + if (obj.type === 'bottom') { + if (objY < sub.y2) { + obj.hit(); + return; + } + } else { + if (objY > sub.y2) { + obj.hit(); + return; + } + } + } + } + } + }; + + exports.Collider = Collider; +})(this); diff --git a/pool/shard011/JavaScript/0069929_Key.js b/pool/shard011/JavaScript/0069929_Key.js new file mode 100644 index 0000000000000000000000000000000000000000..43eb4fd63dfd2cb98e87d4be90638ee39d531f52 --- /dev/null +++ b/pool/shard011/JavaScript/0069929_Key.js @@ -0,0 +1,193 @@ +var ECKey = require('../../browser/vendor-bundle.js').ECKey; +var SecureRandom = require('../SecureRandom'); +var Curve = require('../Curve'); +var bignum = require('bignum'); + +var Key = function() { + this._pub = null; + this._compressed = true; // default +}; + +var bufferToArray = Key.bufferToArray = function(buffer) { + var ret = []; + + var l = buffer.length; + for(var i =0; i 0) + $scope.currentPage.songs = true; + else if(currentPagePath.indexOf("/words/glossary")>0) + $scope.currentPage.glossary = true; + else if (currentPagePath.indexOf("/words/") > 0) + $scope.currentPage.words = true; + else if (currentPagePath.indexOf("/reflections") > 0) + $scope.currentPage.reflections = true; + else if(currentPagePath.indexOf("/people") > 0) + $scope.currentPage.people = true; + + }; + $scope.init(); + } + } +}); diff --git a/pool/shard011/JavaScript/0069940_filterPrivateDocs.spec.js b/pool/shard011/JavaScript/0069940_filterPrivateDocs.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..8715abd688e8cb938e416178fc2c69abce1f1c21 --- /dev/null +++ b/pool/shard011/JavaScript/0069940_filterPrivateDocs.spec.js @@ -0,0 +1,40 @@ +const testPackage = require('../../helpers/test-package'); +const processorFactory = require('./filterPrivateDocs'); +const Dgeni = require('dgeni'); + +describe('filterPrivateDocs processor', () => { + + it('should be available on the injector', () => { + const dgeni = new Dgeni([testPackage('angular-api-package')]); + const injector = dgeni.configureInjector(); + const processor = injector.get('filterPrivateDocs'); + expect(processor.$process).toBeDefined(); + }); + + it('should run before the correct processor', () => { + const processor = processorFactory(); + expect(processor.$runBefore).toEqual(['computing-paths']); + }); + + it('should run after the correct processor', () => { + const processor = processorFactory(); + expect(processor.$runAfter).toEqual(['extra-docs-added', 'checkContentRules']); + }); + + it('should remove docs that are marked as private exports', () => { + const processor = processorFactory(); + const docs = [ + { name: 'public1'}, + { name: 'ɵPrivate1', privateExport: true }, + { name: 'public2'}, + { name: 'ɵPrivate2', privateExport: true }, + { id: 'other'} + ]; + const filteredDocs = processor.$process(docs); + expect(filteredDocs).toEqual([ + { name: 'public1'}, + { name: 'public2'}, + { id: 'other'} + ]); + }); +}); diff --git a/pool/shard011/JavaScript/0069941_import-translation.js b/pool/shard011/JavaScript/0069941_import-translation.js new file mode 100644 index 0000000000000000000000000000000000000000..40c74f3a018f1adebcd8a0c08bc5b77a04323214 --- /dev/null +++ b/pool/shard011/JavaScript/0069941_import-translation.js @@ -0,0 +1,89 @@ +'use strict'; + +const recast = require('recast'); +const { parse, types: { builders }, print } = recast; + +const lastImportStatement = require('./utils/last-import-statement'); +const createImportStatement = require('./utils/create-import-statement'); + +/** + * Turns a dash-erized locale name into a camelCase module name + * + * @param {string} locale + * @return {string} the name for the module + */ +function createModuleNameFromLocale(locale) { + return locale.split('-') + .map((part, index) => index === 0 ? part : part.toUpperCase()) + .join(''); +} + +function findTranslationMap(ast) { + return ast.program.body + .filter(({ type }) => type === 'VariableDeclaration') + .find(({ declarations }) => { + return declarations.find(({ id: { name } }) => name === 'translationMap'); + }); +} + +function findTranslationDefinition(ast) { + return ast.program.body + .filter(({ type }) => type === 'ExpressionStatement') + .filter(({ expression }) => expression.type === 'CallExpression') + .filter(({ expression: { callee: { object: { type, name } } } }) => type === 'Identifier' && name === 'translationMap') + .reduce((prev, lastExpression) => lastExpression, undefined); +} + +function createTranslationDefinition(locale, moduleName) { + return builders.expressionStatement( + builders.callExpression( + builders.memberExpression( + builders.identifier('translationMap'), + builders.identifier('set') + ), + [ + builders.literal(locale), + builders.identifier(moduleName) + ] + ) + ); +} + +function importTranslation(source, locale, moduleLocation) { + const ast = parse(source); + const moduleName = createModuleNameFromLocale(locale); + const importStatement = createImportStatement(moduleName, moduleLocation); + + const translationMapNode = findTranslationMap(ast); + if (!translationMapNode) { + return print(ast, { quote: 'single' }).code; + } + + const lastImport = lastImportStatement(ast); + if (lastImport) { + const index = ast.program.body.indexOf(lastImport); + ast.program.body.splice(index + 1, 0, importStatement); + } else { + ast.program.body.unshift(importStatement); + } + + // Find insertion point for translation definition + let newTranslationDefinitionAnchor = translationMapNode; + const lastTranslationDefinition = findTranslationDefinition(ast); + const newTranslationDefinition = createTranslationDefinition(locale, moduleName); + + if (lastTranslationDefinition) { + newTranslationDefinitionAnchor = lastTranslationDefinition; + } + + const index = ast.program.body.indexOf(newTranslationDefinitionAnchor); + ast.program.body.splice(index + 1, 0, newTranslationDefinition); + + return print(ast, { quote: 'single' }).code; +} + +module.exports = importTranslation; +module.exports.createModuleNameFromLocale = createModuleNameFromLocale; +module.exports.findTranslationMap = findTranslationMap; +module.exports.findTranslationDefinition = findTranslationDefinition; +module.exports.createTranslationDefinition = createTranslationDefinition; diff --git a/pool/shard011/JavaScript/0069942_baseKeysIn.js b/pool/shard011/JavaScript/0069942_baseKeysIn.js new file mode 100644 index 0000000000000000000000000000000000000000..aee2047dfc54c6b588944a95105343828449bf5c --- /dev/null +++ b/pool/shard011/JavaScript/0069942_baseKeysIn.js @@ -0,0 +1,20 @@ +/* */ +var Reflect = require('./_Reflect'), + iteratorToArray = require('./_iteratorToArray'); +var objectProto = Object.prototype; +var enumerate = Reflect ? Reflect.enumerate : undefined, + propertyIsEnumerable = objectProto.propertyIsEnumerable; +function baseKeysIn(object) { + object = object == null ? object : Object(object); + var result = []; + for (var key in object) { + result.push(key); + } + return result; +} +if (enumerate && !propertyIsEnumerable.call({'valueOf': 1}, 'valueOf')) { + baseKeysIn = function(object) { + return iteratorToArray(enumerate(object)); + }; +} +module.exports = baseKeysIn; diff --git a/pool/shard011/JavaScript/0069944_0.6.4-assessment-names.js b/pool/shard011/JavaScript/0069944_0.6.4-assessment-names.js new file mode 100644 index 0000000000000000000000000000000000000000..5c5ea8615aef73772d99a3718b31fd6b9c2696a1 --- /dev/null +++ b/pool/shard011/JavaScript/0069944_0.6.4-assessment-names.js @@ -0,0 +1,24 @@ +"use strict"; +var keystone = require( 'keystone' ); +var async = require('async'); +var Assessment = keystone.list( 'Assessment' ); +exports = module.exports = function( done ){ + Assessment.model + .find( {} ) + .exec() + .then(function(assessments){ + async.eachSeries(assessments, function(assessment, next){ + assessment.name = assessment.comment || assessment.title; + assessment.save(function(err){ + next(err); + }); + }, function(err){ + if(err){ + throw err; + } + }); + }).then(function(){ + console.log('All assessments updated'); + done(); + }).then(null, done); +}; diff --git a/pool/shard011/JavaScript/0069946_WelcomePage.js b/pool/shard011/JavaScript/0069946_WelcomePage.js new file mode 100644 index 0000000000000000000000000000000000000000..e6ae53417e430f4308f8fb781609506232a0d49a --- /dev/null +++ b/pool/shard011/JavaScript/0069946_WelcomePage.js @@ -0,0 +1,53 @@ +import React, {Component, PropTypes} from 'react'; +import {connect} from 'react-redux'; +import Welcome from '../components/Welcome'; +import {asanaConnect} from '../actions/connection'; +import AsanaAPI from '../utils/AsanaAPI'; + +class WelcomePage extends Component { + + constructor(props, context) { + super(props, context); + this.connectToAsana = this.connectToAsana.bind(this); + this.state = { + clicked: false + }; + } + + componentDidUpdate() { + if (this.state.clicked && AsanaAPI.tokenIsValid(this.props.connection)) { + this.context.router.push('/views'); + } + } + + connectToAsana() { + this.setState({clicked: true}); + this.props.dispatch(asanaConnect()); + } + + render() { + return ( +
    + 0}/> +
    + ); + } +} +WelcomePage.contextTypes = { + router: PropTypes.object +}; + +WelcomePage.propTypes = { + connection: PropTypes.object.isRequired, + current: PropTypes.object.isRequired +}; + +function mapStateToProps(state) { + return { + connection: state.connection, + current: state.current, + busy: state.busy + }; +} + +export default connect(mapStateToProps)(WelcomePage) ; diff --git a/pool/shard011/JavaScript/0069948_getBabelRelayPlugin.js b/pool/shard011/JavaScript/0069948_getBabelRelayPlugin.js new file mode 100644 index 0000000000000000000000000000000000000000..84f7dea10c03f6a9e42a6a5a9b4b4ab6718034f2 --- /dev/null +++ b/pool/shard011/JavaScript/0069948_getBabelRelayPlugin.js @@ -0,0 +1,234 @@ +/** + * Copyright 2013-2015, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ + +'use strict'; + +var GraphQLDocumentTransformer = require('./GraphQLDocumentTransformer'); +var buildClientSchema = + require('graphql/utilities/buildClientSchema').buildClientSchema; + +var assert = require('assert'); +var path = require('path'); + +var PROVIDES_MODULE = 'providesModule'; + +/** + * Extract text from a template string. + */ +function extractTemplate(node) { + var text = ''; + var substitutions = []; + var templateElements = node.quasi.quasis; + for (var ii = 0; ii < templateElements.length; ii++) { + var template = templateElements[ii]; + text += template.value.cooked.trim(); + if (!template.tail) { + var sub = 'sub_' + ii; + substitutions.push(sub); + text += '...' + sub; + + var nextTemplate = templateElements[ii + 1]; + if (nextTemplate && !/^\s*[,\}]/.test(nextTemplate)) { + text += ','; + } + } + } + return {text: text, substitutions: substitutions}; +} + +/** + * Returns a new Babel Transformer that uses the supplied schema to transform + * template strings tagged with `Relay.QL` into an internal representation of + * GraphQL queries. + */ +function getBabelRelayPlugin( + schemaProvider /*: Object | Function */ +) /*: Object */ { + return function(babel) { + var Plugin = babel.Plugin; + var parse = babel.parse; + var t = babel.types; + var traverse = babel.traverse; + + /** + * Same as `babel.util.parseTemplate`. + */ + function parseTemplate(loc, code) { + var ast = parse(code, {filename: loc, looseModules: true}).program; + return traverse.removeProperties(ast); + } + + return new Plugin('relay-query', { + visitor: { + /** + * Extract the module name from `@providesModule`. + */ + Program: function(node, parent, scope, state) { + if (state.opts.extra.documentName) { + return; + } + var documentName; + if (parent.comments && parent.comments.length) { + var docblock = parent.comments[0].value || ''; + var propertyRegex = /@(\S+) *(\S*)/g; + var match; + while ((match = propertyRegex.exec(docblock))) { + var property = match[1]; + var value = match[2]; + if (property === PROVIDES_MODULE) { + documentName = value.replace(/[\.-:]/g, '_'); + break; + } + } + } + var filename = state.opts.filename; + if (filename && !documentName) { + var basename = path.basename(filename); + var captures = basename.match(/^[_A-Za-z][_0-9A-Za-z]*/); + if (captures) { + documentName = captures[0]; + } + } + if (documentName) { + state.opts.extra.documentName = documentName; + } + }, + + /** + * Transform Relay.QL`...`. + */ + TaggedTemplateExpression: function(node, parent, scope, state) { + if (!this.get('tag').matchesPattern('Relay.QL')) { + return; + } + + var documentTransformer = state.opts.extra.documentTransformer; + if (!documentTransformer) { + var schema = getSchema(schemaProvider); + documentTransformer = new GraphQLDocumentTransformer(schema); + state.opts.extra.documentTransformer = documentTransformer; + } + assert( + documentTransformer instanceof GraphQLDocumentTransformer, + 'getBabelRelayPlugin(): Expected a document transformer to be ' + + 'configured for this instance of the plugin.' + ); + + var extractedTemplate = extractTemplate(node); + var documentName = state.opts.extra.documentName || 'UnknownFile'; + var code; + try { + code = documentTransformer.transformQuery( + extractedTemplate, + documentName, + 'Relay.QL' + ); + } catch (error) { + // Print a console warning and replace the code with a function + // that will immediately throw an error in the browser. + var filename = state.opts.filename || 'UnknownFile'; + var sourceText = error.sourceText; + var validationErrors = error.validationErrors; + if (validationErrors && sourceText) { + var sourceLines = sourceText.split('\n'); + validationErrors.forEach(function(validationError) { + console.warn( + '\n-- GraphQL Validation Error -- %s --\n', + path.basename(filename) + ); + console.warn( + 'Error: ' + validationError.message + '\n' + + 'File: ' + filename + '\n' + + 'Source:' + ); + validationError.locations.forEach(function(location) { + var preview = sourceLines[location.line - 1]; + var prefix = '> '; + var highlight = repeat(' ', location.column - 1) + '^^^'; + if (preview) { + console.warn(prefix); + console.warn(prefix + preview); + console.warn(prefix + highlight); + } + }); + }); + } else { + console.warn( + '\n-- Relay Transform Error -- %s --\n', + path.basename(filename) + ); + console.warn( + 'Error: ' + error.message + '\n' + + 'File: ' + filename + '\n' + ); + } + + var message = ( + 'Encountered a GraphQL validation error processing file `' + + filename + + '`. Check your terminal for details.' + ); + code = ( + 'function() { throw new Error(\'' + + message.replace(/\'/g, '\\\'') + + '\'); }' + ); + + // also log the full error if `debug` option is set + if (state.opts.extra.debug) { + console.log(error.message); + console.log(error.stack); + } + } + code = '(' + code + ')'; + var funcExpr = parseTemplate('Relay.QL', code).body[0].expression; + + // Immediately invoke the function with substitutions as arguments. + var substitutions = node.quasi.expressions; + var funcCall = t.callExpression( + t.functionExpression( + null, + funcExpr.params, + funcExpr.body + ), + substitutions + ); + this.replaceWith(funcCall); + } + } + }); + } +} + +function repeat(char, count) { + var str = ''; + while (str.length < count) { + str += char; + } + return str; +} + +function getSchema( + schemaProvider /*: Object | Function */ +) /*: GraphQLSchema */ { + var schemaData = typeof schemaProvider === 'function' ? + schemaProvider() : + schemaProvider; + assert( + typeof schemaData === 'object' && + schemaData !== null && + typeof schemaData.__schema === 'object' && + schemaData.__schema !== null, + 'getBabelRelayPlugin(): Expected schema to be an object with a ' + + '`__schema` property.' + ); + return buildClientSchema(schemaData); +} + +module.exports = getBabelRelayPlugin; diff --git a/pool/shard011/JavaScript/0069951_httpRequester.js b/pool/shard011/JavaScript/0069951_httpRequester.js new file mode 100644 index 0000000000000000000000000000000000000000..3d31c507e382d6026bddc396419264a55aa90636 --- /dev/null +++ b/pool/shard011/JavaScript/0069951_httpRequester.js @@ -0,0 +1,51 @@ +window.httpRequester = (function () { + var makeRequest = function (url, type, data, headers) { + var promise = new RSVP.Promise(function (resolve, reject) { + var stringifiedData = ""; + if (data) { + stringifiedData = JSON.stringify(data); + } + + var request = { + url: url, + type: type, + contentType: "application/json", + data: stringifiedData, + headers: headers, + success: function (successData) { + resolve(successData); + }, + error: function (errorData) { + reject(errorData); + } + }; + + $.ajax(request); + }); + + return promise; + }; + + function getJson(url, headers) { + return makeRequest(url, "GET", null, headers); + } + + function postJson(url, data, headers) { + return makeRequest(url, "POST", data, headers); + } + + function deleteJson(url, headers) { + return makeRequest(url, "DELETE", null, headers); + } + + function putJson(url, data, headers) { + return makeRequest(url, "PUT", data, headers); + } + + return { + getJson: getJson, + postJson: postJson, + deleteJson: deleteJson, + putJson: putJson + }; +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069953_gallery-focus-position.js b/pool/shard011/JavaScript/0069953_gallery-focus-position.js new file mode 100644 index 0000000000000000000000000000000000000000..cf6fb91e4d08d2454d5a3381cd806a08ecc6b0db --- /dev/null +++ b/pool/shard011/JavaScript/0069953_gallery-focus-position.js @@ -0,0 +1,29 @@ +YUI.add('gallery-focus-position', function(Y) { + +var _focus = Y.Node.prototype.focus; + +Y.Node.prototype.focus = function (position) { + if (position === "end") { + position = this.get ("value").length; + } else if (!Y.Lang.isNumber (position)) { + _focus.apply (this); + return; + } + + var _node = this._node, range; + /* Code Taken From -> + http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox */ + if(_node.setSelectionRange) { + _node.focus (); + _node.setSelectionRange (position, position); + } else if (_node.createTextRange) { + range = _node.createTextRange(); + range.collapse (true); + range.moveEnd ('character', position); + range.moveStart ('character', position); + range.select (); + } +}; + + +}, 'gallery-2012.05.16-20-37' ,{requires:['node'], skinnable:false}); diff --git a/pool/shard011/JavaScript/0069957_object-analyzer.js b/pool/shard011/JavaScript/0069957_object-analyzer.js new file mode 100644 index 0000000000000000000000000000000000000000..7256889ba504d0673a8acf92a1a79cc12930dfef --- /dev/null +++ b/pool/shard011/JavaScript/0069957_object-analyzer.js @@ -0,0 +1,79 @@ +/** + * Object analyzer. + * https://github.com/RobertoPrevato/KingTable + * + * Copyright 2018, Roberto Prevato + * https://robertoprevato.github.io + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ +import _ from "../../scripts/utils"; + +export default class Analyzer { + + /** + * Returns an object describing the properties of a given item. + * @return {object} + */ + describe(o, options) { + if (_.isArray(o)) + return this.describeList(o, options); + var schema = {}, x; + for (x in o) { + schema[x] = this.getType(o[x]); + } + return schema; + } + + /** + * Returns an object describing the properties of the items contained by a list. + * @return {object} + */ + describeList(a, options) { + var schema = {}; + options = options || {}; + function typ(o) { + return o; // TODO: refactor to return object with "nullable" info? + } + var l = _.isNumber(options.limit) ? options.limit : a.length; + for (var i = 0; i < l; i++) { + var o = this.describe(a[i]); + for (var x in o) { + if (_.has(schema, x)) { + //compare + if (typ(o[x]) != undefined && typ(schema[x]) != typ(o[x])) { + if (!typ(schema[x])) { + schema[x] = typ(o[x]); + } else { + //force string type + schema[x] = "string"; + } + } + } else { + // add new property + _.extend(schema, o); + } + } + if (options.lazy && !_.any(schema, (k, v) => { + return v === undefined; + })) { + break; + } + } + return schema; + } + + /** + * Returns a string representing a type, in greater detail than normal JS. + * @return {string} + */ + getType(o) { + if (o == null || o == undefined) return; + if (o instanceof Array) return "array"; + if (o instanceof Date) return "date"; + if (o instanceof RegExp) return "regex"; + return typeof o; + } + +} diff --git a/pool/shard011/JavaScript/0069958_bounds.test.js b/pool/shard011/JavaScript/0069958_bounds.test.js new file mode 100644 index 0000000000000000000000000000000000000000..06e909ec0ba818a7cbdb5332797943927e30730f --- /dev/null +++ b/pool/shard011/JavaScript/0069958_bounds.test.js @@ -0,0 +1,134 @@ +'use strict'; + +var assert = require('chai').assert; +var Bounds = require('../src/util/Bounds'); + +describe('bounds', function() { + + it('should support constuctor without arguments', function() { + var b = new Bounds(); + assert.strictEqual(b.x1, +Number.MAX_VALUE); + assert.strictEqual(b.y1, +Number.MAX_VALUE); + assert.strictEqual(b.x2, -Number.MAX_VALUE); + assert.strictEqual(b.y2, -Number.MAX_VALUE); + }); + + it('should support constructor with bounds argument', function() { + var b = new Bounds((new Bounds()).set(1,1,2,2)); + assert.strictEqual(b.x1, 1); + assert.strictEqual(b.y1, 1); + assert.strictEqual(b.x2, 2); + assert.strictEqual(b.y2, 2); + }); + + it('should support clone', function() { + var a = (new Bounds()).set(1,1,2,2); + var b = a.clone(); + assert.notEqual(a, b); + assert.strictEqual(b.x1, 1); + assert.strictEqual(b.y1, 1); + assert.strictEqual(b.x2, 2); + assert.strictEqual(b.y2, 2); + + }); + + it('should support set', function() { + var b = (new Bounds()).set(1,1,2,2); + assert.strictEqual(b.x1, 1); + assert.strictEqual(b.y1, 1); + assert.strictEqual(b.x2, 2); + assert.strictEqual(b.y2, 2); + }); + + it('should support add point', function() { + var b = (new Bounds()).add(1,1).add(2,2); + assert.strictEqual(b.x1, 1); + assert.strictEqual(b.y1, 1); + assert.strictEqual(b.x2, 2); + assert.strictEqual(b.y2, 2); + }); + + it('should support expand', function() { + var b = (new Bounds()).add(1,1).add(2,2).expand(1); + assert.strictEqual(b.x1, 0); + assert.strictEqual(b.y1, 0); + assert.strictEqual(b.x2, 3); + assert.strictEqual(b.y2, 3); + }); + + it('should support round', function() { + var b = (new Bounds()).add(0.5, 0.5).add(1.5, 1.5).round(); + assert.strictEqual(b.x1, 0); + assert.strictEqual(b.y1, 0); + assert.strictEqual(b.x2, 2); + assert.strictEqual(b.y2, 2); + }); + + it('should support translate', function() { + var b = (new Bounds()).set(1,1,2,2).translate(2,3); + assert.strictEqual(b.x1, 3); + assert.strictEqual(b.y1, 4); + assert.strictEqual(b.x2, 4); + assert.strictEqual(b.y2, 5); + }); + + it('should support rotate', function() { + var b = (new Bounds()).set(0,0,2,2).rotate(Math.PI, 0, 0); + assert.closeTo(b.x1, -2, 1e-10); + assert.closeTo(b.y1, -2, 1e-10); + assert.closeTo(b.x2, 0, 1e-10); + assert.closeTo(b.y2, 0, 1e-10); + }); + + it('should support union', function() { + var b = (new Bounds()).set(1,1,3,3).union((new Bounds()).set(2,2,5,5)); + assert.strictEqual(b.x1, 1); + assert.strictEqual(b.y1, 1); + assert.strictEqual(b.x2, 5); + assert.strictEqual(b.y2, 5); + }); + + it('should support encloses', function() { + var a = (new Bounds()).set(1,1,3,3), + b = (new Bounds()).set(2,2,5,5), + c = (new Bounds()).set(3,3,4,4); + assert.isFalse(a.encloses(b)); + assert.isFalse(a.encloses(c)); + assert.isFalse(b.encloses(a)); + assert.isTrue(b.encloses(c)); + assert.isFalse(c.encloses(a)); + assert.isFalse(c.encloses(b)); + }); + + it('should support intersects', function() { + var a = (new Bounds()).set(1,1,3,3), + b = (new Bounds()).set(2,2,5,5), + c = (new Bounds()).set(4,4,5,5); + assert.isTrue(a.intersects(b)); + assert.isFalse(a.intersects(c)); + assert.isTrue(b.intersects(a)); + assert.isTrue(b.intersects(c)); + assert.isFalse(c.intersects(a)); + assert.isTrue(c.intersects(b)); + }); + + it('should support contains', function() { + var b = (new Bounds()).set(1,1,3,3); + assert.isFalse(b.contains(0,0)); + assert.isTrue(b.contains(1,1)); + assert.isTrue(b.contains(2,2)); + assert.isTrue(b.contains(3,3)); + assert.isFalse(b.contains(4,4)); + }); + + it('should support width', function() { + var b = (new Bounds()).set(1,1,3,5); + assert.strictEqual(b.width(), 2); + }); + + it('should support height', function() { + var b = (new Bounds()).set(1,1,3,5); + assert.strictEqual(b.height(), 4); + }); + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069959_APIServer_users.js b/pool/shard011/JavaScript/0069959_APIServer_users.js new file mode 100644 index 0000000000000000000000000000000000000000..76e0a599622a6ff6c3708d27d7205250042b312f --- /dev/null +++ b/pool/shard011/JavaScript/0069959_APIServer_users.js @@ -0,0 +1,31 @@ +$('.navbar-header .nav a h4').html('Users'); +url = "/api/proxy/"+slug+"/api_users"; +api = url; +$.ajax({ + url: url, + success: function(data){ + tableConfig.schema = [ + {label: 'Name', name:'app_name', required: true}, + {label: 'Password', name:'app_secret', required: true}, + {label: 'Environment', name:'environment_id', required: true,type:'select',options:'/api/proxy/'+slug+'/environments',format:{"label":'{{name}}',value:function(item){return item.id;}}}, + {label: null, name:'ipshelptext', type:'output', format:{value: '
    Use the following fields to limit requests to one or more IP Addresses, or part (substring) of an IP Address. (Leave blank to allow from any IP)
    ', parse:false}}, + {label: 'IPs','name':'ips',type:"text",array:{min:0, max:10}}, + {name: 'id', type:'hidden'} + ]; + tableConfig.data = data; + tableConfig.actions = [ + {'name':'delete',max:1},'|', + {'name':'edit',max:1}, + {'name':'lookup_app_secret',max:1,min:1, 'label': ' Lookup App Secret'},'|', + {'name':'create'} + ] + tableConfig.name = "api_users"; + grid = new GrapheneDataGrid(tableConfig) + grid.on('model:lookup_app_secret',function(e){ + url = "/api/proxy/"+slug+"/api_users/"+e.model.attributes.id+"/decrypted_secret"; + $.ajax({url:url,success:function(data){ + modal({content:'
    '+atob(data.api_secret)+"
    "}) + }}); + }) + } +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069961_Parser.js b/pool/shard011/JavaScript/0069961_Parser.js new file mode 100644 index 0000000000000000000000000000000000000000..d364a9925f8a5e101d9efc64b1915ebba51505c6 --- /dev/null +++ b/pool/shard011/JavaScript/0069961_Parser.js @@ -0,0 +1,26 @@ +'use strict'; + +var fs = require('fs'); +var path = require('path'); +var jade = require('jade'); +var util = require('util'); +var nodes = jade.nodes; +var BaseParser = jade.Parser; + +function Parser (a,b,c) { + BaseParser.apply(this, arguments); +} + +util.inherits(Parser, BaseParser); + +Parser.prototype.parseInclude = function () { + var tok = this.expect('include').val.trim(); + var file = this.resolvePath(tok, 'include'); + var mod = tok.indexOf('.') === 0 ? tok : './' + tok; + + this.dependencies.push(file); + + return new nodes.Code('buf.push(require("' + mod + '").call(this, locals));'); +}; + +module.exports = Parser; diff --git a/pool/shard011/JavaScript/0069962_Gruntfile.js b/pool/shard011/JavaScript/0069962_Gruntfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b3a7d65ea4ef48e5bfe126744cb9cb55fc89a506 --- /dev/null +++ b/pool/shard011/JavaScript/0069962_Gruntfile.js @@ -0,0 +1,90 @@ +module.exports = function(grunt) { + var pkg = grunt.file.readJSON("package.json"); + + grunt.initConfig({ + pkg:pkg, + //配置js压缩混淆插件 + uglify:{ + options:{ + banner:'/*! <%=pkg.name%> <%=pkg.version%> | <%=grunt.template.today("yyyy-mm-dd HH:MM:ss")%> */\n' + }, + build:{ + src:'dist/<%=pkg.name%>.js', + dest:'dist/<%=pkg.name%>.min.js' + } + }, + //配置文件合并插件 + concat:{ + options: { + separator: '' + }, + dist: { + src: (function(){ + var path = []; + for(var p in pkg.src){ + path.push("src/"+p+".js"); + } + return path; + })(), + dest: 'dist/script.js' + } + }, + //配置css压缩插件 + cssmin:{ + options: { + shorthandCompacting: false, + roundingPrecision: -1 + }, + build: { + src:'src/style.css', + dest:'dist/style.css' + } + }, + watch:{ + scripts: { + files: ['src/*.*'], + tasks: ['concat','cssmin','mytask','uglify'], + options: { + spawn: false + } + } + } + + }); + + //自定义任务 + grunt.registerTask('mytask','',function(){ + var fs = require('fs'); + + //读取文件数据 + var scriptData = fs.readFileSync('dist/script.js','utf-8'); + var styleData = fs.readFileSync('dist/style.css','utf-8'); + + grunt.log.write(scriptData); + + var result = [ + "(function(window){\n", + scriptData, + "document.write(\"\");\n", + "window.$ = b;\n", + "})(this);" + ].join(''); + + //生成最终文件 + fs.writeFileSync('dist/'+pkg.name+".js",result,'utf-8'); + + //删除临时文件 + fs.unlinkSync("dist/script.js"); + fs.unlinkSync("dist/style.css"); + + }); + + grunt.loadNpmTasks('grunt-contrib-uglify'); + grunt.loadNpmTasks('grunt-contrib-concat'); + grunt.loadNpmTasks('grunt-contrib-cssmin'); + grunt.loadNpmTasks('grunt-contrib-watch'); + + grunt.registerTask('default',['concat','cssmin','mytask','uglify','watch']); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069971_OpenStoreController.js b/pool/shard011/JavaScript/0069971_OpenStoreController.js new file mode 100644 index 0000000000000000000000000000000000000000..bebda2961db3e876b60008c03efb343680043aeb --- /dev/null +++ b/pool/shard011/JavaScript/0069971_OpenStoreController.js @@ -0,0 +1,48 @@ + +/* global storezillaadminapp */ + +storezillaadminapp.controller('SZAStoreListController',function($scope,StoreService,$location){ + StoreService.getAllStores().success(function(response){ + StoreService.listStores = response; + $scope.listStores = response; + }); + + $scope.editStore = function(storeId) { + $location.path("/editstore/"+storeId); + }; + $scope.removeStore = function(storeId) { + $location.path("/removestore/"+storeId); + }; + $scope.addStore = function() { + $location.path("/addstore"); + }; +}); + +storezillaadminapp.controller('SZAStoreAddController',function($scope,$location,StoreService){ + $('.menu .item').tab(); + $scope.SaveStore = function() { + StoreService.addStore($scope.store).success(function(response) { + $location.path('/liststores'); + }); + }; +}); + +storezillaadminapp.controller('SZAStoreEditController',function($scope,$routeParams,StoreService,$location){ + $('.menu .item').tab(); + StoreService.getStoreById($routeParams.id).success(function(response) { + $scope.store = response; + }); + + $scope.SaveStore = function() { + StoreService.updateStore($scope.store).success(function(response){ + $location.path('/liststores'); + }); + }; +}); + +storezillaadminapp.controller('SZAStoreDeleteController',function($scope,$routeParams,StoreService,$location){ + $scope.store = StoreService.listStores[$routeParams.id]; + StoreService.removeStore($routeParams.id).success(function(response){ + $location.path('/liststores'); + }); +}); diff --git a/pool/shard011/JavaScript/0069972_media_capture.js b/pool/shard011/JavaScript/0069972_media_capture.js new file mode 100644 index 0000000000000000000000000000000000000000..7ef08588a62ecd3ad4dcd824a9718d4ece1984b6 --- /dev/null +++ b/pool/shard011/JavaScript/0069972_media_capture.js @@ -0,0 +1,123 @@ +/* global MediaRecorder */ +import log from './log'; +import Utils from './utils'; + +export default class MediaCapture { + + constructor() { + this.queue_screenshot = null; + this.video_capture = null; + } + + setCanvas (canvas) { + this.canvas = canvas; + } + + // Take a screenshot, returns a promise that resolves with the screenshot data when available + screenshot () { + if (this.queue_screenshot != null) { + return this.queue_screenshot.promise; // only capture one screenshot at a time + } + + // Will resolve once rendering is complete and render buffer is captured + this.queue_screenshot = {}; + this.queue_screenshot.promise = new Promise((resolve, reject) => { + this.queue_screenshot.resolve = resolve; + this.queue_screenshot.reject = reject; + }); + return this.queue_screenshot.promise; + } + + // Called after rendering, captures render buffer and resolves promise with the image data + completeScreenshot () { + if (this.queue_screenshot != null) { + // Get data URL, convert to blob + // Strip host/mimetype/etc., convert base64 to binary without UTF-8 mangling + // Adapted from: https://gist.github.com/unconed/4370822 + const url = this.canvas.toDataURL('image/png'); + const data = atob(url.slice(22)); + const buffer = new Uint8Array(data.length); + for (let i = 0; i < data.length; ++i) { + buffer[i] = data.charCodeAt(i); + } + const blob = new Blob([buffer], { type: 'image/png' }); + + // Resolve with screenshot data + this.queue_screenshot.resolve({ url, blob, type: 'png' }); + this.queue_screenshot = null; + } + } + + // Starts capturing a video stream from the canvas + startVideoCapture () { + if (typeof window.MediaRecorder !== 'function' || !this.canvas || typeof this.canvas.captureStream !== 'function') { + log('warn', 'Video capture (Canvas.captureStream and/or MediaRecorder APIs) not supported by browser'); + return false; + } + else if (this.video_capture) { + log('warn', 'Video capture already in progress, call Scene.stopVideoCapture() first'); + return false; + } + + // Start a new capture + try { + let cap = this.video_capture = {}; + cap.chunks = []; + cap.stream = this.canvas.captureStream(); + cap.options = { mimeType: 'video/webm' }; // TODO: support other format options + cap.media_recorder = new MediaRecorder(cap.stream, cap.options); + cap.media_recorder.ondataavailable = (event) => { + if (event.data.size > 0) { + cap.chunks.push(event.data); + } + + // Stopped recording? Create the final capture file blob + if (cap.resolve) { + let blob = new Blob(cap.chunks, { type: cap.options.mimeType }); + let url = Utils.createObjectURL(blob); + + // Explicitly remove all stream tracks, and set objects to null + if (cap.stream) { + let tracks = cap.stream.getTracks() || []; + tracks.forEach(track => { + track.stop(); + cap.stream.removeTrack(track); + }); + } + cap.stream = null; + cap.media_recorder = null; + this.video_capture = null; + + cap.resolve({ url, blob, type: 'webm' }); + } + }; + cap.media_recorder.start(); + } + catch (e) { + this.video_capture = null; + log('error', 'Scene video capture failed', e); + return false; + } + return true; + } + + // Stops capturing a video stream from the canvas, returns a promise that resolves with the video when available + stopVideoCapture () { + if (!this.video_capture) { + log('warn', 'No scene video capture in progress, call Scene.startVideoCapture() first'); + return Promise.resolve({}); + } + + // Promise that will resolve when final stream is available + this.video_capture.promise = new Promise((resolve, reject) => { + this.video_capture.resolve = resolve; + this.video_capture.reject = reject; + }); + + // Stop recording + this.video_capture.media_recorder.stop(); + + return this.video_capture.promise; + } + +} diff --git a/pool/shard011/JavaScript/0069973_data.js b/pool/shard011/JavaScript/0069973_data.js new file mode 100644 index 0000000000000000000000000000000000000000..3b4eed6ce42c17f8d373bc5b1ec7490c84061520 --- /dev/null +++ b/pool/shard011/JavaScript/0069973_data.js @@ -0,0 +1,44 @@ +/** + * Extend array primitive to support selection of a member item at random + */ +Array.prototype.random = function() { + return this[Math.floor(Math.random() * this.length)]; +} + +/** + * Extend array primitive to support filtering for unique values - no dupes + */ +function uniques(value, index, self) { + + return self.indexOf(value) === index; +} + +Array.prototype.unique = function() { + + return this.filter(uniques); +} + +/** + * Extend object primitive to support selection of a member key at random + */ +Object.prototype.random = function() { + var keys = Object.keys(this); + var selected = Math.floor(Math.random() * keys.length); + return this[selected]; +} + +/** + * Extend string primitive to support selection of non-article "keywords" contained in string + * Ignores words less than 6 characters in length + * Explicitly excludes some helper words that are 6 characters or longer + * + * Used by Conviviality's hashtagify method + */ +String.prototype.getKeywords = function() { + var articles = ["before", "because", "things", "around", "should", "nearly"]; + var keywords = []; + var tokens = this.split(/\s+/gi); + return tokens.filter(function(token) { + if (articles.indexOf(token) == -1 && token.length >= 6) return true; + }); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069974_chartJs2DCtrl.js b/pool/shard011/JavaScript/0069974_chartJs2DCtrl.js new file mode 100644 index 0000000000000000000000000000000000000000..943f6c1cc8757bad1db75b36a115e3b98df783ae --- /dev/null +++ b/pool/shard011/JavaScript/0069974_chartJs2DCtrl.js @@ -0,0 +1,32 @@ +/** + * @author a.demeshko + * created on 12/16/15 + */ +(function () { + 'use strict'; + + angular.module('PowerAnalyst.pages.charts.chartJs') + .controller('chartJs2DCtrl', chartJs2DCtrl); + + /** @ngInject */ + function chartJs2DCtrl($scope) { + $scope.labels =["May", "June", "Jule", "August", "September", "October", "November"]; + $scope.data = [ + [65, 59, 90, 81, 56, 55, 40], + [28, 48, 40, 19, 88, 27, 45] + ]; + $scope.series = ['Product A', 'Product B']; + + + $scope.changeData = function () { + $scope.data[0] = shuffle($scope.data[0]); + $scope.data[1] = shuffle($scope.data[1]); + }; + + function shuffle(o){ + for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x){} + return o; + } + } + +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069976_tasklistsControllerTest.js b/pool/shard011/JavaScript/0069976_tasklistsControllerTest.js new file mode 100644 index 0000000000000000000000000000000000000000..fbbb6294a7a655199ddb933de978e4829ad3f239 --- /dev/null +++ b/pool/shard011/JavaScript/0069976_tasklistsControllerTest.js @@ -0,0 +1,85 @@ +(function() { + + describe('TasklistsController', function() { + var controller, tasklist, url; + controller = void 0; + tasklist = void 0; + url = void 0; + beforeEach(function(done) { + controller = App.TasklistsController.create(); + agent.controller = controller; + return Tower.start(done); + }); + afterEach(function() { + Tower.stop(); + return delete agent.controller; + }); + describe('routes', function() { + test('index', function() { + return assert.equal(urlFor(App.Tasklist), "/tasklists"); + }); + test('new', function() { + tasklist = App.Tasklist.build(); + return assert.equal(urlFor(tasklist, { + action: 'new' + }), "/tasklists/new"); + }); + test('show', function() { + tasklist = new App.Tasklist({ + id: 1 + }); + return assert.equal(urlFor(tasklist), "/tasklists/" + (tasklist.get('id'))); + }); + return test('edit', function() { + tasklist = new App.Tasklist({ + id: 1 + }); + return assert.equal(urlFor(tasklist, { + action: 'edit' + }), "/tasklists/" + (tasklist.get('id')) + "/edit"); + }); + }); + describe('#index', function() { + beforeEach(function(done) { + var _this = this; + return factory('tasklist', function(error, record) { + tasklist = record; + return done(); + }); + }); + return test('render json', function(done) { + return get(urlFor(App.Tasklist), { + format: "json" + }, function(request) { + assert.equal(this.headers["Content-Type"], 'application/json'); + return done(); + }); + }); + }); + describe('#new', function() {}); + describe('#create', function() { + beforeEach(function() { + return url = urlFor(App.Tasklist); + }); + return test('params', function(done) { + var params; + params = {}; + return post(url, { + format: "json", + params: params + }, function(response) { + var _this = this; + return App.Tasklist.count(function(error, count) { + assert.equal(count, 1); + return done(); + }); + }); + }); + }); + describe("#show", function() {}); + describe("#edit", function() {}); + describe("#update", function() {}); + return describe("#destroy", function() {}); + }); + +}).call(this); diff --git a/pool/shard011/JavaScript/0069979_angel.js b/pool/shard011/JavaScript/0069979_angel.js new file mode 100644 index 0000000000000000000000000000000000000000..ecd3f3027e1090eadb2b51e56321474c2e15905b --- /dev/null +++ b/pool/shard011/JavaScript/0069979_angel.js @@ -0,0 +1,155 @@ +define([ + './Event', + './Store', + './Painter', + './Camera', + './shape/tool/CustomShape', + './animation/AnimateCenter' + ], function ( + Event, + Store, + Painter, + Camera, + CustomShape, + AnimateCenter + ) { + /** + * @author milan(white gourd angel) + * @describe + */ + var Angel = window.Angel = { + version: '2.0.0.', + author: 'milan(white gourd angel)', + describe: '一个怀抱冬瓜的夜晚下的灵感之作--"冬瓜天使"' + }; + + Angel.init = function(container){ + /** + * @describe Angel初始化 + * @param {HTMLElement} dom容器 + * @return Angel实例 + */ + var instance = new AngelFactory(container); + return instance; + } + + var AngelFactory = function(container){ + /** + * @describe Angel实例生成 + */ + var self = this; + self.dom = container; + self.store = new Store(self); + self.event = new Event(container, self.store); + self.painter = new Painter(self); + new AnimateCenter(self.store, self.painter).start(); + } + + AngelFactory.prototype = { + createCamera: function(opt){ + /** + * @describe 创建视角对象(3D 绘制时使用) + * @param + * @return + */ + var self = this; + if(!self.camera){ + self.camera = new Camera(opt || {}, self.dom); + self.store.setType('3D'); + } + return self.camera; + }, + createShape: function(opt){ + /** + * @describe 创建形状 + * @param buildPath: 绘制方法 + * getArroundRect: 返回形状的包围矩形 + * @return shape类对象 + */ + return CustomShape(opt); + }, + addShape: function(shape){ + /** + * @describe 添加形状 + * @param shpae.base/circle/ring... 各类shape对象 + * @return Angel + */ + var self = this; + self.store.addShape(shape); + return this; + }, + removeShape: function(shape){ + /** + * @describe 销毁形状 + * @param shpae.base/circle/ring... 各类shape对象 + * @return Angel + */ + var self = this; + self.store.removeShape(shape); + return self; + }, + modShape: function(shape){ + /** + * @describe 保存修改状态 + * @param shpae.base/circle/ring... 各类shape对象 + * @return + */ + var self = this; + self.store.modShape(shape); + return this; + }, + addGroup: function(){ + /** + * @describe 添加组 + * @param group对象 + * @return Angel + */ + self.store.addGroup(shape); + return this; + }, + removeGroup: function(){ + /** + * @describe 销毁组 + * @param group对象 + * @return Angel + */ + self.store.removeGroup(shape); + return this; + }, + refresh: function(){ + /** + * @describe 刷新canvas(仅刷新有数据变化的canvas层) + * @param + * @return Angel + */ + var self = this; + self.painter.refresh(); + return this; + }, + render: function(){ + /** + * @describe 全局渲染 + * @param + * @return Angel + */ + var self = this; + self.painter.paintAll(); + return this; + }, + clear: function(zIndex){ + this.painter.clear(zIndex); + return this; + }, + dispose: function(){ + /** + * @describe 销毁实例 + * @param + * @return + */ + + } + }; + + return Angel; +}); + diff --git a/pool/shard011/JavaScript/0069982_norm.js b/pool/shard011/JavaScript/0069982_norm.js new file mode 100644 index 0000000000000000000000000000000000000000..a28e3efbe58ae644d9cadb668e2c8fab0cf1a4f2 --- /dev/null +++ b/pool/shard011/JavaScript/0069982_norm.js @@ -0,0 +1,209 @@ +import { factory } from '../../utils/factory' + +const name = 'norm' +const dependencies = [ + 'typed', + 'abs', + 'add', + 'pow', + 'conj', + 'sqrt', + 'multiply', + 'equalScalar', + 'larger', + 'smaller', + 'matrix' +] + +export const createNorm = /* #__PURE__ */ factory(name, dependencies, ({ typed, abs, add, pow, conj, sqrt, multiply, equalScalar, larger, smaller, matrix }) => { + /** + * Calculate the norm of a number, vector or matrix. + * + * The second parameter p is optional. If not provided, it defaults to 2. + * + * Syntax: + * + * math.norm(x) + * math.norm(x, p) + * + * Examples: + * + * math.abs(-3.5) // returns 3.5 + * math.norm(-3.5) // returns 3.5 + * + * math.norm(math.complex(3, -4)) // returns 5 + * + * math.norm([1, 2, -3], Infinity) // returns 3 + * math.norm([1, 2, -3], -Infinity) // returns 1 + * + * math.norm([3, 4], 2) // returns 5 + * + * math.norm([[1, 2], [3, 4]], 1) // returns 6 + * math.norm([[1, 2], [3, 4]], 'inf') // returns 7 + * math.norm([[1, 2], [3, 4]], 'fro') // returns 5.477225575051661 + * + * See also: + * + * abs, hypot + * + * @param {number | BigNumber | Complex | Array | Matrix} x + * Value for which to calculate the norm + * @param {number | BigNumber | string} [p=2] + * Vector space. + * Supported numbers include Infinity and -Infinity. + * Supported strings are: 'inf', '-inf', and 'fro' (The Frobenius norm) + * @return {number | BigNumber} the p-norm + */ + const norm = typed(name, { + number: Math.abs, + + Complex: function (x) { + return x.abs() + }, + + BigNumber: function (x) { + // norm(x) = abs(x) + return x.abs() + }, + + boolean: function (x) { + // norm(x) = abs(x) + return Math.abs(x) + }, + + Array: function (x) { + return _norm(matrix(x), 2) + }, + + Matrix: function (x) { + return _norm(x, 2) + }, + + 'number | Complex | BigNumber | boolean, number | BigNumber | string': function (x) { + // ignore second parameter, TODO: remove the option of second parameter for these types + return norm(x) + }, + + 'Array, number | BigNumber | string': function (x, p) { + return _norm(matrix(x), p) + }, + + 'Matrix, number | BigNumber | string': function (x, p) { + return _norm(x, p) + } + }) + + /** + * Calculate the norm for an array + * @param {Matrix} x + * @param {number | string} p + * @returns {number} Returns the norm + * @private + */ + function _norm (x, p) { + // size + const sizeX = x.size() + + // check if it is a vector + if (sizeX.length === 1) { + // check p + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x, Infinity) = max(abs(x)) + let pinf = 0 + // skip zeros since abs(0) === 0 + x.forEach( + function (value) { + const v = abs(value) + if (larger(v, pinf)) { pinf = v } + }, + true) + return pinf + } + if (p === Number.NEGATIVE_INFINITY || p === '-inf') { + // norm(x, -Infinity) = min(abs(x)) + let ninf + // skip zeros since abs(0) === 0 + x.forEach( + function (value) { + const v = abs(value) + if (!ninf || smaller(v, ninf)) { ninf = v } + }, + true) + return ninf || 0 + } + if (p === 'fro') { + return _norm(x, 2) + } + if (typeof p === 'number' && !isNaN(p)) { + // check p != 0 + if (!equalScalar(p, 0)) { + // norm(x, p) = sum(abs(xi) ^ p) ^ 1/p + let n = 0 + // skip zeros since abs(0) === 0 + x.forEach( + function (value) { + n = add(pow(abs(value), p), n) + }, + true) + return pow(n, 1 / p) + } + return Number.POSITIVE_INFINITY + } + // invalid parameter value + throw new Error('Unsupported parameter value') + } + // MxN matrix + if (sizeX.length === 2) { + // check p + if (p === 1) { + // norm(x) = the largest column sum + const c = [] + // result + let maxc = 0 + // skip zeros since abs(0) == 0 + x.forEach( + function (value, index) { + const j = index[1] + const cj = add(c[j] || 0, abs(value)) + if (larger(cj, maxc)) { maxc = cj } + c[j] = cj + }, + true) + return maxc + } + if (p === Number.POSITIVE_INFINITY || p === 'inf') { + // norm(x) = the largest row sum + const r = [] + // result + let maxr = 0 + // skip zeros since abs(0) == 0 + x.forEach( + function (value, index) { + const i = index[0] + const ri = add(r[i] || 0, abs(value)) + if (larger(ri, maxr)) { maxr = ri } + r[i] = ri + }, + true) + return maxr + } + if (p === 'fro') { + // norm(x) = sqrt(sum(diag(x'x))) + let fro = 0 + x.forEach( + function (value, index) { + fro = add(fro, multiply(value, conj(value))) + }) + return abs(sqrt(fro)) + } + if (p === 2) { + // not implemented + throw new Error('Unsupported parameter value, missing implementation of matrix singular value decomposition') + } + // invalid parameter value + throw new Error('Unsupported parameter value') + } + } + + return norm +}) diff --git a/pool/shard011/JavaScript/0069984_metronomeworker.js b/pool/shard011/JavaScript/0069984_metronomeworker.js new file mode 100644 index 0000000000000000000000000000000000000000..ea4b5d3a1b2198d82df0be5613a4e59b3a57a66a --- /dev/null +++ b/pool/shard011/JavaScript/0069984_metronomeworker.js @@ -0,0 +1,45 @@ +/*! + * + * Tap Tempo + * Copyright 2015 Justin Varghese John + * + * 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 + * + * https://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 + * + */ + +'use strict'; + +var timerID = null; +var interval = 100; + +self.onmessage = function(e) { + if (e.data === 'start') { + timerID = setInterval( () => {postMessage('tick');}, interval); + } + else if (e.data.interval) { + console.log('setting interval'); + interval = e.data.interval; + console.log('interval = ' + interval); + if (timerID) { + clearInterval(timerID); + timerID = setInterval( () => {postMessage('tick');}, interval); + } + } + else if (e.data === 'stop') { + console.log('stopping'); + clearInterval(timerID); + timerID=null; + } +}; + +postMessage('metronome initialized'); diff --git a/pool/shard011/JavaScript/0069988_index.js b/pool/shard011/JavaScript/0069988_index.js new file mode 100644 index 0000000000000000000000000000000000000000..2202915dec3209c7964dd190b79768ea29239023 --- /dev/null +++ b/pool/shard011/JavaScript/0069988_index.js @@ -0,0 +1,149 @@ +'use strict' +const os = require('os') +const t = require('typical') + +/** + * @module wordwrapjs + */ + +const re = { + chunk: /[^\s-]+?-\b|\S+|\s+|\r\n?|\n/g, + ansiEscapeSequence: /\u001b.*?m/g +} + +/** + * @alias module:wordwrapjs + * @typicalname wordwrap + */ +class WordWrap { + constructor (text, options) { + options = options || {} + if (!t.isDefined(text)) text = '' + + this._lines = String(text).split(/\r\n|\n/g) + this.options = options + this.options.width = options.width === undefined ? 30 : options.width + } + + lines () { + const flatten = require('reduce-flatten') + + /* trim each line of the supplied text */ + return this._lines.map(trimLine.bind(this)) + + /* split each line into an array of chunks, else mark it empty */ + .map(line => line.match(re.chunk) || [ '~~empty~~' ]) + + /* optionally, break each word on the line into pieces */ + .map(lineWords => { + if (this.options.break) { + return lineWords.map(breakWord.bind(this)) + } else { + return lineWords + } + }) + .map(lineWords => lineWords.reduce(flatten, [])) + + /* transforming the line of words to one or more new lines wrapped to size */ + .map(lineWords => { + return lineWords + .reduce((lines, word) => { + let currentLine = lines[lines.length - 1] + if (replaceAnsi(word).length + replaceAnsi(currentLine).length > this.options.width) { + lines.push(word) + } else { + lines[lines.length - 1] += word + } + return lines + }, [ '' ]) + }) + .reduce(flatten, []) + + /* trim the wrapped lines */ + .map(trimLine.bind(this)) + + /* filter out empty lines */ + .filter(line => line.trim()) + + /* restore the user's original empty lines */ + .map(line => line.replace('~~empty~~', '')) + } + + wrap () { + return this.lines().join(os.EOL) + } + + toString () { + return this.wrap() + } + + /** + * @param {string} - the input text to wrap + * @param [options] {object} - optional configuration + * @param [options.width] {number} - the max column width in characters (defaults to 30). + * @param [options.break] {boolean} - if true, words exceeding the specified `width` will be forcefully broken + * @param [options.noTrim] {boolean} - By default, each line output is trimmed. If `noTrim` is set, no line-trimming occurs - all whitespace from the input text is left in. + * @return {string} + */ + static wrap (text, options) { + const block = new this(text, options) + return block.wrap() + } + + /** + * Wraps the input text, returning an array of strings (lines). + * @param {string} - input text + * @param {object} - Accepts same options as constructor. + */ + static lines (text, options) { + const block = new this(text, options) + return block.lines() + } + + /** + * Returns true if the input text would be wrapped if passed into `.wrap()`. + * @param {string} - input text + * @return {boolean} + */ + static isWrappable (text) { + if (t.isDefined(text)) { + text = String(text) + var matches = text.match(re.chunk) + return matches ? matches.length > 1 : false + } + } + + /** + * Splits the input text into an array of words and whitespace. + * @param {string} - input text + * @returns {string[]} + */ + static getChunks (text) { + return text.match(re.chunk) || [] + } +} + +function trimLine (line) { + return this.options.noTrim ? line : line.trim() +} + +function replaceAnsi (string) { + return string.replace(re.ansiEscapeSequence, '') +} + +/* break a word into several pieces */ +function breakWord (word) { + if (replaceAnsi(word).length > this.options.width) { + const letters = word.split('') + let piece + const pieces = [] + while ((piece = letters.splice(0, this.options.width)).length) { + pieces.push(piece.join('')) + } + return pieces + } else { + return word + } +} + +module.exports = WordWrap diff --git a/pool/shard011/JavaScript/0069992_55.is-promise.js b/pool/shard011/JavaScript/0069992_55.is-promise.js new file mode 100644 index 0000000000000000000000000000000000000000..0d9f6f71b202805e2b8506c38cbecca587e018f3 --- /dev/null +++ b/pool/shard011/JavaScript/0069992_55.is-promise.js @@ -0,0 +1,78 @@ +'use strict' +var toString = require('../tools/test/to-string') +require('../tools/test/describe')('Promise.isPromise', function (Promise, expect) { + function falseWhenGiven(value, string) { + specify('given: ' + (string || toString(value)), function () { + expect(Promise.isPromise(value)).to.be.false + }) + } + function trueWhenGiven(value, string) { + specify('given: ' + (string || toString(value)), function () { + expect(Promise.isPromise(value)).to.be.true + }) + } + + it('should throw when accessing .then throws', function () { + expect(function () { + Promise.isPromise({get then() { + throw new RangeError('foo') + }}) + }).to.throw(RangeError) + }) + describe('should return false when', function () { + falseWhenGiven(undefined) + falseWhenGiven(null) + falseWhenGiven(0) + falseWhenGiven(123) + falseWhenGiven(NaN) + falseWhenGiven(Infinity) + falseWhenGiven(true) + falseWhenGiven(false) + falseWhenGiven('foo') + falseWhenGiven({}, '{}') + falseWhenGiven([]) + falseWhenGiven(function then() {}) + falseWhenGiven({then: true}, '{then: true}') + falseWhenGiven({then: {name: 'then'}}, '{then: {name: "then"}}') + falseWhenGiven({then: Object.create(Function.prototype)}, '{then: Object.create(Function.prototype)}') + falseWhenGiven({Then: function () {}}, '{Then: function () {}}') + falseWhenGiven({THEN: function () {}}, '{THEN: function () {}}') + falseWhenGiven({"then ": function () {}}, '{"then ": function () {}}') + + specify('given: "foo" with String.prototype.then', function () { + var thenInString = 'then' in String.prototype + var originalStringThen = String.prototype.then + String.prototype.then = function () {} + try { + expect(Promise.isPromise('foo')).to.be.false + } finally { + if (thenInString) { + String.prototype.then = originalStringThen + } else { + delete String.prototype.then + } + } + }) + + var fn = function () {} + fn.then = {} + falseWhenGiven(fn, '(function () {}).then = {}') + + if (typeof Symbol === 'function') { + falseWhenGiven(Symbol()) + falseWhenGiven({then: Symbol()}, '{then: Symbol()}') + } + }) + describe('should return true when', function () { + var unnamedFunction = function () {} + trueWhenGiven({then: unnamedFunction}, '{then: function () {}}') + + var nullObject = Object.create(null) + nullObject.then = function () {} + trueWhenGiven(nullObject, 'Object.create(null).then = function () {}') + + var fn = function () {} + fn.then = function () {} + trueWhenGiven(fn, '(function () {}).then = function () {}') + }) +}) diff --git a/pool/shard011/JavaScript/0069994_SampleViewer.js b/pool/shard011/JavaScript/0069994_SampleViewer.js new file mode 100644 index 0000000000000000000000000000000000000000..25a011bc4e42ca65a937d76ff8efe09d626512e0 --- /dev/null +++ b/pool/shard011/JavaScript/0069994_SampleViewer.js @@ -0,0 +1,64 @@ +define(['utilities/OmnyApiRequester', 'utilities/QueryStringReader'], + function(apiRequester, queryStringReader) { + + function ThemeViewer() { + this.getDirectivePromise = function(data, $q) { + var deferred = $q.defer(); + deferred.resolve("
    "); + return deferred.promise; + }; + } + + directiveMaker.directive('omnySampleViewer', ['$location', function($location) { + return { + restrict: 'E', + templateUrl: versioned("/js/modules/SampleViewer/Samples.html"), + link: function(scope, ele, attrs) { + scope.createPage = function(sampleName) { + var pageTitle = queryStringReader.getParameter("title"); + var pageName = queryStringReader.getParameter("page"); + if(typeof pageTitle =="undefined") { + pageTitle = pageName; + } + + if(pageTitle=="default") { + pageTitle = "Home"; + } + apiRequester.apiRequest("pages", "", { + type: "POST", + data: JSON.stringify({ + "name": pageName, + "fromSample": { + "sampleName": sampleName + }, + "pageDetails": { + "title": pageTitle + } + }), + processData: false, + contentType: 'application/json', + success: function(data) { + window.location = window.location.origin+"/site/page.html?site="+queryStringReader.getParameter("site")+"&page="+pageName; + } + }); + } + }, + }; + } + ]); + + controllerMaker.register("OmnySampleViewer", ['$scope', '$route', '$element', + function($scope, $route, $element) { + var data = window.omnyData[$element.attr('guid')]; + apiRequester.apiRequest("themes", "default/samples", { + success: function(samples) { + $scope.$apply(function() { + $scope.samples = samples; + }); + } + }); + } + ]); + return ThemeViewer; + } +); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0069997_dev_test.js b/pool/shard011/JavaScript/0069997_dev_test.js new file mode 100644 index 0000000000000000000000000000000000000000..cbd5d03348effc8431bfa26572e72f7007637d39 --- /dev/null +++ b/pool/shard011/JavaScript/0069997_dev_test.js @@ -0,0 +1,139 @@ +"use strict" + +const botcore = require('../index') + +class MyBot extends botcore.bot.Bot { + constructor() { + super(); + + this.state = 0; + this.base_wager = 7000; + this.base_score = 0.0; + this.max_profit = 2000000000; + + this.max_score = 0.0; + } + + async get_bet_options() { + let bet_opts = { target: 48, condition_high: false, wager: 0 }; + + let exceeding_low = this.getexceedinggaps(this.low_gaps, this.base_score, 0.01, 0.1); + let exceeding_low_second = this.getexceedinggaps(this.low_gaps, this.base_score, 0.01, 0.20); + let exceeding_high = this.getexceedinggaps(this.high_gaps, this.base_score, 0.01, 0.1); + let exceeding_high_second = this.getexceedinggaps(this.high_gaps, this.base_score, 0.01, 0.20); + + let low_gaps_score = 0; + let high_gaps_score = 0; + let low_gaps_score_second = 0; + let high_gaps_score_second = 0; + + for (let i = 0; i < exceeding_low.length; ++i) { + low_gaps_score += exceeding_low[i].score; + } + + for (let i = 0; i < exceeding_high.length; ++i) { + high_gaps_score += exceeding_high[i].score; + } + + for (let i = 0; i < exceeding_low_second.length; ++i) { + low_gaps_score_second += exceeding_low_second[i].score; + } + + for (let i = 0; i < exceeding_high_second.length; ++i) { + high_gaps_score_second += exceeding_high_second[i].score; + } + + if (low_gaps_score > this.max_score) { + if (low_gaps_score-this.max_score > 10) { + this.max_score = low_gaps_score; + console.log('lgs', low_gaps_score); + await this.sleep(1000); + } + } + + if (high_gaps_score > this.max_score) { + if (high_gaps_score-this.max_score > 10) { + this.max_score = high_gaps_score; + console.log('hgs', high_gaps_score); + await this.sleep(1000); + } + } + + let lgs1 = this.gethighgapscore(exceeding_low, 0.01, 0.1); + let lgs2 = this.gethighgapscore(exceeding_low_second, 0.01, 0.2); + let hgs1 = this.gethighgapscore(exceeding_high, 0.01, 0.1); + let hgs2 = this.gethighgapscore(exceeding_high_second, 0.01, 0.2); + + // update current state + if (this.state == 2) { + if (this.last_bet.won) { + this.state = 0; + //this.base_score += 0.25; + } + } + + if (this.state == 1) { + if (this.last_bet.won) { + this.state = 0; + bet_opts.wager = 0; + } else if (this.streak_cost >= 100000) { + this.state = 2 + } + } + + if (this.state == 0) { + if ((low_gaps_score > 30 && low_gaps_score_second > 60 && lgs2.score > lgs1.score+2) || (high_gaps_score > 30 && high_gaps_score_second > 60 && hgs2.score > hgs1.score+2)) { + this.state = 1; + bet_opts.wager = this.base_wager; + } + } + + // update bet_opts according to current state + if (this.state == 1) { + if (low_gaps_score_second > 0 || high_gaps_score_second > 0) { + if (high_gaps_score_second > low_gaps_score_second) { + let gap = this.gethighgapscore(exceeding_high_second, 0.01, 0.2); + bet_opts = this.make_target(48, true, true); + } else { + let gap = this.gethighgapscore(exceeding_low_second, 0.01, 0.2); + bet_opts = this.make_target(48, false, true); + } + } + + if (this.streak_cost == 0) { + bet_opts.wager = this.base_wager; + } else if (this.streak_cost < 100000) { + bet_opts.wager = this.last_bet.wager * 2; + } + + } else if (this.state == 2) { + if (low_gaps_score_second > 0 || high_gaps_score_second > 0) { + const amount = Math.round(this.balance*0.0033 <= 500000000 ? this.balance*0.0033 : 500000000); + + if (high_gaps_score_second > low_gaps_score_second) { + let gap = this.gethighgapscore(exceeding_high_second, 0.01, 0.2); + bet_opts = this.make_target(gap.chance, true, true); + bet_opts.wager = this.getwagerforprofit(bet_opts.chance, this.streak_cost, amount, false); + } else { + let gap = this.gethighgapscore(exceeding_low_second, 0.01, 0.2); + bet_opts = this.make_target(gap.chance, false, true); + bet_opts.wager = this.getwagerforprofit(bet_opts.chance, this.streak_cost, amount, false); + } + } + } + + return bet_opts; + } +} + +(function() { + let init = async () => { + let bot = new MyBot(); + let success = await bot.initialize(botcore.options.site, botcore.options.profile); + if (success) + await bot.run(); + + process.exit(0); + } + init(); +})() diff --git a/pool/shard011/JavaScript/0070002_fn.scrollT.js b/pool/shard011/JavaScript/0070002_fn.scrollT.js new file mode 100644 index 0000000000000000000000000000000000000000..19d50d2590e994858ffb6a2b999e2ade0fe3bda4 --- /dev/null +++ b/pool/shard011/JavaScript/0070002_fn.scrollT.js @@ -0,0 +1,51 @@ +(function($) { + /* + * fonction srcollT() qui permet de remonter en haut de page. + * + * @param [(int) d, (int) t] + * d : le delai (en ms) avant le defilement vers le haut, (default = 30ms). + * t : le temps (en ms) du defilement vers le haut, (default = 800ms) + * + */ + $.fn.scrollT = function(d, t) { + d = d || 30; + t = t || 800; + + $('.scrollT').fadeOut(100); // on cache le bouton. + + + /* + * @event SCROLL + * affiche/cache le bouton selon la hauteur du scroll. + * + */ + $(window).scroll(function() { + + if ($(this).scrollTop() <= 200) { + $('.scrollT').fadeOut(100); + } else { + $('.scrollT').fadeIn(100); + } + + }); // scroll() + + + /* + * @event CLICK + * Remonte en haut de page au clic sur le bouton. + * + */ + $('.scrollT').click(function(e) { + e.preventDefault(); + e.stopPropagation(); + + $('html, body').animate({ + scrollTop: 0 + }, 'slow'); + + + }); // click() + + + }; // scrollT() +})(jQuery); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070008_client.js b/pool/shard011/JavaScript/0070008_client.js new file mode 100644 index 0000000000000000000000000000000000000000..953985020dc845fe0c447645f157f3fabaae5eef --- /dev/null +++ b/pool/shard011/JavaScript/0070008_client.js @@ -0,0 +1,63 @@ +var request = require('request'); +var xml2js = require('xml2js'); + +/** + * Creates an instance of Client + * + * @constructor + * @this {Client} + */ +var Client = function() { + + this._xmlBuilder = new xml2js.Builder(); + this._xmlParser = xml2js.parseString; + +}; + + +Client.prototype.request = function(options, callback) { + + var self = this; + options = options || {}; + + + // Add SOAP headers to request body + var xml = { + 'soap12:Envelope': { + '$': { + 'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance', + 'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema', + 'xmlns:soap12': 'http://www.w3.org/2003/05/soap-envelope' + }, + 'soap12:Header': {}, + 'soap12:Body': options.soapBody + } + }; + + var reqOptions = { + url: options.url, + method: 'POST', + headers: { + 'Content-Type': 'application/soap+xml; charset=utf-8' + }, + body: this._xmlBuilder.buildObject(xml) + }; + + return request(reqOptions, function(err, res, body) { + if (err || !body) return callback(err, body, res); + + self._xmlParser(body, { explicitArray: false, mergeAttrs: true }, function(err, result) { + if (err && callback) return callback(err, body, res); + + // remove SOAP headers from body + try { + body = result['soap:Envelope']['soap:Body']; + } catch(e) {} + + if (callback) callback(err, body, res); + }); + }); + +}; + +module.exports = Client; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070011_index.js b/pool/shard011/JavaScript/0070011_index.js new file mode 100644 index 0000000000000000000000000000000000000000..94306b613aa7ac00950a7ab665dd9f0463053332 --- /dev/null +++ b/pool/shard011/JavaScript/0070011_index.js @@ -0,0 +1,38 @@ +'use strict' + +class Heroku { + constructor (options) { + this.options = options || {} + } + + request (options) { + var Request = require('./request') + options = options || {} + options.headers = Object.assign(Object.assign({}, this.options.headers), options.headers) + options = Object.assign({}, this.options, options) + let request = new Request(options) + return request.request() + } + + get (path, options) { + return this.request(Object.assign({}, options, {method: 'GET', path: path})) + } + + put (path, options) { + return this.request(Object.assign({}, options, {method: 'PUT', path: path})) + } + + post (path, options) { + return this.request(Object.assign({}, options, {method: 'POST', path: path})) + } + + patch (path, options) { + return this.request(Object.assign({}, options, {method: 'PATCH', path: path})) + } + + delete (path, options) { + return this.request(Object.assign({}, options, {method: 'DELETE', path: path})) + } +} + +module.exports = Heroku diff --git a/pool/shard011/JavaScript/0070012_special.js b/pool/shard011/JavaScript/0070012_special.js new file mode 100644 index 0000000000000000000000000000000000000000..9f31d12dd7100d0bc69c5f53ac4aa296191c2678 --- /dev/null +++ b/pool/shard011/JavaScript/0070012_special.js @@ -0,0 +1,87 @@ +(function(window, $, undefined) { + + $(function() { + + // 绑定专题类别 + fnBindNavList(); + + // 绑定专题列表 + fnBindSpecial(); + + // top-nav option + fnInitTopNav(); + + }); + + // 绑定专题类别 + function fnBindNavList(){ + var $oNavList = $('#navList'); + var _data = { + list: ['全部专题','美食','运动健身','咖啡饮品','幼儿早教','机票','高端酒店','宠物','百货商场','体检','社区生活','旅游','生活百科'] + }; + var _html = template('tplNavList', _data); + $oNavList.html(_html); + + } + + // 绑定专题列表 + function fnBindSpecial(){ + var $oSpecial = $('#special'); + var _data = { + list: [{ + imgUrl: 'assets/imgs/special/img_special_01.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_02.jpg', + speText: '尊享东航国际航线1000元红包尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_03.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_04.jpg', + speText: '尊享东航国际航线1000元红包尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_05.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_06.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_07.jpg', + speText: '尊享东航国际航线1000元红包尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_08.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_09.jpg', + speText: '尊享东航国际航线1000元红包' + },{ + imgUrl: 'assets/imgs/special/img_special_10.jpg', + speText: '尊享东航国际航线1000元红包尊享东航国际航线1000元红包' + }] + }; + var _html = template('tplSpecial', _data); + $oSpecial.html(_html); + } + + // top-nav option + function fnInitTopNav(){ + var $oNav = $('.top-nav'), + $oList = $oNav.find('.nav-list'), + $oNavHeight = $oList.height(), + $aBtnSelect = $oNav.find('.btn-select'); + + // init list height + $oList.height('90px'); + + $aBtnSelect.on('click', function(){ + if($(this).hasClass('active')){ + $oList.removeClass('active').animate({height:'90px'}); + }else{ + $oList.addClass('active').animate({height:$oNavHeight}); + } + $(this).toggleClass('active'); + }); + } + +})(window, jQuery); diff --git a/pool/shard011/JavaScript/0070014_mediawiki.UtilitiesTime.js b/pool/shard011/JavaScript/0070014_mediawiki.UtilitiesTime.js new file mode 100644 index 0000000000000000000000000000000000000000..ad0bb3ba14f0c157b377b43c58011fb8c80d60f8 --- /dev/null +++ b/pool/shard011/JavaScript/0070014_mediawiki.UtilitiesTime.js @@ -0,0 +1,124 @@ +/** + * dependencies: [ mw ] + */ +( function( mw ) { + + /** + * Given a float number of seconds, returns npt format response. ( ignore + * days for now ) + * + * @param {Float} + * sec Seconds + * @param {Boolean} + * show_ms If milliseconds should be displayed. + * @param {Boolean} + * mm_format if you want to show 2 digits for minutes + * @return {Float} String npt format + */ + mw.seconds2npt = function( sec, show_ms , mm_format ) { + if ( isNaN( sec ) ) { + mw.log("Warning: mediawiki.UtilitiesTime, trying to get npt time on NaN:" + sec); + return '0:00:00'; + } + + var tm = mw.seconds2Measurements( sec ); + + // Round the number of seconds to the required number of significant + // digits + if ( show_ms ) { + tm.seconds = Math.round( tm.seconds * 1000 ) / 1000; + } else { + tm.seconds = Math.round( tm.seconds ); + } + if ( tm.seconds < 10 ){ + tm.seconds = '0' + tm.seconds; + } + if( tm.hours == 0 ){ + hoursStr = ''; + if (mm_format && tm.minutes < 10) + tm.minutes = '0' + tm.minutes; + } else { + if ( tm.minutes < 10 ) + tm.minutes = '0' + tm.minutes; + + hoursStr = tm.hours + ":"; + } + + return hoursStr + tm.minutes + ":" + tm.seconds; + }; + + /** + * Given seconds return array with 'days', 'hours', 'min', 'seconds' + * + * @param {float} + * sec Seconds to be converted into time measurements + */ + mw.seconds2Measurements = function ( sec ){ + var tm = {}; + tm.days = Math.floor( sec / ( 3600 * 24 ) ); + tm.hours = Math.floor( Math.round( sec ) / 3600 ); + tm.minutes = Math.floor( ( Math.round( sec ) / 60 ) % 60 ); + tm.seconds = Math.round(sec) % 60; + return tm; + }; + /** + * Given a timeMeasurements object return the number of seconds + * @param {object} timeMeasurements + */ + mw.measurements2seconds = function( timeMeasurements ){ + var seconds = 0; + if( timeMeasurements.days ){ + seconds += parseInt( timeMeasurements.days, 10 ) * 24 * 3600; + } + if( timeMeasurements.hours ){ + seconds += parseInt( timeMeasurements.hours, 10 ) * 3600; + } + if( timeMeasurements.minutes ){ + seconds += parseInt( timeMeasurements.minutes, 10 ) * 60; + } + if( timeMeasurements.seconds ){ + seconds += parseInt( timeMeasurements.seconds, 10 ); + } + if( timeMeasurements.milliseconds ){ + seconds += parseFloat(timeMeasurements.milliseconds); + } + return seconds; + }; + + /** + * Take hh:mm:ss,ms or hh:mm:ss.ms input, return the number of seconds + * + * @param {String} + * npt_str NPT time string + * @return {Float} Number of seconds + */ + mw.npt2seconds = function ( npt_str ) { + if ( !npt_str ) { + // mw.log('npt2seconds:not valid ntp:'+ntp); + return 0; + } + // Strip {npt:}01:02:20 or 32{s} from time if present + npt_str = npt_str.replace( /npt:|s/g, '' ); + + var hour = 0; + var min = 0; + var sec = 0; + + times = npt_str.split( ':' ); + if ( times.length == 3 ) { + sec = times[2]; + min = times[1]; + hour = times[0]; + } else if ( times.length == 2 ) { + sec = times[1]; + min = times[0]; + } else { + sec = times[0]; + } + // Sometimes a comma is used instead of period for ms + sec = sec.replace( /,\s?/, '.' ); + // Return seconds float + return parseInt( hour * 3600 ) + parseInt( min * 60 ) + parseFloat( sec ); + }; + +} )( window.mediaWiki ); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070016_app.js b/pool/shard011/JavaScript/0070016_app.js new file mode 100644 index 0000000000000000000000000000000000000000..64d4e15282474c0dfef6c8eb6e7814165e39981c --- /dev/null +++ b/pool/shard011/JavaScript/0070016_app.js @@ -0,0 +1,105 @@ +/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2; js-indent-level: 2; -*- */ +define(function (require) { + 'use strict'; + + var Backbone = require("backbone"); + var React = require("react"); + var _ = require("underscore"); + var FileUtil = require("spa/helpers/fileUtil"); + + + // Set CSRF + var _sync = Backbone.sync; + Backbone.sync = function(method, model, options){ + options.beforeSend = function(xhr){ + xhr.setRequestHeader('X-CSRF-Token', CSRF_TOKEN); + }; + return _sync(method, model, options); + }; + + // Models + var documentModel = new (require("spa/models/document"))(); + var marginaliaModel = new (require("spa/models/marginalia"))(); + + // Components + var TopBar = React.createFactory(require("jsx!components/topBar")); + var Document = React.createFactory(require("jsx!spa/components/document")); + var Marginalia = React.createFactory(require("jsx!spa/components/marginalia")); + + var process = function(data) { + var upload = FileUtil.upload("/topologies/gen2phen", data); + documentModel.loadFromData(data); + upload.then(function(result) { + var marginalia = JSON.parse(result); + marginaliaModel.reset(marginaliaModel.parse(marginalia)); + }); + }; + + var topBarComponent = React.render( + new TopBar({ + callback: process, + accept: ".pdf", + mimeType: /application\/(x-)?pdf|text\/pdf/ + }), + document.getElementById("top-bar") + ); + + var documentComponent = React.render( + new Document({pdf: documentModel, marginalia: marginaliaModel}), + document.getElementById("viewer") + ); + + var marginaliaComponent = React.render( + new Marginalia({marginalia: marginaliaModel}), + document.getElementById("marginalia") + ); + + // Dispatch logic + // Listen to model change callbacks -> trigger updates to components + marginaliaModel.on("all", function(e, obj) { + switch(e) { + case "reset": + documentModel.annotate(marginaliaModel.getActive()); + marginaliaComponent.forceUpdate(); + break; + case "annotations:change": + break; + case "change:active": + case "annotations:add": + case "annotations:remove": + documentModel.annotate(marginaliaModel.getActive()); + marginaliaComponent.forceUpdate(); + break; + case "annotations:select": + documentComponent.setState({select: obj}); + break; + default: + marginaliaComponent.forceUpdate(); + } + }); + + documentModel.on("all", function(e, obj) { + switch(e) { + case "change:raw": + documentComponent.setState({ + fingerprint: documentModel.get("fingerprint") + }); + break; + case "change:binary": + marginaliaModel.reset(); + break; + case "pages:change:state": + if(obj.get("state") == window.RenderingStates.HAS_CONTENT) { + documentModel.annotate(marginaliaModel.getActive()); + } + documentComponent.forceUpdate(); + break; + case "pages:change:annotations": + documentModel.annotate(marginaliaModel.getActive()); + documentComponent.forceUpdate(); + break; + default: + break; + } + }); +}); diff --git a/pool/shard011/JavaScript/0070017_build-watch-test.js b/pool/shard011/JavaScript/0070017_build-watch-test.js new file mode 100644 index 0000000000000000000000000000000000000000..b025dc47fd6349bb02ec09c24fca61e4c0b7d238 --- /dev/null +++ b/pool/shard011/JavaScript/0070017_build-watch-test.js @@ -0,0 +1,76 @@ +'use strict'; + +const RSVP = require('rsvp'); +const BuildWatchTask = require('../../../lib/tasks/build-watch'); +const Builder = require('../../../lib/models/builder'); +const MockProject = require('../../helpers/mock-project'); +const expect = require('chai').expect; + +const Promise = RSVP.Promise; + +describe('build-watch task', function() { + let task, ui; + + function setupBroccoliBuilder() { + this.builder = { + build() { + return Promise.resolve('build results'); + }, + + cleanup() { + return Promise.resolve('cleanup result'); + }, + + processBuildResult(results) { + return Promise.resolve(results); + }, + }; + } + + function runBuildWatchTask() { + let project = new MockProject(); + + ui = project.ui; + let _builder = new Builder({ + ui, + project, + setupBroccoliBuilder, + onProcessInterrupt: { + addHandler() {}, + removeHandler() {}, + }, + }); + + let _watcher = { + then(fulfillmentHandler, rejectionHandler) { + return Promise.resolve().then(fulfillmentHandler, rejectionHandler); + }, + }; + + task = new BuildWatchTask({ + ui, + project, + }); + + let options = { + outputPath: 'tmp/build-watch-task-test', + environment: 'test', + _builder, + _watcher, + }; + return task.run(options); + } + + describe('onInterrupt', function() { + it('fulfills the run promise and cleans up the builder', function() { + let runPromise = runBuildWatchTask(); + + RSVP.resolve().then(() => task.onInterrupt()); + + return runPromise.then(() => { + expect(ui.output).to.include('cleaning up...'); + expect(ui.output).to.include('Environment: test'); + }); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070018_TuioPoint.js b/pool/shard011/JavaScript/0070018_TuioPoint.js new file mode 100644 index 0000000000000000000000000000000000000000..41fff1890bd4e71809e22c76cd9cf32277ee8b4e --- /dev/null +++ b/pool/shard011/JavaScript/0070018_TuioPoint.js @@ -0,0 +1,73 @@ +$(document).ready(function() { + module("Tuio.Point", { + setup: function() { + + }, + + teardown: function() { + + } + }); + + test("initialize with position", function() { + var point = new Tuio.Point({xp: 10, yp: 20}); + + equal(point.getX(), 10); + equal(point.getY(), 20); + }); + + test("initialize with time and position", function() { + var point = new Tuio.Point({ + ttime: new Tuio.Time(2, 5000), + xp: 10, + yp: 20 + }); + + equal(point.getX(), 10); + equal(point.getY(), 20); + ok(point.currentTime.equals(point.getTuioTime())); + ok(point.startTime.equals(point.getStartTime())); + }); + + test("updateToPoint", function() { + var point1 = new Tuio.Point({xp: 2, yp: 18}), + point2 = new Tuio.Point({xp: 4, yp: 4}); + point1.updateToPoint(point2); + + equal(point1.getX(), 4); + equal(point1.getY(), 4); + }); + + test("getDistance", function() { + var point = new Tuio.Point({xp: 0, yp: 0}); + + equal(point.getDistance(0, 10), 10); + }); + + test("getDistanceToPoint", function() { + var point1 = new Tuio.Point({xp: 2, yp: 2}), + point2 = new Tuio.Point({xp: 6, yp: 2}); + + equal(point1.getDistanceToPoint(point2), 4); + }); + + test("getAngleDegrees", function() { + var point = new Tuio.Point({xp: 10, yp: 10}); + + equal(point.getAngleDegrees(20, 20), 315); + }); + + test("getAngleDegreesToPoint", function() { + var point1 = new Tuio.Point({xp: 100, yp: 100}), + point2 = new Tuio.Point({xp: 50, yp: 50}); + + equal(point1.getAngleDegreesToPoint(point2), 135); + }); + + test("getScreenX/Y", function() { + var point = new Tuio.Point({xp: 0.5, yp: 0.1}); + + equal(point.getScreenX(800), 400); + equal(point.getScreenY(600), 60); + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070022_ReactPropTransferer.js b/pool/shard011/JavaScript/0070022_ReactPropTransferer.js new file mode 100644 index 0000000000000000000000000000000000000000..9f473265b56ec53ba789b676bc147adde62e800c --- /dev/null +++ b/pool/shard011/JavaScript/0070022_ReactPropTransferer.js @@ -0,0 +1,162 @@ +/** + * Copyright 2013-2014 Facebook, 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. + * + * @providesModule ReactPropTransferer + */ + +"use strict"; + +var emptyFunction = require('emptyFunction'); +var invariant = require('invariant'); +var joinClasses = require('joinClasses'); +var merge = require('merge'); + +/** + * Creates a transfer strategy that will merge prop values using the supplied + * `mergeStrategy`. If a prop was previously unset, this just sets it. + * + * @param {function} mergeStrategy + * @return {function} + */ +function createTransferStrategy(mergeStrategy) { + return function(props, key, value) { + if (!props.hasOwnProperty(key)) { + props[key] = value; + } else { + props[key] = mergeStrategy(props[key], value); + } + }; +} + +var transferStrategyMerge = createTransferStrategy(function(a, b) { + // `merge` overrides the first object's (`props[key]` above) keys using the + // second object's (`value`) keys. An object's style's existing `propA` would + // get overridden. Flip the order here. + return merge(b, a); +}); + +/** + * Transfer strategies dictate how props are transferred by `transferPropsTo`. + * NOTE: if you add any more exceptions to this list you should be sure to + * update `cloneWithProps()` accordingly. + */ +var TransferStrategies = { + /** + * Never transfer `children`. + */ + children: emptyFunction, + /** + * Transfer the `className` prop by merging them. + */ + className: createTransferStrategy(joinClasses), + /** + * Never transfer the `key` prop. + */ + key: emptyFunction, + /** + * Never transfer the `ref` prop. + */ + ref: emptyFunction, + /** + * Transfer the `style` prop (which is an object) by merging them. + */ + style: transferStrategyMerge +}; + +/** + * Mutates the first argument by transferring the properties from the second + * argument. + * + * @param {object} props + * @param {object} newProps + * @return {object} + */ +function transferInto(props, newProps) { + for (var thisKey in newProps) { + if (!newProps.hasOwnProperty(thisKey)) { + continue; + } + + var transferStrategy = TransferStrategies[thisKey]; + + if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { + transferStrategy(props, thisKey, newProps[thisKey]); + } else if (!props.hasOwnProperty(thisKey)) { + props[thisKey] = newProps[thisKey]; + } + } + return props; +} + +/** + * ReactPropTransferer are capable of transferring props to another component + * using a `transferPropsTo` method. + * + * @class ReactPropTransferer + */ +var ReactPropTransferer = { + + TransferStrategies: TransferStrategies, + + /** + * Merge two props objects using TransferStrategies. + * + * @param {object} oldProps original props (they take precedence) + * @param {object} newProps new props to merge in + * @return {object} a new object containing both sets of props merged. + */ + mergeProps: function(oldProps, newProps) { + return transferInto(merge(oldProps), newProps); + }, + + /** + * @lends {ReactPropTransferer.prototype} + */ + Mixin: { + + /** + * Transfer props from this component to a target component. + * + * Props that do not have an explicit transfer strategy will be transferred + * only if the target component does not already have the prop set. + * + * This is usually used to pass down props to a returned root component. + * + * @param {ReactDescriptor} descriptor Component receiving the properties. + * @return {ReactDescriptor} The supplied `component`. + * @final + * @protected + */ + transferPropsTo: function(descriptor) { + invariant( + descriptor._owner === this, + '%s: You can\'t call transferPropsTo() on a component that you ' + + 'don\'t own, %s. This usually means you are calling ' + + 'transferPropsTo() on a component passed in as props or children.', + this.constructor.displayName, + descriptor.type.displayName + ); + + // Because descriptors are immutable we have to merge into the existing + // props object rather than clone it. + transferInto(descriptor.props, this.props); + + return descriptor; + } + + } +}; + +module.exports = ReactPropTransferer; diff --git a/pool/shard011/JavaScript/0070027_slurp.js b/pool/shard011/JavaScript/0070027_slurp.js new file mode 100644 index 0000000000000000000000000000000000000000..8dde0a852d4a8e622776add61925068a72d53723 --- /dev/null +++ b/pool/shard011/JavaScript/0070027_slurp.js @@ -0,0 +1,97 @@ +'use strict'; + +let chai = require("chai"); +let sinon = require("sinon"); +let sinonChai = require("sinon-chai"); +let expect = chai.expect; +chai.use(sinonChai); + +let EventEmitter = require('events'); +let path = require('path'); +let slurpdir = require('..'); + +function assetPath(id) { + return path.join(__dirname, 'assets', id); +} + +describe('slurpdir', function() { + + it('should callback an object of all files in a directory', (done) => { + slurpdir(assetPath('simple'), (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['simple']); + expect(tree.simple).to.equal('simple string'); + done(); + }); + }); + + it('should recurse directories when recurse:true', (done) => { + slurpdir(assetPath('recursive'), {recursive: true}, (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['foo', 'bar']); + done(); + }); + }); + + it('should default to recurse:false', (done) => { + slurpdir(assetPath('recursive'), (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['foo']); + done(); + }); + }); + + it('should ignore unknown file types', (done) => { + slurpdir(assetPath('parsers'), (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['js', 'json']); + done(); + }); + }); + + it('should not treat extensions case sensitively', (done) => { + slurpdir(assetPath('uppercase'), (err, tree) => { + if (err) return done(err); + expect(Object.keys(tree)).to.have.length(1); + done(); + }); + }); + + it('should treat basenames case sensitively', (done) => { + slurpdir(assetPath('both_cases'), (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['lower', 'upper']); + done(); + }); + }); + + it('should parse other file types with custom parsers', (done) => { + let args = { + parsers: { + '.jsonlines': function (input) { + return input.data.toString().split('\n').map((l) => l && JSON.parse(l)); + } + } + }; + slurpdir(assetPath('parsers'), args, (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['js', 'json', 'jsonlines']); + done(); + }); + }); + + it('should disable built in parser when custom parser is null', (done) => { + let args = { + parsers: { + '.js': null + } + }; + slurpdir(assetPath('parsers'), args, (err, tree) => { + if (err) return done(err); + expect(tree).to.have.keys(['json']); + done(); + }); + + }); + +}); diff --git a/pool/shard011/JavaScript/0070029_tools.js b/pool/shard011/JavaScript/0070029_tools.js new file mode 100644 index 0000000000000000000000000000000000000000..89c3922ec05c7bdd50f36c9f6764a9cf600abba9 --- /dev/null +++ b/pool/shard011/JavaScript/0070029_tools.js @@ -0,0 +1,93 @@ +var quirksTools = ( function() { + 'use strict'; + + var DEL = 46, + BACKSPACE = 8, + + keyNames = { + 46: 'DEL', + 8: 'BACKSPACE' + }; + + function assertKeystroke( key, keyModifiers, handled, html, expected ) { + function decodeBoguses( html ) { + return html.replace( /@/g, '
    ' ); + } + + return function() { + var bot = this.editorBot, + editor = bot.editor, + handledNatively = 0; + + html = decodeBoguses( html ); + + bot.htmlWithSelection( html ); + + var listener = editor.on( 'key', function() { + ++handledNatively; + }, null, null, 999 ); + + editor.editable().fire( 'keydown', new CKEDITOR.dom.event( { + keyCode: key, + ctrlKey: keyModifiers & CKEDITOR.CTRL, + shiftKey: keyModifiers & CKEDITOR.SHIFT, + } ) ); + + assert.areSame( decodeBoguses( expected ), + bender.tools.getHtmlWithSelection( editor.editable(), editor.document ).replace( /\u200b/g, '' ), '(' + keyNames[ key ] + ') Correct DOM state after the keystroke' ); + assert.areSame( handled, handledNatively, '(' + keyNames[ key ] + ') Keystroke handled by the browser' ); + + listener.removeListener(); + }; + } + + function d() { + return assertKeystroke.apply( this, [ DEL, 0, 0 ].concat( [].slice.call( arguments ) ) ); + } + + function b() { + return assertKeystroke.apply( this, [ BACKSPACE, 0, 0 ].concat( [].slice.call( arguments ) ) ); + } + + function bf( html ) { + return assertKeystroke.apply( this, [ BACKSPACE, 0, 1, html, html ] ); + } + + function df( html ) { + return assertKeystroke.apply( this, [ DEL, 0, 1, html, html ] ); + } + + return { + DEL: DEL, + BACKSPACE: BACKSPACE, + + assertKeystroke: assertKeystroke, + d: d, + b: b, + + // Calls d() and b() for the same arguments. + bd: function() { + var bfn = b.apply( this, arguments ), + dfn = d.apply( this, arguments ); + + return function() { + bfn.call( this ); + dfn.call( this ); + }; + }, + + bf: bf, + df: df, + + // Calls df() and bf() for the same arguments. + bdf: function() { + var bffn = bf.apply( this, arguments ), + dffn = df.apply( this, arguments ); + + return function() { + bffn.call( this ); + dffn.call( this ); + }; + } + }; +} )(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070030_command.js b/pool/shard011/JavaScript/0070030_command.js new file mode 100644 index 0000000000000000000000000000000000000000..5c589f8da891278c08084afe93b0194b4d04468f --- /dev/null +++ b/pool/shard011/JavaScript/0070030_command.js @@ -0,0 +1,97 @@ +var path = require('path'); +var fs = require('fs'); +var clap = require('clap'); + + +function applyConfig(command, config){ + command.values.base = path.resolve(config._configPath || ''); + + if ('l10n' in config) + command.values.l10n = !!config.l10n; + + command.values._configPath = config._configPath; + command.values._paths = config.path; + command.values.templates = config.templates; + command.values.appName = config.appName || 'app'; + + return command; +} + +function normOptions(options){ + if (!options.name) + { + console.warn('Name is not specified'); + process.exit(); + } + + if (!/^[a-z\_$][\.a-z0-9\_\-$]*$/i.test(options.name)) + { + console.warn('Topic name has wrong symbols:', options.name); + process.exit(); + } + + options.base = path.normalize(path.resolve(options.base || '') + '/'); // [base] + + // resolve output dir + var paths = options._paths || {}; + switch (options.topic) + { + case 'component': + options.output = path.resolve(options.base, paths.component || ''); + options.index = paths.typeIndex ? path.resolve(options.base, paths.typeIndex) : false; + break; + default: + options.output = path.resolve(options.output); + } + options.outputDir = path.normalize(options.output); + + // resolve input dir + options.templates = (options.templates || []) + .concat(__dirname + '/template/') + .map(function(dir){ + return path.resolve(options._configPath || options.base, dir); + }); + + return options; +} + +var command = clap.create('create') + .description('Code generator') + .option('-b, --base ', 'base path for relative path resolving (current path by default)', '.') + .init(function(){ + if (this.config) + { + var data = this.config[this.name] || {}; + data._configPath = this.configPath; + applyConfig(this, data); + } + }) + .delegate(function(nextCommand){ + if (this.config) + { + var data = this.config[this.name] || {}; + data._configPath = this.configPath; + nextCommand.configFile = this.configFile; + applyConfig(nextCommand, data); + } + }); + +// create component +command.command('component', '[name]') + .description('Create a data type') + .option('-b, --base ', 'base path for relative path resolving (current path by default)', '.') + .option('-t, --template ', 'name of template', 'default') + .option('-n, --name ', 'name of component') + .option('-i, --ignorePath ', 'ignore path') + .args(function(name){ + this.setOption('name', name); + }) + .action(function(){ + if (this.configFile) + console.log('Config: ' + this.configFile + '\n'); + + require('./index.js').create.call(this, 'component', this.values); + }); + +module.exports = command; +module.exports.norm = normOptions; diff --git a/pool/shard011/JavaScript/0070033_UserConfigTest.js b/pool/shard011/JavaScript/0070033_UserConfigTest.js new file mode 100644 index 0000000000000000000000000000000000000000..2535668e478d124ecb7afbecf36dc6d38ef7bf3e --- /dev/null +++ b/pool/shard011/JavaScript/0070033_UserConfigTest.js @@ -0,0 +1,12 @@ +var path = require('path'); +var fs = require('fs'); +var expect = require('chai').expect; +var UserConfig = require("../lib/UserConfig"); + +describe('new UserConfig()', function(){ + it('Should be an object.', function(){ + var uc = new UserConfig(); + + expect(uc).to.be.an('object'); + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070034_app.js b/pool/shard011/JavaScript/0070034_app.js new file mode 100644 index 0000000000000000000000000000000000000000..225708c026ac3c2da35133460c05d3ebf2cc7eb5 --- /dev/null +++ b/pool/shard011/JavaScript/0070034_app.js @@ -0,0 +1,190 @@ +var scan = require('./scanner'); + +scan(process.env.FILE_REPO_DIR, function (appFiles) { + var fs = require('fs'); + var path = require('path'); + var requirejs = require('requirejs'); + var http = require('http'); + var _ = require('lodash'); + var bootstrap; + var appJSON = fs.readFileSync(path.normalize(process.env.FILE_REPO_DIR + '/app/app.json')); + var routes = {}; + + try { + appJSON = JSON.parse(appJSON); + routes = appJSON.routes; + } catch (e) { + console.log('Error reading app/routes.json: ' + e); + process.exit(code=0); + } + + function mergeArrays(a, b) { + if (_.isArray(a)) { + return a.concat(b); + } + } + + function resolveConf(conf, env) { + return _.merge(conf.requirejs.common || {}, conf.requirejs[env] || {}, mergeArrays); + } + + var conf = (function() { + var conf = JSON.parse(fs.readFileSync(path.normalize(process.env.BASE_PATH + '/' + 'conf.json'))); + + var appConfPath = path.normalize(process.env.FILE_REPO_DIR + '/conf.json'); + var appConf = fs.existsSync(appConfPath) ? fs.readFileSync(appConfPath) : null; + + if (appConf) { + try { + appConf = JSON.parse(appConf); + } catch (e) { + console.log('Error reading conf.json: ' + e); + process.exit(code=0); + } + + _.merge(conf, appConf, mergeArrays); + } + + return conf; + })(); + + global.LAZO = { + BASE_PATH: process.env.BASE_PATH, + FILE_REPO_DIR: process.env.FILE_REPO_DIR, + SHARED_REPO_DIR: process.env.SHARED_REPO_DIR, + FILE_REPO_PATH: path.resolve(process.env.FILE_REPO_DIR), + PORT: process.env.PORT ? parseInt(process.env.PORT, 10) : conf.server.port, + CLUSTER: process.env.CLUSTER === '1', + ROBUST: process.env.ROBUST === '1', + conf: conf, + routes: routes, + files: appFiles + }; + + bootstrap = requirejs.config({ + baseUrl: LAZO.BASE_PATH, + context: 'bootstrap', + paths: { + 'json': 'lib/vendor/json', + 'text': 'lib/vendor/text', + 'common': 'lib/common', + 'base': 'lib/common/base', + 'resolver': 'lib/common/resolver' + } + }); + + // load requireConfigure directly as opposed to resolver/main because resolver + // sub modules have need requirejs to be configured prior to being loaded + bootstrap(['resolver/requireConfigure'], function (requireConfigure) { + + 'use strict'; + + var options = { + basePath: LAZO.BASE_PATH, + baseUrl: LAZO.FILE_REPO_DIR + }; + + requireConfigure.get('server', _.merge(_.clone(options), resolveConf(conf, 'server')), function (err, serverConf) { + if (err) { + throw new Error(err); + } + + requireConfigure.get('client', _.merge(_.clone(options), resolveConf(conf, 'client')), function (err, clientConf) { + if (err) { + throw new Error(err); + } + + function addPaths(serverConf) { + var customBundlerPath = path.normalize(LAZO.FILE_REPO_DIR + path.sep + 'app' + path.sep + 'bundle.js'); + var customAssetPath = path.normalize(LAZO.FILE_REPO_DIR + path.sep + 'app' + path.sep + 'assets.js'); + var customServerSetup = path.normalize(LAZO.FILE_REPO_DIR + path.sep + 'app' + path.sep + + 'server' + path.sep + 'server.js'); + var customPageTemplate = path.normalize(LAZO.FILE_REPO_DIR + path.sep + 'app' + path.sep + 'views' + + path.sep + 'page.hbs'); + + if (fs.existsSync(customBundlerPath)) { + serverConf.paths.bundler = path.resolve(path.normalize(LAZO.FILE_REPO_DIR + '/app/bundle')); + } else { + serverConf.paths.bundler = serverConf.paths.lazoBundle; + } + if (fs.existsSync(customAssetPath)) { + serverConf.paths.assets = path.resolve(path.normalize(LAZO.FILE_REPO_DIR + '/app/assets')); + } + if (fs.existsSync(customServerSetup)) { + serverConf.paths.appServerSetup = path.resolve(path.normalize(LAZO.FILE_REPO_DIR + '/app/server/server')); + } + if (fs.existsSync(customPageTemplate)) { + serverConf.paths.pageTemplate = path.resolve(path.normalize(LAZO.FILE_REPO_DIR + '/app/views/page.hbs')); + } + + return serverConf; + } + + LAZO.require = requirejs.config(addPaths(serverConf)); + LAZO.contexts = { + request: JSON.parse(JSON.stringify(clientConf)), // request combo handling + lib: JSON.parse(JSON.stringify(clientConf)), // lib combo handling + server: JSON.parse(JSON.stringify(serverConf)), // paths are used for generating combo handled file + app: _.omit(clientConf, 'basePath') + }; + + // these are needed by dependencies of lazoApp + LAZO.isServer = true; + LAZO.isClient = false; + // these cannot be loaded until the requirejs app config has been set + LAZO.require(['config'], function (config) { + LAZO.config = config; + LAZO.require(['app/application'], function (LazoApp) { + LAZO.app = new LazoApp(); + LAZO.app.isServer = LAZO.isServer; + LAZO.app.isClient = LAZO.isClient; + LAZO.app.css = appJSON.css || []; + LAZO.app.js = appJSON.js || []; + LAZO.app.imports = appJSON.imports || []; + LAZO.app.getAssets = appJSON.assets || false; + LAZO.app.defaultLayout = appJSON.defaultLayout; + + // these are dependent on the + LAZO.require(['server', 'resolver/file', 'error', 'logger'], function (server, file, err, logger) { + + LAZO.error = err; + LAZO.logger = logger; + + // process appArgs command line argument into application.args + var args = process.argv.filter(function (elem) { + return elem.indexOf('--appArgs') !== -1; + }); + + if (args.length) { + LAZO.app.args = {}; + var appArgs = args[0].split('='), + args = appArgs[1].split(';'); + for (var i = 0, il = args.length; i < il; i++) { + var arg = args[i].split(':'); + LAZO.app.args[arg[0]] = arg[1]; + } + } + + LAZO.logger.warn(['server.app'], 'Initializing with arguments: %j', LAZO.app.args); + + http.globalAgent.maxSockets = LAZO.conf.server.maxSockets; + LAZO.conf.server.instances.primary.port = LAZO.PORT || LAZO.conf.server.instances.primary.port; + + LAZO.app.initialize(function () { + file.getErrorTemplatePaths(function (err, templates) { + if (err) { + throw err; + } + + LAZO.errorTemplates = templates; + server.initialize(templates); + }); + }); + }); + }); + }); + }); + }); + + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070038_array-iterator.js b/pool/shard011/JavaScript/0070038_array-iterator.js new file mode 100644 index 0000000000000000000000000000000000000000..8203f1f9f5933e46727f4fab187c5e24665f2af2 --- /dev/null +++ b/pool/shard011/JavaScript/0070038_array-iterator.js @@ -0,0 +1,171 @@ +// Copyright 2013 the V8 project authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +(function(global, utils) { + +"use strict"; + +%CheckIsBootstrapping(); + +// ----------------------------------------------------------------------- +// Imports + +var arrayIterationKindSymbol = + utils.ImportNow("array_iteration_kind_symbol"); +var arrayIteratorNextIndexSymbol = + utils.ImportNow("array_iterator_next_symbol"); +var arrayIteratorObjectSymbol = + utils.ImportNow("array_iterator_object_symbol"); +var GlobalArray = global.Array; +var IteratorPrototype = utils.ImportNow("IteratorPrototype"); +var iteratorSymbol = utils.ImportNow("iterator_symbol"); +var MakeTypeError; +var toStringTagSymbol = utils.ImportNow("to_string_tag_symbol"); +var GlobalTypedArray = %object_get_prototype_of(global.Uint8Array); + +utils.Import(function(from) { + MakeTypeError = from.MakeTypeError; +}) + +// ----------------------------------------------------------------------- + +function ArrayIterator() {} + + +// TODO(wingo): Update section numbers when ES6 has stabilized. The +// section numbers below are already out of date as of the May 2014 +// draft. + + +// 15.4.5.1 CreateArrayIterator Abstract Operation +function CreateArrayIterator(array, kind) { + var object = TO_OBJECT(array); + var iterator = new ArrayIterator; + SET_PRIVATE(iterator, arrayIteratorObjectSymbol, object); + SET_PRIVATE(iterator, arrayIteratorNextIndexSymbol, 0); + SET_PRIVATE(iterator, arrayIterationKindSymbol, kind); + return iterator; +} + + +// 22.1.5.2.2 %ArrayIteratorPrototype%[@@iterator] +function ArrayIteratorIterator() { + return this; +} + + +// ES6 section 22.1.5.2.1 %ArrayIteratorPrototype%.next( ) +function ArrayIteratorNext() { + var iterator = this; + var value = UNDEFINED; + var done = true; + + if (!IS_RECEIVER(iterator) || + !HAS_DEFINED_PRIVATE(iterator, arrayIteratorNextIndexSymbol)) { + throw MakeTypeError(kIncompatibleMethodReceiver, + 'Array Iterator.prototype.next', this); + } + + var array = GET_PRIVATE(iterator, arrayIteratorObjectSymbol); + if (!IS_UNDEFINED(array)) { + var index = GET_PRIVATE(iterator, arrayIteratorNextIndexSymbol); + var itemKind = GET_PRIVATE(iterator, arrayIterationKindSymbol); + var length = TO_UINT32(array.length); + + // "sparse" is never used. + + if (index >= length) { + SET_PRIVATE(iterator, arrayIteratorObjectSymbol, UNDEFINED); + } else { + SET_PRIVATE(iterator, arrayIteratorNextIndexSymbol, index + 1); + + if (itemKind == ITERATOR_KIND_VALUES) { + value = array[index]; + } else if (itemKind == ITERATOR_KIND_ENTRIES) { + value = [index, array[index]]; + } else { + value = index; + } + done = false; + } + } + + return %_CreateIterResultObject(value, done); +} + + +function ArrayEntries() { + return CreateArrayIterator(this, ITERATOR_KIND_ENTRIES); +} + + +function ArrayValues() { + return CreateArrayIterator(this, ITERATOR_KIND_VALUES); +} + + +function ArrayKeys() { + return CreateArrayIterator(this, ITERATOR_KIND_KEYS); +} + +// TODO(littledan): Check for detached TypedArray in these three methods +function TypedArrayEntries() { + if (!IS_TYPEDARRAY(this)) throw MakeTypeError(kNotTypedArray); + return %_Call(ArrayEntries, this); +} + + +function TypedArrayValues() { + if (!IS_TYPEDARRAY(this)) throw MakeTypeError(kNotTypedArray); + return %_Call(ArrayValues, this); +} + + +function TypedArrayKeys() { + if (!IS_TYPEDARRAY(this)) throw MakeTypeError(kNotTypedArray); + return %_Call(ArrayKeys, this); +} + + +%FunctionSetPrototype(ArrayIterator, {__proto__: IteratorPrototype}); +%FunctionSetInstanceClassName(ArrayIterator, 'Array Iterator'); + +utils.InstallFunctions(ArrayIterator.prototype, DONT_ENUM, [ + 'next', ArrayIteratorNext +]); +utils.SetFunctionName(ArrayIteratorIterator, iteratorSymbol); +%AddNamedProperty(ArrayIterator.prototype, toStringTagSymbol, + "Array Iterator", READ_ONLY | DONT_ENUM); + +utils.InstallFunctions(GlobalArray.prototype, DONT_ENUM, [ + // No 'values' since it breaks webcompat: http://crbug.com/409858 + 'entries', ArrayEntries, + 'keys', ArrayKeys +]); + +// TODO(adam): Remove this call once 'values' is in the above +// InstallFunctions block, as it'll be redundant. +utils.SetFunctionName(ArrayValues, 'values'); + +%AddNamedProperty(GlobalArray.prototype, iteratorSymbol, ArrayValues, + DONT_ENUM); + +utils.InstallFunctions(GlobalTypedArray.prototype, DONT_ENUM, [ + 'entries', TypedArrayEntries, + 'keys', TypedArrayKeys, + 'values', TypedArrayValues +]); +%AddNamedProperty(GlobalTypedArray.prototype, + iteratorSymbol, TypedArrayValues, DONT_ENUM); + +// ------------------------------------------------------------------- +// Exports + +utils.Export(function(to) { + to.ArrayValues = ArrayValues; +}); + +%InstallToContext(["array_values_iterator", ArrayValues]); + +}) diff --git a/pool/shard011/JavaScript/0070040_messageInfoAndSplashPage.js b/pool/shard011/JavaScript/0070040_messageInfoAndSplashPage.js new file mode 100644 index 0000000000000000000000000000000000000000..64f7cae3111b7987b25b91356a1671591601436a --- /dev/null +++ b/pool/shard011/JavaScript/0070040_messageInfoAndSplashPage.js @@ -0,0 +1,86 @@ +/* + * Cerberus Copyright (C) 2013 - 2017 cerberustesting + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This file is part of Cerberus. + * + * Cerberus 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. + * + * Cerberus 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 Cerberus. If not, see . + */ + + +/* + * When the document is ready if the user is on the splashPage, we fill that page we some information and function + * + * On every page we check if a message information needs to be displayed for the user + */ +$(document).ready(function () { + + if (document.title !== "Login") { + var user = getUser(); + var cerberusInformation = getCerberusInformation(); + + if (cerberusInformation != null) { + if ((cerberusInformation.isGlobalSplashPageActive || cerberusInformation.isInstanceSplashPageActive)) { + if (!user.isAdmin) { + redirectionToSplashPage(); + } else { + + showMessageMainPage("warning", "Cerberus maintenance is in progress !! Splash page activated for non admin users.", false, 10000); + } + } + + if (getPageName(window.location.pathname) === "SplashPage.jsp") { + displayAdminEmailOnSplashPage(); + addRedictionSplashPageButton(); + var doc = new Doc(); + displayFooter(doc) + } + + if (cerberusInformation.isMessageInformationEnabled) { + displayMessageInfoforAllUsers(cerberusInformation.messageInformation); + } + } + } +}); + +function redirectionToSplashPage() { + if (getPageName(window.location.pathname) !== "SplashPage.jsp") { + window.location.replace("SplashPage.jsp"); + } +} + +function displayAdminEmailOnSplashPage() { + var adminEmail = getParameter("cerberus_support_email", "", true); + $('#adminMailLink').attr("href", ('mailto:' + adminEmail.value)).text(adminEmail.value); +} + +function addRedictionSplashPageButton() { + $('#reloadButton').click(function () { + var cerberusInformation = getCerberusInformation(); + if (!cerberusInformation.isGlobalSplashPageActive && !cerberusInformation.isInstanceSplashPageActive) { + window.location.replace("Homepage.jsp"); + } else { + showMessageMainPage("info", "Cerberus maintenance is still in progress", false, 10000); + } + }); +} + +function getPageName(url) { + var index = url.lastIndexOf("/") + 1; + return url.substr(index); +} + +function displayMessageInfoforAllUsers(messageInfo) { + showMessageMainPage("info", messageInfo, false, 10000); +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070041_model.js b/pool/shard011/JavaScript/0070041_model.js new file mode 100644 index 0000000000000000000000000000000000000000..ca488f50d2d96c2fe499baf2974e1468c65ce01a --- /dev/null +++ b/pool/shard011/JavaScript/0070041_model.js @@ -0,0 +1,135 @@ +/** + * Data model provider. + * + * @package webmaker + * @author Andrew Sliwinski + */ + +var watch = require('watchjs').watch; +var localForage = require('localforage'); +var uuid = require('./uuid'); + +/** + * Constructor + */ +function Model (options) { + var self = this; + + if (!(self instanceof Model)) return new Model(); + + // Options + // memory: (false) Use memory provider for Makedrive + // noConnect: () if true, will not connect to remote server + self.options = options || {}; + + // Internal + self._sessionKey = 'webmaker.app.session'; + self._ready = false; + self._logger = function (prefix, msg) { + if (typeof msg === 'undefined') { + msg = prefix; + prefix = 'Model'; + } + + if (msg) console.log('[' + prefix + '] ', msg); + }; + + // Public + self.data = {}; + self.data.session = { + ftu: true, + path: '/sign-in', + locale: null, + offline: false, + guestId: uuid(), + user: {} + }; + +} + +Model.prototype.restoreSession = function restoreSession(callback) { + var self = this; + localForage.getItem(self._sessionKey, function (err, val) { + if (err) { + callback(err); + } + try { + val = JSON.parse(val); + for (var key in self.data.session) { + if (typeof val[key] !== 'undefined') { + self.data.session[key] = val[key]; + self._logger('restore session: ' + key, val[key]); + } + } + callback(null); + } catch (e) { + callback(e); + } + }); +}; + +Model.prototype.restore = function (callback) { + var self = this; + + self.anonymousConnect = function () { + self._logger('Starting in offline mode'); + self.data.session.offline = true; + self.data.session.user = { + id: self.data.session.guestId + }; + callback(); + }; + + self.restoreSession(function onRestore(err) { + self._logger('session restore', err || 'successful'); + self.observe(); + self.ftu = false; + self._ready = true; + + self.anonymousConnect(); + }); +}; + +/** + * Saves the current model state to localforage. + * + * @param {Function} callback + * + * @return {void} + */ +Model.prototype.save = function (callback) { + var self = this; + callback = callback || function () {}; + + var putItem = JSON.stringify(self.data.session); + localForage.setItem(self._sessionKey, putItem, callback); +}; + +/** + * Starts observing ("watch"-ing) for object changes. + * + * @return {void} + */ +Model.prototype.observe = function () { + var self = this; + + // Only run this once + if (self.observing) return; + self.observing = true; + + watch(self.data, function () { + self._dirty = true; + self.save(function onSave(err) { + self._logger('observe.onSave', err || 'successful'); + }); + }, 10); +}; + +var model; +function instantiateModel (options) { + // If the instance doesn't exist, create it. + if (!model) model = new Model(options); + return model; +} + +module.exports = instantiateModel; diff --git a/pool/shard011/JavaScript/0070045_items.js b/pool/shard011/JavaScript/0070045_items.js new file mode 100644 index 0000000000000000000000000000000000000000..9c16ba06dedde1e1252c629b9421cb22f4a9e611 --- /dev/null +++ b/pool/shard011/JavaScript/0070045_items.js @@ -0,0 +1,231 @@ +$(function() { // DOM ready + var items = new Items(); + var view = new ItemView({ items: items, parent: $('#section') }); +}); + +/* + * The Items class defines the operations available from the controller. + */ +var Items = function() { +}; + +Items.prototype.id = "#items"; + +Items.prototype.formName = "modalItem"; + +Items.prototype.modalId = "#modalItem"; + +Items.prototype.get = function(options) { + $.ajax({ + url: options.url + }) + .always(options.always) + .done(options.success) + .fail(function(jqXHR) { + var status_msg = getStatusMsg(jqXHR); + showPermanentError(options.errorSibling, status_msg); + }); +}; + +Items.prototype.post = function(options) { + $.ajax({ + url: options.url, + type: 'POST', + data: options.data + }) + .always(options.always) + .done(options.success) + .fail(function(jqXHR) { + var status_msg = getStatusMsg(jqXHR); + showPermanentError(options.errorSibling, status_msg); + }); +}; + +/* + * The ItemView class defines the DOM operations from the Web interface. + */ +var ItemView = function(options) { + this.parent = options.parent; + var items = options.items + this.items = items; + this.disableToggle = false; + var id = items.id; + var formName = items.formName; + + // Display the switch in a modal + var read = $.proxy(this.readItem, this); + options.parent.on('click', id + ' [href$="/read"], ' + id + ' [href$="/clone"], #createItem', read); + + // Save the modifications from the modal + var update = $.proxy(this.updateItem, this); + options.parent.on('submit', 'form[name="' + formName + '"]', update); + + // Delete the switch + var delete_item = $.proxy(this.deleteItem, this); + options.parent.on('click', id + ' [href$="/delete"]', delete_item); + + var list_items = $.proxy(this.listItems, this); + options.parent.on('click', id + ' [href*="/list/"]', list_items); + // + // Save the modifications from the modal + var search = $.proxy(this.search, this); + options.parent.on('submit', 'form[name="search"]', search); + + var search_next = $.proxy(this.searchNext, this); + options.parent.on('click', id + ' [href*="/search/"]', search_next); + +}; + + +ItemView.prototype.readItem = function(e) { + e.preventDefault(); + + var that = this; + var modal = $(this.items.modalId); + var section = $('#section'); + var loader = section.prev('.loader'); + loader.show(); + section.fadeTo('fast', 0.5); + modal.empty(); + $('.chzn-drop').remove(); // fixes a chzn bug with optgroups + this.items.get({ + url: $(e.target).attr('href'), + always: function() { + loader.hide(); + section.stop(); + section.fadeTo('fast', 1.0); + }, + success: function(data) { + modal.append(data); + modal.find('.chzn-select').chosen(); + modal.find('.chzn-deselect').chosen({allow_single_deselect: true}); + modal.one('shown', function() { + modal.find(':input:visible').first().focus(); + }); + modal.modal({ shown: true }); + }, + errorSibling: section.find('h2').first() + }); +}; + +ItemView.prototype.updateItem = function(e) { + e.preventDefault(); + + var that = this; + var form = $(e.target); + var table = $(this.items.id); + var btn = form.find('.btn-primary'); + var modal = form.closest('.modal'); + var valid = isFormValid(form); + if (valid) { + var modal_body = modal.find('.modal-body').first(); + resetAlert(modal_body); + btn.button('loading'); + form.find('tr.hidden :input').attr('disabled', 'disabled'); + this.items.post({ + url: form.attr('action'), + data: form.serialize(), + always: function() { + // Restore hidden/template rows + form.find('tr.hidden :input').removeAttr('disabled'); + btn.button('reset'); + }, + success: function(data) { + modal.modal('toggle'); + showSuccess(table, data.status_msg); + that.list(); + }, + errorSibling: modal_body.children().first() + }); + } +}; + +ItemView.prototype.list = function() { + var table = $(this.items.id); + this.items.get({ + url: table.attr('data-list-uri'), + success: function(data) { + table.html(data); + }, + errorSibling: table + }); +}; + +ItemView.prototype.deleteItem = function(e) { + e.preventDefault(); + var table = $(this.items.id); + var btn = $(e.target); + var that = this; + var row = btn.closest('tr'); + var url = btn.attr('href'); + this.items.get({ + url: url, + success: function(data) { + showSuccess(table, data.status_msg); + that.list(e); + }, + errorSibling: table + }); +}; + +ItemView.prototype.list = function() { + var table = $('#items'); + this.listRefresh(table.attr('data-list-uri')); +}; + +ItemView.prototype.listItems = function(e) { + e.preventDefault(); + var link = $(e.target); + this.listRefresh( link.attr('href')); +}; + +ItemView.prototype.listRefresh = function(list_url) { + var table = $('#items'); + var that = this; + table.fadeTo('fast',0.5,function() { + that.items.get({ + url: list_url, + always: function() { + table.fadeTo('fast',1.0); + }, + success: function(data) { + table.replaceWith(data); + }, + errorSibling: $('#items') + }); + }); +}; + + +ItemView.prototype.search = function(e) { + e.preventDefault(); + var form = $(e.target); + var url = form.attr('action'); + this.searchRefresh(url,form); +}; + +ItemView.prototype.searchNext = function(e) { + e.preventDefault(); + var form = $("#search"); + var link = $(e.target); + var url = link.attr('href'); + this.searchRefresh(url,form); +}; + +ItemView.prototype.searchRefresh = function(search_url,form) { + var table = $('#items'); + var that = this; + table.fadeTo('fast',0.5,function() { + that.items.post({ + url: search_url, + data: form.serialize(), + always: function() { + table.fadeTo('fast',1.0); + }, + success: function(data) { + table.replaceWith(data); + }, + errorSibling: $('#items') + }); + }); +}; diff --git a/pool/shard011/JavaScript/0070047_connect.js b/pool/shard011/JavaScript/0070047_connect.js new file mode 100644 index 0000000000000000000000000000000000000000..5d22dfda8ae926b0adf9b282ab88021ff5ad42a5 --- /dev/null +++ b/pool/shard011/JavaScript/0070047_connect.js @@ -0,0 +1,78 @@ +/* global $ch, $$CHOP */ +$ch.define('connect', function () { + 'use strict'; + $$CHOP.connect = {}; + + $$CHOP.connect = { + worker: function (url, callback) { + if (!window.Worker) { + throw new Error('Worker is not supported by this browser.'); + } + + if (arguments.length !== 2) { + throw new Error('$ch.connect.worker requires two parameters.') ; + } + + if (typeof url !== 'string') { + throw new Error('$ch.connect.worker requires a string-type URL parameter.'); + } + + if (typeof callback !== 'function') { + throw new Error('$ch.connect.worker requires a function-type callback parameter.'); + } + + var w = new Worker(url); + w.onmessage = function (evt) { + var data = evt.data; + callback(data); + }; + w.postMessage(); + return w; + }, + + sse: function (param) { + if (!window.EventSource) { + throw new Error('Server-Sent Event is not supported by this browser.'); + } + + if (typeof param !== 'object') { + throw new Error('$ch.connect.sse requires an object-type parameter.'); + } + + if (param.url === undefined) { + throw new Error('$ch.connect.sse requires an URL value in parameter object.'); + } + + var source = new window.EventSource(param.url); + $$CHOP.each(param, function (key, value) { + if (key.toUpperCase() !== 'URL') { + source.addEventListener(key, value, false); + } + }); + + return source; + }, + + socket: function (param) { + if (!window.WebSocket) { + throw new Error('WebSocket is not supported by this browser.'); + } + + if (typeof param !== 'object') { + throw new Error('$ch.connect.socket requires an object-type parameter.'); + } + + if (param.url === undefined) { + throw new Error('$ch.connect.socket requires an URL value in parameter object.'); + } + + var connection = new window.WebSocket(param.url); + $$CHOP.each(param, function (key, value) { + if (key.toUpperCase() !== 'URL') { + connection['on' + key.toLowerCase()] = value; + } + }); + return connection; + } + }; +}); diff --git a/pool/shard011/JavaScript/0070048_validations.js b/pool/shard011/JavaScript/0070048_validations.js new file mode 100644 index 0000000000000000000000000000000000000000..8318119e926491fbb403c86d662224078cb2c761 --- /dev/null +++ b/pool/shard011/JavaScript/0070048_validations.js @@ -0,0 +1,128 @@ +var hyperstore = require('../lib/hyperstore.js'); +var expect = require('chai').expect; +var standard = require('../lib/standards.js').Schemas.Standards; + +'use strict'; + +describe('Validation tests', function () +{ + var testSchema = + { + $import : { + std: standard + }, + id:"Test", + constraints: { + "required": { + message: "Property {propertyName} is required", + check: function (val) { + return val != undefined; + } + } + }, + Container : { + references: { + Items: { + end: "Item", + kind : "1=>*" + } + } + }, + Item : { + properties: { + Num: {type: "number", constraints: {"$ref": "std.required"}}, + Key: "std.identity", + Flag: "boolean", + Values: {type: "std.enum", values: ['A', 'B', 'C']}, + Range: {type: "std.range", min: 1, max: 10}, + Name : "string" + } + } + }; + + var store; + var root; + var domain; + + beforeEach(function() { + store = new hyperstore.Store(); + store.loadSchema(testSchema); + domain = store.createDomain("Test", "Test", { + Container: { + Items: { + Key: "1", + Flag: true + } + } + }); + root = domain.getElements("Container").firstOrDefault(); + }); + + it('should failed on wrong primitive values', function() { + + var schema = store.getSchema("Test"); + // schema.constraints.__dump(); + + var session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + var item = domain.create("Item"); + item.Name = {test:"str"}; + var r = session.close(); + expect(r.aborted).to.equal(true); + }); + + it('can get constraints on element', function() { + var sch = store.getSchemaElement("Item"); + expect(sch).to.be.not.null(); + + var constraints = sch.getConstraints(); + expect(constraints).to.be.not.null(); + }); + + it('should failed on wrong range values', function() { + var session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + var item = domain.create("Item"); + item.Values = "A"; + item.Num = 0; + item.Range = "str"; + session.acceptChanges(); + var r = session.close(); + expect(r.hasErrorsOrWarnings).to.equal(true); + }); + + it('should failed on wrong range values', function() { + var session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + var item = domain.create("Item"); + item.Values = "A"; + item.Num=0; + item.Range = 1; + item.Name = "str"; + session.acceptChanges(); + var r = session.close(); + expect(r.hasErrorsOrWarnings).to.equal(false); + + session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + item.Range = 0; + session.acceptChanges(); + r = session.close(); + expect(r.hasErrorsOrWarnings).to.equal(true); + + session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + item.Range = 1; + session.acceptChanges(); + r = session.close(); + expect(r.hasErrorsOrWarnings).to.equal(false); + + }); + + it('on demand validations', function() { + var session = store.beginSession({mode:64/*SessionMode*/}); // Don't throw exception on validation errors + var item = domain.create("Item"); + session.acceptChanges(); + var r = session.close(); + expect(r.hasErrorsOrWarnings).to.equal(true); + var cx = r.messages.length; + + var diags = domain.validate(); + expect(diags.length).to.equal(cx); + }); +}); diff --git a/pool/shard011/JavaScript/0070052_templates.js b/pool/shard011/JavaScript/0070052_templates.js new file mode 100644 index 0000000000000000000000000000000000000000..f916c5b7d851137526caad6059e7162089b326f2 --- /dev/null +++ b/pool/shard011/JavaScript/0070052_templates.js @@ -0,0 +1,40 @@ +/** + * Created by ralemy on 11/2/15. + * support dynamic jade templates + */ + +var express = require("express"), + fs = require("fs"), + path = require("path"), + jade = require("jade"), + q = require("q"), + router = express.Router(); + +function promiseReadFile(filename, encoding){ + var defer = q.defer(); + if(!encoding) encoding = "utf8"; + fs.readFile(filename,encoding,defer.makeNodeResolver()); + return defer.promise; +} + +function renderJade(req, res) { + var templateFileName = path.resolve(path.dirname(__dirname), + "views", "templates", req.params[0] ); + return promiseReadFile(templateFileName + ".jade") + .catch(error => promiseReadFile(templateFileName + ".pug")) + .then(data => { + res.status(200).send(jade.compile(data,{filename: templateFileName})(req.body)); + }) + .catch(error => { + console.log("Jade error", error); + res.status(500).send(error); + }); +} +router.get("/*", function (req, res) { + renderJade(req, res); +}); +router.post("/*", function (req, res) { + renderJade(req, res); +}); + +module.exports = router; diff --git a/pool/shard011/JavaScript/0070057_action.js b/pool/shard011/JavaScript/0070057_action.js new file mode 100644 index 0000000000000000000000000000000000000000..e14689d659afe2f31e0b6f8361e089af78fe116f --- /dev/null +++ b/pool/shard011/JavaScript/0070057_action.js @@ -0,0 +1,142 @@ +$(document).ready(function() { + var token = $('meta[name="csrf-token"]').attr('content'); + + var action = { + title: null, + params: null, + text: null, + route: null, + element: null, + listType: null, + remove: function(force) { + if (action.listType != "all" || force) { + var $target = action.element; + $target.hide('slow', function(){ + $target.remove(); + }); + } + }, + __pushToServer: function(ajaxType, callback) { + var type = ajaxType ? ajaxType : "PUT", + data = "_token=" + token; + + data = action.params ? data + "&" + action.params : data; + + $.ajax({ + url: action.route, + type: type, + data: data, + success: callback + }); + }, + __exec: function(type, force, ajaxType) { + action.__pushToServer(ajaxType, function() { + new PNotify({ + title: action.title, + text: action.text, + type: type, + addclass: "stack-custom2", + delay: 1000, + }); + action.remove(force); + }); + }, + elementHold: function() { + action.__exec('info'); + }, + elementAccept: function() { + action.__exec('success'); + }, + elementBan: function() { + action.__exec('notice'); + }, + elementDelete: function() { + action.__exec('error', true, 'DELETE'); + } + } + + var getCheckedElements = function() { + var ids = []; + $(".checkbox-auto-toggle input[type='checkbox']:checked").each(function(key, el) { + ids.push($(el).closest( "[data-element-parent-action]" ).data('id')); + }); + + if (ids.length) { + return ids.join(); + } + + return false; + } + + var elementAction = function(obj, params, isMany) { + var $this = $(obj), + element = isMany ? getJqueryCheckedElements() : $this.closest( "[data-element-parent-action]" ); + elementId = isMany ? getCheckedElements() : element.data('id'), + type = isMany ? $this.data('elements-action') : $this.data('element-action'); + + if (type && elementId) { + action.text = isMany ? getElementsText($this.data('elements-action-text'), elementId) : $this.data('element-action-text'); + action.route = isMany ? getElementsRoute($this.data('elements-action-route'), elementId) : $this.data('element-action-route'); + action.element = element; + action.params = params; + action.title = isMany ? $this.data('elements-action-title') : element.data('title'); + action.listType = $("#elementList").data('type'); + + action["element" + type.capitalizeFirstLetter()](); + } + } + + var getJqueryCheckedElements = function() { + return $(".checkbox-auto-toggle input[type='checkbox']:checked").closest( "[data-element-parent-action]" ); + } + + var getElementsText = function(text, elementsId) { + var nbr = elementsId.split(",").length; + return text.replace('{nbr}', nbr); + } + var getElementsRoute = function(route, elementsId) { + return route.replace('_elements_', elementsId); + } + + $(document).on("click", '[data-element-action]', function() { + elementAction(this); + }); + + $(document).on("click", '[data-elements-action]', function() { + elementAction(this, false, true); + }); + + $('#dialogBanAd').find('.modal-footer #confirm').on('click', function(){ + var $element = $(this).data('parent').children(), + params = $("#banAdForm").formSerialize(); + + var isMany = $element.attr('data-element-action') == undefined; + var constructor = isMany ? 'elements-action' : 'element-action'; + + $element.data(constructor, "ban"); + elementAction($element, params, isMany); + $element.data(constructor, ""); + }); + + /* Delete */ + + var deleteResource = function($element, forceDelete) { + var isMany = $element.attr('data-element-action') == undefined; + var constructor = isMany ? 'elements-action' : 'element-action'; + var params = forceDelete ? '__forceDelete=true': false; + + $element.data(constructor, "delete"); + elementAction($element, params, isMany); + $element.data(constructor, ""); + } + + $('#confirmDeleteAction').find('.modal-footer #confirmToTrash').on('click', function(){ + var $element = $(this).parent().children('#confirm').first().data('parent').children(); + deleteResource($element, false); + }); + + $('#confirmDeleteAction').find('.modal-footer #confirm').on('click', function(){ + var $element = $(this).data('parent').children(); + deleteResource($element, true); + }); +}) diff --git a/pool/shard011/JavaScript/0070059_activity.js b/pool/shard011/JavaScript/0070059_activity.js new file mode 100644 index 0000000000000000000000000000000000000000..140fa31db0c7ef4094a8801bc4b47e9483e1baee --- /dev/null +++ b/pool/shard011/JavaScript/0070059_activity.js @@ -0,0 +1,128 @@ +/** + * activity model + * @author adrienjoly, whyd + **/ + +var mongodb = require('../models/mongodb.js'); +var postModel = require('../models/post.js'); +var followModel = require('../models/follow.js'); + +var ObjectId = mongodb.ObjectID.createFromHexString; + +var DEFAULT_LIMIT_HISTORY = 10; + +function getCol() { + return mongodb.collections['activity']; +} + +// primitives + +exports.fetch = function (q, options, callback) { + options = options || {}; + if (options.after) q._id = { $lt: ObjectId('' + options.after) }; + if (options.until) + q._id = { $gt: mongodb.ObjectId(mongodb.dateToHexObjectId(options.until)) }; + options.sort = options.sort || [['_id', 'desc']]; + getCol().find(q, options, function (err, results) { + results.toArray(function (err, results) { + callback(results); + }); + }); +}; + +exports.add = function (d, callback) { + if (d && d.like && d.like.pId) d.like.pId = '' + d.like.pId; + getCol().insertOne(d, function (err, result) { + callback && callback(result || err); + }); +}; + +exports.remove = function (q, callback) { + getCol().deleteOne(q, function (err, result) { + callback && callback(result || err); + }); +}; + +// fetch helpers + +/* +exports.countUserLikes = function(uid, callback) { + getCol().countDocuments({"like.pId":{$exists: true}, "id":""+uid}, function(err, count) { + callback(count); + }); +} +*/ + +exports.fetchLikersOfUser = function (uid, options, callback) { + exports.fetch({ 'like.id': '' + uid }, options, callback); +}; + +exports.fetchHistoryFromUidList = function (uidList, options, callback) { + options = options || {}; + var limit = options.limit || DEFAULT_LIMIT_HISTORY; + options.limit = limit + 1; + var q = { id: { $in: uidList } }; + if (options.likesOnly) q.like = { $exists: true }; + function whenDone(activities) { + activities = activities.sort(function (a, b) { + return b._id.getTimestamp() - a._id.getTimestamp(); // sort by _id + }); + //console.log("sorted likes with subscr:", activities); + var hasMore = activities && activities.length > limit; + if (hasMore) activities = activities.slice(0, limit); + //console.log("filtered likes with subscr:", activities); + // console.log( + // '=> reduced to', + // activities.length, + // 'activities, hasmore:', + // hasMore + // ); + callback(activities, hasMore); + } + exports.fetch(q, options, function (activities) { + //console.log("likes:", activities); + // console.log('=> fetched', activities.length, 'likes'); + if (options.likesOnly) return whenDone(activities); + options.fromUId = uidList; + //followModel.fetchUsersSubscriptionsHistory(uidList, options, function(subscriptions) { + followModel.fetchSubscriptionHistory(options, function (subscriptions) { + for (let i in subscriptions) + activities.push({ + _id: subscriptions[i]._id, + id: subscriptions[i].uId, + name: subscriptions[i].uNm, + subscription: { + id: subscriptions[i].tId, + name: subscriptions[i].tNm, + }, + }); + //console.log("unsorted likes with subscr:", activities); + whenDone(activities); + }); + }); +}; + +// update helpers + +exports.addLikeByPost = function (post, liker, callback) { + if (post) + exports.add( + { + id: liker.id, + name: liker.name, + like: { pId: post._id, id: post.uId, name: post.uNm }, + }, + callback + ); + else callback && callback({ error: 'post not found' }); +}; + +exports.addLikeByPid = function (pId, liker, callback) { + postModel.fetchPostById(pId, function (post) { + exports.addLikeByPost(post, liker, callback); + }); +}; + +exports.removeLike = function (pId, likerUid, callback) { + exports.remove({ 'like.pId': pId, id: '' + likerUid }, callback); +}; diff --git a/pool/shard011/JavaScript/0070062_tg-stop-marker-cluster.js b/pool/shard011/JavaScript/0070062_tg-stop-marker-cluster.js new file mode 100644 index 0000000000000000000000000000000000000000..d14badfc2d410da1fee56c9ea352472e39c4ac31 --- /dev/null +++ b/pool/shard011/JavaScript/0070062_tg-stop-marker-cluster.js @@ -0,0 +1,13 @@ +import { MarkerCluster } from '/resources/gis/tg-marker-cluster.js'; + +export const StopMarkerCluster = function (_map, _markerFactory, progressDiv, progressBarDiv) { + MarkerCluster.call(this, _map, _markerFactory, progressDiv, progressBarDiv); +}; + +StopMarkerCluster.prototype = Object.create(MarkerCluster.prototype); +StopMarkerCluster.prototype.constructor = StopMarkerCluster; + +StopMarkerCluster.prototype.getCircleClusterIconLocation = function () { + // return MarkerCluster.prototype.getCircleClusterIconLocation.call(this); + return 'resources/gis/images/circle-orange.png'; +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070063_clean.js b/pool/shard011/JavaScript/0070063_clean.js new file mode 100644 index 0000000000000000000000000000000000000000..3ff5de6be24a3b40281b2bc8aec4baed1fc02f81 --- /dev/null +++ b/pool/shard011/JavaScript/0070063_clean.js @@ -0,0 +1,15 @@ +/** + * Created by Davinci28 on 2014-10-18. + */ +'use strict'; + +var config = require('../config/gulp.config'); +var gulp = require('gulp'); +var $ = require('gulp-load-plugins')(); +var $$ = $.loadUtils(['colors', 'env', 'log', 'pipeline']); +var _ = require('lodash'); + +gulp.task('clean', function () { + return gulp.src([TMP_DIR, BUILD_DIR], { read: false }) + .pipe($.rimraf()); +}); diff --git a/pool/shard011/JavaScript/0070067_remotingproviderfix.js b/pool/shard011/JavaScript/0070067_remotingproviderfix.js new file mode 100644 index 0000000000000000000000000000000000000000..d81393c7e667594a88b159208e9ceeba135a20c9 --- /dev/null +++ b/pool/shard011/JavaScript/0070067_remotingproviderfix.js @@ -0,0 +1,136 @@ +/* + This file is part of Badaap Comic Reader. + + Copyright (c) 2012 Jeroen Walter + + Badaap Comic Reader 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. + + Badaap Comic Reader 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 Badaap Comic Reader. If not, see . +*/ +/* + Fix that adds the following: + - call the callbacks if the JSON parsing fails. +*/ + + +/* +Ext.define('Fix.Ext.data.proxy.Direct', { + override: 'Ext.data.proxy.Direct', + setException: function(operation, response) { + console.log("Exception in DirectProxy"); + console.log(response); + operation.setException(response); + }, +}); +*/ + +Ext.define('Comic.Remotingproviderfix', { + override: 'Ext.direct.RemotingProvider', + /** + * React to the ajax request being completed + * @private + */ + onData: function(options, success, response) { + var me = this, + i = 0, + ln, events, event, + transaction, transactions; + + if (success) { + events = me.createEvents(response); + for (ln = events.length; i < ln; ++i) { + event = events[i]; + transaction = me.getTransaction(event); + me.fireEvent('data', me, event); + + if (event.getCode() == Ext.direct.Manager.exceptions.PARSE) + { + console.log("Error while parsing the response for one or more ExtDirect methods:"); + if (event.getData()) + console.log(event.getData().message); + + if (Ext.isFunction(ShowError)) + { + var msg = "

    Outstanding Ext.Direct transactions:
    "; + transactions = [].concat(options.transaction); + for (ln = transactions.length; i < ln; ++i) + { + transaction = me.getTransaction(transactions[i]); + msg += transaction.getAction() + "." + transaction.getMethod() + "
    "; + } + + ShowError("

    Error while parsing the response for one or more ExtDirect methods:


    " + event.getData().message + msg); + } + + // If JSON parsing fails, the events array will only have 1 entry. + // Now callback all transactions with an exception per transaction. + transactions = [].concat(options.transaction); + for (ln = transactions.length; i < ln; ++i) + { + transaction = me.getTransaction(transactions[i]); + + //Ext.Msg.alert("Error while parsing the response for the remote method:" + transaction.getAction() + "." + transaction.getMethod()); + + if (transaction && transaction.getRetryCount() < me.getMaxRetries()) + { + transaction.retry(); + } + else + { + //var newevent = Ext.clone(event); + + var errorresponse = { type : 'rpc', result: { code: 'PARSE_ERROR', message: "" + event.getData().message }, tid: transaction.getTid(), action: transaction.getAction(), method : transaction.getMethod() }; + + var newevent = Ext.create('direct.rpc', errorresponse); + newevent.transaction = transaction; + newevent.setStatus(false); + + me.fireEvent('data', me, newevent); + if (transaction) + { + me.runCallback(transaction, newevent, false); + Ext.direct.Manager.removeTransaction(transaction); + } + } + } + } + else + if (transaction) { + me.runCallback(transaction, event, true); + Ext.direct.Manager.removeTransaction(transaction); + } + } + } else { + transactions = [].concat(options.transaction); + for (ln = transactions.length; i < ln; ++i) { + transaction = me.getTransaction(transactions[i]); + if (transaction && transaction.getRetryCount() < me.getMaxRetries()) { + transaction.retry(); + } else { + event = Ext.create('Ext.direct.ExceptionEvent', { + data: null, + transaction: transaction, + code: Ext.direct.Manager.exceptions.TRANSPORT, + message: 'Unable to connect to the server.', + xhr: response + }); + + me.fireEvent('data', me, event); + if (transaction) { + me.runCallback(transaction, event, false); + Ext.direct.Manager.removeTransaction(transaction); + } + } + } + } + }, +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070069_map.js b/pool/shard011/JavaScript/0070069_map.js new file mode 100644 index 0000000000000000000000000000000000000000..a19d28ce7e87c341f5a5009bb70c62f233a15c91 --- /dev/null +++ b/pool/shard011/JavaScript/0070069_map.js @@ -0,0 +1,34 @@ +(function(){ + S.ui.createMapView = function(){ + var view = Ti.UI.createView( + { + backgroundColor: "red", + layout: 'vertical' + } + ); + //display information regarding concern + var alertText = Ti.UI.createLabel( + S.combine( + { + text: "mapping phones unimplemented at this time" + }, //@todo get concern text from WARNING type in controller + $$.Label + ) + ); + //create a cancel button + var backButton = Ti.UI.createButton( + S.combine( + { + title: "Back to main window." + }, + $$.Button + ) + ); + //add it to the view + view.add( + alertText, + backButton + ); + return view; + }; +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070071_SecondsConverter.js b/pool/shard011/JavaScript/0070071_SecondsConverter.js new file mode 100644 index 0000000000000000000000000000000000000000..b09a4ab95368c22d913cde4f6c0f3a0d30f25d16 --- /dev/null +++ b/pool/shard011/JavaScript/0070071_SecondsConverter.js @@ -0,0 +1,35 @@ +/** + * Provides approaches to convert seconds represented by double value to required value + * @type {{toTimeObject: SecondsConverter.toTimeObject, toString: SecondsConverter.toString}} + */ +class SecondsConverter { + /** + * Convert seconds to custom time object + * @returns {{minutes: string, seconds: string, milliseconds: string}} + */ + static toTimeObject (incomingSeconds) { + let innerTime = incomingSeconds; + + let minutes = Math.floor(innerTime / 60).toString().padStart(2, '0'); + + innerTime = innerTime % 60; + let secondsMilliSeconds = String(innerTime).split('.'); + + let seconds = secondsMilliSeconds[0].padStart(2, '0'); + let milliseconds = secondsMilliSeconds[1] && secondsMilliSeconds[1] !== '' ? secondsMilliSeconds[1][0] + : '0'; + + return {minutes, seconds, milliseconds}; + } + + /** + * Convert custom time object to readable string + * @returns {string} + */ + static toString (incomingSeconds) { + const timeObject = this.toTimeObject(incomingSeconds); + return `${timeObject.minutes}:${timeObject.seconds}:${timeObject.milliseconds}`; + } +} + +export default SecondsConverter \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070075_assign_to.js b/pool/shard011/JavaScript/0070075_assign_to.js new file mode 100644 index 0000000000000000000000000000000000000000..950443de57aab6a7b70e16515107a9b8f0e1f41b --- /dev/null +++ b/pool/shard011/JavaScript/0070075_assign_to.js @@ -0,0 +1,205 @@ +// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors +// MIT License. See license.txt + +frappe.provide("frappe.ui.form"); + +frappe.ui.form.AssignTo = Class.extend({ + init: function(opts) { + var me = this; + + $.extend(this, opts); + this.btn = this.parent.find(".add-assignment").on("click", function() { me.add(); }); + this.btn_wrapper = this.btn.parent(); + + this.refresh(); + }, + refresh: function() { + if(this.frm.doc.__islocal) { + this.parent.toggle(false); + return; + } + this.parent.toggle(true); + this.render(this.frm.get_docinfo().assignments); + }, + render: function(d) { + var me = this; + this.frm.get_docinfo().assignments = d; + this.parent.find(".assignment-row").remove(); + + if(me.primary_action) { + me.primary_action.remove(); + me.primary_action = null; + } + + if(this.dialog) { + this.dialog.hide(); + } + + if(d && d.length) { + for(var i=0; i 10) { + info._fullname = info.fullname.substr(0, 10) + '...'; + } + + $(repl('
  • \ + ×\ + %(avatar)s\ + %(_fullname)s\ +
  • ', info)) + .insertBefore(this.parent.find('.add-assignment')); + + if(d[i].owner===frappe.session.user) { + me.primary_action = this.frm.page.add_menu_item(__("Assignment Complete"), function() { + me.remove(frappe.session.user); + }, "fa fa-check", "btn-success") + } + + if(!(d[i].owner === frappe.session.user || me.frm.perm[0].write)) { + me.parent.find('a.close').remove(); + } + } + + // set remove + this.parent.find('a.close').click(function() { + me.remove($(this).attr('data-owner')); + return false; + }); + + //this.btn_wrapper.addClass("hide"); + } else { + //this.btn_wrapper.removeClass("hide"); + } + }, + add: function() { + var me = this; + + if(this.frm.is_new()) { + frappe.throw(__("Please save the document before assignment")); + return; + } + + if(!me.dialog) { + me.dialog = new frappe.ui.form.AssignToDialog({ + obj: me, + method: 'frappe.desk.form.assign_to.add', + doctype: me.frm.doctype, + docname: me.frm.docname, + callback: function(r) { + me.render(r.message); + } + }); + } + me.dialog.clear(); + + if(me.frm.meta.title_field) { + me.dialog.set_value("description", me.frm.doc[me.frm.meta.title_field]) + } + + me.dialog.show(); + }, + remove: function(owner) { + var me = this; + + if(this.frm.is_new()) { + frappe.throw(__("Please save the document before removing assignment")); + return; + } + + frappe.call({ + method:'frappe.desk.form.assign_to.remove', + args: { + doctype: me.frm.doctype, + name: me.frm.docname, + assign_to: owner + }, + callback:function(r,rt) { + me.render(r.message); + } + }); + } +}); + + +frappe.ui.form.AssignToDialog = Class.extend({ + init: function(opts){ + var me = this + $.extend(me, new frappe.ui.Dialog({ + title: __('Add to To Do'), + fields: [ + {fieldtype: 'Link', fieldname:'assign_to', options:'User', + label:__("Assign To"), reqd:true, filters: {'user_type': 'System User'}}, + {fieldtype:'Check', fieldname:'myself', label:__("Assign to me"), "default":0}, + {fieldtype:'Small Text', fieldname:'description', label:__("Comment"), reqd:true}, + {fieldtype: 'Section Break'}, + {fieldtype: 'Column Break'}, + {fieldtype:'Date', fieldname:'date', label: __("Complete By")}, + {fieldtype:'Check', fieldname:'notify', + label:__("Notify by Email"), "default":1}, + {fieldtype: 'Column Break'}, + {fieldtype:'Select', fieldname:'priority', label: __("Priority"), + options:[ + {value:'Low', label:__('Low')}, + {value:'Medium', label:__('Medium')}, + {value:'High', label:__('High')}], + 'default':'Medium'}, + ], + primary_action: function() { frappe.ui.add_assignment(opts, me) }, + primary_action_label: __("Add") + })); + + me.fields_dict.assign_to.get_query = "frappe.core.doctype.user.user.user_query"; + + var myself = me.get_input("myself").on("click", function() { + me.toggle_myself(this); + }); + me.toggle_myself(myself); + }, + toggle_myself: function(myself) { + var me = this; + if($(myself).prop("checked")) { + me.set_value("assign_to", frappe.session.user); + me.set_value("notify", 0); + me.get_field("notify").$wrapper.toggle(false); + me.get_field("assign_to").$wrapper.toggle(false); + } else { + me.set_value("assign_to", ""); + me.set_value("notify", 1); + me.get_field("notify").$wrapper.toggle(true); + me.get_field("assign_to").$wrapper.toggle(true); + } + }, + +}); + +frappe.ui.add_assignment = function(opts, dialog) { + var assign_to = opts.obj.dialog.fields_dict.assign_to.get_value(); + var args = opts.obj.dialog.get_values(); + if(args && assign_to) { + return frappe.call({ + method: opts.method, + args: $.extend(args, { + doctype: opts.doctype, + name: opts.docname, + assign_to: assign_to, + bulk_assign: opts.bulk_assign || false, + re_assign: opts.re_assign || false + }), + callback: function(r,rt) { + if(!r.exc) { + if(opts.callback){ + opts.callback(r); + } + dialog && dialog.hide(); + } + }, + btn: this + }); + } +} diff --git a/pool/shard011/JavaScript/0070077_vat_calculator.js b/pool/shard011/JavaScript/0070077_vat_calculator.js new file mode 100644 index 0000000000000000000000000000000000000000..04d43e31c4800a100489b9db2eb2beca7a3c7bfd --- /dev/null +++ b/pool/shard011/JavaScript/0070077_vat_calculator.js @@ -0,0 +1,234 @@ +(function () { + var DATA_PREFIX = 'data-vat'; + + + /** + * Private methods + */ + function bindCalculatorEvents() { + var form = document.querySelector(VATCalculator.selector); + if (form !== null) { + var dropDown = form.querySelector('[' + DATA_PREFIX + '="country"]'); + if (dropDown !== null) { + dropDown.addEventListener('change', calculate); + // Try to preselect based on the user IP + VATCalculator.getCountryCode({ + success: function (status, response) { + for( var i=0; i 0) { + for (var i = 0; i < entries.length; i++) { + entries[i].innerHTML = value; + } + return true; + } + return false; + } + + function getJSONResponse(responseText) { + try { + return JSON.parse(responseText); + } catch (e) { + return false; + } + } + + function makeRequest(type, url, callbacks) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange = function () { + if (xhr.readyState == 4) { + var response = getJSONResponse(xhr.responseText); + if (xhr.status === 200) { + if (callbacks.success) { + callbacks.success(xhr.status, response); + } + } else { + if (callbacks.error) { + callbacks.error(xhr.status, response); + } + } + } + }; + xhr.open(type, url, true); + xhr.setRequestHeader("Content-Type", "application/json"); + xhr.send(null); + } + + /** + * Calculate the gross price + * @param successCallback + */ + function calculate(successCallback) { + var form = document.querySelector(VATCalculator.selector); + if (form !== null) { + var amount = parseInt(form.getAttribute('data-amount')), + country = getValue('country'), + vat_number = getValue('vat-number'); + makeRequest('GET', '/vatcalculator/calculate?netPrice=' + (amount / 100) + '&country=' + country + '&vat_number=' + vat_number, { + success: function (status, response) { + setHTML('total', response.gross_price.toFixed(2)); + setHTML('subtotal', response.net_price.toFixed(2)); + setHTML('taxes', response.tax_value.toFixed(2)); + if (successCallback && typeof(successCallback) === 'function') { + successCallback(response); + } + VATCalculator.setCalculation(response); + }, + error: function (status, response) { + console.log(response.error); + } + }); + } + } + + var Calculator = function () { + /** + * Form selector + * @type {string} + */ + this.selector = "#payment-form"; + + /** + * Last calculation results + * @type {Object} + */ + this.calculation = {}; + }; + + Calculator.prototype = { + + /** + * Lookup the IP based country code + * @param callbacks + */ + getCountryCode: function (callbacks) { + makeRequest('GET', '/vatcalculator/country-code', callbacks); + }, + + /** + * Set the last used calculation response + * @param calculation + */ + setCalculation: function (calculation) { + return this.calculation = calculation; + }, + + /** + * Get the last saved calculation + * @returns {Calculator.calculation|Function} + */ + calculation: function () { + return this.calculation; + }, + + /** + * Perform the calculation task + * @param {function} successCallback + */ + calculate: function (successCallback) { + calculate(successCallback); + }, + + /** + * Get the current selector + * @returns {Calculator.selector|Function} + */ + selector: function () { + return this.selector; + }, + + /** + * Sets the form selector + * @param {string} selector + * @returns {*} + */ + setSelector: function (selector) { + return this.selector = selector; + }, + + /** + * Initializes the calculator and sets the form + * selector to use + * @param {string} selector + * @returns {boolean} + */ + init: function (selector) { + if (document.querySelectorAll(selector).length === 1) { + this.setSelector(selector); + bindCalculatorEvents(); + return true; + } + return false; + } + }; + + // Make VAT calculator globally accessible + window.VATCalculator = new Calculator(); + + // Add VAT calculator onload event + if (window.onload) { + var onLoad = window.onload; + window.onload = function () { + onLoad(); + bindCalculatorEvents(); + }; + } else { + window.onload = bindCalculatorEvents; + } +}).call(this); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070079_index.js b/pool/shard011/JavaScript/0070079_index.js new file mode 100644 index 0000000000000000000000000000000000000000..de5ce67dd7eaea7a522ebfbe95849b026c4ed0e8 --- /dev/null +++ b/pool/shard011/JavaScript/0070079_index.js @@ -0,0 +1,34 @@ + +var map = new maptalks.Map('map', { + center: [-0.113049,51.498568], + zoom: 14, + baseLayer: new maptalks.TileLayer('base', { + urlTemplate: '$(urlTemplate)', + subdomains: $(subdomains), + attribution: '$(attribution)' + }) +}); + +var marker = new maptalks.Marker( + map.getCenter(), + { + symbol : { + 'textName' : 'Layer is shown.', + 'textWeight' : 'bold', + 'textSize' : 50, + 'textFill' : '#1bbc9b', + 'textHaloFill' : '#fff', + 'textHaloRadius' : 5 + } + } +); +var layer = new maptalks.VectorLayer('vector', [marker]) + .addTo(map); + +function show() { + layer.show(); +} + +function hide() { + layer.hide(); +} diff --git a/pool/shard011/JavaScript/0070080_input.js b/pool/shard011/JavaScript/0070080_input.js new file mode 100644 index 0000000000000000000000000000000000000000..8422b53bd23e6171d874967db83700ed3083fea7 --- /dev/null +++ b/pool/shard011/JavaScript/0070080_input.js @@ -0,0 +1,108 @@ +/* + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://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. + */ + +/** + * External dependencies + */ +import { fireEvent, screen } from '@testing-library/react'; + +/** + * Internal dependencies + */ +import { renderWithProviders } from '../../../testUtils/renderWithProviders'; +import SearchInput from '../input'; +import { noop } from '../../../utils'; + +describe('Search ', () => { + const onClickMock = jest.fn(); + const handleClearInputMock = jest.fn(); + + beforeEach(jest.clearAllMocks); + + it('should render a searchbox by default', () => { + renderWithProviders( + + ); + + const input = screen.getByRole('searchbox'); + expect(input).toBeInTheDocument(); + }); + + it('should render a combobox if it has a list id', () => { + renderWithProviders( + + ); + + const input = screen.getByRole('combobox'); + expect(input).toBeInTheDocument(); + }); + + it('should not trigger onClickMock on click if input is disabled', () => { + renderWithProviders( + + ); + + const input = screen.getByPlaceholderText('search placeholder'); + fireEvent.click(input); + + expect(onClickMock).toHaveBeenCalledTimes(0); + }); + + it('should trigger handleClearInputMock on click of clear button if input has content', () => { + renderWithProviders( + + ); + + const clearButton = screen.getByTestId('clear-search-icon'); + expect(clearButton).toBeInTheDocument(); + + fireEvent.click(clearButton); + + expect(handleClearInputMock).toHaveBeenCalledTimes(1); + }); +}); diff --git a/pool/shard011/JavaScript/0070083_CraftyStore.js b/pool/shard011/JavaScript/0070083_CraftyStore.js new file mode 100644 index 0000000000000000000000000000000000000000..efb483c934e92011284cab6795d0b0465828e6fa --- /dev/null +++ b/pool/shard011/JavaScript/0070083_CraftyStore.js @@ -0,0 +1,42 @@ +import EventEmitter from 'events'; +import Pastel from 'pastel-lang'; + +/** + * Crafty Store + * Keeps crafty variables + * + * @data + * tree : current code in parsed tree + */ +class CraftyStore extends EventEmitter { + + constructor(...args) { + super(...args); + + this.data = { + tree: undefined + }; + } + + get(key) { + console.log(`STORE::: Loading ${key}...`); + return this.data[key]; + } + + set(key, value) { + console.log(`STORE::: Saving ${key}...`); + return this.data[key] = value; + } + + + emitChange(caller) { + console.log(`STORE::: Change emitted by ${caller}!`); + this.emit('modifytree', caller, this.data); + } + + addChangeListener(callback) { + this.on('modifytree', callback, this.data); + } +} + +export default new CraftyStore(); diff --git a/pool/shard011/JavaScript/0070089_logicBundle.js b/pool/shard011/JavaScript/0070089_logicBundle.js new file mode 100644 index 0000000000000000000000000000000000000000..5e79361605376fd00b3d790907a80197b1ed19db --- /dev/null +++ b/pool/shard011/JavaScript/0070089_logicBundle.js @@ -0,0 +1,82 @@ +/* global process */ +import nock from "nock"; +import reducer, { + addTodo, + completeTodo, + fetchTodos, + removeTodo, + setTodos +} from "../logicBundle"; + +describe("Module: Todos", () => { + describe("Actions", () => { + describe("fetchTodos", () => { + const todos = [ + { text: "Todo 1", complete: false }, + { text: "Todo 2", complete: false }, + { text: "Todo 3", complete: false }, + { text: "Todo 4", complete: false } + ]; + let RUNTIME_ENV; + + beforeAll(() => { + RUNTIME_ENV = process.env.RUNTIME_ENV; + + process.env.RUNTIME_ENV = "server"; + + nock(`http://localhost:${process.env.PORT}`) + .get("/api/v1/todos") + .reply(200, todos); + }); + + afterAll(() => { + process.env.RUNTIME_ENV = RUNTIME_ENV; + }); + + it("should return a function when calls 'fetchTodos' then return 'setTodos' action", async () => { + const callback = jest.fn(); + const action = fetchTodos(); + + await action(callback); + + expect(callback).toBeCalledWith(setTodos(todos)); + }); + }); + }); + + describe("Reducer", () => { + it("should return the default state", () => { + expect( + reducer([], { type: "ANOTHER_ACTION", payload: "random value" }) + ).toEqual([]); + }); + + it("should return a todos list with 1 todo item when calls 'addTodo' action", () => { + expect(reducer([], addTodo("do chore"))).toEqual([ + { text: "do chore", complete: false } + ]); + }); + + it("should return an empty todos list when calls 'removeTodo' action", () => { + expect( + reducer([{ text: "do chore", complete: false }], removeTodo(0)) + ).toEqual([]); + }); + + it("should return an todos list when calls 'setTodos' action", () => { + expect( + reducer([], setTodos([{ text: "do chore", complete: false }])) + ).toEqual([{ text: "do chore", complete: false }]); + }); + + it("should return a todos list with 1 completed todo when calls 'completeTodo' action", () => { + expect( + reducer([{ text: "do chore", complete: false }], completeTodo(0)) + ).toEqual([{ text: "do chore", complete: true }]); + + expect( + reducer([{ text: "do chore", complete: true }], completeTodo(0)) + ).toEqual([{ text: "do chore", complete: false }]); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070093_user.js b/pool/shard011/JavaScript/0070093_user.js new file mode 100644 index 0000000000000000000000000000000000000000..a6512d2636639f22d909c0df2abe30b69772599a --- /dev/null +++ b/pool/shard011/JavaScript/0070093_user.js @@ -0,0 +1,111 @@ +var model = require('../../models/model'), + userModel = model.User, + roleModel = model.Role, + msg = require("../../other/msg"), + then = require("thenjs"); + +exports.add = function(req, res) { + then(function (cont) { + var user = { + loginId: req.body.loginId + }; + + userModel.findOne(user).exec(function(err, doc) { + if (doc) { + cont(new Error(msg.USER.loginIdExist)); + return; + }else{ + cont(err, doc); + } + }); + }).then(function(cont) { + roleModel.findById(req.body.role).exec(function(err, doc) { + if (!doc) { + cont(new Error(msg.ROLE.roleNone)); + }else{ + cont(err, doc); + } + }); + }).then(function(cont, doc) { + var user = new userModel({ + loginId: req.body.loginId, + name: req.body.name, + password: req.body.password, + img: req.body.img, + sex: req.body.sex, + idNo: req.body.idNo, + birthday: req.body.birthday, + phone: req.body.phone, + email: req.body.email, + address: req.body.address, + role: req.body.role + }); + + user.save(function (err, doc) { + cont(err, doc); + }); + }).then(function(cont, doc) { + userModel.findOne(doc).select("name phone role status").populate("role").exec(function(err, doc) { + cont(err, doc) + }); + }).then(function(err, doc){ + res.json(doc) + }).fail(function (cont, err) { + __REST.fail(res, err) + }); + +}; + +exports.list = function (req, res) { + userModel.find().populate("role").exec(function (err, doc) { + __REST.http(res, doc, err) + }); + +}; + +exports.detail = function (req, res) { + userModel.findById(req.body.id).populate("role").exec(function (err, doc) { + __REST.http(res, doc, err) + }); +}; + +exports.edit = function (req, res) { + var user = { + name: req.body.name, + sex: req.body.sex, + idNo: req.body.idNo, + birthday: req.body.birthday, + phone: req.body.phone, + email: req.body.email, + address: req.body.address, + role: req.body.role + }; + if(req.body.password){ + user.password = req.body.password; + } + userModel.findByIdAndUpdate(req.body.id, user, function (err, doc) { + __REST.http(res, doc, err) + }); +}; + +exports.delete = function (req, res) { + userModel.findByIdAndRemove(req.body.id, function (err, doc) { + __REST.http(res, doc, err) + }); +}; + +exports.lock = function(req, res) { + var user = {status: 2} + + userModel.findByIdAndUpdate(req.body.id, user, function (err, doc) { + __REST.http(res, doc, err) + }); +} + +exports.unlock = function (req, res) { + var user = {status: 1} + + userModel.findByIdAndUpdate(req.body.id, user, function (err, doc) { + __REST.http(res, doc, err) + }); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070094_ready.js b/pool/shard011/JavaScript/0070094_ready.js new file mode 100644 index 0000000000000000000000000000000000000000..3e74b862f269b634598a2b97d16d679f301a81fb --- /dev/null +++ b/pool/shard011/JavaScript/0070094_ready.js @@ -0,0 +1,82 @@ +(function (scope, enyo) { + + // we need to register appropriately to know when + // the document is officially ready, to ensure that + // client code is only going to execute at the + // appropriate time + + var doc = scope.document; + var queue = []; + var ready = ("complete" === doc.readyState); + var run; + var init; + var remove; + var add; + var flush; + var flushScheduled = false; + + //*@public + /** + Register a callback (and optional "this" context) to run + after all the enyo and library code has loaded and the DOMContentLoaded + (or equivalent on older browsers) event has been sent. + + If called after system is in a ready state, run the supplied code + asynchronously at earliest opportunity. + */ + enyo.ready = function (fn, context) { + queue.push([fn, context]); + // schedule another queue flush if needed to run new ready calls + if (ready && !flushScheduled) { + enyo.asyncMethod(window, flush); + flushScheduled = true; + } + }; + + //*@protected + run = function (fn, context) { + fn.call(context || enyo.global); + }; + + init = function (event) { + // if we're interactive, it should be safe to move + // forward because the content has been parsed + if ((ready = ("interactive" === doc.readyState))) { + if (!~enyo.indexOf(event.type, ["DOMContentLoaded", "readystatechange"])) { + remove(event.type, init); + flush(); + } + } + // for an IE8 fallback and legacy WebKit (including webOS 3.x and less) and assurance + if ((ready = ("complete" === doc.readyState || "loaded" === doc.readyState))) { + remove(event.type, init); + flush(); + } + }; + + add = function (event, fn) { + var name = doc.addEventListener? "addEventListener": "attachEvent"; + var on = name === "attachEvent"? "on": ""; + doc[name](on + event, fn, false); + }; + + remove = function (event, fn) { + var name = doc.addEventListener? "removeEventListener": "detachEvent"; + var on = name === "detachEvent"? "on": ""; + doc[name](on + event, fn, false); + }; + + flush = function () { + if (ready && queue.length) { + while (queue.length) { + run.apply(scope, queue.shift()); + } + } + flushScheduled = false; + }; + + // ok, let's hook this up + add("DOMContentLoaded", init); + add("readystatechange", init); + +})(window, enyo); diff --git a/pool/shard011/JavaScript/0070098_preset.js b/pool/shard011/JavaScript/0070098_preset.js new file mode 100644 index 0000000000000000000000000000000000000000..ae2743fae752b6a5c6ea380675f60a7d9c71a1de --- /dev/null +++ b/pool/shard011/JavaScript/0070098_preset.js @@ -0,0 +1,296 @@ +/** + * KIRKI CONTROL: PRESET + */ + +wp.customize.controlConstructor['preset'] = wp.customize.Control.extend( { + ready: function() { + var control = this; + var element = this.container.find( 'select' ); + + jQuery( element ).selectize(); + + this.container.on( 'change', 'select', function() { + + /** + * First of all we have to get the control's value + */ + var select_value = jQuery( this ).val(); + /** + * Update the value using the customizer API and trigger the "save" button + */ + control.setting.set( select_value ); + /** + * We have to get the choices of this control + * and then start parsing them to see what we have to do for each of the choices. + */ + jQuery.each( control.params.choices, function( key, value ) { + /** + * If the current value of the control is the key of the choice, + * then we can continue processing. + * Otherwise there's no reason to do anything. + */ + if ( select_value == key ) { + /** + * Each choice has an array of settings defined in it. + * We'll have to loop through them all and apply the changes needed to them. + */ + jQuery.each( value['settings'], function( preset_setting, preset_setting_value ) { + /** + * Get the control of the sub-setting. + * This will be used to get properties we need from that control, + * and determine if we need to do any further work based on those. + */ + var sub_control = wp.customize.settings.controls[ preset_setting ]; + /** + * Check if the control we want to affect actually exists. + * If not then skip the item, + */ + if ( typeof sub_control === undefined ) { + return true; + } + + /** + * Get the control-type of this sub-setting. + * We want the value to live-update on the controls themselves, + * so depending on the control's type we'll need to do different things. + */ + var sub_control_type = sub_control['type']; + + /** + * Below we're starting to check the control tyype and depending on what that is, + * make the necessary adjustments to it. + */ + + /** + * Control types: + * checkbox + * switch + * toggle + * kirki-checkbox + */ + if ( 'checkbox' == sub_control_type || 'switch' == sub_control_type || 'toggle' == sub_control_type || 'kirki-checkbox' == sub_control_type ) { + + var input_element = wp.customize.control( preset_setting ).container.find( 'input' ); + if ( 1 == preset_setting_value ) { + /** + * Update the value visually in the control + */ + jQuery( input_element ).prop( "checked", true ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( true ); + } else { + /** + * Update the value visually in the control + */ + jQuery( input_element ).prop( "checked", false ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( false ); + } + + } + /** + * Control types: + * select + * select2 + * select2-multiple + * kirki-select + */ + else if ( 'select' == sub_control_type || 'select2' == sub_control_type || 'select2-multiple' == sub_control_type || 'kirki-select' == sub_control_type ) { + + /** + * Update the value visually in the control + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'select' ); + var $select = jQuery( input_element ).selectize(); + var selectize = $select[0].selectize; + selectize.setValue( preset_setting_value, true ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + + } + /** + * Control types: + * slider + */ + else if ( 'slider' == sub_control_type ) { + + /** + * Update the value visually in the control (slider) + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'input' ); + jQuery( input_element ).prop( "value", preset_setting_value ); + /** + * Update the value visually in the control (number) + */ + var numeric_element = wp.customize.control( preset_setting ).container.find( '.kirki_range_value .value' ); + jQuery( numeric_element ).html( preset_setting_value ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + + } + /** + * Control types: + * textarea + * kirki-textarea + */ + else if ( 'textarea' == sub_control_type || 'kirki-textarea' == sub_control_type ) { + + /** + * Update the value visually in the control + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'textarea' ); + jQuery( input_element ).prop( "value", preset_setting_value ); + /** + * Update the value in the customizer object + */ + wp.customize( preset_setting ).set( preset_setting_value ); + + } + /** + * Control types: + * color + * kirki-color + */ + else if ( 'color' == sub_control_type || 'kirki-color' == sub_control_type ) { + + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + /** + * Update the value visually in the control + */ + + wp.customize.control( preset_setting ).container.find( '.color-picker-hex' ) + .attr( 'data-default-color', preset_setting_value ) + .data( 'default-color', preset_setting_value ) + .wpColorPicker( 'color', preset_setting_value ); + + } + else if ( 'color-alpha' == sub_control_type ) { + + /** + * Update the value visually in the control + */ + var alphaColorControl = wp.customize.control( preset_setting ).container.find( '.kirki-color-control' ); + + alphaColorControl + .attr( 'data-default-color', preset_setting_value ) + .data( 'default-color', preset_setting_value ) + .wpColorPicker( 'color', preset_setting_value ); + + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + + } + /** + * Control types: + * dimension + */ + else if ( 'dimension' == sub_control_type ) { + + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + /** + * Update the numeric value visually in the control + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'input[type=number]' ); + var numeric_value = parseFloat( preset_setting_value ); + jQuery( input_element ).prop( "value", numeric_value ); + /** + * Update the units value visually in the control + */ + var select_element = wp.customize.control( preset_setting ).container.find( 'select' ); + var units_value = preset_setting_value.replace( parseFloat( preset_setting_value ), '' ); + jQuery( select_element ).prop( "value", units_value ); + + } + /** + * Control types: + * multicheck + */ + else if ( 'multicheck' == sub_control_type ) { + + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + /** + * Update the value visually in the control. + * This value is an array so we'll have to go through each one of the items + * in order to properly apply the value and check each checkbox separately. + * + * First we uncheck ALL checkboxes in the control + * Then we check the ones that we want. + */ + wp.customize.control( preset_setting ).container.find( 'input' ).each(function() { + jQuery( this ).prop( "checked", false ); + }); + + for ( index = 0; index < preset_setting_value.length; index++ ) { + var input_element = wp.customize.control( preset_setting ).container.find( 'input[value="' + preset_setting_value[ index ] + '"]' ); + jQuery( input_element ).prop( "checked", true ); + } + + } + /** + * Control types: + * radio-buttonset + * radio-image + * radio + * kirki-radio + */ + else if ( 'radio-buttonset' == sub_control_type || 'radio-image' == sub_control_type || 'radio' == sub_control_type || 'kirki-radio' == sub_control_type ) { + + /** + * Update the value visually in the control + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'input[value="' + preset_setting_value + '"]' ); + jQuery( input_element ).prop( "checked", true ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + + } + /** + * Fallback for all other controls. + */ + else { + + /** + * Update the value visually in the control + */ + var input_element = wp.customize.control( preset_setting ).container.find( 'input' ); + jQuery( input_element ).prop( "value", preset_setting_value ); + /** + * Update the value in the customizer object + */ + wp.customize.instance( preset_setting ).set( preset_setting_value ); + + } + + }); + + } + + }); + + wp.customize.previewer.refresh(); + + }); + + } +}); diff --git a/pool/shard011/JavaScript/0070100_util.js b/pool/shard011/JavaScript/0070100_util.js new file mode 100644 index 0000000000000000000000000000000000000000..2364d5915273c21b75f3ad2233d4c60408cc6994 --- /dev/null +++ b/pool/shard011/JavaScript/0070100_util.js @@ -0,0 +1,28 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +var util = { + isAppearSupported: function isAppearSupported(props) { + return props.transitionName && props.transitionAppear || props.animation.appear; + }, + isEnterSupported: function isEnterSupported(props) { + return props.transitionName && props.transitionEnter || props.animation.enter; + }, + isLeaveSupported: function isLeaveSupported(props) { + return props.transitionName && props.transitionLeave || props.animation.leave; + }, + + allowAppearCallback: function allowAppearCallback(props) { + return props.transitionAppear || props.animation.appear; + }, + allowEnterCallback: function allowEnterCallback(props) { + return props.transitionEnter || props.animation.enter; + }, + allowLeaveCallback: function allowLeaveCallback(props) { + return props.transitionLeave || props.animation.leave; + } +}; +exports["default"] = util; +module.exports = exports["default"]; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070104_authentication.js b/pool/shard011/JavaScript/0070104_authentication.js new file mode 100644 index 0000000000000000000000000000000000000000..514dea75af26dd9a6b42803bb017465170246e0f --- /dev/null +++ b/pool/shard011/JavaScript/0070104_authentication.js @@ -0,0 +1,74 @@ +'use strict'; + + +module.exports = function($q, $http, Config) { + + var _api = Config.api.url(); + var _tokenKey = 'tb-access-token-user'; + + return { + loginUser: function(user) { + var self = this; + + return $http.post(_api + 'auth/login', user) + .then(function(response) { + var token = response.headers('x-access-token'); + self.setUserToken(token); + }); + }, + + loginGuest: function(boardId, accessCode, username) { + var self = this; + + return $http.post(_api + 'boards/' + boardId + '/access/' + accessCode, { username: username }) + .then(function(response) { + var token = response.headers('x-access-token') + self.setGuestToken(boardId, token); + }); + }, + + logout: function() { + var self = this; + + return $http.post(_api + 'auth/logout') + .then(function() { + self.removeToken(); + }); + }, + + register: function(user) { + return $http.post(_api + 'auth/register', user); + }, + + getUser: function() { + return $http.get(_api + 'auth').then(function(response) { + return response.data; + }); + }, + + getTokenKey: function() { + return _tokenKey; + }, + + setTokenKey: function(tokenKey) { + _tokenKey = tokenKey; + }, + + getToken: function() { + return localStorage.getItem(_tokenKey); + }, + + setUserToken: function(token) { + localStorage.setItem('tb-access-token-user', token); + }, + + setGuestToken: function(boardId, token) { + localStorage.setItem('tb-access-token-guest-' + boardId, token); + }, + + removeToken: function() { + console.log(_tokenKey); + localStorage.removeItem(_tokenKey); + } + } +} diff --git a/pool/shard011/JavaScript/0070106_linear-test.js b/pool/shard011/JavaScript/0070106_linear-test.js new file mode 100644 index 0000000000000000000000000000000000000000..c638814e62c596b75fca2e665a47345717e33dc9 --- /dev/null +++ b/pool/shard011/JavaScript/0070106_linear-test.js @@ -0,0 +1,36 @@ +var tape = require("tape"), + ease = require("../").ease; + +require("./inDelta"); + +tape('ease("linear") returns the expected results', function(test) { + var e = ease("linear"); + test.inDelta(e(0.0), 0.0); + test.inDelta(e(0.1), 0.1); + test.inDelta(e(0.2), 0.2); + test.inDelta(e(0.3), 0.3); + test.inDelta(e(0.4), 0.4); + test.inDelta(e(0.5), 0.5); + test.inDelta(e(0.6), 0.6); + test.inDelta(e(0.7), 0.7); + test.inDelta(e(0.8), 0.8); + test.inDelta(e(0.9), 0.9); + test.inDelta(e(1.0), 1.0); + test.equal(e(".9"), e(0.9), "numeric coercion"); + test.end(); +}); + +tape('ease("linear-in") is an alias for ease("linear")', function(test) { + test.equal(ease("linear-in"), ease("linear")); + test.end(); +}); + +tape('ease("linear-out") is an alias for ease("linear")', function(test) { + test.equal(ease("linear-out"), ease("linear")); + test.end(); +}); + +tape('ease("linear-in-out") is an alias for ease("linear")', function(test) { + test.equal(ease("linear-in-out"), ease("linear")); + test.end(); +}); diff --git a/pool/shard011/JavaScript/0070107_asat.console.js b/pool/shard011/JavaScript/0070107_asat.console.js new file mode 100644 index 0000000000000000000000000000000000000000..74406fed4f2bb85a9ee91fa7d42790db8145b1b7 --- /dev/null +++ b/pool/shard011/JavaScript/0070107_asat.console.js @@ -0,0 +1,52 @@ +function Console(){ + return this; +} + +Console.prototype.log = function(text){ + $('#console').append(" " + getTime() + " - " + text + "
    "); + document.getElementById("console").scrollTop = document.getElementById("console").scrollHeight; + console.log(text); +}; +Console.prototype.error = function(text){ + $('#console').append(" " + getTime() + " - error - " + text + "
    "); + document.getElementById("console").scrollTop = document.getElementById("console").scrollHeight; + console.log(text); +}; +Console.prototype.warning = function(text){ + $('#console').append(" " + getTime() + " - warning - " + text + "
    "); + document.getElementById("console").scrollTop = document.getElementById("console").scrollHeight; + console.log(text); +}; +Console.prototype.info = function(text){ + $('#console').append(" " + getTime() + " - info - " + text + "
    "); + document.getElementById("console").scrollTop = document.getElementById("console").scrollHeight; + console.log(text); +}; +Console.prototype.debug = function(text){ + $('#console').append(" " + getTime() + " - debug - " + text + "
    "); + document.getElementById("console").scrollTop = document.getElementById("console").scrollHeight; + console.log(text); +}; + +function getTime(){ + var now = new Date(); + var hours = now.getHours().toString(); + if (hours.length < 2){ + hours = "0"+hours; + } + var minutes = now.getMinutes().toString(); + if (minutes.length < 2){ + minutes = "0"+minutes; + } + var seconds = now.getSeconds().toString(); + if (seconds.length < 2){ + seconds = "0"+seconds; + } + var milli = now.getMilliseconds().toString(); + if (milli.length < 2){ + milli = "00"+milli; + } else if (milli.length < 3) { + milli = "0" + milli + } + return hours + ":" + minutes +":"+seconds+"."+milli; +} diff --git a/pool/shard011/JavaScript/0070108_ColorManager.js b/pool/shard011/JavaScript/0070108_ColorManager.js new file mode 100644 index 0000000000000000000000000000000000000000..84a55d37044fb3cec3262f25c9f2d30a78f82e0a --- /dev/null +++ b/pool/shard011/JavaScript/0070108_ColorManager.js @@ -0,0 +1,181 @@ +/** + * Copyright (c) 2008 The Open Planning Project + */ + +/** + * @requires widgets/form/ColorField.js + */ + +Ext.namespace("gxp"); + +/** + * Class: gxp.ColorManager + * A simple manager that handles the rendering of a ColorPicker window and + * coordinates the setting of values in a ColorField. May be used as a + * plugin for a ColorField (or any text field that is intended to gather a + * RGB hex color value). + */ +gxp.ColorManager = function(config) { + Ext.apply(this, config); +}; + +Ext.apply(gxp.ColorManager.prototype, { + + /** + * Property: field + * {} The currently focussed field. + */ + field: null, + + /** + * Method: init + * Called when the color manager is used as a plugin. + * + * Parameters: + * field - {} The field using this manager as a + * plugin. + */ + init: function(field) { + this.register(field); + }, + + /** + * Method: destroy + * Cleans up the manager. + */ + destroy: function() { + if(this.field) { + this.unregister(this.field); + } + }, + + + /** + * Method: register + * Register a field with this manager. + * + * Parameters: + * field - {} The field using this manager as a + * plugin. + */ + register: function(field) { + if(this.field) { + this.unregister(this.field); + } + this.field = field; + field.on({ + focus: this.fieldFocus, + destroy: this.destroy, + scope: this + }); + }, + + /** + * Method: unregister + * Unregister a field with this manager. + * + * Parameters: + * field - {} The field using this manager as a + * plugin. + */ + unregister: function(field) { + field.un("focus", this.fieldFocus, this); + field.un("destroy", this.destroy, this); + if(gxp.ColorManager.picker && field == this.field) { + gxp.ColorManager.picker.un("pickcolor", this.setFieldValue, this); + } + this.field = null; + }, + + /** + * Method: fieldFocus + * Listener for "focus" event on a field. + * + * Parameters: + * field - {} The focussed field. + */ + fieldFocus: function(field) { + if(!gxp.ColorManager.pickerWin) { + gxp.ColorManager.picker = new Ext.ColorPalette(); + gxp.ColorManager.pickerWin = new Ext.Window({ + title: "Color Picker", + closeAction: "hide", + autoWidth: true, + autoHeight: true + }); + } else { + gxp.ColorManager.picker.purgeListeners(); + } + var listenerCfg = { + select: this.setFieldValue, + scope: this + }; + var value = this.getPickerValue(); + if (value) { + var colors = [].concat(gxp.ColorManager.picker.colors); + if (!~colors.indexOf(value)) { + if (gxp.ColorManager.picker.ownerCt) { + gxp.ColorManager.pickerWin.remove(gxp.ColorManager.picker); + gxp.ColorManager.picker = new Ext.ColorPalette(); + } + colors.push(value); + gxp.ColorManager.picker.colors = colors; + } + gxp.ColorManager.pickerWin.add(gxp.ColorManager.picker); + gxp.ColorManager.pickerWin.doLayout(); + if (gxp.ColorManager.picker.rendered) { + gxp.ColorManager.picker.select(value); + } else { + listenerCfg.afterrender = function() { + gxp.ColorManager.picker.select(value); + }; + } + } + gxp.ColorManager.picker.on(listenerCfg); + gxp.ColorManager.pickerWin.show(); + }, + + /** + * Method: setFieldValue + * Listener for the "pickcolor" event of the color picker. Only sets the + * field value if the field is visible. + * + * Parameters: + * picker - {Ext.ux.ColorPicker} The color picker + * color - {String} The RGB hex value (not prefixed with "#") + */ + setFieldValue: function(picker, color) { + if(this.field.isVisible()) { + this.field.setValue("#" + color); + } + }, + + /** + * Method: getPickerValue + */ + getPickerValue: function() { + var field = this.field; + var hex = field.getHexValue ? + (field.getHexValue() || field.defaultBackground) : + field.getValue(); + if (hex) { + return hex.substr(1); + } + } + +}); + +(function() { + // register the color manager with every color field + Ext.util.Observable.observeClass(gxp.form.ColorField); + gxp.form.ColorField.on({ + render: function(field) { + var manager = new gxp.ColorManager(); + manager.register(field); + } + }); +})(); + +gxp.ColorManager.picker = null; + +gxp.ColorManager.pickerWin = null; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070111_register.js b/pool/shard011/JavaScript/0070111_register.js new file mode 100644 index 0000000000000000000000000000000000000000..84a8e167c1a3f221aa3f85a395ff90782241d85a --- /dev/null +++ b/pool/shard011/JavaScript/0070111_register.js @@ -0,0 +1,89 @@ +$(document).ready(function(){ + $('#registerBtn').live('click', function() { + var that = this; + $(this).addClass('loading'); + //clear tips + $('div.error').removeClass('error'); + $('span.tip').text(''); + + var username = $.trim($('#username').val()); + var email = $.trim($('#email').val()); + var password = $('#password').val(); + var cfmPwd = $('#cfmPwd').val(); + + $.ajax({ + url: basePath+'/account/register', + type: 'POST', + dataType: 'json', + data: { username:username, + email: email, + password: password, + cfmPwd: cfmPwd}, + }) + .success(function(data) { + $(that).removeClass('loading'); + if(data.status == SUCCESS_ACCOUNT_REG) { + self.location = basePath + '/account/activation/mail/send?email='+email; + } else { //error + var status = data.status; + switch(status.charAt(2)) { + case '0': //username error + if(status == '000003') { //user name exist + username = ''; + $('#usernameTip').text('用户名已存在'); + } else if(status == '000004') { //user name empty + $('#usernameTip').text('请输入用户名'); + } + $('#username').parent('div.field:first').addClass('error'); + break; + + case '1': //email error + if(status == '001000') { + $('#emailTip').text('邮箱已注册 登录'); + } else if(status == '001001') { + $('#emailTip').text('请输入邮箱地址'); + } else if(status == '001002') { + $('#emailTip').text('请输入正确的邮箱地址'); + } + $('#email').parent('div.field:first').addClass('error'); + break; + + case '2': //password error + if(status == '002000') { //password empty + $('#passwordTip').text('请输入密码'); + } + $('#password').parent('div.field:first').addClass('error'); + break; + + case '3': //confirm password error + if(status == '003000') { + $('#cfmPwdTip').text('请再次输入密码'); + $('#cfmPwdTip').parent('div.field:first').addClass('error'); + } else if(status == '003001') { + $('#passwordTip').text('密码输入不一致'); + $('#password').parent('div.field:first').addClass('error'); + $('#cfmPwd').parent('div.field:first').addClass('error'); + } + break; + case '4': //注册成功,等待激活 + if(status == '004003') { + var activationUrl = basePath + '/account/activation/mail/send?email='+email; + $('#emailTip').html('已注册,请激活'); + } + $('#email').parent('div.field:first').addClass('error'); + break; + default: + break; + } + } + + }) + .fail(function() { + console.log("error"); + }) + .always(function() { + console.log("complete"); + }); + + }); +}) \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070112_config.test.js b/pool/shard011/JavaScript/0070112_config.test.js new file mode 100644 index 0000000000000000000000000000000000000000..2fbd4b5fb524d1e8684fccbb3065b37f23c6ea83 --- /dev/null +++ b/pool/shard011/JavaScript/0070112_config.test.js @@ -0,0 +1,43 @@ +'use strict'; +var chai = require('chai'); +var expect = chai.expect; +var assert = chai.assert; + +describe('Configuration setup', function describeConfigurationSuite() { + it('should load local configurations', function testLocalConfiguration(next) { + let config = require('../../../config')('local'); + expect(config.mode).to.equal('local'); + expect(config.level).to.equal('debug'); + expect(config.port).to.equal(8081); + assert.isDefined(config.logDir); + expect(config.basePath).to.equal('localhost:8081'); + next(); + }); + it('should load ci configurations', function testCiConfiguration(next) { + let config = require('../../../config')('ci'); + expect(config.mode).to.equal('ci'); + expect(config.level).to.equal('debug'); + expect(config.port).to.equal(8081); + assert.isDefined(config.logDir); + expect(config.basePath).to.equal('ci-cnid-user-service.conde.io'); + next(); + }); + it('should load staging configurations', function testStagingConfiguration(next) { + let config = require('../../../config')('staging'); + expect(config.mode).to.equal('stag'); + expect(config.level).to.equal('info'); + expect(config.port).to.equal(8081); + assert.isDefined(config.logDir); + expect(config.basePath).to.equal('stag-cnid-user-service.conde.io'); + next(); + }); + it('should load production configurations', function testProductionConfiguration(next) { + let config = require('../../../config')('production'); + expect(config.mode).to.equal('prod'); + expect(config.level).to.equal('info'); + expect(config.port).to.equal(8081); + assert.isDefined(config.logDir); + expect(config.basePath).to.equal('prod-cnid-user-service.conde.io'); + next(); + }); +}); diff --git a/pool/shard011/JavaScript/0070114_02._JSON_s_Table.js b/pool/shard011/JavaScript/0070114_02._JSON_s_Table.js new file mode 100644 index 0000000000000000000000000000000000000000..e1c5f6df2d35088adb511be9e45f52f6f6a32340 --- /dev/null +++ b/pool/shard011/JavaScript/0070114_02._JSON_s_Table.js @@ -0,0 +1,25 @@ +function jsonTable(input) { + let html = '\n'; + for (let line of input) { + let obj = JSON.parse(line); + html += ` \n \n \n \n \n`; + } + html += '
    ${htmlEscape(obj.name)}${htmlEscape(obj.position)}${obj.salary}
    '; + + console.log(html); + + function htmlEscape(text) { + let map = { + '"': '"', + '&': '&', + "'": ''', + '<': '<', + '>': '>' + }; + return text.replace(/[\"&'<>]/g, ch => map[ch]); + } +} + +/* jsonTable(['{"name":"Pesho","position":"Promenliva","salary":100000}', + '{"name":"Teo","position":"Lecturer","salary":1000}' +]); */ \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070115_TimeForWar.js b/pool/shard011/JavaScript/0070115_TimeForWar.js new file mode 100644 index 0000000000000000000000000000000000000000..122a2ed25c61367876536cb762b6f2f2f63969f0 --- /dev/null +++ b/pool/shard011/JavaScript/0070115_TimeForWar.js @@ -0,0 +1,39 @@ +const DrawCard = require('../../drawcard.js'); +const AbilityDsl = require('../../abilitydsl'); +const CardSelector = require('../../CardSelector'); +const { Locations, Players, CardTypes } = require('../../Constants'); + +class TimeForWar extends DrawCard { + setupCardAbilities() { + const attachAction = AbilityDsl.actions.attach(); + this.reaction({ + title: 'Put a weapon into play', + when: { + afterConflict: (event, context) => event.conflict.loser === context.player && event.conflict.conflictType === 'political' + }, + target: { + cardType: CardTypes.Character, + controller: Players.Self, + cardCondition: card => card.hasTrait('bushi'), + gameAction: AbilityDsl.actions.selectCard(context => ({ + selector: CardSelector.for({ + activePromptTitle: 'Choose a weapon attachment', + cardType: CardTypes.Attachment, + location: [Locations.ConflictDiscardPile, Locations.Hand], + controller: Players.Self, + cardCondition: card => card.costLessThan(4) && card.hasTrait('weapon') && attachAction.canAffect(context.target, context, { attachment: card }) + }), + message: '{0} chooses to attach {1} to {2}', + messageArgs: (card, player) => [player, card, context.target], + subActionProperties: card => ({ attachment: card }), + gameAction: attachAction + })) + }, + effect: 'attach a weapon to {0}' + }); + } +} + +TimeForWar.id = 'time-for-war'; + +module.exports = TimeForWar; diff --git a/pool/shard011/JavaScript/0070116_base64.js b/pool/shard011/JavaScript/0070116_base64.js new file mode 100644 index 0000000000000000000000000000000000000000..a7742715530fceabea7abd5db2e196ec7a5b86d2 --- /dev/null +++ b/pool/shard011/JavaScript/0070116_base64.js @@ -0,0 +1,36 @@ +// Base64.js Polyfill (@davidchambers) +(function() { + var object = typeof exports != 'undefined' ? exports : this; + var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; + + function InvalidCharacterError(message) { + this.message = message; + } + InvalidCharacterError.prototype = new Error; + InvalidCharacterError.prototype.name = 'InvalidCharacterError'; + + object.btoa || ( + object.btoa = function(input) { + var str = String(input); + for (var block, charCode, idx = 0, map = chars, output = ''; str.charAt(idx | 0) || (map = '=', idx % 1); output += map.charAt(63 & block >> 8 - idx % 1 * 8)) { + charCode = str.charCodeAt(idx += 3 / 4); + if (charCode > 0xFF) { + throw new InvalidCharacterError("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range."); + } + block = block << 8 | charCode; + } + return output; + }); + + object.atob || ( + object.atob = function(input) { + var str = String(input).replace(/=+$/, ''); + if (str.length % 4 == 1) { + throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded."); + } + for (var bc = 0, bs, buffer, idx = 0, output = ''; buffer = str.charAt(idx++); ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer, bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) { + buffer = chars.indexOf(buffer); + } + return output; + }); +}()); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070117_statement.js b/pool/shard011/JavaScript/0070117_statement.js new file mode 100644 index 0000000000000000000000000000000000000000..4cda8f2d14c3cfc21cac527d2a2e572cae7b2d24 --- /dev/null +++ b/pool/shard011/JavaScript/0070117_statement.js @@ -0,0 +1,58 @@ +const moment = require('moment'); +const Client = require('../../../../base/client'); +const Currency = require('../../../../common/currency'); +const localize = require('../../../../../_common/localize').localize; +const toTitleCase = require('../../../../../_common/string_util').toTitleCase; + +const Statement = (() => { + const getStatementData = (statement, currency) => { + const date_obj = new Date(statement.transaction_time * 1000); + const moment_obj = moment.utc(date_obj); + const date_str = moment_obj.format('YYYY-MM-DD'); + const time_str = `${moment_obj.format('HH:mm:ss')} GMT`; + const payout = parseFloat(statement.payout); + const amount = parseFloat(statement.amount); + const balance = parseFloat(statement.balance_after); + const is_ico_bid = /binaryico/i.test(statement.shortcode); // TODO: remove ico exception when all ico contracts are removed + + // action_type may be (buy|sell|deposit|withdrawal) from API + let localized_action = localize(toTitleCase(statement.action_type) /* localize-ignore */); + if (is_ico_bid) { + localized_action = /buy/i.test(statement.action_type) ? localize('Bid') : localize('Closed Bid'); + } + + return { + localized_action, + action_type: statement.action_type, + date : `${date_str}\n${time_str}`, + ref : statement.transaction_id, + payout : isNaN(payout) || is_ico_bid || !+payout ? '-' : Currency.formatMoney(currency, payout, true), + amount : isNaN(amount) ? '-' : Currency.formatMoney(currency, amount, true), + balance : isNaN(balance) ? '-' : Currency.formatMoney(currency, balance, true), + desc : localize(statement.longcode.replace(/\n/g, '
    ') /* localize-ignore */), // untranslated desc + id : statement.contract_id, + app_id : statement.app_id, + }; + }; + + const generateCSV = (all_data) => { + const columns = ['date', 'ref', 'payout', 'action', 'desc', 'amount', 'balance']; + const header = localize(['Date', 'Reference ID', 'Potential Payout', 'Action', 'Description', 'Credit/Debit']); + const currency = Client.get('currency'); + header.push(localize('Balance') + (currency ? ` (${Currency.getCurrencyDisplayCode(currency)})` : '')); + const sep = ','; + let csv = [header.join(sep)]; + if (all_data && all_data.length > 0) { + // eslint-disable-next-line no-control-regex + csv = csv.concat(all_data.map(data => columns.map(key => (data[key] ? data[key].replace(Currency.formatCurrency(currency), '¥').replace(new RegExp(sep, 'g'), '').replace(new RegExp('\n|
    ', 'g'), ' ') : '')).join(sep))); + } + return csv.join('\r\n'); + }; + + return { + getStatementData, + generateCSV, + }; +})(); + +module.exports = Statement; diff --git a/pool/shard011/JavaScript/0070118_EditLinkModal.js b/pool/shard011/JavaScript/0070118_EditLinkModal.js new file mode 100644 index 0000000000000000000000000000000000000000..ae2229e42b4c0f31af4855f256c298a9eef8a813 --- /dev/null +++ b/pool/shard011/JavaScript/0070118_EditLinkModal.js @@ -0,0 +1,140 @@ +/* global m*/ +/* global confirm*/ + +import app from 'flarum/app'; +import Modal from 'flarum/components/Modal'; +import Button from 'flarum/components/Button'; + +/** + * The `EditlinksModal` component shows a modal dialog which allows the user + * to create or edit a link. + */ +export default class EditlinksModal extends Modal { + init() { + super.init(); + + this.link = this.props.link || app.store.createRecord('links'); + + this.itemTitle = m.prop(this.link.title() || ''); + this.url = m.prop(this.link.url() || ''); + this.isInternal = m.prop(this.link.isInternal() && true); + this.isNewtab = m.prop(this.link.isNewtab() && true); + } + + className() { + return 'EditLinkModal Modal--small'; + } + + title() { + const title = this.itemTitle(); + return title || app.translator.trans('sijad-links.admin.edit_link.title'); + } + + content() { + return ( +
    +
    +
    + + { + this.itemTitle(e.target.value); + }} + /> +
    + +
    + + { + this.url(e.target.value); + }} + /> +
    + +
    +
    + + +
    +
    + +
    + {Button.component({ + type: 'submit', + className: 'Button Button--primary EditLinkModal-save', + loading: this.loading, + children: app.translator.trans('sijad-links.admin.edit_link.submit_button'), + })} + {this.link.exists ? ( + + ) : ''} +
    +
    +
    + ); + } + + onsubmit(e) { + e.preventDefault(); + + this.loading = true; + + this.link.save({ + title: this.itemTitle(), + url: this.url(), + isInternal: this.isInternal(), + isNewtab: this.isNewtab(), + }).then( + () => this.hide(), + response => { + this.loading = false; + this.handleErrors(response); + } + ); + } + + delete() { + if (confirm( + app.translator.trans('sijad-links.admin.edit_link.delete_link_confirmation'))) { + this.link.delete().then(() => m.redraw()); + this.hide(); + } + } +} diff --git a/pool/shard011/JavaScript/0070124_animate-color-calcMode-discrete.js b/pool/shard011/JavaScript/0070124_animate-color-calcMode-discrete.js new file mode 100644 index 0000000000000000000000000000000000000000..59a9a55100a2c670b5ce70b5d428eebd3cb3df3e --- /dev/null +++ b/pool/shard011/JavaScript/0070124_animate-color-calcMode-discrete.js @@ -0,0 +1,51 @@ +description("Test calcMode discrete with from-to animation on colors. You should see a green 100x100 rect and only PASS messages"); +createSVGTestCase(); + +// Setup test document +var rect = createSVGElement("rect"); +rect.setAttribute("id", "rect"); +rect.setAttribute("width", "100"); +rect.setAttribute("height", "100"); +rect.setAttribute("color", "rgb(128,255,255)"); +rect.setAttribute("fill", "currentColor"); +rect.setAttribute("onclick", "executeTest()"); + +var animate = createSVGElement("animate"); +animate.setAttribute("id", "animation"); +animate.setAttribute("attributeName", "color"); +animate.setAttribute("from", "rgb(255,0,0)"); +animate.setAttribute("to", "rgb(0,255,255)"); +animate.setAttribute("begin", "click"); +animate.setAttribute("dur", "4s"); +animate.setAttribute("calcMode", "discrete"); +rect.appendChild(animate); +rootSVGElement.appendChild(rect); + +// Setup animation test +function sample1() { + expectFillColor(rect, 128, 255, 255); +} + +function sample2() { + expectFillColor(rect, 255, 0, 0); +} + +function sample3() { + expectFillColor(rect, 0, 255, 255); +} + +function executeTest() { + const expectedValues = [ + // [animationId, time, sampleCallback] + ["animation", 0.0, sample1], + ["animation", 0.001, sample2], + ["animation", 1.999, sample2], + ["animation", 2.001, sample3], + ["animation", 3.999, sample3], + ["animation", 4.001, sample1] + ]; + + runAnimationTest(expectedValues); +} + +var successfullyParsed = true; diff --git a/pool/shard011/JavaScript/0070130_navbar.directive.js b/pool/shard011/JavaScript/0070130_navbar.directive.js new file mode 100644 index 0000000000000000000000000000000000000000..5bfae64207e08f80e1a9f4e8c63f04804cff0dd4 --- /dev/null +++ b/pool/shard011/JavaScript/0070130_navbar.directive.js @@ -0,0 +1,40 @@ +'use strict'; + +angular.module('ewsclientApp') + .directive('activeMenu', function($translate, $locale, tmhDynamicLocale) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + var language = attrs.activeMenu; + + scope.$watch(function() { + return $translate.use(); + }, function(selectedLanguage) { + if (language === selectedLanguage) { + tmhDynamicLocale.set(language); + element.addClass('active'); + } else { + element.removeClass('active'); + } + }); + } + }; + }) + .directive('activeLink', function(location) { + return { + restrict: 'A', + link: function (scope, element, attrs) { + var clazz = attrs.activeLink; + var path = attrs.href; + path = path.substring(1); //hack because path does bot return including hashbang + scope.location = location; + scope.$watch('location.path()', function(newPath) { + if (path === newPath) { + element.addClass(clazz); + } else { + element.removeClass(clazz); + } + }); + } + }; + }); diff --git a/pool/shard011/JavaScript/0070131_resolver_sync.js b/pool/shard011/JavaScript/0070131_resolver_sync.js new file mode 100644 index 0000000000000000000000000000000000000000..ac9c758e3e082e879606228e335518d3ddbf1cd0 --- /dev/null +++ b/pool/shard011/JavaScript/0070131_resolver_sync.js @@ -0,0 +1,206 @@ +var path = require('path'); +var test = require('tape'); +var resolve = require('../'); + +test('foo', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./foo', { basedir: dir }), + path.join(dir, 'foo.js') + ); + + t.equal( + resolve.sync('./foo.js', { basedir: dir }), + path.join(dir, 'foo.js') + ); + + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }); + + t.end(); +}); + +test('bar', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('foo', { basedir: path.join(dir, 'bar') }), + path.join(dir, 'bar/node_modules/foo/index.js') + ); + t.end(); +}); + +test('baz', function (t) { + var dir = path.join(__dirname, 'resolver'); + + t.equal( + resolve.sync('./baz', { basedir: dir }), + path.join(dir, 'baz/quux.js') + ); + t.end(); +}); + +test('biz', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules'); + t.equal( + resolve.sync('./grux', { basedir: dir }), + path.join(dir, 'grux/index.js') + ); + + t.equal( + resolve.sync('tiv', { basedir: path.join(dir, 'grux') }), + path.join(dir, 'tiv/index.js') + ); + + t.equal( + resolve.sync('grux', { basedir: path.join(dir, 'tiv') }), + path.join(dir, 'grux/index.js') + ); + t.end(); +}); + +test('normalize', function (t) { + var dir = path.join(__dirname, 'resolver/biz/node_modules/grux'); + t.equal( + resolve.sync('../grux', { basedir: dir }), + path.join(dir, 'index.js') + ); + t.end(); +}); + +test('cup', function (t) { + var dir = path.join(__dirname, 'resolver'); + t.equal( + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'cup.coffee') + ); + + t.equal( + resolve.sync('./cup.coffee', { basedir: dir }), + path.join(dir, 'cup.coffee') + ); + + t.throws(function () { + resolve.sync('./cup', { + basedir: dir, + extensions: ['.js'] + }); + }); + + t.end(); +}); + +test('mug', function (t) { + var dir = path.join(__dirname, 'resolver'); + t.equal( + resolve.sync('./mug', { basedir: dir }), + path.join(dir, 'mug.js') + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.coffee', '.js'] + }), + path.join(dir, 'mug.coffee') + ); + + t.equal( + resolve.sync('./mug', { + basedir: dir, + extensions: ['.js', '.coffee'] + }), + path.join(dir, 'mug.js') + ); + + t.end(); +}); + +test('other path', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'bar'); + var otherDir = path.join(resolverDir, 'other_path'); + + t.equal( + resolve.sync('root', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/root.js') + ); + + t.equal( + resolve.sync('lib/other-lib', { + basedir: dir, + paths: [otherDir] + }), + path.join(resolverDir, 'other_path/lib/other-lib.js') + ); + + t.throws(function () { + resolve.sync('root', { basedir: dir }); + }); + + t.throws(function () { + resolve.sync('zzz', { + basedir: dir, + paths: [otherDir] + }); + }); + + t.end(); +}); + +test('incorrect main', function (t) { + var resolverDir = path.join(__dirname, 'resolver'); + var dir = path.join(resolverDir, 'incorrect_main'); + + t.equal( + resolve.sync('./incorrect_main', { basedir: resolverDir }), + path.join(dir, 'index.js') + ); + + t.end(); +}); + +test('#25: node modules with the same name as node stdlib modules', function (t) { + var resolverDir = path.join(__dirname, 'resolver/punycode'); + + t.equal( + resolve.sync('punycode', { basedir: resolverDir }), + path.join(resolverDir, 'node_modules/punycode/index.js') + ); + + t.end(); +}); + +var stubStatSync = function stubStatSync(fn) { + var fs = require('fs'); + var statSync = fs.statSync; + try { + fs.statSync = function () { + throw new EvalError('Unknown Error'); + }; + return fn(); + } finally { + fs.statSync = statSync; + } +}; + +test('#79 - re-throw non ENOENT errors from stat', function (t) { + var dir = path.join(__dirname, 'resolver'); + + stubStatSync(function () { + t.throws(function () { + resolve.sync('foo', { basedir: dir }); + }, /Unknown Error/); + }); + + t.end(); +}); + diff --git a/pool/shard011/JavaScript/0070135_TreeGridEditorDragZone.js b/pool/shard011/JavaScript/0070135_TreeGridEditorDragZone.js new file mode 100644 index 0000000000000000000000000000000000000000..19d71535ac2d3948378077e12b0e1ccbef1be1e2 --- /dev/null +++ b/pool/shard011/JavaScript/0070135_TreeGridEditorDragZone.js @@ -0,0 +1,21 @@ +/** + * @author zhangdaiping@vip.qq.com + * @version 1.4.0 (30/5/2010) + */ +Ext.ux.tree.TreeGridEditorDragZone = Ext.extend(Ext.tree.TreeDragZone, { + // private + onBeforeDrag: function(data, e) { + var n = data.node; + n.getOwnerTree().outShowObar(n); + return Ext.ux.tree.TreeGridEditorDragZone.superclass.onBeforeDrag.apply(this, arguments); + }, + + // private + onEndDrag: function(data, e) { + var n = data.node, t = n.getOwnerTree(); + if (!t.mouseoverShowObar || n.getEditMode()) { + t.overShowObar(n); + } + return Ext.ux.tree.TreeGridEditorDragZone.superclass.onEndDrag.apply(this, arguments); + } +}); diff --git a/pool/shard011/JavaScript/0070137_cookie_auth.js b/pool/shard011/JavaScript/0070137_cookie_auth.js new file mode 100644 index 0000000000000000000000000000000000000000..8ad993cca1b43ba68fcfce23a05bf33a3a4cab60 --- /dev/null +++ b/pool/shard011/JavaScript/0070137_cookie_auth.js @@ -0,0 +1,256 @@ +// 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. + +couchTests.cookie_auth = function(debug) { + // This tests cookie-based authentication. + + var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"}); + db.deleteDb(); + db.createDb(); + if (debug) debugger; + + // Simple secret key generator + function generateSecret(length) { + var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + var secret = ''; + for (var i=0; i .ibg-bg").css({ + width: $(window).outerWidth(), + height: $(window).outerHeight() + }) +}) + +// get login state +var loginState = LoginState.get("europe2034loginstate"); +if(loginState) { + console.log(loginState); +} else { + console.log('not logged in'); +} diff --git a/pool/shard011/JavaScript/0070145_middleware.js b/pool/shard011/JavaScript/0070145_middleware.js new file mode 100644 index 0000000000000000000000000000000000000000..09382e1f35b9e3fc3760a753e8edb3bb1a791d4f --- /dev/null +++ b/pool/shard011/JavaScript/0070145_middleware.js @@ -0,0 +1,50 @@ + +var url = require('url'); +var playback = require('./playback.js'); + +/** + * Returns connect middleware that will record and playback for Angular.dart's + * HTTP playback service. + * @param opts + * path is the path where the record / playback endpoint is served + * playbackImpl is the playback module, used for mocking + * @returns {Function} + */ +function endpoint(opts) { + opts = opts || {}; + opts.path = opts.path || '/record'; + opts.playbackImpl = opts.playbackImpl || playback.playback(); + + + return function playbackEndpoint(req, res, next) { + if (url.parse(req.url).path != opts.path) { + next(); + return; + } + + if (req.method == 'POST') { + var body = ''; + req.on('data', function(data) { + body += data; + }); + req.on('end', function() { + var parsedBody = JSON.parse(body); + + opts.playbackImpl.record(parsedBody.key, parsedBody.data); + res.writeHead(200); + res.end(); + }); + } else if (req.method == 'GET') { + var data = opts.playbackImpl.playback(); + res.writeHead(200, { + 'Content-Type': 'application/dart', + 'Content-Length': Buffer.byteLength(data) + }); + res.end(data); + } + } +} + +module.exports = { + endpoint: endpoint +}; diff --git a/pool/shard011/JavaScript/0070146_protos.js b/pool/shard011/JavaScript/0070146_protos.js new file mode 100644 index 0000000000000000000000000000000000000000..abf00909e04b29d46463e41f7a82615d807883b7 --- /dev/null +++ b/pool/shard011/JavaScript/0070146_protos.js @@ -0,0 +1,54 @@ +/* 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. + * + * Copyright (c) 2013-2016, Kenneth Leung. All rights reserved. */ + + +"use strict";/** + * @requires zotohlab/asx/online + * @requires zotohlab/asx/msgbox + * @requires zotohlab/asx/ynbox + * @requires zotohlab/asx/asterix + * @requires p/splash + * @requires p/mmenu + * @requires p/game + * @module p/protos + */ + +import online from 'zotohlab/asx/online'; +import msgbox from 'zotohlab/asx/msgbox'; +import ynbox from 'zotohlab/asx/ynbox'; +import sh from 'zotohlab/asx/asterix'; +import splash from 'p/splash'; +import mmenu from 'p/mmenu'; +import arena from 'p/game'; + +let ps= [online, splash, mmenu, msgbox, ynbox, arena], +protos= sh.protos, +sjs= sh.skarojs, +R = sjs.ramda, +undef; + +R.forEach((obj) => { + protos[obj.rtti] = obj; +}, ps); + +/** @alias module:p/protos */ +const xbox = protos; + +sjs.merge(exports, xbox); +/*@@ +return xbox; +@@*/ +////////////////////////////////////////////////////////////////////////////// +//EOF + diff --git a/pool/shard011/JavaScript/0070147_progress_bar.js b/pool/shard011/JavaScript/0070147_progress_bar.js new file mode 100644 index 0000000000000000000000000000000000000000..1408fc5029aa78be4446fa4421001e51b73fc01f --- /dev/null +++ b/pool/shard011/JavaScript/0070147_progress_bar.js @@ -0,0 +1,169 @@ +/** + * DevExtreme (ui/progress_bar.js) + * Version: 16.2.6 + * Build date: Tue Mar 28 2017 + * + * Copyright (c) 2012 - 2017 Developer Express Inc. ALL RIGHTS RESERVED + * EULA: https://www.devexpress.com/Support/EULAs/DevExtreme.xml + */ +"use strict"; +var $ = require("jquery"), + TrackBar = require("./track_bar"), + registerComponent = require("../core/component_registrator"); +var PROGRESSBAR_CLASS = "dx-progressbar", + PROGRESSBAR_CONTAINER_CLASS = "dx-progressbar-container", + PROGRESSBAR_RANGE_CONTAINER_CLASS = "dx-progressbar-range-container", + PROGRESSBAR_RANGE_CLASS = "dx-progressbar-range", + PROGRESSBAR_WRAPPER_CLASS = "dx-progressbar-wrapper", + PROGRESSBAR_STATUS_CLASS = "dx-progressbar-status", + PROGRESSBAR_INDETERMINATE_SEGMENT_CONTAINER = "dx-progressbar-animating-container", + PROGRESSBAR_INDETERMINATE_SEGMENT = "dx-progressbar-animating-segment"; +var ProgressBar = TrackBar.inherit({ + _getDefaultOptions: function() { + return $.extend(this.callBase(), { + value: 0, + statusFormat: function(ratio) { + return "Progress: " + Math.round(100 * ratio) + "%" + }, + showStatus: true, + onComplete: null, + activeStateEnabled: false, + statusPosition: "bottom left", + _animatingSegmentCount: 0 + }) + }, + _defaultOptionsRules: function() { + return this.callBase().concat([{ + device: { + platform: "win" + }, + options: { + _animatingSegmentCount: 5 + } + }, { + device: function(device) { + return "android" === device.platform + }, + options: { + _animatingSegmentCount: 2 + } + }]) + }, + _init: function() { + this.callBase() + }, + _render: function() { + this._createCompleteAction(); + this._renderStatus(); + this.callBase(); + this.element().addClass(PROGRESSBAR_CLASS); + this.setAria("role", "progressbar"); + this._$wrapper.addClass(PROGRESSBAR_WRAPPER_CLASS); + this._$bar.addClass(PROGRESSBAR_CONTAINER_CLASS); + $("
    ").addClass(PROGRESSBAR_RANGE_CONTAINER_CLASS).appendTo(this._$wrapper).append(this._$bar); + this._$range.addClass(PROGRESSBAR_RANGE_CLASS); + this._toggleStatus(this.option("showStatus")) + }, + _createCompleteAction: function() { + this._completeAction = this._createActionByOption("onComplete") + }, + _renderStatus: function() { + this._$status = $("
    ").addClass(PROGRESSBAR_STATUS_CLASS) + }, + _renderIndeterminateState: function() { + this._$segmentContainer = $("
    ").addClass(PROGRESSBAR_INDETERMINATE_SEGMENT_CONTAINER); + var segments = this.option("_animatingSegmentCount"); + for (var i = 0; i < segments; i++) { + $("
    ").addClass(PROGRESSBAR_INDETERMINATE_SEGMENT).addClass(PROGRESSBAR_INDETERMINATE_SEGMENT + "-" + (i + 1)).appendTo(this._$segmentContainer) + } + this._$segmentContainer.appendTo(this._$wrapper) + }, + _toggleStatus: function(value) { + var splitPosition = this.option("statusPosition").split(" "); + if (value) { + if ("top" === splitPosition[0] || "left" === splitPosition[0]) { + this._$status.prependTo(this._$wrapper) + } else { + this._$status.appendTo(this._$wrapper) + } + } else { + this._$status.detach() + } + this._togglePositionClass() + }, + _togglePositionClass: function() { + var position = this.option("statusPosition"), + splitPosition = position.split(" "); + this._$wrapper.removeClass("dx-position-top-left dx-position-top-right dx-position-bottom-left dx-position-bottom-right dx-position-left dx-position-right"); + var positionClass = "dx-position-" + splitPosition[0]; + if (splitPosition[1]) { + positionClass += "-" + splitPosition[1] + } + this._$wrapper.addClass(positionClass) + }, + _toggleIndeterminateState: function(value) { + if (value) { + this._renderIndeterminateState(); + this._$bar.toggle(false) + } else { + this._$bar.toggle(true); + this._$segmentContainer.remove(); + delete this._$segmentContainer + } + }, + _renderValue: function() { + var val = this.option("value"), + max = this.option("max"); + if (!val && 0 !== val) { + this._toggleIndeterminateState(true); + return + } + if (this._$segmentContainer) { + this._toggleIndeterminateState(false) + } + if (val === max) { + this._completeAction() + } + this.callBase(); + this._setStatus() + }, + _setStatus: function() { + var format = this.option("statusFormat"); + if ($.isFunction(format)) { + format = $.proxy(format, this) + } else { + format = function(value) { + return value + } + } + var statusText = format(this._currentRatio, this.option("value")); + this._$status.text(statusText) + }, + _dispose: function() { + this._$status.remove(); + this.callBase() + }, + _optionChanged: function(args) { + switch (args.name) { + case "statusFormat": + this._setStatus(); + break; + case "showStatus": + this._toggleStatus(args.value); + break; + case "statusPosition": + this._toggleStatus(this.option("showStatus")); + break; + case "onComplete": + this._createCompleteAction(); + break; + case "_animatingSegmentCount": + break; + default: + this.callBase(args) + } + } +}); +registerComponent("dxProgressBar", ProgressBar); +module.exports = ProgressBar; +module.exports.default = module.exports; diff --git a/pool/shard011/JavaScript/0070149_setup_img.js b/pool/shard011/JavaScript/0070149_setup_img.js new file mode 100644 index 0000000000000000000000000000000000000000..a44ad34848e8383338261b98f6209342b35ca458 --- /dev/null +++ b/pool/shard011/JavaScript/0070149_setup_img.js @@ -0,0 +1,155 @@ +/* + Copyright 2016-2018 Replay SDK (http://www.replay-sdk.com) + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + 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. +*/ + +var db = require('../routes/db'); // database utilities +var debug = require('debug')('bibliopuce:setup_img'); +var request = require('request'); +var jsdom = require("jsdom"); +var async = require("async"); +var fs = require('fs'); +var mkdirp = require('mkdirp'); +var path = require('path'); +objSQLConnection = db.new_connection(); + +db.runsql("\ +DROP TEMPORARY TABLE IF EXISTS temp_img \n\ +; \n\ +CREATE TEMPORARY TABLE temp_img( \n\ + isbn13 VARCHAR(13) NOT NULL PRIMARY KEY, \n\ + result_json TEXT NOT NULL \n\ +) \n\ +; \n\ +INSERT IGNORE INTO temp_img(isbn13, result_json) \n\ +SELECT SUBSTRING(request, LOCATE('isbn=',request)+5) AS isbn13, CONVERT( UNCOMPRESS( result ) USING 'utf8' ) AS result_json \n\ +FROM log \n\ +WHERE request LIKE 'http://localhost:3000/item/aws%' \n\ +ORDER BY id DESC \n\ +; \n\ +SELECT temp_img.*, item_detail.id AS item_detail_id, item_detail.title \n\ +FROM temp_img \n\ +JOIN item_detail ON item_detail.isbn13 = temp_img.isbn13 \n\ +WHERE item_detail.img_url IS NULL \n\ +; \n\ +DROP TEMPORARY TABLE IF EXISTS temp_img \n\ +; \n\ +" /* strSQL */, + function(err, arrRows, fields) { + if (err) + { + if (objSQLConnection) + { + objSQLConnection.end(); + } + throw err; + } + var rows = db.rows(arrRows); + + async.eachLimit(rows, 1, function (row, callback) { + + var strISBN13 = row.isbn13; + var intItemDetailId = row.item_detail_id; + var strTitle = row.title; + if (strISBN13) + { + debug("isbn13 = %s", strISBN13); + var objResult = JSON.parse(row.result_json); + if (objResult) + { + // debug("objResult = %j", objResult); + if (objResult.ItemLookupResponse && objResult.ItemLookupResponse.Items && objResult.ItemLookupResponse.Items.Item && objResult.ItemLookupResponse.Items.Item.DetailPageURL) + { + var strDetailsURL = objResult.ItemLookupResponse.Items.Item.DetailPageURL; + // debug("strDetailsURL=%s",strDetailsURL); + // console.log("Downloading Book URL "+strDetailsURL); + request({url : strDetailsURL}, + function(err, res, body) { + if (err) + { + console.log("ERROR: Can't download URL %s for %s %s : %s", strDetailsURL, strISBN13, strTitle, err); + } + else + { + console.log("Book Page downloaded for %s %s ", strISBN13, strTitle); + // Fetch img URL from HTML + jsdom.env( + body, + ["http://code.jquery.com/jquery.js"], + function (err, window) { + if (err) + { + console.log("ERROR: Can't parse HTML for %s %s : %s", strISBN13, strTitle, err); + } + else + { + var strImageLink = window.$("img[id='imgBlkFront']").attr("src"); + console.log("src of img.id=imgBlkFront = %s", strImageLink); + if (strImageLink && strImageLink.match(/^https?\:/)) + { + db.runsql("UPDATE item_detail SET img_url = "+objSQLConnection.escape(strImageLink)+" WHERE id = "+intItemDetailId.toString(10)+";", + function(err, arrRows, fields) { + if (err) + { + console.log("ERROR: Can't update item_detail for %s %s : %s", strISBN13, strTitle, err); + } + // Download and save image in cache (public/img/item/00/00/00/00/0000000001.jpg) + var strImageFolder = db.img_folder(intItemDetailId); + var strImageFilePath = db.img_file(intItemDetailId, path.extname(strImageLink)); + console.log("Cache image file : \"%s\"", strImageFilePath); + mkdirp.sync(strImageFolder); + request.head(strImageLink, function(err, res, body){ + if (err) + { + console.log("ERROR: Can't download image %s for %s %s : %s", strImageLink, strISBN13, strTitle, err); + } + else + { + console.log("Book Image downloaded for %s %s ", strISBN13, strTitle); + console.log('content-type:', res.headers['content-type']); + console.log('content-length:', res.headers['content-length']); + request(strImageLink).pipe(fs.createWriteStream(strImageFilePath)); + } + }); + }); + } // if (strImageLink && strImageLink.match(/^https?\:/)) + else + { + console.log("ERROR: Can't find img.id=imgBlkFront in HTML for %s %s (%s)", strISBN13, strTitle, strDetailsURL); + } // if (strImageLink && strImageLink.match(/^https?\:/)) + + } + } + ); + } // else if (err) + } + ); + } // if (objResult.ItemLookupResponse && objResult.ItemLookupResponse.Items && objResult.ItemLookupResponse.Items.Item && objResult.ItemLookupResponse.Items.Item.DetailPageURL) + else + { + console.log("ERROR: Invalid Web Service result for %s %s (no DetailPageURL)", strISBN13, strTitle); + } // // if (objResult.ItemLookupResponse && objResult.ItemLookupResponse.Items && objResult.ItemLookupResponse.Items.Item && objResult.ItemLookupResponse.Items.Item.DetailPageURL) + } // if (objResult) + } // if (strISBN13) + + // Pause 1.5s to avoid being blocked by source + setTimeout(function() { + callback(); + }, 1500); + + }, function done() { +// process.exit(0); + }); + + }, objSQLConnection); diff --git a/pool/shard011/JavaScript/0070151_Particle.js b/pool/shard011/JavaScript/0070151_Particle.js new file mode 100644 index 0000000000000000000000000000000000000000..60f378b75f427fb630febd740996d071f17c8a09 --- /dev/null +++ b/pool/shard011/JavaScript/0070151_Particle.js @@ -0,0 +1,49 @@ +import * as THREE from 'three'; +import { TweenMax, Power2 } from 'gsap'; +import { particlesPool } from '../config'; + +class Particle { + constructor() { + const geom = new THREE.TetrahedronGeometry(3, 0); + const mat = new THREE.MeshPhongMaterial({ + color: 0x009999, + shininess: 0, + specular: 0xffffff, + shading: THREE.FlatShading, + }); + this.mesh = new THREE.Mesh(geom, mat); + } + + explode(pos, color, scale) { + const self = this; + const p = this.mesh.parent; + this.mesh.material.color = new THREE.Color(color); + this.mesh.material.needsUpdate = true; + this.mesh.scale.set(scale, scale, scale); + const targetX = pos.x + (-1 + Math.random() * 2) * 50; + const targetY = pos.y + (-1 + Math.random() * 2) * 50; + const speed = 0.6 * Math.random() * 0.2; + TweenMax.to(this.mesh.rotation, speed, { + x: Math.random() * 12, + y: Math.random() * 12, + }); + TweenMax.to(this.mesh.scale, speed, { + x: 0.1, + y: 0.1, + z: 0.1, + }); + TweenMax.to(this.mesh.position, speed, { + x: targetX, + y: targetY, + delay: Math.random() * 0.1, + ease: Power2.easeOut, + onComplete() { + if (p) p.remove(self.mesh); + self.mesh.scale.set(1, 1, 1); + particlesPool.unshift(self); + }, + }); + } +} + +export default Particle; diff --git a/pool/shard011/JavaScript/0070152_getJsonFromTypedArraySpec.js b/pool/shard011/JavaScript/0070152_getJsonFromTypedArraySpec.js new file mode 100644 index 0000000000000000000000000000000000000000..02257e193fcc1b714566ca877806f845ddba196c --- /dev/null +++ b/pool/shard011/JavaScript/0070152_getJsonFromTypedArraySpec.js @@ -0,0 +1,45 @@ +import { getJsonFromTypedArray } from "../../Source/Cesium.js"; + +describe("Core/getJsonFromTypedArray", function () { + it("converts a typed array to string", function () { + if (TextEncoder === undefined) { + return; + } + + var json = { + a: [0, 1, 2], + b: "b", + c: { + d: true, + }, + }; + + var string = JSON.stringify(json); + var encoder = new TextEncoder(); + var typedArray = encoder.encode(string); + var result = getJsonFromTypedArray(typedArray); + + expect(result).toEqual(json); + }); + + it("converts a sub-region of a typed array to json", function () { + if (TextEncoder === undefined) { + return; + } + + var json = { + a: [0, 1, 2], + b: "b", + c: { + d: true, + }, + }; + + var string = JSON.stringify(json); + var encoder = new TextEncoder(); + var typedArray = encoder.encode(string); + var result = getJsonFromTypedArray(typedArray, 25, 10); + + expect(result).toEqual(json.c); + }); +}); diff --git a/pool/shard011/JavaScript/0070154_FrequenciesByTopicAggregator.js b/pool/shard011/JavaScript/0070154_FrequenciesByTopicAggregator.js new file mode 100644 index 0000000000000000000000000000000000000000..5c1a4ae205e90d02659e406a6e035d3eccb3f0c2 --- /dev/null +++ b/pool/shard011/JavaScript/0070154_FrequenciesByTopicAggregator.js @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2013 Oculus Info Inc. + * http://www.oculusinfo.com/ + * + * Released under the MIT License. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + * of the Software, and to permit persons to whom the Software is furnished to do + * so, subject to the following conditions: + + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ + +( function() { + + "use strict"; + + var Aggregator = require('./Aggregator'), + Util = require('../../../util/Util'); + + /** + * Instantiate a FrequenciesByTopicAggregator object. + * @class FrequenciesByTopicAggregator + * @classdesc + */ + function FrequenciesByTopicAggregator() { + } + + FrequenciesByTopicAggregator.prototype = Object.create( Aggregator.prototype ); + + /** + * Given an array of buckets, will execute the provided aggregation + * specification against all relevant entries. + * @memberof FrequenciesByTopicAggregator + * + * @param {Array} buckets - The array of buckets. + * + * @returns {Array} The aggregated buckets. + */ + FrequenciesByTopicAggregator.prototype.aggregate = function( buckets ) { + var frequenciesByTopic = {}, + range = this.getBucketRange( buckets ), + bucketCount = range.end - range.start + 1; + this.forEach( + buckets, + function( bucket, index ) { + var topic, + i; + if ( bucket ) { + for ( i=0; i { + it('extracts authorities from jwt token prefixed with `Bearer`', () => { + const payload = btoa(JSON.stringify({ + sub: 'AUSER', + deviceFingerprintHashCode: -656086319, + allowRefreshToken: false, + userPrincipal: { + username: 'AUSER', + authorities: [{ authority: 'ROLE_A' }, { authority: 'ROLE_B' }], + }, + iss: 'http://www.foo.net', + iat: 1508507284, + exp: 1508509084, + })); + + const algorithm = btoa(JSON.stringify({ alg: 'HS512' })); + const aToken = `Bearer ${algorithm}.${payload}.zzz`; + + expect(extractAuthoritiesFrom(aToken)).to.eql([ + { authority: 'ROLE_A' }, + { authority: 'ROLE_B' }, + ]); + }); + + it('extracts authorities from jwt token', () => { + const payload = btoa(JSON.stringify({ + sub: 'AUSER', + deviceFingerprintHashCode: -656086319, + allowRefreshToken: false, + userPrincipal: { + username: 'AUSER', + authorities: [{ authority: 'ROLE_A' }, { authority: 'ROLE_B' }], + }, + iss: 'http://www.foo.net', + iat: 1508507284, + exp: 1508509084, + })); + + const algorithm = btoa(JSON.stringify({ alg: 'HS512' })); + const aToken = `${algorithm}.${payload}.zzz`; + + expect(extractAuthoritiesFrom(aToken)).to.eql([ + { authority: 'ROLE_A' }, + { authority: 'ROLE_B' }, + ]); + }); +}); diff --git a/pool/shard011/JavaScript/0070162_customer.js b/pool/shard011/JavaScript/0070162_customer.js new file mode 100644 index 0000000000000000000000000000000000000000..3a2d070913ab439eb756c5967da611606b6c7093 --- /dev/null +++ b/pool/shard011/JavaScript/0070162_customer.js @@ -0,0 +1,240 @@ +$(document).ready( + function() { + + var timer; + var doAutoRefresh = false; + + __init(); + + function __init() { + $('#servers-add .btn-info').click(function() { + addServer($('#host').val(), $('#port').val()); + $("#host,#port").val(''); + $('#servers-add').modal('hide'); + window.location.href = window.location.href; + return false; + }); + $('#addJob').on('click', function() { + $('#modalAddJob').modal('toggle'); + return false; + }); + $('#filter input[type=checkbox]').click(function() { + $('table') + .find('[name=' + $(this).attr('name') + ']') + .toggle($(this).is(':checked')); + var names = []; + $('#filter input:checked').each(function() { + names.push($(this).attr('name')); + }); + $.cookie($('#filter').data('cookie'), names, {expires: 365}); + $('.row-full').attr('colspan', names.length); + }); + + $('#tubeSave').on('click', function() { + var result = addNewJob(); + + if (result == 'empty') { + $('#tubeSaveAlert').fadeIn('fast'); + } else { + $('#modalAddJob').modal('toggle'); + } + + return false; + }); + + $('#autoRefresh').on('click', function() { + if (!$('#autoRefresh').hasClass('btn-success')) { + reloader(); + $('#autoRefresh').toggleClass('btn-success'); + $('#autoRefresh i').toggleClass('icon-white'); + } else { + clearTimeout(timer); + doAutoRefresh = false; + $('#autoRefresh').toggleClass('btn-success'); + $('#autoRefresh i').toggleClass('icon-white'); + } + + return false; + }); + + if (contentType == 'json') { + var cn = $('pre code').html(); + var jn = formatJson(cn); + $('pre code').html(jn); + } + $('#clearTubesSelect').on('click', function() { + $('#clear-tubes input[type=checkbox]:regex(name,' + $("#tubeSelector").val() + ')').prop('checked', true); + $.cookie("tubeSelector", $("#tubeSelector").val(), { + expires: 365 + }); + $('#clearTubes').text('Clear ' + $('#clear-tubes input[type=checkbox]:checked').length + ' selected tubes'); + }); + $('#clearTubes').on('click', function() { + clearTubes(); + }); + } + + function addServer(host, port) { + if (host) { + myCoockie = $.cookie("beansServers"); + if (myCoockie == null) { + server = host + ":" + port; + } else { + server = myCoockie + ";" + host + ":" + port; + } + $.cookie("beansServers", server, { + expires: 365 + }); + } else { + alert("Some fields empty.."); + } + } + + function addNewJob() { + + if (!$('#tubeName').val() || !$('#tubeData').val()) { + return 'empty'; + } + + var params = { + 'tubeName': $('#tubeName').val(), + 'tubeData': $('#tubeData').val(), + 'tubePriority': $('#tubePriority').val(), + 'tubeDelay': $('#tubeDelay').val(), + 'tubeTtr': $('#tubeTtr').val() + } + + $.ajax({ + 'url': url + '&action=addjob', + 'data': params, + 'success': function(data) { + var result = data.result; + cleanFormNewJob(); + location.reload(); + }, + 'type': 'POST', + 'dataType': 'json', + 'error': function() { + console.log('error ajax...'); + } + }); + } + + function cleanFormNewJob() { + // $('#tubeName').val(''); + $('#tubeData').val(''); + $('#tubePriority').val(''); + $('#tubeDelay').val(''); + $('#tubeTtr').val(''); + } + + function formatJson(val) { + + var retval = ''; + var str = val; + var pos = 0; + var strLen = str.length; + var indentStr = ' '; + var newLine = "\n"; + var char = ''; + + for (var i = 0; i < strLen; i++) { + char = str.substring(i, i + 1); + nextChar = str.substring(i + 1, i + 2); + if ((char == '}' || char == ']') && nextChar != newLine) { + + retval = retval + newLine; + pos = pos - 1; + for (var j = 0; j < pos; j++) { + retval = retval + indentStr; + } + } + retval = retval + char; + + if ((char == '{' || char == '[' || char == ',') && nextChar != newLine) { + retval = retval + newLine; + if (char == '{' || char == '[') { + pos = pos + 1; + } + + for (var k = 0; k < pos; k++) { + retval = retval + indentStr; + } + } + } + + return retval; + + } + + function reloader() { + var params = { + 'action': 'reloader', + 'tplMain': 'ajax', + 'tplBlock': 'allTubes', + 'secondary': new Date().getTime() + } + var res; + + doAutoRefresh = true; + $.ajax({ + 'url': url, + 'data': params, + 'success': function(data) { + if (doAutoRefresh) { + // wrapping all of this to prevent last update + // after you turn it off + var html = $('#idAllTubes').html(); + $('#idAllTubes').html(data); + $('#idAllTubesCopy').html(html); + updateTable(); + timer = setTimeout(reloader, 500); + } + }, + 'type': 'GET', + 'dataType': 'html', + 'error': function() { + console.log('error ajax...'); + } + }); + } + + function updateTable() { + var td1 = $('#idAllTubes table').find('td'), td2 = $('#idAllTubesCopy table').find('td'); + for (i = 0, il = td1.length; i < il; i++) { + if (typeof td2[i] === 'undefined' || typeof td1[i] === 'undefined') { // tube is missing + continue; + } + var l = td1[i].innerText || td1[i].innerHTML || td1[i].textContent; + var r = td2[i].innerText || td2[i].innerHTML || td2[i].textContent; + if (l != r) { + var $td1 = $(td1[i]), color = $td1.css('background-color'); + $td1.css({ + 'background-color': '#afa' + }).animate({ + 'background-color': color + }, 500); + } + } + } + + function clearTubes() { + if ($('#clear-tubes input[type=checkbox]:checked').length === 0) { + return; + } + + $.ajax({ + 'url': url + '&action=clearTubes', + 'data': $('#clear-tubes input[type=checkbox]:checked').serialize(), + 'success': function(data) { + var result = data.result; + location.reload(); + }, + 'type': 'POST', + 'error': function() { + alert('error from ajax (clear might take a while, be patient)...'); + } + }); + } + } +); diff --git a/pool/shard011/JavaScript/0070164_suggestions.js b/pool/shard011/JavaScript/0070164_suggestions.js new file mode 100644 index 0000000000000000000000000000000000000000..969c7e7e1524b51653d27045a36bc28bc4021793 --- /dev/null +++ b/pool/shard011/JavaScript/0070164_suggestions.js @@ -0,0 +1,50 @@ +/* global $ */ +$(function() { + 'use strict'; + + var $form = $('form.new_suggestion'); + var $submit = $form.find('.submit-button'); + var booleans = [ + 'missing_fields', 'incorrect_fields', 'duplicate_profile', + 'inappropriate_content', 'person_left' + ]; + + // Show or hide the submit button based on checked fields + // Show if any are checked, hide if all unchecked + var showHideSubmit = function() { + $submit.hide(); + for (var i in booleans) { + var field = booleans[i]; + if ($form.find('input[name="suggestion[' + field + ']"]'). + is(':checked')) { + $submit.show(); + } + } + }; + + // Show or hide the extra info fields for all checkboxes + // Show if it's checked, hide if unchecked + var showHideInfo = function() { + $form.find('input[type="checkbox"]').each(function() { + var $checkbox = $(this); + var targetSelector = $checkbox.attr('target'); + if ($checkbox.is(':checked')) { + $(targetSelector).show(); + } else { + $(targetSelector).hide(); + } + }); + }; + + var updateForm = function() { + showHideSubmit(); + showHideInfo(); + }; + + // Update the form when any input on the form changes + $form.on('change', 'input', updateForm); + + // Update the form on page load + updateForm(); + +}); diff --git a/pool/shard011/JavaScript/0070166_mergeDecoratorDocs.js b/pool/shard011/JavaScript/0070166_mergeDecoratorDocs.js new file mode 100644 index 0000000000000000000000000000000000000000..86571ea5faaa93e921af8234dca500f9be756d7c --- /dev/null +++ b/pool/shard011/JavaScript/0070166_mergeDecoratorDocs.js @@ -0,0 +1,124 @@ +/** + * Decorators in the Angular code base are made up from three code items: + * + * 1) An interface that represents the call signature of the decorator. E.g. + * + * ``` + * export interface ComponentDecorator { + * (obj: Component): TypeDecorator; + * new (obj: Component): Component; + * } + * ``` + * + * 2) An interface that represents the members of the object that should be passed + * into the decorator. E.g. + * + * ``` + * export interface Component extends Directive { + * changeDetection?: ChangeDetectionStrategy; + * viewProviders?: Provider[]; + * templateUrl?: string; + * ... + * } + * ``` + * + * 3) A constant that is created by a call to a generic function, whose type parameter is + * the call signature interface of the decorator. E.g. + * + * ``` + * export const Component: ComponentDecorator = + * makeDecorator('Component', { ... }, Directive) + * ``` + * + * This processor searches for these constants (3) by looking for a call to + * `make...Decorator(...)`. (There are variations to the call for property and param + * decorators). From this call we identify the `decoratorType` (e.g. `ComponentDecorator`). + * + * Calls to `make...Decorator` will return an object of type X. This type is the document + * referred to in (2). This is the primary doc that we care about for documenting the decorator. + * It holds all of the members of the metadata that is passed to the decorator call. + * + * Finally we want to capture the documentation attached to the call signature interface of the + * associated decorator (1). We copy across the properties that we care about from this call + * signature (e.g. description, whatItDoes and howToUse). + */ + +module.exports = function mergeDecoratorDocs(log) { + return { + $runAfter: ['processing-docs'], + $runBefore: ['docs-processed'], + makeDecoratorCalls: [ + {type: '', description: 'toplevel', functionName: 'makeDecorator'}, + {type: 'Prop', description: 'property', functionName: 'makePropDecorator'}, + {type: 'Param', description: 'parameter', functionName: 'makeParamDecorator'}, + ], + $process: function(docs) { + + var makeDecoratorCalls = this.makeDecoratorCalls; + var docsToMerge = Object.create(null); + + docs.forEach(function(doc) { + const initializer = getInitializer(doc); + if (initializer) { + makeDecoratorCalls.forEach(function(call) { + // find all the decorators, signified by a call to `make...Decorator(metadata)` + if (initializer.expression && initializer.expression.text === call.functionName) { + log.debug('mergeDecoratorDocs: found decorator', doc.docType, doc.name); + doc.docType = 'decorator'; + doc.decoratorLocation = call.description; + // Get the type of the decorator metadata from the first "type" argument of the call. + // For example the `X` of `createDecorator(...)`. + doc.decoratorType = initializer.arguments[0].text; + // clear the symbol type named since it is not needed + doc.symbolTypeName = undefined; + + // keep track of the names of the metadata interface that will need to be merged into this decorator doc + docsToMerge[doc.name + 'Decorator'] = doc; + } + }); + } + }); + + // merge the metadata docs into the decorator docs + docs = docs.filter(function(doc) { + if (docsToMerge[doc.name]) { + // We have found an `XxxDecorator` document that will hold the call signature of the decorator + var decoratorDoc = docsToMerge[doc.name]; + var callMember = doc.members.filter(function(member) { return member.isCallMember; })[0]; + log.debug( + 'mergeDecoratorDocs: merging', doc.name, 'into', decoratorDoc.name, + callMember.description.substring(0, 50)); + // Merge the documentation found in this call signature into the original decorator + decoratorDoc.description = callMember.description; + decoratorDoc.usageNotes = callMember.usageNotes; + + // remove doc from its module doc's exports + doc.moduleDoc.exports = + doc.moduleDoc.exports.filter(function(exportDoc) { return exportDoc !== doc; }); + + + // remove from the overall list of docs to be rendered + return false; + } + return true; + }); + } + }; +}; + +function getInitializer(doc) { + var initializer = doc.symbol && doc.symbol.valueDeclaration && doc.symbol.valueDeclaration.initializer; + // There appear to be two forms of initializer: + // export var Injectable: InjectableFactory = + // makeDecorator(InjectableMetadata); + // and + // export var RouteConfig: (configs: RouteDefinition[]) => ClassDecorator = + // makeDecorator(RouteConfigAnnotation); + // In the first case, the type assertion `` causes the AST to contain an + // extra level of expression + // to hold the new type of the expression. + if (initializer && initializer.expression && initializer.expression.expression) { + initializer = initializer.expression; + } + return initializer; +} diff --git a/pool/shard011/JavaScript/0070167_templater.js b/pool/shard011/JavaScript/0070167_templater.js new file mode 100644 index 0000000000000000000000000000000000000000..8ea66a32d8df67101d398cae65e584010c672f60 --- /dev/null +++ b/pool/shard011/JavaScript/0070167_templater.js @@ -0,0 +1,156 @@ +/*! + * templater.js v3.0.1 - Minimal JavaScript templating. + * On the web at https://pinjasaur.github.io/templater.js/ + * Written by Paul Esch-Laurent + * Licensed under MIT + */ +(function() { + + "use strict"; + + function templater(template) { + + /** + * Resolves values for an object given a property in dot-notation form. + * @param {Object} haystack The object to search + * @param {String} needle The property to search for + * @return {*} The value found + */ + function resolve(haystack, needle) { + + if (haystack[needle]) { + + return haystack[needle]; + + } else { + + var needles = needle.split("."), + prop = needles.shift(); + + if (haystack[prop]) { + return resolve(haystack[prop], needles.join(".")); + } + + return null; + + } + } + + /** + * Traverses an object and returns all properties in dot-notation form. + * @param {Object} obj Object to traverse + * @param {Array} arr Array to push properties to + * @param {String} ctx Current object context (used in recursive calls) + * @return None + */ + function traverse(obj, arr, ctx) { + + for (var prop in obj) { + + if (typeof obj[prop] !== "object") { + arr.push((ctx !== undefined) ? ctx + "." + prop : prop); + } else { + traverse(obj[prop], arr, (ctx !== undefined) ? ctx + "." + prop : prop); + } + + } + } + + // return a function to use the replacement values + return function(data) { + + // regex for the #if, body, /if + var start = "{{\\s?#if\\s+(!)?\\((.+)\\)\\s?}}", + end = "{{\\s?/if\\s?}}", + regex = start + "[\\s\\S]+?" + end, + // save a reference to the template so it can be restored at the end + tmpl = template, + props = [], + match; + + // get all properties with values + traverse(data, props); + + // keep matching conditions until there are none + while (match = new RegExp(regex, "g").exec(template)) { + + // assume it meets all conditions + var meetsConditions = true; + + // if a match for /(!)?/ was found, it's `notted` + var notted = !!match[1]; + + // remove all whitespace between conditions, split on commas + var conditions = match[2].replace(/\s+/g, "").split(","); + + // check each condition to see if it's truthy + for (var i = 0; i < conditions.length; i++) { + // if it isn't, break out + if (!resolve(data, conditions[i])) { + meetsConditions = false; + break; + } + } + + // perform an XOR operation based on if the #if was notted (!) and + // whether all the arguments were `truthy` + meetsConditions = notted ^ meetsConditions; + + // check if it doesn't meet the conditions + if (!meetsConditions) { + // wipe the #if, /if, and body if it doesn't + template = template.split(match[0]).join(""); + } else { + // otherwise just get rid of the #if and /if statements + var open = new RegExp(start, "g"), + close = new RegExp(end, "g"); + + // beginning of the template + template = template.substring(0, match["index"]) + // body of the condition + + match[0].replace(open, "").replace(close, "") + // end of the template + + template.substring(match["index"] + match[0].length, template.length); + } + } + + // loop through each property of the data + props.forEach(function(prop) { + // create the regex to match the '{{ prop }}' format + regex = "{{\\s?" + prop + "\\s?}}"; + + // get the value depending on type, casted to string + var value = resolve(data, prop); + value = String((typeof value === "function") ? value() : value); + + // replace the instances in the template with the property value + // (escaping characters if necessary) + template = template.replace(new RegExp(regex, "g"), value.replace(/[&<>"']/g, function(tag) { + // characters mapped to their entities + var replacements = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + + return replacements[tag] || tag; + })); + }); + + // set the template back to its original state (so it can be used again) + var ret = template; + template = tmpl; + return ret; + } + } + + // expose templater globally (to `window` or `module.exports`) + if (typeof module !== "undefined" && typeof module.exports !== "undefined") { + module.exports = templater; + } else { + window.templater = templater; + } + +})(); diff --git a/pool/shard011/JavaScript/0070171_filters.js b/pool/shard011/JavaScript/0070171_filters.js new file mode 100644 index 0000000000000000000000000000000000000000..da091f7ab601fde4c16d2e28f057bfe315e31bc2 --- /dev/null +++ b/pool/shard011/JavaScript/0070171_filters.js @@ -0,0 +1,64 @@ +(function (Filter) { + 'use strict'; + + let constants = require('./constants'), + controller = require('./controller'); + + /** + * Hook to render a user profile. + * 'userData' will be used as payload in hook handler. + * + * @param {object} payload structure {userData: userData, uid: callerUID} + * @param {function} callback + */ + Filter.account = function (payload, callback) { + controller.getAccountWithRewards(payload.userData, function (error, account) { + if (error) { + return callback(error); + } + payload.userData = account; + callback(null, payload); + }); + }; + + Filter.menuAdmin = function (header, callback) { + header.plugins.push({ + route: '/plugins/awards', + icon : 'fa-trophy', + name : 'Awards' + }); + callback(null, header); + }; + + Filter.navigation = function (items, callback) { + items.push({ + route : constants.CLIENT_PAGE_PATH, + title : 'Awards', + enabled : true, + iconClass: 'fa-trophy', + textClass: 'visible-xs-inline', + text : 'Awards' + }); + callback(null, items); + }; + + /** + * Hook to render a topic thread + * + * @param {object} payload fields: {posts: posts, uid: uid} + * @param {function} callback + */ + Filter.getPosts = function (payload, callback) { + // Remove purged posts + let posts = payload.posts.filter(post => post !== null); + + controller.getPostsWithRewards(posts, function (error, posts) { + if (error) { + return callback(error); + } + payload.posts = posts; + callback(null, payload); + }); + }; + +})(module.exports); diff --git a/pool/shard011/JavaScript/0070175_test.js b/pool/shard011/JavaScript/0070175_test.js new file mode 100644 index 0000000000000000000000000000000000000000..5ec41d32b17be3223841d286682adb872800ecf8 --- /dev/null +++ b/pool/shard011/JavaScript/0070175_test.js @@ -0,0 +1,27 @@ +var expect = require('chai').expect; +var errorInEachBrowserContains = require('../../../../assertion-helper.js').errorInEachBrowserContains; + +describe('[Raw API] Type action', function () { + it('Should type in an input', function () { + return runTests('./testcafe-fixtures/type.testcafe', 'Type in simple input', { shouldFail: true }) + .catch(function (errs) { + errorInEachBrowserContains(errs, 'Type in input raised', 0); + }); + }); + + it("Should fail if a 'text' argument does not have string type", function () { + return runTests('./testcafe-fixtures/type.testcafe', 'Type with numeric text argument', { shouldFail: true }) + .catch(function (errs) { + expect(errs[0]).contains('The "text" argument is expected to be a non-empty string, but it was number.'); + expect(errs[0]).contains('[[Type with numeric text argument callsite]]'); + }); + }); + + it("Should fail if a 'text' argument is empty", function () { + return runTests('./testcafe-fixtures/type.testcafe', 'Type with empty text argument', { shouldFail: true }) + .catch(function (errs) { + expect(errs[0]).contains('The "text" argument is expected to be a non-empty string, but it was "".'); + expect(errs[0]).contains('[[Type with empty text argument callsite]]'); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070176_data.js b/pool/shard011/JavaScript/0070176_data.js new file mode 100644 index 0000000000000000000000000000000000000000..d1dd5e579e1943b8ffab18908a450c43dff55e1d --- /dev/null +++ b/pool/shard011/JavaScript/0070176_data.js @@ -0,0 +1,48 @@ +vg.parse.data = function(spec, callback) { + var model = { + defs: spec, + load: {}, + flow: {}, + source: {} + }; + + var count = 0; + + function load(d) { + return function(error, data) { + if (error) { + vg.error("LOADING FAILED: " + d.url); + } else { + model.load[d.name] = vg.data.read(data, d.format); + } + if (--count === 0) callback(); + } + } + + (spec || []).forEach(function(d) { + if (d.url) { + count += 1; + vg.data.load(d.url, load(d)); + } + + if (d.values) { + if (d.format && d.format.parse) { + // run specified value parsers + vg.data.read.parse(d.values, d.format.parse); + } + model.load[d.name] = d.values; + } + + if (d.source) { + var list = model.source[d.source] || (model.source[d.source] = []); + list.push(d.name); + } + + if (d.transform) { + model.flow[d.name] = vg.parse.dataflow(d); + } + }); + + if (count === 0) setTimeout(callback, 1); + return model; +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070177_unallowed-properties.js b/pool/shard011/JavaScript/0070177_unallowed-properties.js new file mode 100644 index 0000000000000000000000000000000000000000..74303f3afc36a289181cd81982b60b3886b5e511 --- /dev/null +++ b/pool/shard011/JavaScript/0070177_unallowed-properties.js @@ -0,0 +1,81 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.ensureCollectionNameValid = ensureCollectionNameValid; +exports.ensureDatabaseNameIsValid = ensureDatabaseNameIsValid; +exports.validateDatabaseName = validateDatabaseName; + +var _rxError = require("../../rx-error"); + +var _entityProperties = require("./entity-properties"); + +var _util = require("../../util"); + +/** + * if the name of a collection + * clashes with a property of RxDatabase, + * we get problems so this function prohibits this + */ +function ensureCollectionNameValid(args) { + if ((0, _entityProperties.rxDatabaseProperties)().includes(args.name)) { + throw (0, _rxError.newRxError)('DB5', { + name: args.name + }); + } + + validateDatabaseName(args.name); +} + +function ensureDatabaseNameIsValid(args) { + validateDatabaseName(args.name); + /** + * The server-plugin has problems when a path with and ending slash is given + * So we do not allow this. + * @link https://github.com/pubkey/rxdb/issues/2251 + */ + + if ((0, _util.isFolderPath)(args.name)) { + if (args.name.endsWith('/') || args.name.endsWith('\\')) { + throw (0, _rxError.newRxError)('DB11', { + name: args.name + }); + } + } +} + +var validCouchDBStringRegexStr = '^[a-z][_$a-z0-9\\-]*$'; +var validCouchDBStringRegex = new RegExp(validCouchDBStringRegexStr); +/** + * Validates that a given string is ok to be used with couchdb-collection-names. + * We only allow these strings as database- or collection names because it ensures + * that you later do not get in troubble when you want to use the database together witch couchdb. + * + * @link https://docs.couchdb.org/en/stable/api/database/common.html + * @link https://neighbourhood.ie/blog/2020/10/13/everything-you-need-to-know-about-couchdb-database-names/ + * @throws {RxError} + */ + +function validateDatabaseName(name) { + if (typeof name !== 'string' || name.length === 0) { + throw (0, _rxError.newRxTypeError)('UT1', { + name: name + }); + } // do not check, if foldername is given + + + if ((0, _util.isFolderPath)(name)) { + return true; + } + + if (!name.match(validCouchDBStringRegex)) { + throw (0, _rxError.newRxError)('UT2', { + regex: validCouchDBStringRegexStr, + givenName: name + }); + } + + return true; +} +//# sourceMappingURL=unallowed-properties.js.map \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070182_home.js b/pool/shard011/JavaScript/0070182_home.js new file mode 100644 index 0000000000000000000000000000000000000000..6e4a416d82e422250cf10d8be2a86eaf1ff2a50c --- /dev/null +++ b/pool/shard011/JavaScript/0070182_home.js @@ -0,0 +1,88 @@ +/** + * Each section of the site has its own module. It probably also has + * submodules, though this boilerplate is too simple to demonstrate it. Within + * 'src/app/home', however, could exist several additional folders representing + * additional modules that would then be listed as dependencies of this one. + * For example, a 'note' section could have the submodules 'note.create', + * 'note.delete', 'note.edit', etc. + * + * Regardless, so long as dependencies are managed correctly, the build process + * will automatically take take of the rest. + */ +(function(app) { + + app.config(function ($stateProvider) { + $stateProvider.state('home', { + url: '/home', + views: { + "main": { + controller: 'HomeController', + templateUrl: 'home/home.tpl.html' + } + }, + data:{ pageTitle: 'SaltySea Home' } + }); + }); + + // As you add controllers to a module and they grow in size, feel free to place them in their own files. + // Let each module grow organically, adding appropriate organization and sub-folders as needed. + app.controller('HomeController', ['$scope', '$rootScope', '$state', 'Droplet', 'configService', 'BulkActions', function ($scope, $rootScope, $state, Droplet, configService, BulkActions) { + + + $scope.config = configService; + + $scope.bulk_actions_list = [ + {name: 'Delete', warning: "Will all be deleted", action: function(selected_droplets) { var bulk = new BulkActions(selected_droplets); bulk.delete();}}, + ]; + $scope.selected_bulk_action = null; + var init = function() { + + + if (!$scope.config.keys.digital_ocean || !$scope.config.keys.salt || !$scope.config.urls.salt) { + + $state.go('setup'); + } + else { + $scope.droplet_resource = new Droplet(configService.keys.digital_ocean).query(); + + } + }; + $scope.takeBulkAction = function () { + var droplets_to_act_upon = []; + angular.forEach($scope.droplet_resource.droplets, function(d, i){ + if (d.selected) { + droplets_to_act_upon.push(d); + } + }); + + if (droplets_to_act_upon.length > 0) { + var confirm_text = "Are you sure you want to do this?\n\n"; + angular.forEach(droplets_to_act_upon, function (d, i) { + confirm_text += d.name + "\n"; + }); + confirm_text += "\n" + $scope.selected_bulk_action.warning; + + if (confirm(confirm_text)) { + $scope.selected_bulk_action.action(droplets_to_act_upon); + $state.transitionTo($state.current, { + reload: true, + inherit: false, + notify: true + }); + } + } + else { + alert("No droplets were selected"); + } + + }; + init(); + }]); + +// The name of the module, followed by its dependencies (at the bottom to facilitate enclosure) +}(angular.module("salty-sea.home", [ + 'ui.router', + 'dropletService', + 'configService', + 'bulkActions' +]))); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070184_play_20170606144034.js b/pool/shard011/JavaScript/0070184_play_20170606144034.js new file mode 100644 index 0000000000000000000000000000000000000000..b747ee6ceaf4dedcb99c183d144f2a3719ff9039 --- /dev/null +++ b/pool/shard011/JavaScript/0070184_play_20170606144034.js @@ -0,0 +1,116 @@ +var playState = { + + create: function(){ + var background = game.add.sprite(0, 0, 'cidade'); + background.width = 1300; + background.height = 650; + + graphics = game.add.graphics(0, 0); + + groupCidade = game.add.group(); + + groupCidade.inputEnableChildren = true; + + var x = 100; + + for (var i = 0; i < 3; i++){ + // Gera os retangulos que ficarão atras das imagens + graphics.beginFill(0xFFFFFF); + graphics.lineStyle(3, 0x05005e, 1); + graphics.drawRoundedRect(x, 200, 315, 190, 10); + graphics.endFill(); + + var button = groupCidade.create(x, 200, graphics.generateTexture()); + button.tint = 0xff8800; + button.name = 'groupCidade-child-' + i; + + x = x + 400; + } + graphics.destroy(); + + var cachorro = game.add.sprite(110, 210, 'cachorro'); + cachorro.width = 300; + cachorro.height = 170; + + + // Desenha o gato e a borda da box + + var gato = game.add.sprite(510, 210, 'gato'); + gato.width = 300; + gato.height = 170; + + // Desenha o passaro e a borda da box + + var passaro = game.add.sprite(910, 210, 'passaro'); + passaro.width = 300; + passaro.height = 170; + + start(); + + game.time.events.add(Phaser.Timer.SECOND * 4, initial, this); + + function start(){ + groupCidade.children[1].alpha = 0; + groupCidade.children[2].visible = false; + gato.visible = false; + passaro.visible = false; + background.alpha = 0.5; + groupCidade.children[0].x += 230; + cachorro.x += 230; + groupCidade.children[0].y -= 70; + cachorro.y -= 70; + game.add.tween(groupCidade.children[0].scale).to( { x: 2, y: 2 }, 1000, Phaser.Easing.Elastic.Out, true); + game.add.tween(cachorro.scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Elastic.Out, true); + } + + function initial(){ + game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 500, Phaser.Easing.Elastic.In, true); + game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 500, Phaser.Easing.Elastic.In, true); + groupCidade.children[0].x -= 230; + cachorro.x -= 230; + groupCidade.children[0].y += 70; + cachorro.y += 70; + background.alpha = 0.5; + game.time.events.add(Phaser.Timer.SECOND * 2, groupCidade.children[1].visible = true, this); + game.time.events.add(Phaser.Timer.SECOND * 2, groupCidade.children[2].visible = true, this); + game.time.events.add(Phaser.Timer.SECOND * 2, gato.visible = true, this); + game.time.events.add(Phaser.Timer.SECOND * 2, passaro.visible = true, this); + // groupCidade.children[1].visible = true; + // groupCidade.children[2].visible = true; + // gato.visible = true; + // passaro.visible = true; + + activateButtons(); + } + + function activateButtons(){ + groupCidade.onChildInputDown.add(onDown, this); + groupCidade.onChildInputOver.add(onOver, this); + groupCidade.onChildInputOut.add(onOut, this); + } + + function onDown (sprite) { + sprite.tint = 0x00ff00; + } + + function onOver (sprite) { + sprite.tint = 0xffff00; + } + + function onOut (sprite) { + sprite.tint = 0xff8800; + // sprite.tint = Math.random() * 0xffffff; + + } + + }, + + + update: function(){ + + }, + + Win: function(){ + game.state.start('win'); + } +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070190_viewpoint.js b/pool/shard011/JavaScript/0070190_viewpoint.js new file mode 100644 index 0000000000000000000000000000000000000000..dc4a80eb37284930c5099c118c1d4bc6b39b5c2b --- /dev/null +++ b/pool/shard011/JavaScript/0070190_viewpoint.js @@ -0,0 +1,111 @@ +// Copyright (c) 2013-2015 Marco Biasini +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to +// deal in the Software without restriction, including without limitation the +// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +// sell copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +// DEALINGS IN THE SOFTWARE. + +define(['gl-matrix', 'geom'], function(glMatrix, geom) { + +"use strict"; + +var vec3 = glMatrix.vec3; +var mat3 = glMatrix.mat3; + +var calculateCovariance = (function() { + var center = vec3.create(); + var shiftedPos = vec3.create(); + return function(go, covariance) { + vec3.set(center, 0, 0, 0); + var atomCount = 0; + go.eachCentralAtom(function(atom, transformedPos) { + vec3.add(center, center, transformedPos); + atomCount += 1; + }); + if (atomCount === 0) { + return; + } + vec3.scale(center, center, 1.0/atomCount); + covariance[0] = 0; covariance[1] = 0; covariance[2] = 0; + covariance[3] = 0; covariance[4] = 0; covariance[5] = 0; + covariance[6] = 0; covariance[7] = 0; covariance[8] = 0; + go.eachCentralAtom(function(atom, transformedPos) { + vec3.sub(shiftedPos, transformedPos, center); + var x = shiftedPos[0], y = shiftedPos[1], z = shiftedPos[2]; + // No need to fill in covariance[3]/covariance[6]/covariance[7], the + // matrix is symmetric. + covariance[0] += y * y + z * z; + covariance[1] -= x * y; + covariance[2] -= x * z; + covariance[5] -= y * z; + covariance[4] += x * x + z * z; + covariance[8] += x * x + y * y; + }); + covariance[3] = covariance[1]; + covariance[6] = covariance[2]; + covariance[7] = covariance[5]; + }; +})(); + +var principalAxes = (function() { + var covariance = mat3.create(); + var diag = mat3.create(); + var min = vec3.create(); + var max = vec3.create(); + var projected = vec3.create(); + var range = vec3.create(); + var x = vec3.create(); + var y = vec3.create(); + var z = vec3.create(); + return function(go) { + calculateCovariance(go, covariance); + var q = geom.diagonalizer(covariance); + mat3.fromQuat(diag, q); + var first = true; + go.eachCentralAtom(function(atom, transformedPos) { + vec3.transformMat3(projected, transformedPos, diag); + if (first) { + vec3.copy(min, projected); + vec3.copy(max, projected); + first = false; + } else { + vec3.min(min, min, projected); + vec3.max(max, max, projected); + } + }); + vec3.sub(range, max, min); + var axes = [ [range[0], 0], [range[1], 1], [range[2], 2] ]; + axes.sort(function(a, b) { + return b[0] - a[0]; + }); + var xIndex = axes[0][1]; + var yIndex = axes[1][1]; + vec3.set(x, diag[xIndex + 0], diag[xIndex + 3], diag[xIndex + 6]); + vec3.set(y, diag[yIndex + 0], diag[yIndex + 3], diag[yIndex + 6]); + vec3.cross(z, x, y); + var rotation = mat3.create(); + rotation[0] = x[0]; rotation[1] = y[0]; rotation[2] = z[0]; + rotation[3] = x[1]; rotation[4] = y[1]; rotation[5] = z[1]; + rotation[6] = x[2]; rotation[7] = y[2]; rotation[8] = z[2]; + return rotation; + }; +})(); + +return { + principalAxes :principalAxes +}; + +}); diff --git a/pool/shard011/JavaScript/0070196_index.js b/pool/shard011/JavaScript/0070196_index.js new file mode 100644 index 0000000000000000000000000000000000000000..266a5e60f5c9db5d93a6db9da16bd2a0ae167c1a --- /dev/null +++ b/pool/shard011/JavaScript/0070196_index.js @@ -0,0 +1,54 @@ +const tpl = require('./index.html') + +export default Regular.extend({ + name: 'modalForm', + template: tpl, + config () { + this.supr() + this.initParamList() + }, + // 子类重写这个方法来初始化参数列表 + initParamList () { + }, + init () { + var data = this.data + // 确认的时候不要自动隐藏, 要在请求结束后再隐藏, 隐藏后会自动销毁 + data.autoHideWhenConfirm = false + data.list = data.paramList || [] + data.paramsLimit = 0 + this.$refs.modal.data = Object.assign(this.$refs.modal.data, data, data.modalData || {}) + this.$refs.params.data = Object.assign(this.$refs.params.data, data, data.paramsData || {}) + this.$refs.params.reset() + this.$refs.params.parseParamList() + if (data.autoShow !== false) { + this.show() + } + }, + show () { + this.$refs.modal.show() + }, + hide () { + this.$refs.modal.hide() + }, + // override, 检查参数, 如果不合法那么直接返回, 否则抛出 create + confirm () { + let params = this.$refs.params + if (params) { + // 重置所有的错误 + params.clearAllInvalid() + params = params.getParams() + if (params) { + this.$refs.modal.data.loading = true + this.$emit('confirm') + this.afterConfirm(params) + } + } + }, + afterConfirm () { + this.resetLoading() + }, + resetLoading () { + this.$refs.modal.data.loading = false + this.$update() + } +}) diff --git a/pool/shard011/JavaScript/0070200_param.js b/pool/shard011/JavaScript/0070200_param.js new file mode 100644 index 0000000000000000000000000000000000000000..43cfe8730a9e565ab2bdce030d3ca2744f6db88b --- /dev/null +++ b/pool/shard011/JavaScript/0070200_param.js @@ -0,0 +1,13 @@ +var express = require('express'), + app = express(); + +app.put('/message/:id', function (req, res) { + var hash = require('crypto') + .createHash('sha1') + .update(new Date().toDateString() + req.params.id) + .digest('hex') + + res.end(hash); +}); + +app.listen(process.argv[2]); diff --git a/pool/shard011/JavaScript/0070203_SDK.js b/pool/shard011/JavaScript/0070203_SDK.js new file mode 100644 index 0000000000000000000000000000000000000000..0bb5ef705f2a81b05450cbdfcb08b5b13ed1edda --- /dev/null +++ b/pool/shard011/JavaScript/0070203_SDK.js @@ -0,0 +1,28 @@ +/** + * @license Copyright 2020 The Lighthouse Authors. All Rights Reserved. + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. + */ +'use strict'; +const SDK = { + TextSourceMap: require('./generated/SourceMap.js'), +}; + +// Add `lastColumnNumber` to mappings. This will eventually be added to CDT. +// @ts-expect-error +SDK.TextSourceMap.prototype.computeLastGeneratedColumns = function() { + const mappings = this.mappings(); + if (mappings.length && mappings[0].lastColumnNumber !== undefined) return; + + for (let i = 0; i < mappings.length - 1; i++) { + const mapping = mappings[i]; + const nextMapping = mappings[i + 1]; + if (mapping.lineNumber === nextMapping.lineNumber) { + mapping.lastColumnNumber = nextMapping.columnNumber; + } + } + + // Now, all but the last mapping on each line will have 'lastColumnNumber' set to a number. +}; + +module.exports = SDK; diff --git a/pool/shard011/JavaScript/0070204_subscribers.js b/pool/shard011/JavaScript/0070204_subscribers.js new file mode 100644 index 0000000000000000000000000000000000000000..5f68e98f16291c03abb59a71cbdf235a10a5b40d --- /dev/null +++ b/pool/shard011/JavaScript/0070204_subscribers.js @@ -0,0 +1,57 @@ +/* eslint-disable newline-per-chained-call */ + + +var nav = require('./utils').nav; + +module.exports = new Subscribers(); + +function Subscribers() { + this.list = element.all(by.repeater('subscriber in subscribers')); + this.saveSubscriberButton = element(by.css('[ng-click="save()"]')); + this.cancelSubscriberButton = element(by.css('[ng-click="cancel()"]')); + + this.get = function() { + nav('/settings/publish'); + browser.sleep(500); + }; + + this.getSubscriber = function(name) { + return this.list.filter((elem, index) => + elem.element(by.binding('subscriber.name')) + .getText() + .then((text) => text.toUpperCase() === name.toUpperCase()) + ); + }; + + this.getCount = function(index) { + return this.list.count(); + }; + + this.edit = function(name) { + this.getSubscriber(name).then((rows) => { + rows[0].click(); + rows[0].element(by.className('icon-pencil')).click(); + browser.sleep(500); + }); + }; + + this.setType = function(ingestType) { + element(by.id('subType')).all(by.tagName('option')) + .filter((elem, index) => elem.getText().then((label) => label.toLowerCase().indexOf(ingestType) > -1)) + .then((options) => { + options[0].click(); + }); + }; + + this.setDestinationFormat = function(ingestType) { + element(by.id('destination-format')).all(by.tagName('option')) + .filter((elem, index) => elem.getText().then((label) => label.toLowerCase().indexOf(ingestType) > -1)) + .then((options) => { + options[0].click(); + }); + }; + + this.cancel = function() { + this.cancelSubscriberButton.click(); + }; +} diff --git a/pool/shard011/JavaScript/0070208_download.js b/pool/shard011/JavaScript/0070208_download.js new file mode 100644 index 0000000000000000000000000000000000000000..6b71afff1e422544a506561e47f31eacbf40b20a --- /dev/null +++ b/pool/shard011/JavaScript/0070208_download.js @@ -0,0 +1,87 @@ +// This file is part of Pa11y Dashboard. +// +// Pa11y Dashboard 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. +// +// Pa11y Dashboard 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 Pa11y Dashboard. If not, see . +'use strict'; + +const moment = require('moment'); + +module.exports = route; + +// Route definition +function route(app) { + + function getTaskAndResult(request, response, next) { + app.webservice.task(request.params.id).get({}, (error, task) => { + if (error) { + return next('route'); + } + app.webservice + .task(request.params.id) + .result(request.params.rid) + .get({full: true}, (error, result) => { + if (error) { + return next('route'); + } + response.locals.task = task; + response.locals.result = result; + next(); + }); + }); + } + + function getDownloadFileName(task, result, extension) { + return [ + 'pa11y', + '--', + task.url + .replace(/^https?:\/\//i, '') + .replace(/\/$/, '') + .replace(/[^a-z0-9.\-_]+/gi, '-'), + '--', + task.standard.toLowerCase(), + '--', + moment(result.date).format('YYYY-MM-DD'), + '.', + extension + ].join(''); + } + + app.express.get('/:id/:rid.csv', getTaskAndResult, (request, response) => { + const task = response.locals.task; + const result = response.locals.result; + const rows = ['"code","message","type","context","selector"']; + result.results.forEach(msg => { + rows.push([ + JSON.stringify(msg.code), + JSON.stringify(msg.message), + JSON.stringify(msg.type), + JSON.stringify(msg.context), + JSON.stringify(msg.selector) + ].join(',')); + }); + response.attachment(getDownloadFileName(task, result, 'csv')); + response.send(rows.join('\n')); + }); + + app.express.get('/:id/:rid.json', getTaskAndResult, (request, response) => { + const task = response.locals.task; + const result = response.locals.result; + response.attachment(getDownloadFileName(task, result, 'json')); + delete task.id; + delete result.id; + result.task = task; + response.send(result); + }); + +} diff --git a/pool/shard011/JavaScript/0070210_coinmarketcapSchedule.js b/pool/shard011/JavaScript/0070210_coinmarketcapSchedule.js new file mode 100644 index 0000000000000000000000000000000000000000..f3d077a18f9874e1155168baab63505585c48dc4 --- /dev/null +++ b/pool/shard011/JavaScript/0070210_coinmarketcapSchedule.js @@ -0,0 +1,58 @@ +import https from 'https'; +import cache from '../cache/appCache'; +import schedule from 'node-schedule'; + +const URL = "https://api.coinmarketcap.com/v1/ticker/nem/"; + +let scheduleFetchPrice = () => { + fetchPrice(); + let rule = new schedule.RecurrenceRule(); + rule.second = [1, 11, 21, 31, 41, 51]; + schedule.scheduleJob(rule, () => { + fetchPrice(); + }); +} + +/** + * fetch price from coinmarketcap.com + */ +let fetchPrice = () => { + httpsGet(URL, html => { + if(!html) + return; + let result = null; + try{ + result = JSON.parse(html); + } catch (e) { + console.error(e); + } + if(!result || result.length==0) + return; + let market = result[0]; + if(!market || !market.price_usd || !market.price_btc) + return; + let saveObj = {}; + saveObj.usd = market.price_usd; + saveObj.btc = market.price_btc; + saveObj.cap = market.market_cap_usd; + cache.appCache.set(cache.marketPrefix, saveObj); + }); +} + +let httpsGet = function(url, callback) { + https.get(url, function(res) { + let html = ''; + res.on('data', function(data) { + html += data; + }); + res.on('end',function() { + callback(html); + }); + }).on('error', function() { + callback(null); + }); +} + +module.exports = { + scheduleFetchPrice +} diff --git a/pool/shard011/JavaScript/0070212_jquery.tinycarousel.js b/pool/shard011/JavaScript/0070212_jquery.tinycarousel.js new file mode 100644 index 0000000000000000000000000000000000000000..fe4d14c09004713195e8de50ee95f65c8b7b0704 --- /dev/null +++ b/pool/shard011/JavaScript/0070212_jquery.tinycarousel.js @@ -0,0 +1,210 @@ +;(function (factory) +{ + if (typeof define === 'function' && define.amd) + { + define(['jquery'], factory); + } + else if (typeof exports === 'object') + { + factory(require('jquery')); + } + else + { + factory(jQuery); + } +} +(function ($) +{ + var pluginName = "tinycarousel" + , defaults = + { + start: 0 // The starting slide + , axis: "x" // vertical or horizontal scroller? ( x || y ). + , buttons: true // show left and right navigation buttons. + , bullets: false // is there a page number navigation present? + , interval: false // move to another block on intervals. + , intervalTime: 3000 // interval time in milliseconds. + , animation: true // false is instant, true is animate. + , animationTime: 1000 // how fast must the animation move in ms? + , infinite: true // infinite carousel. + , marginSet: 0 // Adjusting the margin + } + ; + + function Plugin($container, options) + { + this.options = $.extend({}, defaults, options); + this._defaults = defaults; + this._name = pluginName; + + var self = this + , $viewport = $container.find(".viewport:first") + , $overview = $container.find(".overview:first") + , $slides = 0 + , $next = $container.find(".next:first") + , $prev = $container.find(".prev:first") + , $bullets = $container.find(".bullet") + + , viewportSize = 0 + , contentStyle = {} + , slidesVisible = 0 + , slideSize = 0 + , slideIndex = 0 + + , isHorizontal = this.options.axis === 'x' + , sizeLabel = isHorizontal ? "Width" : "Height" + , posiLabel = isHorizontal ? "left" : "top" + , intervalTimer = null + ; + + this.slideCurrent = 0; + this.slidesTotal = 0; + + function initialize() + { + self.update(); + self.move(self.slideCurrent); + + setEvents(); + + return self; + } + + this.update = function() + { + $overview.find(".mirrored").remove(); + + $slides = $overview.children(); + viewportSize = $viewport[0]["offset" + sizeLabel]; + slideSize = $slides.first()["outer" + sizeLabel](true); + self.slidesTotal = $slides.length; + self.slideCurrent = self.options.start || 0; + slidesVisible = Math.ceil(viewportSize / slideSize); + + $overview.append($slides.slice(0, slidesVisible).clone().addClass("mirrored")); + $overview.css(sizeLabel.toLowerCase(), slideSize * (self.slidesTotal + slidesVisible)); + + return self; + }; + + function setEvents() + { + if(self.options.buttons) + { + $prev.click(function() + { + self.move(--slideIndex); + + return false; + }); + + $next.click(function() + { + self.move(++slideIndex); + + return false; + }); + } + + $(window).resize(self.update); + + if(self.options.bullets) + { + $container.on("click", ".bullet", function() + { + self.move(slideIndex = +$(this).attr("data-slide")); + + return false; + }); + } + } + + this.start = function() + { + if(self.options.interval) + { + clearTimeout(intervalTimer); + + intervalTimer = setTimeout(function() + { + self.move(++slideIndex); + + }, self.options.intervalTime); + } + + return self; + }; + + this.stop = function() + { + clearTimeout(intervalTimer); + + return self; + }; + + this.move = function(index) + { + slideIndex = index; + self.slideCurrent = slideIndex % self.slidesTotal; + + if(slideIndex < 0) + { + self.slideCurrent = slideIndex = self.slidesTotal - 1; + $overview.css(posiLabel, -(self.slidesTotal) * slideSize); + } + + if(slideIndex > self.slidesTotal) + { + self.slideCurrent = slideIndex = 1; + $overview.css(posiLabel, 0); + } + + //This is line modified as per the design + contentStyle[posiLabel] = (-slideIndex * slideSize) - self.options.marginSet; + + $overview.animate( + contentStyle + , { + queue : false + , duration : self.options.animation ? self.options.animationTime : 0 + , always : function() + { + $container.trigger("move", [$slides[self.slideCurrent], self.slideCurrent]); + } + }); + + setButtons(); + self.start(); + + return self; + }; + + function setButtons() + { + if(self.options.buttons && !self.options.infinite) + { + $prev.toggleClass("disable", self.slideCurrent <= 0); + $next.toggleClass("disable", self.slideCurrent >= self.slidesTotal - slidesVisible); + } + + if(self.options.bullets) + { + $bullets.removeClass("active"); + $($bullets[self.slideCurrent]).addClass("active"); + } + } + + return initialize(); + } + + $.fn[pluginName] = function(options) + { + return this.each(function() + { + if(!$.data(this, "plugin_" + pluginName)) + { + $.data(this, "plugin_" + pluginName, new Plugin($(this), options)); + } + }); + }; +})); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070214_debug-return-value.js b/pool/shard011/JavaScript/0070214_debug-return-value.js new file mode 100644 index 0000000000000000000000000000000000000000..77717ceb7c3944da1fb681fae1ce9f8dd24bff7e --- /dev/null +++ b/pool/shard011/JavaScript/0070214_debug-return-value.js @@ -0,0 +1,116 @@ +// Copyright 2010 the V8 project authors. All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided +// with the distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +Debug = debug.Debug + +listener_complete = false; +exception = false; +break_count = 0; +expected_return_value = 0; +expected_source_position = []; +debugger_source_position = 0; + +// Listener which expects to do four steps to reach returning from the function. +function listener(event, exec_state, event_data, data) { + try { + if (event == Debug.DebugEvent.Break) + { + break_count++; + if (break_count < 4) { + switch (break_count) { + case 1: + // Collect the position of the debugger statement. + debugger_source_position = exec_state.frame(0).sourcePosition(); + break; + case 2: + // Position now at the if statement. + assertEquals(expected_source_position.shift() + debugger_source_position, + exec_state.frame(0).sourcePosition()); + break; + case 3: + // Position now at either of the returns. + assertEquals(expected_source_position.shift() + debugger_source_position, + exec_state.frame(0).sourcePosition()); + break; + default: + fail("Unexpected"); + } + exec_state.prepareStep(Debug.StepAction.StepIn); + } else { + // Position at the end of the function. + assertEquals(expected_source_position.shift() + debugger_source_position, + exec_state.frame(0).sourcePosition()); + // Just about to return from the function. + assertEquals(expected_return_value, + exec_state.frame(0).returnValue().value()); + + listener_complete = true; + } + } + } catch (e) { + exception = e + print(e + e.stack) + }; +}; + +// Add the debug event listener. +Debug.setListener(listener); + +// Four steps from the debugger statement in this function will position us at +// the function return. +// 0 1 2 3 4 5 +// 0123456789012345678901234567890123456789012345678901 + +function f(x) {debugger; if (x) { return 1; } else { return 2; } }; + +// Call f expecting different return values. +break_count = 0; +expected_return_value = 2; +expected_source_position = [10, 38, 47]; +listener_complete = false; +f(); +assertFalse(exception, "exception in listener") +assertTrue(listener_complete); +assertEquals(4, break_count); + +break_count = 0; +expected_return_value = 1; +expected_source_position = [10, 19, 28]; +listener_complete = false; +f(true); +assertFalse(exception, "exception in listener") +assertTrue(listener_complete); +assertEquals(4, break_count); + +break_count = 0; +expected_return_value = 2; +expected_source_position = [10, 38, 47]; +listener_complete = false; +f(false); +assertFalse(exception, "exception in listener") +assertTrue(listener_complete); +assertEquals(4, break_count); diff --git a/pool/shard011/JavaScript/0070216_js.js b/pool/shard011/JavaScript/0070216_js.js new file mode 100644 index 0000000000000000000000000000000000000000..86a6255f659e051cfe3f09f56c2345e34cc824f3 --- /dev/null +++ b/pool/shard011/JavaScript/0070216_js.js @@ -0,0 +1,30 @@ +import RSVP from 'rsvp'; +import { createLoadElement, nodeLoader } from './utilities'; + +/** + * Default loader function for JS assets. Loads them by inserting a script tag + * with onload/onerror handlers that correspond to the resolve/reject callbacks + * of the return Promise. + * + * @param {String} uri + * @return {Promise} + */ +export default nodeLoader(function js(uri) { + return new RSVP.Promise((resolve, reject) => { + if (document.querySelector(`script[src="${uri}"]`)) { + return resolve(); + } + + const script = createLoadElement('script', resolve, function(error) { + if (this.parentNode) { + this.parentNode.removeChild(this); + } + reject(error); + }); + + script.src = uri; + script.async = false; + + document.head.appendChild(script); + }); +}); diff --git a/pool/shard011/JavaScript/0070219_ModuleScope.js b/pool/shard011/JavaScript/0070219_ModuleScope.js new file mode 100644 index 0000000000000000000000000000000000000000..6d643cedaa54a5d4d76e68d3a1bf7a5554342362 --- /dev/null +++ b/pool/shard011/JavaScript/0070219_ModuleScope.js @@ -0,0 +1,75 @@ +import { forOwn } from '../../utils/object.js'; +import relativeId from '../../utils/relativeId.js'; +import Scope from './Scope.js'; +import { UNDEFINED_ASSIGNMENT } from '../values'; +import LocalVariable from '../variables/LocalVariable'; + +export default class ModuleScope extends Scope { + constructor ( module ) { + super( { + isModuleScope: true, + parent: module.bundle.scope + } ); + + this.module = module; + this.variables.this = new LocalVariable( 'this', null, UNDEFINED_ASSIGNMENT ); + } + + deshadow ( names ) { + names = new Set( names ); + + forOwn( this.module.imports, specifier => { + if ( specifier.module.isExternal ) return; + + const addDeclaration = declaration => { + if ( declaration.isNamespace && !declaration.isExternal ) { + declaration.module.getExports().forEach( name => { + addDeclaration( declaration.module.traceExport( name ) ); + } ); + } + + names.add( declaration.name ); + }; + + specifier.module.getExports().forEach( name => { + addDeclaration( specifier.module.traceExport( name ) ); + } ); + + if ( specifier.name !== '*' ) { + const declaration = specifier.module.traceExport( specifier.name ); + if ( !declaration ) { + this.module.warn( { + code: 'NON_EXISTENT_EXPORT', + name: specifier.name, + source: specifier.module.id, + message: `Non-existent export '${specifier.name}' is imported from ${relativeId( specifier.module.id )}` + }, specifier.specifier.start ); + return; + } + + const name = declaration.getName( true ); + if ( name !== specifier.name ) { + names.add( declaration.getName( true ) ); + } + + if ( specifier.name !== 'default' && specifier.specifier.imported.name !== specifier.specifier.local.name ) { + names.add( specifier.specifier.imported.name ); + } + } + } ); + + super.deshadow( names ); + } + + findLexicalBoundary () { + return this; + } + + findVariable ( name ) { + if ( this.variables[ name ] ) { + return this.variables[ name ]; + } + + return this.module.trace( name ) || this.parent.findVariable( name ); + } +} diff --git a/pool/shard011/JavaScript/0070221_findSummoner.js b/pool/shard011/JavaScript/0070221_findSummoner.js new file mode 100644 index 0000000000000000000000000000000000000000..8ee043f631db51d0a2f79976e38ccf3b684d9669 --- /dev/null +++ b/pool/shard011/JavaScript/0070221_findSummoner.js @@ -0,0 +1,53 @@ +'use strict'; +var React = require('react'); +var Router = require('react-router'); +var Navigation = Router.Navigation; +var services = require('./../services'); +var ENTER_KEY = 13; +var FindSummoner = React.createClass({ + mixins: [Navigation], + getInitialState: function(){ + return { + summonerName: '', + summoner: null, + regionId: 'eune' + }; + }, + handleInputChange: function(e){ + this.setState({summonerName: e.target.value}); + }, + handleKeyDown: function(event){ + if (event.which !== ENTER_KEY) { + return; + } + this.searchSummoner(event); + }, + searchSummoner: function(e){ + var self = this; + services.searchSummoner(this.state.summonerName, this.state.regionId, function(summoner){ + self.transitionTo('summonerTournaments',{ id: summoner.id }); + }); + }, + render: function() { + return ( +
    +
    + +
    + +
    + +
    +
    ); + } +}); + +module.exports = FindSummoner; diff --git a/pool/shard011/JavaScript/0070222_converter.js b/pool/shard011/JavaScript/0070222_converter.js new file mode 100644 index 0000000000000000000000000000000000000000..0721925c601bebe6b8a89ec73489d656065a4ebd --- /dev/null +++ b/pool/shard011/JavaScript/0070222_converter.js @@ -0,0 +1,115 @@ +//*******************************************************************************************// +// // +// Download Free Evaluation Version From: https://bytescout.com/download/web-installer // +// // +// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup // +// // +// Copyright © 2017-2020 ByteScout, Inc. All rights reserved. // +// https://www.bytescout.com // +// https://pdf.co // +// // +//*******************************************************************************************// + + +var apiKey, formData, toType, isInline; + +$(document).ready(function () { + $("#resultBlock").hide(); + $("#errorBlock").hide(); + $("#result").attr("href", '').html(''); +}); + +$(document).on("click", "#submit", function () { + $("#resultBlock").hide(); + $("#errorBlock").hide(); + $("#inlineOutput").text(''); // inline output div + $("#status").text(''); // status div + + apiKey = $("#apiKey").val().trim(); //Get your API key at https://app.pdf.co + + formData = $("#form input[type=file]")[0].files[0]; // file to upload + toType = $("#convertType").val(); // output type + isInline = $("#outputType").val() == "inline"; // if we need output as inline content or link to output file + + $("#status").html('Requesting presigned url for upload...     '); + + $.ajax({ + url: 'https://api.pdf.co/v1/file/upload/get-presigned-url?name=test.pdf&contenttype=application/pdf&encrypt=true', + type: 'GET', + headers: {'x-api-key': apiKey}, // passing our api key + success: function (result) { + + if (result['error'] === false) { + + var presignedUrl = result['presignedUrl']; // reading provided presigned url to put our content into + $("#status").html('Uploading...     '); + + $.ajax({ + url: presignedUrl, // no api key is required to upload file + type: 'PUT', + headers: {'content-type': 'application/pdf'}, // setting to pdf type as we are uploading pdf file + data: formData, + processData: false, + success: function (result) { + + $("#status").html('Processing...     '); + + $.ajax({ + url: 'https://api.pdf.co/v1/pdf/convert/to/'+toType+'?url='+ presignedUrl + '&encrypt=true&inline=' + isInline + '&async=True', + type: 'POST', + headers: {'x-api-key': apiKey}, + success: function (result) { + if (result.error) { + $("#status").text('Error uploading file.'); + } + else { + checkIfJobIsCompleted(result.jobId, result.url); + } + } + }); + }, + error: function () { + $("#status").text('error'); + } + }); + + } + } + }); +}); + +function checkIfJobIsCompleted(jobId, resultFileUrl) { + $.ajax({ + url: 'https://api.pdf.co/v1/job/check?jobid=' + jobId, + type: 'GET', + headers: { 'x-api-key': apiKey }, // passing our api key + success: function (jobResult) { + + $("#status").html(jobResult.status + '     '); + + if (jobResult.status == "working") { + // Check again after 3 seconds + setTimeout(checkIfJobIsCompleted(jobId, resultFileUrl), 3000) + } + else if (jobResult.status == "success") { + + $("#status").text('Done converting.'); + + $("#resultBlock").show(); + + if (isInline && toType != "xls" && toType != "xlsx") { + $.ajax({ + url: resultFileUrl, + dataType: 'text', + success: function (respText) { + $("#inlineOutput").text(respText); + } + }); + } + else { + $("#result").attr("href", resultFileUrl).html(resultFileUrl); + } + } + } + }); +} diff --git a/pool/shard011/JavaScript/0070225_MigrationDAO.js b/pool/shard011/JavaScript/0070225_MigrationDAO.js new file mode 100644 index 0000000000000000000000000000000000000000..feb96b4dd5a08b9d5864112c97cecfd26e5a9785 --- /dev/null +++ b/pool/shard011/JavaScript/0070225_MigrationDAO.js @@ -0,0 +1,104 @@ +/** + * @license + * Copyright 2015 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +CLASS({ + name: 'MigrationDAO', + package: 'foam.core.dao', + extendsModel: 'foam.dao.ProxyDAO', + + requires: [ + 'foam.core.dao.MigrationRule', + 'foam.dao.FutureDAO', + 'foam.dao.DAOVersion' + ], + + imports: [ + 'daoVersionDao' + ], + + properties: [ + { + name: 'delegate' + }, + { + model_: 'ArrayProperty', + subType: 'foam.core.dao.MigrationRule', + name: 'rules' + }, + { + name: 'name' + } + ], + + methods: { + init: function() { + var dao = this.delegate; + var future = afuture() + this.delegate = this.FutureDAO.create({future: future.get}); + + var self = this; + var version; + aseq( + function(ret) { + self.daoVersionDao.find(self.name, { + put: function(c) { + version = c; + ret(); + }, + error: function() { + version = self.DAOVersion.create({ + name: self.name, + version: 0 + }); + ret(); + } + }); + }, + function(ret) { + function updateVersion(ret, v) { + var c = version.clone(); + c.version = v; + self.daoVersionDao.put(c, ret); + } + + var rulesDAO = self.rules.dao; + rulesDAO + .where(AND(GT(self.MigrationRule.VERSION, version.version))) + .select()(function(rules) { + var seq = []; + for ( var i = 0; i < rules.length; i++ ) { + (function(rule) { + seq.push( + aseq( + function(ret) { + rule.migration(ret, dao); + }, + function(ret) { + updateVersion(ret, rule.version); + })); + })(self.rules[i]); + } + if ( seq.length > 0 ) aseq.apply(null, seq)(ret); + else ret(); + }); + })(function() { + future.set(dao); + }); + this.SUPER(); + } + } +}); diff --git a/pool/shard011/JavaScript/0070228_ranks.js b/pool/shard011/JavaScript/0070228_ranks.js new file mode 100644 index 0000000000000000000000000000000000000000..2400b183cdb924762ff31e9d5f87a676bba5c282 --- /dev/null +++ b/pool/shard011/JavaScript/0070228_ranks.js @@ -0,0 +1,114 @@ +var Ranks = function () { + this.respondsWith = ['html', 'json', 'xml', 'js', 'txt']; + + this.index = function (req, resp, params) { + var self = this; + + geddy.model.Rank.all(function(err, ranks) { + if (err) { + throw err; + } + self.respondWith(ranks, {type:'Rank'}); + }); + }; + + this.add = function (req, resp, params) { + this.respond({params: params}); + }; + + this.create = function (req, resp, params) { + var self = this + , rank = geddy.model.Rank.create(params); + + if (!rank.isValid()) { + this.respondWith(rank); + } + else { + rank.save(function(err, data) { + if (err) { + throw err; + } + self.respondWith(rank, {status: err}); + }); + } + }; + + this.show = function (req, resp, params) { + var self = this; + + geddy.model.Rank.first(params.id, function(err, rank) { + if (err) { + throw err; + } + if (!rank) { + throw new geddy.errors.NotFoundError(); + } + else { + self.respondWith(rank); + } + }); + }; + + this.edit = function (req, resp, params) { + var self = this; + + geddy.model.Rank.first(params.id, function(err, rank) { + if (err) { + throw err; + } + if (!rank) { + throw new geddy.errors.BadRequestError(); + } + else { + self.respondWith(rank); + } + }); + }; + + this.update = function (req, resp, params) { + var self = this; + + geddy.model.Rank.first(params.id, function(err, rank) { + if (err) { + throw err; + } + rank.updateProperties(params); + + if (!rank.isValid()) { + self.respondWith(rank); + } + else { + rank.save(function(err, data) { + if (err) { + throw err; + } + self.respondWith(rank, {status: err}); + }); + } + }); + }; + + this.remove = function (req, resp, params) { + var self = this; + + geddy.model.Rank.first(params.id, function(err, rank) { + if (err) { + throw err; + } + if (!rank) { + throw new geddy.errors.BadRequestError(); + } + else { + geddy.model.Rank.remove(params.id, function(err) { + if (err) { + throw err; + } + self.respondWith(rank); + }); + } + }); + }; + +}; + +exports.Ranks = Ranks; diff --git a/pool/shard011/JavaScript/0070231_routes.js b/pool/shard011/JavaScript/0070231_routes.js new file mode 100644 index 0000000000000000000000000000000000000000..c73fb5d4c00b85c0bb42ca569730edca912c17ed --- /dev/null +++ b/pool/shard011/JavaScript/0070231_routes.js @@ -0,0 +1,32 @@ +var express = require('express'); +var router = express.Router(); +var apiRouter = express.Router(); +var protectedRouter = express.Router(); +var oauth = require('../oauth'); +var loader = require('flat-load'); + +var resources = require('auto-loader').load(__dirname + '/resources'); + +// Namespaces all API Resources to /api +router.use('/api', apiRouter); + +// Protects Protected Routes using OAuth2 Filter +protectedRouter.use(oauth.authorise()); + +// Allows User Registration +apiRouter.use('/register', resources.auth.register); + +// Auto Load Public Resources +loader(__dirname + '/resources/public').forEach((route) => { + apiRouter.use(route); +}); + +// Auto Load Protected Resources +loader(__dirname + '/resources/protected').forEach((route) => { + protectedRouter.use(route); +}); + +// Merges Protected Routes into API Router +apiRouter.use(protectedRouter); + +module.exports = router; diff --git a/pool/shard011/JavaScript/0070233_auth.js b/pool/shard011/JavaScript/0070233_auth.js new file mode 100644 index 0000000000000000000000000000000000000000..1db9494dbd5f972039b9ae5ba380fa2e061511d5 --- /dev/null +++ b/pool/shard011/JavaScript/0070233_auth.js @@ -0,0 +1,113 @@ +'use strict'; + +const Co = require('co'); +const JsonWebToken = require('jsonwebtoken'); +const Pify = require('pify'); +const TwitterHelper = require('../twitter_helper'); + +const internals = {}; + +internals.kRedirectUrl = 'https://api.twitter.com/oauth/authenticate?oauth_token='; +internals.kLoginRedirect = '/login'; + +internals.signJsonWebToken = Pify(JsonWebToken.sign); + +/** + * Handles the HTTP requests for auth related operations. + * + * @class AuthHandler + * @param {Dasein.tConfiguration} config The configuration to + * initialize. + */ +module.exports = internals.AuthHandler = class AuthHandler { + + constructor(config) { + + this._twitterHelper = new TwitterHelper(config.twitter); + this._jwtConfig = config.jwt; + } + + /** + * Triggers the twitter login flow. Redirects to twitter's oauth + * request page + * + * @function login + * @memberof AuthHandler + * @instance + * @return {generator} a koa compatible handler generator function + */ + login() { + + const twitterHelper = this._twitterHelper; + + return function *handleLogin() { + + const requestToken = yield twitterHelper.getRequestToken(); + const loginUrl = `${internals.kRedirectUrl}${requestToken.oAuthToken}`; + + this.body = { loginUrl }; + }; + } + + /** + * Handles twitter's callback. Fetches the oAuth Verifier, attempts to + * obtain a user object and responds with the JWT + * + * @function callback + * @memberof AuthHandler + * @instance + * @return {generator} a koa compatible handler generator function + */ + callback() { + + const self = this; + + return function *handleCallback() { + + if (this.request.query.denied) { + return this.throw(401); + } + + const oAuthToken = this.request.body.oAuthToken; + const oAuthVerifier = this.request.body.oAuthVerifier; + let user; + + try { + const accessToken = yield self._twitterHelper.getAccessToken(oAuthToken, oAuthVerifier); + user = yield self._twitterHelper.getUser(accessToken.oAuthAccessToken, accessToken.oAuthAccessTokenSecret); + } + catch (err) { + console.error(err.stack || err.message || err); + return this.throw(401); + } + + const expiresAt = Date.now() + self._jwtConfig.duration * 1000; + + const token = yield self._getToken(user); + + const response = { + expiresAt, + user, + token + }; + + this.body = response; + }; + } + + // Generates a JSON Web Token + + _getToken(payload) { + + const self = this; + + return Co(function * () { + + const token = yield internals.signJsonWebToken(payload, self._jwtConfig.secret, { + expiresIn: self._jwtConfig.duration + }); + + return token; + }); + } +}; diff --git a/pool/shard011/JavaScript/0070234_angular-daterangepicker.js b/pool/shard011/JavaScript/0070234_angular-daterangepicker.js new file mode 100644 index 0000000000000000000000000000000000000000..e7d382d459d8f0fe54bd36926cd20befd67c5bfc --- /dev/null +++ b/pool/shard011/JavaScript/0070234_angular-daterangepicker.js @@ -0,0 +1,227 @@ +(function() { + var picker; + + picker = angular.module('daterangepicker', []); + + picker.constant('dateRangePickerConfig', { + separator: ' - ', + format: 'MM/DD/YYYY', + clearLabel: 'Clear' + }); + + picker.directive('dateRangePicker', function($compile, $timeout, $parse, dateRangePickerConfig) { + return { + require: 'ngModel', + restrict: 'A', + scope: { + dateMin: '=min', + dateMax: '=max', + model: '=ngModel', + opts: '=options', + clearable: '=' + }, + link: function($scope, element, attrs, modelCtrl) { + var clear, customOpts, el, opts, _formatted, _init, _picker, _setEndDate, _setStartDate, _validateMax, _validateMin; + el = $(element); + customOpts = $scope.opts; + opts = angular.extend({}, dateRangePickerConfig, customOpts); + _picker = null; + clear = function() { + _picker.setStartDate(); + _picker.setEndDate(); + return el.val(''); + }; + _setStartDate = function(newValue) { + return $timeout(function() { + var m; + if (_picker) { + if (!newValue) { + return clear(); + } else { + m = moment(newValue); + if (_picker.endDate < m) { + _picker.setEndDate(m); + } + return _picker.setStartDate(m); + } + } + }); + }; + _setEndDate = function(newValue) { + return $timeout(function() { + var m; + if (_picker) { + if (!newValue) { + return clear(); + } else { + m = moment(newValue); + if (_picker.startDate > m) { + _picker.setStartDate(m); + } + return _picker.setEndDate(m); + } + } + }); + }; + $scope.$watch('model.startDate', function(newValue) { + return _setStartDate(newValue); + }); + $scope.$watch('model.endDate', function(newValue) { + return _setEndDate(newValue); + }); + _formatted = function(viewVal) { + var f; + f = function(date) { + if (!moment.isMoment(date)) { + return moment(date).format(opts.format); + } + return date.format(opts.format); + }; + if (opts.singleDatePicker) { + return f(viewVal.startDate); + } else { + return [f(viewVal.startDate), f(viewVal.endDate)].join(opts.separator); + } + }; + _validateMin = function(min, start) { + var valid; + min = moment(min); + start = moment(start); + valid = min.isBefore(start) || min.isSame(start, 'day'); + modelCtrl.$setValidity('min', valid); + return valid; + }; + _validateMax = function(max, end) { + var valid; + max = moment(max); + end = moment(end); + valid = max.isAfter(end) || max.isSame(end, 'day'); + modelCtrl.$setValidity('max', valid); + return valid; + }; + modelCtrl.$formatters.push(function(val) { + if (val && val.startDate && val.endDate) { + _setStartDate(val.startDate); + _setEndDate(val.endDate); + return val; + } + return ''; + }); + modelCtrl.$parsers.push(function(val) { + var startend; + if (angular.isString(val)) { + startend = val.split(opts.separator); + val = { + startDate: moment(startend[0], opts.format), + endDate: moment(startend[1], opts.format) + }; + } + if (!angular.isObject(val) || !(val.hasOwnProperty('startDate') && val.hasOwnProperty('endDate'))) { + return modelCtrl.$modelValue; + } + if ($scope.dateMin && val.startDate) { + _validateMin($scope.dateMin, val.startDate); + } else { + modelCtrl.$setValidity('min', true); + } + if ($scope.dateMax && val.endDate) { + _validateMax($scope.dateMax, val.endDate); + } else { + modelCtrl.$setValidity('max', true); + } + return val; + }); + modelCtrl.$isEmpty = function(val) { + return !val || val.startDate === null || val.endDate === null; + }; + modelCtrl.$render = function() { + if (!modelCtrl.$modelValue) { + return el.val(''); + } + if (modelCtrl.$modelValue.startDate === null) { + return el.val(''); + } + return el.val(_formatted(modelCtrl.$modelValue)); + }; + _init = function() { + var callbackFunction, eventType, locale, _ref; + el.daterangepicker(opts, function(start, end) { + $timeout(function() { + return modelCtrl.$setViewValue({ + startDate: start, + endDate: end + }); + }); + return modelCtrl.$render(); + }); + _picker = el.data('daterangepicker'); + _ref = opts.eventHandlers; + for (eventType in _ref) { + callbackFunction = _ref[eventType]; + el.on(eventType, callbackFunction); + } + if (attrs.clearable) { + locale = opts.locale || {}; + locale.cancelLabel = opts.clearLabel; + opts.locale = locale; + el.on('cancel.daterangepicker', function() { + modelCtrl.$setViewValue({ + startDate: null, + endDate: null + }); + modelCtrl.$render(); + return el.trigger('change'); + }); + } + }; + _init(); + el.change(function() { + if ($.trim(el.val()) === '') { + return $timeout(function() { + return modelCtrl.$setViewValue({ + startDate: null, + endDate: null + }); + }); + } + }); + if (attrs.min) { + $scope.$watch('dateMin', function(date) { + if (date) { + if (!modelCtrl.$isEmpty(modelCtrl.$modelValue)) { + _validateMin(date, modelCtrl.$modelValue.startDate); + } + opts['minDate'] = moment(date); + } else { + opts['minDate'] = false; + } + return _init(); + }); + } + if (attrs.max) { + $scope.$watch('dateMax', function(date) { + if (date) { + if (!modelCtrl.$isEmpty(modelCtrl.$modelValue)) { + _validateMax(date, modelCtrl.$modelValue.endDate); + } + opts['maxDate'] = moment(date); + } else { + opts['maxDate'] = false; + } + return _init(); + }); + } + if (attrs.options) { + $scope.$watch('opts', function(newOpts) { + opts = angular.extend(opts, newOpts); + return _init(); + }); + } + return $scope.$on('$destroy', function() { + return _picker != null ? _picker.remove() : void 0; + }); + } + }; + }); + +}).call(this); diff --git a/pool/shard011/JavaScript/0070236_main.js b/pool/shard011/JavaScript/0070236_main.js new file mode 100644 index 0000000000000000000000000000000000000000..fefdce6a9247d1fece9419e6a686b5c31823b0d8 --- /dev/null +++ b/pool/shard011/JavaScript/0070236_main.js @@ -0,0 +1,116 @@ +var TD = { + pixiStage: null, + renderer: null, + monsters: [], + bullets: [], + towers: [], + map: null +}; + +TD.Displayable = Class.extend({ + init: function(parent, textureSrc, pos, scale){ + this.parent = parent; + + if (textureSrc) { + this.sprite = new PIXI.Sprite(PIXI.Texture.fromImage(textureSrc)); + } else { + this.sprite = new PIXI.DisplayObjectContainer(); + } + + + if (pos) { + this.sprite.position.x = pos.x; + this.sprite.position.y = pos.y; + } + + if (scale) { + this.sprite.scale.x = scale.x; + this.sprite.scale.y = scale.y; + } + + parent.addChild(this.sprite); + } +}); + + + +$(function() { + TD.renderer = new PIXI.autoDetectRenderer(1000, 735); + document.body.appendChild(TD.renderer.view); + scaleRenderer(); + + $(window).resize(scaleRenderer); + TD.pixiStage = new PIXI.Stage; + requestAnimationFrame(animate); + + if (Math.random() < 0.5) { + TD.map = new TD.Map1(); + } else { + TD.map = new TD.Map2(); + } + + + TD.mapAdded(); + + function animate() { + + if (TD.map !== null) { + drawMap(); + } + + TD.renderer.render(TD.pixiStage); + requestAnimationFrame(animate); + } + + function drawMap() { + for(var i in TD.monsters) { + var m = TD.monsters[i]; + if (m.alive === false) { + m.parent.removeChild(m.sprite); + TD.monsters.splice(TD.monsters.indexOf(m), 1); + } else { + m.updatePosition(); + } + } + + for(var i in TD.bullets) { + var b = TD.bullets[i]; + if (b.alive === false) { + b.parent.removeChild(b.sprite); + TD.bullets.splice(TD.bullets.indexOf(b), 1); + } else { + b.updatePosition(); + } + } + + for(var i in TD.towers) { + TD.towers[i].tryshoot(); + } + + TD.map.zIndex(); + } + +}); + +function scaleRenderer() { + TD.renderer.view.style.width = window.innerWidth + "px"; + TD.renderer.view.style.height = window.innerHeight + "px"; +} + +function getRandomInt(min, max) { + return Math.floor(Math.random() * (max - min + 1) + min); +} + +function distance(pos1, pos2) { + var dx = pos1.x-pos2.x; + var dy = pos1.y-pos2.y; + var d = Math.sqrt(dx*dx + dy*dy); + + return {d:d, dy:dy, dx:dx}; +} + +TD.clearPixiStage = function() { + for(var i = TD.pixiStage.children.length - 1; i >= 0; i--) { + TD.pixiStage.removeChild(TD.pixiStage.children[i]); + } +} diff --git a/pool/shard011/JavaScript/0070242_resizeend.js b/pool/shard011/JavaScript/0070242_resizeend.js new file mode 100644 index 0000000000000000000000000000000000000000..ea31a7800ce284b5573e60eb454fffe6c78b8f59 --- /dev/null +++ b/pool/shard011/JavaScript/0070242_resizeend.js @@ -0,0 +1,67 @@ +/*@exclude*/ +/** + * Olli Lib + * This file is part of the Olli-Framework + * Copyright (c) 2012-2015 Oliver Jean Eifler + * + * @version 0.0.1 + * @link http://www.oliver-eifler.info/ + * @author Oliver Jean Eifler + * @license http://www.opensource.org/licenses/mit-license.php MIT License + * + * window.onresize fix and resize:end event + */ +_.define("resizeend",function(global,undefined) { +eval(_.include(["consts","util","event"])); +/*@endexclude*/ + + var resizeend$width = 0, + resizeend$height = 0, + resizeend$type = "resize:end", + resizeend$event = function() { + var event = DOC.createEvent('Event'); + event.initEvent(resizeend$type,true,true); + return event; + }(), + resizeend$orientation = resizeend$getOrientation(), + resizeend$timeout = null; + + function resizeend$dispatch() { + return HTML.dispatchEvent(resizeend$event); + } + function resizeend$getOrientation() { + return (WIN.orientation && WIN.orientation !== undefined) ? Math.abs(+WIN.orientation) % 180 : 0; + } + + + function resizeend$handler(event) { + var width = WIN.innerWidth, + height = WIN.innerHeight; + if (width == resizeend$width && height == resizeend$height) { + event.preventDefault(); + event.stopImmediatePropagation(); + return; + } + resizeend$width = width; + resizeend$height = height; + var orientation = resizeend$getOrientation; + if (orientation !== resizeend$orientation) + { + resizeend$dispatch(); + return resizeend$orientation = orientation; + } + clearTimeout(resizeend$timeout); + return resizeend$timeout = setTimeout(resizeend$dispatch, 100); + } + WIN.addEventListener("resize",resizeend$handler,false); + +/*!add custom event creator*/ +event$creators[resizeend$type] = function(node) { + var el = node[0]; + /*!only for window and */ + return ((el.window && el.window === el) || el.nodeType===1); +}; + +/*@exclude*/ +}); +/*@endexclude*/ \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070245_birthdateFromId.js b/pool/shard011/JavaScript/0070245_birthdateFromId.js new file mode 100644 index 0000000000000000000000000000000000000000..87a7e701fc979d5accc0af01f350e95d446747d9 --- /dev/null +++ b/pool/shard011/JavaScript/0070245_birthdateFromId.js @@ -0,0 +1,29 @@ +'use strict' + +const datePadding = require('../../lib/date-padding') + +module.exports = function birthdateFromId (id) { + if (!id) { + throw new Error('Missing required input') + } + + const personalid = id.toString().replace(/\D+/, '').toString() + + if (personalid.length !== 11) { + throw new Error('Input must be 11 digits') + } + + const now = new Date() + const personalYearEnd = parseInt(personalid.substr(4, 2), 10) + const realYearEnd = parseInt(now.getFullYear().toString().substr(2, 2), 10) + var realYearStart = parseInt(now.getFullYear().toString().substr(0, 2), 10) + var birthYear + + if (personalYearEnd > realYearEnd) { + realYearStart-- + } + + birthYear = realYearStart.toString() + datePadding(personalYearEnd.toString()) + + return personalid.substr(0, 2) + '.' + personalid.substr(2, 2) + '.' + birthYear +} diff --git a/pool/shard011/JavaScript/0070248_SimpleForm.qunit.js b/pool/shard011/JavaScript/0070248_SimpleForm.qunit.js new file mode 100644 index 0000000000000000000000000000000000000000..1b16253bbdc88ac03f4b894b9353a95293e964ae --- /dev/null +++ b/pool/shard011/JavaScript/0070248_SimpleForm.qunit.js @@ -0,0 +1,139 @@ +(function () { + "use strict"; + + sap.ui.require([ + "sap/ui/dt/test/report/QUnit", + "sap/ui/dt/test/ElementEnablementTest", + "sap/ui/rta/test/controlEnablingCheck", + "sap/m/Input", + "sap/m/Label", + "sap/ui/core/Title", + "sap/ui/layout/form/SimpleForm", + "sap/m/Toolbar", + "sap/m/Button" + ], function(QUnit, ElementEnablementTest, rtaControlEnablingCheck, Input, Label, Title, SimpleForm, Toolbar, Button) { + + var oElementEnablementTest = new ElementEnablementTest({ + type: "sap.ui.layout.form.SimpleForm", + create: function () { + return new SimpleForm({ + toolbar: new Toolbar({ + content : [ + Button({text: "Button"}) + ] + }), + content: [ + ] + }); + } + }); + oElementEnablementTest.run().then(function(oData) { + var oReport = new QUnit({ + data: oData + }); + oReport.destroy(); + }); + + // Move Action + var fnConfirmElement2IsOn1stPosition = function (oUiComponent, oViewAfterAction, assert) { + assert.strictEqual(oViewAfterAction.byId("simpleForm").getContent()[0].getId(), + oViewAfterAction.byId("title2").getId(), + "then the control has been moved to the first position"); + }; + var fnConfirmElement2IsOn2ndPosition = function (oUiComponent, oViewAfterAction, assert) { + assert.strictEqual(oViewAfterAction.byId("simpleForm").getContent()[3].getId(), + oViewAfterAction.byId("title2").getId(), + "then the control has been moved to the right position"); + }; + + rtaControlEnablingCheck("Checking the move action for SimpleForm control with first Group without title", { + xmlView: + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + + '' + , + action: { + name: "move", + controlId: "simpleForm", + parameter: function(oView) { + return { + movedElements: [{ + element: oView.byId("title2").getParent(), + sourceIndex: 1, + targetIndex: 0 + }], + source: { + aggregation: "form", + parent: oView.byId("simpleForm"), + publicAggregation: "formContainers", + publicParent: oView.byId("simpleForm") + }, + target: { + aggregation: "form", + parent: oView.byId("simpleForm"), + publicAggregation: "formContainers", + publicParent: oView.byId("simpleForm") + } + }; + } + }, + afterAction: fnConfirmElement2IsOn1stPosition, + afterUndo: fnConfirmElement2IsOn2ndPosition, + afterRedo: fnConfirmElement2IsOn1stPosition + }); + + //TODO please include when the controlEnablingCheck is ready for designtime propagation + + // AddSimpleFormGroup + // var fnComfirmGroupIsAddedWithNewLabel = function(oUiComponent, oViewAfterAction, assert) { + // assert.strictEqual(oViewAfterAction.byId("simpleForm").getContent()[2].getLabel(), + // "New Title", + // "then the new group is added with the correct Title"); + // }; + + // var fnConfirmNewGroupIsRemoved = function(oUiComponent, oViewAfterAction, assert) { + // assert.strictEqual(oViewAfterAction.byId("simpleForm").getContent()[2].getLabel(), + // "Old Title", + // "then the new group is removed"); + // }; + + // rtaControlEnablingCheck("Checking the move action for SimpleForm control with first Group without title", { + // xmlView: + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + + // '' + // , + // action: { + // name: "createContainer", + // controlId: "simpleForm--Form", + // parameter: function(oView) { + // return { + // label: "new Title", + // controlId: oView.createId(jQuery.sap.uid()), + // index: 1 + // }; + // } + // }, + // afterAction: fnComfirmGroupIsAddedWithNewLabel, + // afterUndo: fnConfirmNewGroupIsRemoved, + // afterRedo: fnComfirmGroupIsAddedWithNewLabel + // }); + + }); +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070249_test.js b/pool/shard011/JavaScript/0070249_test.js new file mode 100644 index 0000000000000000000000000000000000000000..468d0e83aaba37479c22252de40543ac0996c670 --- /dev/null +++ b/pool/shard011/JavaScript/0070249_test.js @@ -0,0 +1,19 @@ +'use strict' + +const test = require('tap').test +const phr = require('./') + +test('phr', function(t) { + + var h = [ 0, 38013462 ] + var out = phr(h) + t.equal(out, '38.0') + + var out = phr(h, 0, 3) + t.equal(out, '38.013') + + + var out = phr(h, 1e5, 3) + t.equal(out, '380.135') + t.end() +}) diff --git a/pool/shard011/JavaScript/0070251_monthpicker_events.js b/pool/shard011/JavaScript/0070251_monthpicker_events.js new file mode 100644 index 0000000000000000000000000000000000000000..c684f6916302c0bcb40b074dc9684765bf3c191c --- /dev/null +++ b/pool/shard011/JavaScript/0070251_monthpicker_events.js @@ -0,0 +1,128 @@ +/* + * monthpicker_events.js + */ +(function($) { + +var selectedThis = null, + selectedDate = null, + selectedInst = null; + +function callback(date, inst) { + selectedThis = this; + selectedDate = date; + selectedInst = inst; +} + +function callback2(year, inst) { + selectedThis = this; + selectedDate = year; + selectedInst = inst; +} + +test("events", function() { + expect( 24 ); + var dateStr, newMonthYear, inp2, + inp = TestHelpers.monthpicker.init("#inp", {onSelect: callback}), + date = new Date(); + // onSelect + inp.val("").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ENTER}); + equal(selectedThis, inp[0], "Callback selected this"); + equal(selectedInst, $.data(inp[0], TestHelpers.monthpicker.PROP_NAME), "Callback selected inst"); + equal(selectedDate, $.monthpicker.formatDate("mm/yy", date), + "Callback selected date"); + inp.val("").monthpicker("show"). + simulate("keydown", {ctrlKey: true, keyCode: $.ui.keyCode.DOWN}). + simulate("keydown", {keyCode: $.ui.keyCode.ENTER}); + date.setMonth(date.getMonth() + 3); + equal(selectedDate, $.monthpicker.formatDate("mm/yy", date), + "Callback selected date - ctrl+down"); + inp.val("").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ESCAPE}); + equal(selectedDate, $.monthpicker.formatDate("mm/yy", date), + "Callback selected date - esc"); + dateStr = "04/2008"; + inp.val(dateStr).monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ENTER}); + equal(dateStr, selectedDate, + "onSelect is called after enter keydown"); + + // onChangeYear + inp.monthpicker("option", {onChangeYear: callback2, onSelect: null}). + val("").monthpicker("show"); + newMonthYear = function(date) { + return date.getFullYear(); + }; + date = new Date(); + date.setDate(1); + + inp.simulate("keydown", {keyCode: $.ui.keyCode.PAGE_UP}); + date.setYear(date.getFullYear() - 1); + equal(selectedThis, inp[0], "Callback change year this"); + equal(selectedInst, $.data(inp[0], TestHelpers.monthpicker.PROP_NAME), "Callback change year inst"); + equal(selectedDate, newMonthYear(date), + "Callback change year date - pgup"); + + inp.simulate("keydown", {keyCode: $.ui.keyCode.PAGE_DOWN}); + date.setYear(date.getFullYear() + 1); + equal(selectedDate, newMonthYear(date), + "Callback change year date - pgdn"); + + inp.simulate("keydown", {ctrlKey: true, keyCode: $.ui.keyCode.PAGE_UP}); + date.setFullYear(date.getFullYear() - 3); + equal(selectedDate, newMonthYear(date), + "Callback change year date - ctrl+pgup"); + + inp.simulate("keydown", {ctrlKey: true, keyCode: $.ui.keyCode.HOME}); + equal(selectedDate, newMonthYear(new Date()), + "Callback change year date - ctrl+home"); + + inp.simulate("keydown", {ctrlKey: true, keyCode: $.ui.keyCode.PAGE_DOWN}); + date.setFullYear(new Date().getFullYear() + 3); + equal(selectedDate, newMonthYear(date), + "Callback change year date - ctrl+pgdn"); + + inp.monthpicker("setDate", new Date(2007, 2 - 1, 1)); + equal(selectedDate, "2007", "Callback change year date - setDate"); + selectedDate = null; + inp.monthpicker("setDate", new Date(2007, 2 - 1, 1)); + ok(selectedDate == null, "Callback change month/year date - setDate no change"); + + // onChangeYear step by 2 + inp.monthpicker("option", {stepYears: 2}). + monthpicker("hide").val("04/2008").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.PAGE_UP}); + date.setYear(2006); + equal(selectedDate, newMonthYear(date), + "Callback change month/year by 2 date - pgup"); + + inp.simulate("keydown", {keyCode: $.ui.keyCode.PAGE_DOWN}); + date.setYear(date.getFullYear() + 2); + equal(selectedDate, newMonthYear(date), + "Callback change month/year by 2 date - pgdn"); + + // onClose + inp.monthpicker("option", {onClose: callback, onChangeYear: null, stepMonths: 1}). + val("").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ESCAPE}); + equal(selectedThis, inp[0], "Callback close this"); + equal(selectedInst, $.data(inp[0], TestHelpers.monthpicker.PROP_NAME), "Callback close inst"); + equal(selectedDate, "", "Callback close date - esc"); + inp.val("").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ENTER}); + equal(selectedDate, $.monthpicker.formatDate("mm/yy", new Date()), + "Callback close date - enter"); + inp.val("02/04/2008").monthpicker("show"). + simulate("keydown", {keyCode: $.ui.keyCode.ESCAPE}); + equal(selectedDate, "02/04/2008", "Callback close date - preset"); + inp.val("02/04/2008").monthpicker("show"). + simulate("keydown", {ctrlKey: true, keyCode: $.ui.keyCode.END}); + equal(selectedDate, "", "Callback close date - ctrl+end"); + + inp2 = TestHelpers.monthpicker.init("#inp2"); + inp2.monthpicker().monthpicker("option", {onClose: callback}).monthpicker("show"); + inp2.monthpicker("hide"); + equal(selectedThis, inp2[0], "Callback close this"); +}); + +})(jQuery); diff --git a/pool/shard011/JavaScript/0070254_fields_helpers.js b/pool/shard011/JavaScript/0070254_fields_helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..1fe74c2b486fa949946c8e853e0ee07dd76c07b2 --- /dev/null +++ b/pool/shard011/JavaScript/0070254_fields_helpers.js @@ -0,0 +1,267 @@ +define(['backbone', 'jquery', 'underscore', 'common/js/spec_helpers/ajax_helpers', 'common/js/spec_helpers/template_helpers', + 'js/views/fields', + 'string_utils'], + function (Backbone, $, _, AjaxHelpers, TemplateHelpers, FieldViews) { + 'use strict'; + + var API_URL = '/api/end_point/v1'; + + var USERNAME = 'Legolas', + FULLNAME = 'Legolas Thranduil', + EMAIL = 'legolas@woodland.middlearth', + SELECT_OPTIONS = [['si', 'sindarin'], ['el', 'elvish'], ['na', 'nandor']]; + + var UserAccountModel = Backbone.Model.extend({ + idAttribute: 'username', + defaults: { + username: USERNAME, + name: FULLNAME, + email: EMAIL, + language: SELECT_OPTIONS[0][0] + }, + url: API_URL + }); + + var createFieldData = function (fieldType, fieldData) { + var data = { + model: fieldData.model || new UserAccountModel({}), + title: fieldData.title || 'Field Title', + valueAttribute: fieldData.valueAttribute, + helpMessage: fieldData.helpMessage || 'I am a field message', + placeholderValue: fieldData.placeholderValue || 'I am a placeholder message' + }; + + switch (fieldType) { + case FieldViews.DropdownFieldView: + data['required'] = fieldData.required || false; + data['options'] = fieldData.options || SELECT_OPTIONS; + break; + case FieldViews.LinkFieldView: + case FieldViews.PasswordFieldView: + data['linkTitle'] = fieldData.linkTitle || "Link Title"; + data['linkHref'] = fieldData.linkHref || "/path/to/resource"; + data['emailAttribute'] = 'email'; + break; + } + + _.extend(data, fieldData); + + return data; + }; + + var createErrorMessage = function(attribute, user_message) { + var field_errors = {}; + field_errors[attribute] = { + "user_message": user_message + }; + return { + "field_errors": field_errors + }; + }; + + var expectTitleToContain = function(view, expectedTitle) { + expect(view.$('.u-field-title').text().trim()).toContain(expectedTitle); + }; + + var expectMessageContains = function(view, expectedText) { + expect(view.$('.u-field-message').html()).toContain(expectedText); + }; + + var expectTitleAndMessageToContain = function(view, expectedTitle, expectedMessage) { + expectTitleToContain(view, expectedTitle); + expectMessageContains(view, expectedMessage); + }; + + var expectAjaxRequestWithData = function(requests, data) { + AjaxHelpers.expectJsonRequest( + requests, 'PATCH', API_URL, data + ); + }; + + var verifyMessageUpdates = function (view, data, timerCallback) { + + var message = 'Here to help!'; + + view.showHelpMessage(message); + expectMessageContains(view, message); + + view.showHelpMessage(); + expectMessageContains(view, view.helpMessage); + + view.showInProgressMessage(); + expectMessageContains(view, view.indicators.inProgress); + expectMessageContains(view, view.messages.inProgress); + + view.showSuccessMessage(); + expectMessageContains(view, view.indicators.success); + expectMessageContains(view, view.getMessage('success')); + + expect(timerCallback).not.toHaveBeenCalled(); + + view.showErrorMessage({ + responseText: JSON.stringify(createErrorMessage(data.valueAttribute, 'Ops, try again!.')), + status: 400 + }); + expectMessageContains(view, view.indicators.validationError); + + view.showErrorMessage({status: 500}); + expectMessageContains(view, view.indicators.error); + expectMessageContains(view, view.indicators.error); + }; + + var verifySuccessMessageReset = function (view) { + view.showHelpMessage(); + expectMessageContains(view, view.helpMessage); + view.showSuccessMessage(); + expectMessageContains(view, view.indicators.success); + jasmine.Clock.tick(7000); + // Message gets reset + expectMessageContains(view, view.helpMessage); + + view.showSuccessMessage(); + expectMessageContains(view, view.indicators.success); + // But if we change the message, it should not get reset. + view.showHelpMessage("Do not reset this!"); + jasmine.Clock.tick(7000); + expectMessageContains(view, "Do not reset this!"); + }; + + var verifyPersistence = function (fieldClass, requests) { + var fieldData = createFieldData(fieldClass, { + title: 'Username', + valueAttribute: 'username', + helpMessage: 'The username that you use to sign in to edX.', + validValue: 'My Name', + persistChanges: false, + messagePosition: 'header' + }); + var view = new fieldClass(fieldData).render(); + var valueInputSelector; + + switch (fieldClass) { + case FieldViews.TextFieldView: + valueInputSelector = '.u-field-value > input'; + break; + case FieldViews.DropdownFieldView: + valueInputSelector = '.u-field-value > select'; + _.extend(fieldData, {validValue: SELECT_OPTIONS[0][0]}); + break; + case FieldViews.TextareaFieldView: + valueInputSelector = '.u-field-value > textarea'; + break; + } + + view.$(valueInputSelector).val(fieldData.validValue).change(); + expect(view.fieldValue()).toBe(fieldData.validValue); + expectMessageContains(view, view.helpMessage); + AjaxHelpers.expectNoRequests(requests); + }; + + var verifyEditableField = function (view, data, requests) { + var request_data = {}; + var url = view.model.url; + + if (data.editable === 'toggle') { + expect(view.el).toHaveClass('mode-placeholder'); + expectTitleToContain(view, data.title); + expectMessageContains(view, view.indicators.canEdit); + view.$el.click(); + } else { + expectTitleAndMessageToContain(view, data.title, data.helpMessage, false); + } + expect(view.el).toHaveClass('mode-edit'); + + if (view.fieldValue() !== null) { + expect(view.fieldValue()).not.toContain(data.validValue); + } + + view.$(data.valueInputSelector).val(data.validValue).change(); + // When the value in the field is changed + expect(view.fieldValue()).toBe(data.validValue); + expectMessageContains(view, view.indicators.inProgress); + expectMessageContains(view, view.messages.inProgress); + request_data[data.valueAttribute] = data.validValue; + AjaxHelpers.expectJsonRequest( + requests, 'PATCH', url, request_data + ); + + AjaxHelpers.respondWithNoContent(requests); + // When server returns success. + if (data.editable === 'toggle') { + expect(view.el).toHaveClass('mode-display'); + view.$el.click(); + } else { + expectMessageContains(view, view.indicators.success); + } + + view.$(data.valueInputSelector).val(data.invalidValue1).change(); + request_data[data.valueAttribute] = data.invalidValue1; + AjaxHelpers.expectJsonRequest( + requests, 'PATCH', url, request_data + ); + AjaxHelpers.respondWithError(requests, 500); + // When server returns a 500 error + expectMessageContains(view, view.indicators.error); + expectMessageContains(view, view.messages.error); + expect(view.el).toHaveClass('mode-edit'); + + view.$(data.valueInputSelector).val(data.invalidValue2).change(); + request_data[data.valueAttribute] = data.invalidValue2; + AjaxHelpers.expectJsonRequest( + requests, 'PATCH', url, request_data + ); + AjaxHelpers.respondWithError(requests, 400, createErrorMessage(data.valueAttribute, data.validationError)); + // When server returns a validation error + expectMessageContains(view, view.indicators.validationError); + expectMessageContains(view, data.validationError); + expect(view.el).toHaveClass('mode-edit'); + + view.$(data.valueInputSelector).val('').change(); + // When the value in the field is changed + expect(view.fieldValue()).toBe(data.defaultValue); + request_data[data.valueAttribute] = data.defaultValue; + AjaxHelpers.expectJsonRequest( + requests, 'PATCH', url, request_data + ); + AjaxHelpers.respondWithNoContent(requests); + // When server returns success. + if (data.editable === 'toggle') { + expect(view.el).toHaveClass('mode-placeholder'); + } else { + expect(view.el).toHaveClass('mode-edit'); + } + }; + + var verifyTextField = function (view, data, requests) { + verifyEditableField(view, _.extend({ + valueSelector: '.u-field-value', + valueInputSelector: '.u-field-value > input' + }, data + ), requests); + }; + + var verifyDropDownField = function (view, data, requests) { + verifyEditableField(view, _.extend({ + valueSelector: '.u-field-value', + valueInputSelector: '.u-field-value > select' + }, data + ), requests); + }; + + return { + SELECT_OPTIONS: SELECT_OPTIONS, + UserAccountModel: UserAccountModel, + createFieldData: createFieldData, + createErrorMessage: createErrorMessage, + expectTitleToContain: expectTitleToContain, + expectTitleAndMessageToContain: expectTitleAndMessageToContain, + expectMessageContains: expectMessageContains, + expectAjaxRequestWithData: expectAjaxRequestWithData, + verifyMessageUpdates: verifyMessageUpdates, + verifySuccessMessageReset: verifySuccessMessageReset, + verifyEditableField: verifyEditableField, + verifyTextField: verifyTextField, + verifyDropDownField: verifyDropDownField, + verifyPersistence: verifyPersistence + }; + }); diff --git a/pool/shard011/JavaScript/0070255_index.js b/pool/shard011/JavaScript/0070255_index.js new file mode 100644 index 0000000000000000000000000000000000000000..e56d970cbb7a00f6a4de163e8c89459e12942b7d --- /dev/null +++ b/pool/shard011/JavaScript/0070255_index.js @@ -0,0 +1,55 @@ +/* + * Created 2014 Triangle717 + * + * + * Source code licensed under The MIT License + * + * + * Dedicated to the good folks at Rock Raiders United + * + */ + + +var $timer = $("#timer"), + $sandwich = $(".sandwich"), + $saveScore = $(".submit-dialog"), + clickCount = 0, + audioPlayers = []; + + +// Initialize stopwatch +$(function() { + "use strict"; + $timer.runner(); +}); + + +/** + * Test for HTML5 audio compatibility, preferring MP3 audio + * Taken from http://diveintohtml5.info/everything.html#audio-mp3 + */ +var _a = document.createElement("audio"); +var audioFile = (!!(_a.canPlayType && _a.canPlayType("audio/mpeg;").replace(/no/, ""))) ? + "audio/landslide.mp3" : "audio/landslide.ogg"; + + +// Start the timer only once +$sandwich.one("click", function() { + "use strict"; + $timer.runner("start"); +}); + + +// Trigger new landslides with each click of the sandwich +$sandwich.on("click", function() { + "use strict"; + // Keep track of times the user has clicked the sandwich + clickCount += 1; + + // On each click of the sandwich, trigger a landslide + var aLandslide = new Audio(audioFile); + aLandslide.loop = true; + aLandslide.load(); + aLandslide.play(); + audioPlayers.push(aLandslide); +}); diff --git a/pool/shard011/JavaScript/0070256_maybe_example.js b/pool/shard011/JavaScript/0070256_maybe_example.js new file mode 100644 index 0000000000000000000000000000000000000000..354ba411697e4f564d2893af7b03805b40bd7a28 --- /dev/null +++ b/pool/shard011/JavaScript/0070256_maybe_example.js @@ -0,0 +1,41 @@ +var Funky = require("./../dist/funky.min"); +var Students = require("./student"); + +var getGrades = function (student) { + return Funky.read(Funky.prop("grades"), student); +}; + +var calculateAverage = function (arr) { + var sum = 0; + arr.forEach(function (e) { + sum += e; + }); + return sum / arr.length; +} + +function calculateAverageGrade(student) { + return Funky.Maybe + .fromNullable(student) + .map(getGrades) + .map(calculateAverage) + .getOrElse("Cannot calculate average grade, null value provided"); +} + +/** + * Maybe monad handles nullable values and enables the creation of null tolerant processing pipeline. + * Null checking logic is provided automatically, there is no need to use 'if' statements. + */ +function demoMaybeMonad() { + /** + * Calculate average grade for a given student + */ + var gradeAverage = calculateAverageGrade(Students[0]); + console.log("Average grade: " + gradeAverage); + /** + * Calculate average grade for a null student + */ + var gradeAverageNull = calculateAverageGrade(null); + console.log(gradeAverageNull); +} + +demoMaybeMonad(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070257_truncate.js b/pool/shard011/JavaScript/0070257_truncate.js new file mode 100644 index 0000000000000000000000000000000000000000..a935471a9af202f8487a361c7bbdab72acc8a71f --- /dev/null +++ b/pool/shard011/JavaScript/0070257_truncate.js @@ -0,0 +1,327 @@ +/* Truncate.js - v0.1.0 + * Copyright 2013, Jeff Chan + * Released under the MIT license + * More Information: http://github.com/jeffchan/truncate.js + */ +(function (module, $, undefined) { + + var BLOCK_TAGS = ['table', 'thead', 'tbody', 'tfoot', 'tr', 'col', 'colgroup', 'object', 'embed', 'param', 'ol', 'ul', 'dl', 'blockquote', 'select', 'optgroup', 'option', 'textarea', 'script', 'style']; + + function setText(element, text) { + if (element.innerText) { + element.innerText = text; + } else if (element.nodeValue) { + element.nodeValue = text; + } else if (element.textContent) { + element.textContent = text; + } else { + return false; + } + } + + /* Truncate the nearest sibling node. + * If no valid immediate sibling is found, traverse one level up to a cousin node. + * + * $element - The jQuery node to truncate. + * $rootNode - The jQuery root node to measure the truncated height. + * $clipNode - The jQuery node to insert right after the truncation point. + * options - An object containing: + * ellipsis - The ellipsis string to append at the end of the truncation. + * maxHeight - The maximum height for the root node. + * + * Returns true if truncation happened, false otherwise. + */ + function truncateNearestSibling($element, $rootNode, $clipNode, options) { + var $parent = $element.parent(); + var $prevSibling; + + $element.remove(); + + // Take into account length of $clipNode element previous inserted. + var clipLength = $clipNode ? $clipNode.length : 0; + + if ($parent.contents().length > clipLength) { + + // Valid previous sibling element (sharing same parent node) exists, + // so attempt to truncate it. + $prevSibling = $parent.contents().eq(-1 - clipLength); + return truncateTextContent($prevSibling, $rootNode, $clipNode, options); + + } else { + + // No previous sibling element (sharing same parent node) exists. + // Therefore, search parent's sibling. + + var $parentSibling = $parent.prev(); + $prevSibling = $parentSibling.contents().eq(-1); + + if ($prevSibling.length) { + + // Because traversal is in-order so the algorithm already checked that + // this point meets the height requirement. As such, it's safe to truncate here. + setText($prevSibling[0], $prevSibling.text() + options.ellipsis); + $parent.remove(); + + if ($clipNode.length) { + $parentSibling.append($clipNode); + } + return true; + } + } + + return false; + } + + /* Truncates the text content of a node using binary search. + * If no valid truncation point is found, attempt to truncate its nearest sibling. + * + * $textNode - The jQuery node to truncate. + * $rootNode - The jQuery root node to measure the truncated height. + * $clipNode - The jQuery node to insert right after the truncation point. + * options - An object containing: + * ellipsis - The ellipsis string to append at the end of the truncation. + * maxHeight - The maximum height for the root node. + * + * Returns true if truncation happened, false otherwise. + */ + function truncateTextContent($element, $rootNode, $clipNode, options) { + var element = $element[0]; + var original = $element.text(); + + var maxChunk = ''; + var mid, chunk; + var low = 0; + var high = original.length; + + // Binary Search + while (low <= high) { + mid = low + ((high - low) >> 1); // Integer division + + chunk = $.trim(original.substr(0, mid + 1)) + options.ellipsis; + setText(element, chunk); + + if ($rootNode.height() > options.maxHeight) { + high = mid - 1; + } else { + low = mid + 1; + maxChunk = maxChunk.length > chunk.length ? maxChunk : chunk; + } + } + + if (maxChunk.length > 0) { + setText(element, maxChunk); + return true; + } else { + return truncateNearestSibling($element, $rootNode, $clipNode, options); + } + } + + /* Recursively truncates a nested node. Traverses the children node tree in-rder. + * + * $element - The jQuery nested node to truncate. + * $rootNode - The jQuery root node to measure the truncated height. + * $clipNode - The jQuery node to insert right after the truncation point. + * options - An object containing: + * ellipsis - The ellipsis string to append at the end of the truncation. + * maxHeight - The maximum height for the root node. + * + * Returns true if truncation happened, false otherwise. + */ + function truncateNestedNode($element, $rootNode, $clipNode, options) { + var element = $element[0]; + + var $children = $element.contents(); + var $child, child; + + var index = 0; + var length = $children.length; + var truncated = false; + + $element.empty(); + + for (; index < length && !truncated; index++) { + + $child = $children.eq(index); + child = $child[0]; + + if (child.nodeType === 8) { // comment node + continue; + } + + element.appendChild(child); + + if ($clipNode.length) { + if ($.inArray(element.tagName.toLowerCase(), BLOCK_TAGS) >= 0) { + // Certain elements like
  • should not be appended to. + $element.after($clipNode); + } else { + $element.append($clipNode); + } + } + + if ($rootNode.height() > options.maxHeight) { + if (child.nodeType === 3) { // text node + truncated = truncateTextContent($child, $rootNode, $clipNode, options); + } else { + truncated = truncateNestedNode($child, $rootNode, $clipNode, options); + } + } + + if (!truncated && $clipNode.length) { $clipNode.remove(); } + + } + + return truncated; + } + + /* Public: Creates an instance of Truncate. + * + * element - A DOM element to be truncated. + * options - An Object literal containing setup options. + * + * Examples: + * + * var element = document.createElement('span'); + * element.innerHTML = 'This is
    odd.'; + * var truncated = new Truncate(element, { + * lines: 1, + * lineHeight: 16, + * ellipsis: '… ', + * showMore: 'Show More', + * showLess: 'Show Less' + * }); + * + * // Update HTML + * truncated.update('This is not very odd.'); + * + * // Undo truncation + * truncated.expand(); + * + * // Redo truncation + * truncated.collapse(); + */ + function Truncate(element, options) { + this.element = element; + this.$element = $(element); + + this._name = 'truncate'; + this._defaults = { + lines: 1, + ellipsis: '…', + showMore: '', + showLess: '' + }; + + this.options = $.extend({}, this._defaults, options); + this.options.maxHeight = parseInt(this.options.lines, 10) * parseInt(this.options.lineHeight, 10); + + this.$clipNode = $($.parseHTML(this.options.showMore), this.$element); + + this.original = this.cached = element.innerHTML; + + this.isTruncated = false; // True if the original content overflows the container. + this.isCollapsed = true; // True if the container is currently collapsed. + + this.update(); + } + + Truncate.prototype = { + + /* Public: Updates the inner HTML of the element and re-truncates. Will not + * perform an updade if the container is currently expanded, instead it + * will wait until the next time .collapse() is called. + * + * html - The new HTML. + * + * Returns nothing. + */ + update: function (html) { + var wasExpanded = !this.isCollapsed; + + // Update HTML if provided, otherwise use the current html and restore + // the truncated content to the original if it's currently present. + if (html) { + this.original = this.element.innerHTML = html; + } else if (this.isCollapsed && this.element.innerHTML === this.cached) { + this.element.innerHTML = this.original; + } + + // Wrap the contents in order to ignore container's margin/padding. + var $wrap = this.$element.wrapInner('
    ').children(); + $wrap.css({ + border : 'none', + margin : 0, + padding: 0, + width : 'auto', + height : 'auto' + }); + + this.isTruncated = false; + // Check if already meets height requirement + if ($wrap.height() > this.options.maxHeight) { + this.isTruncated = truncateNestedNode($wrap, $wrap, this.$clipNode, this.options); + } else { + this.isCollapsed = false; + } + + // Restore the wrapped contents + $wrap.replaceWith($wrap.contents()); + + // Cache the truncated content + this.cached = this.element.innerHTML; + + // If the container was expanded when .update() was called then restore + // it to it's previous state. + if (wasExpanded) { + this.element.innerHTML = this.original; + } + }, + + /* Public: Expands the element to show content in full. + * + * Returns nothing. + */ + expand: function () { + if (!this.isCollapsed) { return; } + + this.isCollapsed = false; + this.element.innerHTML = this.isTruncated ? this.original + this.options.showLess : this.original; + }, + + /* Public: Collapses the element to the truncated state. + * Uses the cached HTML from .update() by default. + * + * retruncate - True to retruncate original HTML, otherwise use cached HTML. + * + * Returns nothing. + */ + collapse: function (retruncate) { + if (this.isCollapsed) { return; } + + this.isCollapsed = true; + + retruncate = retruncate || false; + if (retruncate) { + this.update(); + } else { + this.element.innerHTML = this.cached; + } + } + }; + + // Lightweight plugin wrapper preventing multiple instantiations + $.fn.truncate = function (options) { + var args = $.makeArray(arguments).slice(1); + return this.each(function () { + var truncate = $.data(this, 'jquery-truncate'); + if (!truncate) { + $.data(this, 'jquery-truncate', new Truncate(this, options)); + } else if (typeof truncate[options] === 'function') { + truncate[options].apply(truncate, args); + } + }); + }; + + module.Truncate = Truncate; + +})(this, jQuery); diff --git a/pool/shard011/JavaScript/0070258_nullabletext.js b/pool/shard011/JavaScript/0070258_nullabletext.js new file mode 100644 index 0000000000000000000000000000000000000000..a1d9644bef089fec2950c93383b6b08c7a1ab395 --- /dev/null +++ b/pool/shard011/JavaScript/0070258_nullabletext.js @@ -0,0 +1,30 @@ +(function($) { + var NullableText = { + 'update_field_status': function ($obj) { + var $isnull = $('#' + $obj.attr('id') + '_isnull'); + if ($obj.val().length > 0) { + $isnull.removeAttr("checked"); + } + if ($isnull.is(":checked")) { + $obj.val('').attr('disabled', 'disabled').attr('readOnly', 'readOnly'); + } else { + $obj.removeAttr('disabled').removeAttr('readOnly'); + } + }, + 'null_event': function (isnull_obj) { + var id = $(isnull_obj).attr('id'); + NullableText.update_field_status($('#' + id.substring(0, id.length - 7))); + }, + 'input_event': function (obj) { + NullableText.update_field_status($(obj)); + } + }; + + $(document).ready(function() { + $('.nullable_text').each(function () { + NullableText.update_field_status($(this)); + }); + }); + + window.NullableText = NullableText; +})(django.jQuery); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070260_retweet.js b/pool/shard011/JavaScript/0070260_retweet.js new file mode 100644 index 0000000000000000000000000000000000000000..672a2231edeacb1be4b3514764b04dd740d24398 --- /dev/null +++ b/pool/shard011/JavaScript/0070260_retweet.js @@ -0,0 +1,168 @@ +/* + * Easy Retweet Button + * http://ejohn.org/blog/retweet/ + * by John Resig (ejohn.org) + * + * Licensed under the MIT License: + * http://www.opensource.org/licenses/mit-license.php + */ + +(function(){ + +window.RetweetJS = { + // Your Bit.ly Username + bitly_user: "retweetjs", + + // Your Bit.ly API Key + // Found here: http://bit.ly/account + bitly_key: "R_6287c92ecaf9efc6f39e4f33bdbf80b1", + + // The text to replace the links with + link_text: "♻ Retweet", + + // What # to show (Use "clicks" for # of clicks or "none" for nothing) + count_type: "none", + + // Tweet Prefix text + // "RT @jeresig " would result in: "RT @jeresig Link Title http://bit.ly/asdf" + prefix: "", + + // Style information + styling: false +}; + +//////////////// No Need to Configure Below Here //////////////// + +var loadCount = 1; + +// Asynchronously load the Bit.ly JavaScript API +// If it hasn't been loaded already +if ( typeof BitlyClient === "undefined" ) { + var head = document.getElementsByTagName("head")[0] || + document.documentElement; + var script = document.createElement("script"); + script.src = "http://bit.ly/javascript-api.js?version=latest&login=" + + RetweetJS.bitly_user + "&apiKey=" + RetweetJS.bitly_key; + script.charSet = "utf-8"; + head.appendChild( script ); + + var check = setInterval(function(){ + if ( typeof BitlyCB !== "undefined" ) { + clearInterval( check ); + head.removeChild( script ); + loaded(); + } + }, 10); + + loadCount = 0; +} + +if ( document.addEventListener ) { + document.addEventListener("DOMContentLoaded", loaded, false); + +} else if ( window.attachEvent ) { + window.attachEvent("onload", loaded); +} + +function loaded(){ + // Need to wait for doc ready and js ready + if ( ++loadCount < 2 ) { + return; + } + + var elems = [], urlElem = {}, hashURL = {}; + + BitlyCB.shortenResponse = function(data) { + for ( var url in data.results ) { + var hash = data.results[url].userHash; + hashURL[hash] = url; + + var elems = urlElem[ url ]; + + for ( var i = 0; i < elems.length; i++ ) { + elems[i].href += hash; + } + + if ( RetweetJS.count_type === "clicks" ) { + BitlyClient.stats(hash, 'BitlyCB.statsResponse'); + } + } + }; + + BitlyCB.statsResponse = function(data) { + var clicks = data.results.clicks, hash = data.results.userHash; + var url = hashURL[ hash ], elems = urlElem[ url ]; + + if ( clicks > 0 ) { + for ( var i = 0; i < elems.length; i++ ) { + var strong = document.createElement("strong"); + strong.appendChild( document.createTextNode( clicks + " " ) ); + elems[i].insertBefore(strong, elems[i].firstChild); + + if ( /(^|\s)vert(\s|$)/.test( elems[i].className ) ) { + elems[i].firstChild.className = elems[i].lastChild.className = "vert"; + } + } + } + + hashURL[ hash ] = urlElem[ url ] = null; + }; + + if ( document.getElementsByClassName ) { + elems = document.getElementsByClassName("retweet"); + } else { + var tmp = document.getElementsByTagName("a"); + for ( var i = 0; i < tmp.length; i++ ) { + if ( /(^|\s)retweet(\s|$)/.test( tmp[i].className ) ) { + elems.push( tmp[i] ); + } + } + } + + if ( elems.length && RetweetJS.styling ) { + var style = document.createElement("style"); + + style.type = "text/css"; + + try { + style.appendChild( document.createTextNode( RetweetJS.styling ) ); + } catch (e) { + if ( style.styleSheet ) { + style.styleSheet.cssText = RetweetJS.styling; + } + } + var head = document.getElementsByTagName("head")[0]; + if( head == null ) { + document.body.appendChild( style ); + } else { + head.appendChild( style ); + } + } + + for ( var i = 0; i < elems.length; i++ ) { + var elem = elems[i]; + + if ( /(^|\s)self(\s|$)/.test( elem.className ) ) { + elem.href = window.location; + elem.title = document.title; + } + + var origText = elem.title || elem.textContent || elem.innerText, + href = elem.href; + + elem.innerHTML = "" + RetweetJS.link_text + ""; + elem.title = ""; + elem.href = "http://twitter.com/home?status=" + + encodeURIComponent(RetweetJS.prefix + origText + " http://bit.ly/"); + + if ( urlElem[ href ] ) { + urlElem[ href ].push( elem ); + } else { + urlElem[ href ] = [ elem ]; + BitlyClient.shorten(href, 'BitlyCB.shortenResponse'); + } + } + +} + +})(); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070261_CommunicationService.js b/pool/shard011/JavaScript/0070261_CommunicationService.js new file mode 100644 index 0000000000000000000000000000000000000000..c5e101f0fa1947f40a6bc87940a8931622b04fb0 --- /dev/null +++ b/pool/shard011/JavaScript/0070261_CommunicationService.js @@ -0,0 +1,114 @@ +import { browserHistory } from 'react-router'; +import {gm} from '../common/Common' + +class CommunicationService { + constructor() { + this.stack = []; + this.subscribeMap = {}; + } + + init(store) { + this.store = store; + } + + dispatch(action, callback) { + this.currentAction = action; + action.options = action.options||{} + if (callback!==undefined) { + action.options.type = "CALLBACK"; + action.options.callback = callback; + } + + this.store.dispatch(action); + } + subscribe(type, listener, owner) { + var self = this; + //tracking subscribed type + this.subscribeMap[type] = this.store.subscribe(()=>{ + //We filter by type so that we won't call the handle when type is not match + if (cs.currentAction.type===type) { + if (owner){ + listener.apply(owner, [cs.currentAction]); + } else { + listener(cs.currentAction); + } + + } + }); + return this.subscribeMap[type]; + } + unsubscribe(type) { + if (this.subscribeMap[type]===undefined) { + return; + } + this.subscribeMap[type](); + delete this.subscribeMap[type]; + } + registerGlobal(key, obj) { + window[key] = obj; + } + + getState(key) { + let state = this.store.getState(); + if (key===undefined) { + return state; + } else { + return state[key]; + } + } + popup(c, id) { + let isEmpty = this.isStackEmpty(); + this.stack.push(browserHistory.getCurrentLocation().pathname); + this.selectedPopup = [c, id]; + if (this.stack.length===1) { + this.popupBase = browserHistory.getCurrentLocation() + } + + if (isEmpty) { + this.go('popup'); + } else { + this.dispatch({"type":"pushPopup", "data":[c, id]}) + } + + } + popStack() { + this.stack.pop(); + if (this.stack.length===0) { + this.selectedPopup = null; + } + } + + go(url) { + browserHistory.push(url); + } + goBack() { + browserHistory.goBack(); + } + isStackEmpty() { + return this.stack.length==0; + } + + isStackContain(c) { + for (let i=0; i'); + this.view.setContent(template); + this.view.set('tooltip', tooltip); + this.view.set('closable', true); + + workbench.appendView(this.view, 'bottom'); + } + }; + + ViewCommand.prototype.getView = function () { + return this.view; + }; + + return ViewCommand; +}); diff --git a/pool/shard011/JavaScript/0070267_abstractRule.js b/pool/shard011/JavaScript/0070267_abstractRule.js new file mode 100644 index 0000000000000000000000000000000000000000..070be5ffac3c9e73ac233e0a6ad65bf8a4c81bbe --- /dev/null +++ b/pool/shard011/JavaScript/0070267_abstractRule.js @@ -0,0 +1,34 @@ +"use strict"; +var AbstractRule = (function () { + function AbstractRule(ruleName, value, disabledIntervals) { + var ruleArguments = []; + if (Array.isArray(value) && value.length > 1) { + ruleArguments = value.slice(1); + } + this.value = value; + this.options = { + disabledIntervals: disabledIntervals, + ruleArguments: ruleArguments, + ruleName: ruleName + }; + } + AbstractRule.prototype.getOptions = function () { + return this.options; + }; + AbstractRule.prototype.applyWithWalker = function (walker) { + walker.walk(walker.getSourceFile()); + return walker.getFailures(); + }; + AbstractRule.prototype.isEnabled = function () { + var value = this.value; + if (typeof value === "boolean") { + return value; + } + if (Array.isArray(value) && value.length > 0) { + return value[0]; + } + return false; + }; + return AbstractRule; +}()); +exports.AbstractRule = AbstractRule; diff --git a/pool/shard011/JavaScript/0070268_events.js b/pool/shard011/JavaScript/0070268_events.js new file mode 100644 index 0000000000000000000000000000000000000000..5a278a2385a8c7c03a58a183570bb00de8cc875b --- /dev/null +++ b/pool/shard011/JavaScript/0070268_events.js @@ -0,0 +1,27 @@ +var Promise = require('bluebird'); +var db = require('./mongoLabConnection.js') + +var events = db.get('events'); +Promise.promisifyAll(events); + +module.exports = { + + get: function(params) { + params = params || {}; + return events.findAsync(params); + }, + + insert: function(records) { + return events.insertAsync(records); + }, + + count: function() { + return events.countAsync({}); + }, + + remove: function(params) { + params = params || {}; + return events.removeAsync(params); + } + +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070269_defaults.js b/pool/shard011/JavaScript/0070269_defaults.js new file mode 100644 index 0000000000000000000000000000000000000000..08bcdbfd30378126d0479597afa56de81f295fac --- /dev/null +++ b/pool/shard011/JavaScript/0070269_defaults.js @@ -0,0 +1,80 @@ +const getElementById = require('../../../_common/common_functions').getElementById; +const isVisible = require('../../../_common/common_functions').isVisible; +const State = require('../../../_common/storage').State; +const Url = require('../../../_common/url'); +const isEmptyObject = require('../../../_common/utility').isEmptyObject; + +/* + * Handles trading page default values + * + * Priorities: + * 1. Client's input: on each change to form, it will reflect to both query string & session storage + * 2. Query string parameters: will change session storage values + * 3. Session storage values: if none of the above, it will be the source + * + */ + +const Defaults = (() => { + let params = {}; + const getDefault = (key) => { + const p_value = params[key] || Url.param(key); + const s_value = sessionStorage.getItem(key); + if (p_value && (!s_value || p_value !== s_value)) { + sessionStorage.setItem(key, p_value); + } + if (!p_value && s_value) { + setDefault(key, s_value); + } + return p_value || s_value; + }; + + const setDefault = (key, value = '') => { + if (!key) return; + if (isEmptyObject(params)) params = Url.paramsHash(); + if (params[key] !== value) { + params[key] = value; + // to increase speed, do not set values when form is still loading + if (!isVisible(getElementById('trading_init_progress'))) { + sessionStorage.setItem(key, value); + updateURL(); + } + } + }; + + const removeDefault = (...keys) => { + if (isEmptyObject(params)) params = Url.paramsHash(); + let is_updated = false; + keys.forEach((key) => { + if (key in params) { + sessionStorage.removeItem(key); + delete params[key]; + is_updated = true; + } + }); + if (is_updated) { + updateURL(); + } + }; + + const updateAll = () => { + Object.keys(params).forEach((key) => { + sessionStorage.setItem(key, params[key]); + }); + updateURL(); + }; + + const updateURL = () => { + if (!State.get('is_trading')) return; + Url.updateParamsWithoutReload(params, false); + }; + + return { + get : getDefault, + set : setDefault, + update: updateAll, + remove: removeDefault, + clear : () => { params = {}; }, + }; +})(); + +module.exports = Defaults; diff --git a/pool/shard011/JavaScript/0070271_login.controller.js b/pool/shard011/JavaScript/0070271_login.controller.js new file mode 100644 index 0000000000000000000000000000000000000000..99387a4afcd43d4ae4a11295908ac80495e9d3da --- /dev/null +++ b/pool/shard011/JavaScript/0070271_login.controller.js @@ -0,0 +1,31 @@ +/** + * Created by markel on 12.03.17. + */ +angular + .module('app') + .controller('Login.IndexController', Controller); + +function Controller($location, AuthenticationService) { + var vm = this; + + vm.login = login; + + initController(); + + function initController() { + // reset login status + AuthenticationService.Logout(); + }; + + function login() { + vm.loading = true; + AuthenticationService.Login(vm.username, vm.password, function (result) { + if (result === true) { + $location.path('/'); + } else { + vm.error = 'Username or password is incorrect'; + vm.loading = false; + } + }); + }; +} \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070276_codeGenerator.CustomHelpers.js b/pool/shard011/JavaScript/0070276_codeGenerator.CustomHelpers.js new file mode 100644 index 0000000000000000000000000000000000000000..9d50b1ae45aa0e7fc9069533c050f9d5dfd04f71 --- /dev/null +++ b/pool/shard011/JavaScript/0070276_codeGenerator.CustomHelpers.js @@ -0,0 +1,89 @@ +//@module blueHTML +var _ = require('underscore'); + + +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// TAGS // +////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + +//@class CodeGenerator +module.exports = { + + //@method _joinExternalFunctionParameters Internal method to join parameters used by external functions + //@param {Array} parameters + //@param {CodeGenerationContext} code_generation_context + //@return {String} + _joinExternalFunctionParameters: function (parameters, code_generation_context) + { + 'use strict'; + + var self = this; + + //TODO TAKE INTO ACCOUNT THAT PARAMETERS CAN BE REFERENCE VALUES (@index) + return _.reduce(parameters, function (acc, param) + { + switch (param.subType) { + case 'SIMPLEVALUE': + acc += ',' + param.value; + break; + case 'LOOKUPSINGLE': + acc += ',' + self._getLookUpContextName(code_generation_context, param); + break; + case 'SINGLEEVALUATION': + if ((+param.value).toString() === param.value) + { + //This is the case of numbers + acc += ',' + param.value; + } + else + { + acc += ',' + code_generation_context.currentContextName.value + '.' + param.value; + } + break; + default: + acc += ',' + param.value; + } + return acc; + }, ''); + }, + + //@method runtimeGenericSingleHandle This method converts all passed in function that represent extra helpers to string in a safe way + //@param {CodeGenerationContext} code_generation_context + //@return {Function} + runtimeGenericSingleHandle: function (code_generation_context) + { + 'use strict'; + + var fn = this['singleInstance' + code_generation_context.astNode.value].toString() + , result = '(function(){var fn = '+fn+'; return fn.call(this'+ this._joinExternalFunctionParameters(code_generation_context.astNode.parameters, code_generation_context)+'); })()'; + + if (code_generation_context.isSettingAttributes) + { + if (code_generation_context.isSettingValue) + { + return code_generation_context.objectName + '["'+code_generation_context.keyName+'"]+=' + result +';'; + } + else + { + return code_generation_context.objectName + '['+result+']="";'; + } + } + else + { + return code_generation_context.isInsideContext ? code_generation_context.variableName + '=' + code_generation_context.variableName + '.concat(['+result+']);' : result; + } + }, + + //@method runtimeGenericBlockHandle This method converts all passed in function that represent extra helpers to string in a safe way + //@param {CodeGenerationContext} code_generation_context + //@return {Function} + runtimeGenericBlockHandle: function (code_generation_context) + { + 'use strict'; + + var fn = this['blockInstance' + code_generation_context.astNode.openTag].toString() + , result = '(function(){var fn = '+fn+'; return fn.call(this'+ this._joinExternalFunctionParameters(code_generation_context.astNode.parameters, code_generation_context)+'); })()'; + + return code_generation_context.isInsideContext ? code_generation_context.variableName + '=' + code_generation_context.variableName + '.concat(['+result+']);' : result; + } +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070277_index.js b/pool/shard011/JavaScript/0070277_index.js new file mode 100644 index 0000000000000000000000000000000000000000..1d8d2a5c90d92a6461d242fbb9b63258a377fa87 --- /dev/null +++ b/pool/shard011/JavaScript/0070277_index.js @@ -0,0 +1,74 @@ +import _ from 'lodash'; +import winston from 'winston'; +import VK from 'vksdk'; +import Apartment from '../models/Apartment'; + +import {rgx} from '../helpers/rgx'; +import {ROOMS, PRICE, PHONE, STREET} from '../helpers/regexp.js'; + +// Configs +const groupsIds = ['ruby_ch']; +const vk = new VK({ + 'appId': 6015096, + 'appSecret': 'lpNkoSBzUFjCtBsYZWpV', + 'language': 'ru' +}); + +export default { + start() { + vk.request('groups.getById', { + group_ids: groupsIds.join(',') + }, answer => { + let res = answer.response; + if (res) { + res.map(group => { + vk.request('wall.get', { + owner_id: -Math.abs(group.id), + count: 10 + }, answer => { + let posts = answer.response.items; + + if (posts) { + posts.map(post => { + + if ( + post.post_type === 'post' && + post.attachments !== undefined && + post.text !== '' + ) { + + Apartment.find({description: post.text}).then(data => {if(data.length === 0) return;}); + + const apartmentObj = new Apartment({ + title: 'Test Title', + type: 'Flat', + street: _.get(rgx(STREET).exec(post.text, 0), 'res'), + rooms: _.get(rgx(ROOMS).exec(post.text, 0), 'res', '0').replace(/\D/g,''), + price: _.get(rgx(PRICE).exec(post.text, 0), 'res', '0').replace(/\D/g,''), + number: _.get(rgx(PHONE).exec(post.text, 0), 'res'), + vk_profile: post.from_id, + description: post.text, + images: _.map(post.attachments, P => P.photo["photo_604"]), + }); + + + apartmentObj.save() + .then(() => { + console.log('Post successfully saved!'); + }, err => { + // ignore duplicate key error, post_id + if (err.code !== 11000) { + winston.error(err); + } + }); + } + }); + } else { + winston.log('info', 'answer.response.items was empty'); + } + }); + }); + } + }); + } +} diff --git a/pool/shard011/JavaScript/0070278_requestFileSystem.js b/pool/shard011/JavaScript/0070278_requestFileSystem.js new file mode 100644 index 0000000000000000000000000000000000000000..6626acc7d310c3d41108de448650fe0a2d5c655a --- /dev/null +++ b/pool/shard011/JavaScript/0070278_requestFileSystem.js @@ -0,0 +1,78 @@ +cordova.define("cordova-plugin-file.requestFileSystem", function(require, exports, module) { /* + * + * 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. + * +*/ + +//For browser platform: not all browsers use this file. +function checkBrowser() { + if (cordova.platformId === "browser" && navigator.userAgent.search(/Chrome/) > 0) { + var requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; + module.exports = requestFileSystem; + return; + } +} +checkBrowser(); + +var argscheck = require('cordova/argscheck'), + FileError = require('./FileError'), + FileSystem = require('./FileSystem'), + exec = require('cordova/exec'); +var fileSystems = require('./fileSystems'); + +/** + * Request a file system in which to store application data. + * @param type local file system type + * @param size indicates how much storage space, in bytes, the application expects to need + * @param successCallback invoked with a FileSystem object + * @param errorCallback invoked if error occurs retrieving file system + */ +var requestFileSystem = function(type, size, successCallback, errorCallback) { + argscheck.checkArgs('nnFF', 'requestFileSystem', arguments); + var fail = function(code) { + errorCallback && errorCallback(new FileError(code)); + }; + + if (type < 0) { + fail(FileError.SYNTAX_ERR); + } else { + // if successful, return a FileSystem object + var success = function(file_system) { + if (file_system) { + if (successCallback) { + fileSystems.getFs(file_system.name, function(fs) { + // This should happen only on platforms that haven't implemented requestAllFileSystems (windows) + if (!fs) { + fs = new FileSystem(file_system.name, file_system.root); + } + successCallback(fs); + }); + } + } + else { + // no FileSystem object returned + fail(FileError.NOT_FOUND_ERR); + } + }; + exec(success, fail, "File", "requestFileSystem", [type, size]); + } +}; + +module.exports = requestFileSystem; + +}); diff --git a/pool/shard011/JavaScript/0070279_client.js b/pool/shard011/JavaScript/0070279_client.js new file mode 100644 index 0000000000000000000000000000000000000000..29fcb7a0bffe59912632544a1791b25e260f90ad --- /dev/null +++ b/pool/shard011/JavaScript/0070279_client.js @@ -0,0 +1,116 @@ +/* + * Creates a new ZeroClipboard client. from an element, or array of elements. + * + * returns the client instance if it's already created + */ +var ZeroClipboard = function (elements, options) { + + // If the elements exist glue + if (elements) (ZeroClipboard.prototype._singleton || this).glue(elements); + + // If there's a client already, return the singleton + if (ZeroClipboard.prototype._singleton) return ZeroClipboard.prototype._singleton; + + ZeroClipboard.prototype._singleton = this; + + this.options = {}; + + // set the defaults + for (var kd in _defaults) this.options[kd] = _defaults[kd]; + + // overried the defaults + for (var ko in options) this.options[ko] = options[ko]; + + // event handlers + this.handlers = {}; + + // setup the flash->Javascript bridge + if (ZeroClipboard.detectFlashSupport()) _bridge(); + +}; + + +var currentElement, // Keep track of the current element that is being hovered. + gluedElements = []; // Watch glued elements so we don't double glue. + +/* + * Sets the current html object that the flash object should overlay. + * This will put the global flash object on top of the current object and set + * the text and title from the html object. + * + * returns nothing + */ +ZeroClipboard.prototype.setCurrent = function (element) { + + // What element is current + currentElement = element; + + this.reposition(); + + // If the dom element has a title + var titleAttr = element.getAttribute("title"); + if (titleAttr) { + this.setTitle(titleAttr); + } + + // If the element has a pointer style, set to hand cursor + var useHandCursor = this.options.forceHandCursor === true || _getStyle(element, "cursor") === "pointer"; + // Update the hand cursor state without updating the `forceHandCursor` option + _setHandCursor.call(this, useHandCursor); +}; + +/* + * Sends a signal to the flash object to set the clipboard text. + * + * returns nothing + */ +ZeroClipboard.prototype.setText = function (newText) { + if (newText && newText !== "") { + this.options.text = newText; + if (this.ready()) this.flashBridge.setText(newText); + } +}; + +/* + * Adds a title="" attribute to the htmlBridge to give it tooltip capabiities + * + * returns nothing + */ +ZeroClipboard.prototype.setTitle = function (newTitle) { + if (newTitle && newTitle !== "") this.htmlBridge.setAttribute("title", newTitle); +}; + +/* + * Sends a signal to the flash object to change the stage size. + * + * returns nothing + */ +ZeroClipboard.prototype.setSize = function (width, height) { + if (this.ready()) this.flashBridge.setSize(width, height); +}; + +/* + * @deprecated in [v1.2.0-beta.4], slated for removal in [v2.0.0]. See docs for alternatives. + * + * Sends a signal to the flash object to display the hand cursor if true. + * Updates the value of the `forceHandCursor` option. + * + * returns nothing + */ +ZeroClipboard.prototype.setHandCursor = function (enabled) { + enabled = typeof enabled === "boolean" ? enabled : !!enabled; + _setHandCursor.call(this, enabled); + this.options.forceHandCursor = enabled; +}; + +/* + * @private + * + * Sends a signal to the flash object to display the hand cursor if true. + * Does NOT update the value of the `forceHandCursor` option. + * + * returns nothing + */ +var _setHandCursor = function (enabled) { + if (this.ready()) this.flashBridge.setHandCursor(enabled); +}; diff --git a/pool/shard011/JavaScript/0070281_app.spec.js b/pool/shard011/JavaScript/0070281_app.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..c1dfef86d8cb2616722bfd3370b90c131c23ff75 --- /dev/null +++ b/pool/shard011/JavaScript/0070281_app.spec.js @@ -0,0 +1,41 @@ +describe('wokArmyBuilder', function () { + var filter; + + beforeEach(module('wokArmyBuilder')); + + describe('optionsFilter', function () { + beforeEach(inject(function (_$filter_) { + filter = _$filter_('optionsFilter'); + })); + + it('should cast argument as a number', function () { + expect(filter('3')).toEqual('1'); + }); + + it('should return one third of the argument', function () { + expect(filter(3)).toEqual('1'); + }); + + it('should replace thirds with ⅓', function () { + expect(filter(4)).toEqual('1⅓'); + }); + + it('should replace two-thirds with ⅔', function () { + expect(filter(8)).toEqual('2⅔'); + }); + }); + + describe('spinalCaseFilter', function () { + beforeEach(inject(function (_$filter_) { + filter = _$filter_('spinalCaseFilter'); + })); + + it('should return undefined when argument is undefined', function () { + expect(filter()).toBe(undefined); + }); + + it('should return lower-spinalcase string', function () { + expect(filter('Lower ~ Me')).toBe('lower-me'); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070283_popup.js b/pool/shard011/JavaScript/0070283_popup.js new file mode 100644 index 0000000000000000000000000000000000000000..7ee9453ff66bba96afc35d2d377434ef1e8d7368 --- /dev/null +++ b/pool/shard011/JavaScript/0070283_popup.js @@ -0,0 +1,79 @@ +/** @module layout/popup */ + +var CurrentListView = require('../views/popup/CurrentList'); +var EditorView = require('../views/popup/Editor'); +var EncryptionView = require('../views/options/Encryption'); +var SearchListView = require('../views/popup/SearchList'); +var browser = require('../browser'); +var layout = require('./'); +var storage = require('../storage'); +var template = require('../../templates/popup/popup.hbs'); +var utils = require('../utils'); + +/** + * Initialize and render the popup layout. + * @param {!Window} window Global object. + * @param {!Object} app + * @param {!string} tabUrl URL of the web browser's active tab. + */ +module.exports = function(window, app, tabUrl) { + var initialFirstModified = storage.firstModified; + var isPopout = browser.isPopoutUrl(window.location.href); + var notes = app.notes; + var query = utils.getHostname(tabUrl); + var synchronizer = app.synchronizer; + var editView = new EditorView({ + collection: notes, + isPopout: isPopout, + tabUrl: tabUrl, + window: window + }); + var encryptionView = new EncryptionView({ + notes: notes, + synchronizer: synchronizer + }); + var searchListView = new SearchListView({ + collection: notes, + isPopout: isPopout + }); + var unloadCallback; + var views; + + + // Toggle the EncryptionView, when the EditorView's encryption icon is + // clicked. + editView.$el.on('click', '.encryption-toggle', function(event) { + event.preventDefault(); + encryptionView.$el.toggle(); + editView.updateEncryptionIcon(); + }); + encryptionView.$el.on('click', '.close', function(event) { + event.preventDefault(); + editView.updateEncryptionIcon(); + }); + + views = { + '#edit': editView, + '#encryption': encryptionView, + '#search': searchListView + }; + + if (!isPopout) { + views['#current'] = new CurrentListView({ + collection: notes, + isPopout: isPopout, + query: query, + searchListView: searchListView + }); + } + + // Synchronize when the EditorView is unloaded if one or more notes were + // changed. + unloadCallback = function() { + editView.saveState(); + if (storage.firstModified > initialFirstModified) { + synchronizer.syncModified(); + } + }; + layout(window, template, views, unloadCallback); +}; \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070284_contextual.js b/pool/shard011/JavaScript/0070284_contextual.js new file mode 100644 index 0000000000000000000000000000000000000000..63f83de982878f01789eeec0e1b1091619d82812 --- /dev/null +++ b/pool/shard011/JavaScript/0070284_contextual.js @@ -0,0 +1,106 @@ +(function (Q, $, window, document, undefined) { + + +/** + * Q Tools + * @module Q-tools + */ + +/** + * This plugin Makes a contextual menu from given options and handles its showing / hiding. + * @class Q contextual + * @constructor + * @param {Object} [options] options an object that can include: + * @param {Array} [options.elements] elements is an array of LI elements to add + * @param {String} [options.className=''] className is a CSS class name for additional styling. Optional + * @param {Q.Event|function|String} [options.defaultHandler=null] defaultHandler is a Q.Event, or function which is called when a specific handler for selected item is not defined. + * So you can use just one handler for whole contextual or provide separate handlers for each item. + * @param {Object} [options.size=null] size is an object with values for override default contextual size. + * @param {Number} [options.size.width] width + * @param {Number} [options.size.height] height + */ +Q.Tool.jQuery('Q/contextual', function _Q_contextual() { + + var $this = $(this); + var state = $this.state('Q/contextual'); + + // the first time when any contextual is added we need to preload its graphics, + if ($('.Q_contextual_arrows_preloaded').length == 0) { + $('
    ' + + '
    ' + + '
    ' + + '
    ').appendTo(document.body); + } + if (state.defaultHandler + && Q.typeOf(state.defaultHandler) != 'Q.Event' + && typeof(state.defaultHandler) != 'function' + && typeof(state.defaultHandler) != 'string') { + console.warn("Default handler must be a valid Q.Event object, function or function string name."); + } + + if ($this.hasClass('Q_selected')) { + $this.removeClass('Q_selected'); + state.restoreSelected = true; + } + + var contextual = $('
    '); + if (state.className) contextual.addClass(state.className); + var listingWrapper = $('
    '); + if (state.defaultHandler) { + if (typeof(state.defaultHandler) == 'string') { + contextual.attr('data-handler', state.defaultHandler); + } else { + contextual.data('defaultHandler', state.defaultHandler); + } + } + var listing = $('
      '); + if (state.elements) { + for (var i = 0; i < state.elements.length; ++i) { + listing.append(state.elements[i]); + } + } + contextual.append(listingWrapper.append(listing)); + $(document.body).append(contextual); + + var cid = Q.Contextual.add($this, contextual, null, state.size); + state.id = cid; + state.contextual = contextual; + + Q.handle(state.onConstruct, $this, [contextual, cid]); +}, + +{ + className: '', + defaultHandler: null, + size: null, + onConstruct: new Q.Event(), + onShow: new Q.Event() +}, + +{ + /** + * Removes the contextual functionality from the element + * @method remove + */ + remove: function () { + var $this = $(this); + var state = $this.state('Q/contextual'); + if (!state) return; + var cid = state.id; + if (cid !== undefined) { + var removed = Q.Contextual.remove(cid); + removed.contextual.remove(); + } + if (state.restoreSelected) { + $this.addClass('Q_selected'); + state.restoreSelected = false; + } + state.contextual.removeData('Q/contextual trigger'); + } +} + +); + +Q.addStylesheet('{{Q}}/css/contextual.css', { slotName: 'Q' }); + +})(Q, Q.$, window, document); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070286_index.js b/pool/shard011/JavaScript/0070286_index.js new file mode 100644 index 0000000000000000000000000000000000000000..c78c527b9df31c3bf114dcbbecfda8c0c27c54f9 --- /dev/null +++ b/pool/shard011/JavaScript/0070286_index.js @@ -0,0 +1,68 @@ +import sinon from 'sinon'; +import noop from 'lodash/noop'; +import isFunction from 'lodash/isFunction'; + +/** + * Use sinon's fake time controls + * + * This helper spins up and down sinon's fake clock. + * If you provide a callback, it will be invoked with the clock instance created by sinon. + * This allows you to get at the clock instance even if you're using arrow functions in your test + * and cannot access the `this` provided by mocha. + * + * You can pass clockCallback as the first argument with no 'now' if you wish + * + * See http://sinonjs.org/docs/#clock + * @param {Number} now The timestamp to set "now" to. + * @param {Function} clockCallback A function invoked with the clock created by sinon + */ +export function useFakeTimers( now = 0, clockCallback = noop ) { + if ( isFunction( now ) && clockCallback === noop ) { + clockCallback = now; + now = 0; + } + + // these _cannot_ be arrow functions because we're using the `this` that mocha provides + before( function turnOnSinonFakeTimers() { + this.clock = sinon.useFakeTimers( now ); + clockCallback( this.clock ); + } ); + + after( function turnOffSinonFakeTimers() { + if ( this.clock ) { + this.clock.restore(); + this.clock = null; + } + } ); +} + +/** + * Use a full sinon sandbox for this test block + * + * See http://sinonjs.org/docs/#sandbox + * + * @param {Object|Function} config The configuration to use, or a callback that is invoked with the sandbox instance + * @param {Function} sandboxCallback A callback function that is invoked with the sandbox instance + */ +export function useSandbox( config, sandboxCallback = noop ) { + if ( isFunction( config ) && sandboxCallback === noop ) { + sandboxCallback = config; + config = undefined; + } + + before( function() { + this.sandbox = sinon.sandbox.create( config ); + sandboxCallback( this.sandbox ); + } ); + + beforeEach( function() { + this.sandbox.reset(); + } ); + + after( function() { + if ( this.sandbox ) { + this.sandbox.restore(); + this.sandbox = null; + } + } ); +} diff --git a/pool/shard011/JavaScript/0070288_requestify-spec.js b/pool/shard011/JavaScript/0070288_requestify-spec.js new file mode 100644 index 0000000000000000000000000000000000000000..7b73897874c19f36e5004f45323b3507534bf446 --- /dev/null +++ b/pool/shard011/JavaScript/0070288_requestify-spec.js @@ -0,0 +1,241 @@ +'use strict'; + +var mocha = require('mocha'), + sinon = require('sinon'), + expect = require('chai').expect, + rewire = require('rewire'), + requestify = rewire('../lib/requestify.js'), + Q = require('q'); + +describe('Requestify', function() { + var cacheStub; + + afterEach(function() { + requestify.responseEncoding('utf8'); + }); + + beforeEach(function() { + cacheStub = { + setCacheTransporter: sinon.stub(), + get: sinon.stub(), + set: sinon.stub(), + purge: sinon.stub(), + isTransportAvailable: sinon.stub() + }; + + requestify.__set__('cache', cacheStub); + }); + + describe('#responseEncoding()', function() { + + it('Should return utf8 by default', function() { + expect(requestify.responseEncoding()).to.equal('utf8'); + }); + + it('Should set the new encoding and return it on request', function() { + requestify.responseEncoding('newEncoding'); + + expect(requestify.responseEncoding()).to.equal('newEncoding'); + }); + }); + + describe('#request()', function() { + var httpStub, + httpsStub, + cacheStub; + + beforeEach(function() { + httpStub = sinon.stub().returns({ + on: function() {}, + end: function() {} + }); + + httpsStub = sinon.stub().returns({ + on: function() {}, + end: function() {} + }); + + requestify.__set__('http', { + request: httpStub + }); + + requestify.__set__('https', { + request: httpsStub + }); + }); + + afterEach(function() { + httpStub = null; + httpsStub = null; + }); + + it('Should return a promise', function() { + requestify.request('http://wix.com', { + method: 'POST', + dataType: 'json' + }); + }); + + it('Should call https module since the request is https: protocol', function() { + requestify.request('https://wix.com', { + method: 'POST' + }); + + expect(httpsStub.called).to.equal(true); + }); + + it('Should call http module since request is http: protocol', function() { + requestify.request('http://wix.com', { + method: 'POST' + }); + + expect(httpStub.called).to.equal(true); + }); + + it('Should return a promise object', function() { + expect(requestify.request('https://wix.com', { + method: 'POST' + })).to.have.property('then'); + }); + }); + + describe('Method specific public methods', function() { + beforeEach(function() { + requestify.request = sinon.stub(); + }); + + afterEach(function() { + requestify.request = null; + }); + + describe('#get()', function() { + it('should call #request() with then given url, cookies and method GET', function() { + requestify.get('http://www.example.com', { + cookies: { + key: 'val' + } + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'GET', + cookies: { + key: 'val' + } + })).to.equal(true); + }); + + it('should call #request with the given url and method GET only', function() { + requestify.get('http://www.example.com'); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'GET' + })); + }); + }); + + describe('#post()', function() { + it('should call #request() with then given body and method POST', function() { + requestify.post('http://www.example.com', { + foo: 'bar' + }, { + cookies: { + key: 'val' + } + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'POST', + cookies: { + key: 'val' + }, + body: { + foo: 'bar' + } + })).to.equal(true); + }); + + it('should call #request with the given url and body in method POST', function() { + requestify.post('http://www.example.com', { + 'foo': 'bar' + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'POST', + body: { + 'foo': 'bar' + } + })); + }); + }); + + describe('#put()', function() { + it('should call #request() with then given body and method PUT', function() { + requestify.put('http://www.example.com', { + foo: 'bar' + }, { + cookies: { + key: 'val' + } + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'PUT', + cookies: { + key: 'val' + }, + body: { + foo: 'bar' + } + })).to.equal(true); + }); + }); + + describe('#delete()', function() { + it('should call #request() with then given body and method DELETE', function() { + requestify.delete('http://www.example.com', { + cookies: { + key: 'val' + } + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'DELETE', + cookies: { + key: 'val' + } + })).to.equal(true); + }); + }); + + describe('#head()', function() { + it('should call #request() with then given body and method HEAD', function() { + requestify.head('http://www.example.com', { + body: { + key: 'val' + } + }); + + expect(requestify.request.calledWith('http://www.example.com', { + method: 'HEAD', + body: { + key: 'val' + } + })).to.equal(true); + }); + }); + + describe('#cacheTransporter()', function() { + it('should do nothing since called it without any transporter', function() { + requestify.cacheTransporter(); + + expect(cacheStub.setCacheTransporter.called).to.equal(false); + }); + + it('should call cache.setCacheTransporter with the transporter', function() { + requestify.cacheTransporter({}); + + expect(cacheStub.setCacheTransporter.called).to.equal(true); + }); + }); + }); +}); diff --git a/pool/shard011/JavaScript/0070290_main.js b/pool/shard011/JavaScript/0070290_main.js new file mode 100644 index 0000000000000000000000000000000000000000..62f1357a93561ea7f54c8c1f4d6e77d81d6a2c68 --- /dev/null +++ b/pool/shard011/JavaScript/0070290_main.js @@ -0,0 +1,41 @@ +var ContainerModel = Backbone.Model.extend({}); + +var UserModel = Backbone.Model.extend({}); + +var UserCollection = Backbone.Collection.extend({ + model: UserModel +}); + +var ChatModel = Backbone.Model.extend({}); + +var ChatCollection = Backbone.Collection.extend({ + model: ChatModel +}); + +var HomeModel = Backbone.Model.extend({ + defaults: { + onlineUsers: new UserCollection(), + userChats: new ChatCollection([ + new ChatModel({ sender: '', message: 'Chat Server v.1' }) + ]) + }, + addUser: function(username) { + this.get('onlineUsers').add(new UserModel({ name: username })); + }, + removeUser: function(username) { + var onlineUsers = this.get('onlineUsers'); + var u = onlineUsers.find(function(item) { return item.get('name') == username }); + if (u) { + onlineUsers.remove(u); + } + }, + addChat: function(chat) { + this.get('userChats').add(new ChatModel({ sender: chat.sender, message: chat.message })); + }, +}); + +var LoginModel = Backbone.Model.extend({ + defaults: { + error: "" + } +}); diff --git a/pool/shard011/JavaScript/0070293_main.js b/pool/shard011/JavaScript/0070293_main.js new file mode 100644 index 0000000000000000000000000000000000000000..ad95c7e00161df8b5a8f38bda730dbc4a69ce897 --- /dev/null +++ b/pool/shard011/JavaScript/0070293_main.js @@ -0,0 +1,67 @@ +$(document).ready(function () { + + var toggle_sidebar_btn = $('[data-toggle="offcanvas"]'); + var page_sidebar = $('.row-offcanvas'); + var page_content = $('.row-offcanvas > .page-content'); + var page_navbar = $('body > .navbar:first'); + + // open sidebar + toggle_sidebar_btn.on('click', function (event) { + if (show_sidebar()) { + // don't follow link + event.preventDefault(); + // need to prevent close sidebar by click outside sidebar + event.stopPropagation(); + // scroll to top of page (to show full sidebar) + $("body").scrollTop(0); + } + }); + + // close sidebar on click outside it + both(page_navbar, page_content).on('click', function (event) { + // don't follow click actions when press outside opened sidebar + if (close_sidebar()) { + // don't follow actions on clicked element + event.preventDefault(); + event.stopPropagation(); + } + }); + + + /* + * Return intersection between two jQuery selectors. + */ + function both(selector1, selector2) { + return selector1.add(selector2); + } + + + /* + * Close sidebar. + * Return true if sidebar was opened. + */ + function close_sidebar() { + if (page_sidebar.hasClass('active')) { + page_sidebar.removeClass('active'); + // return page content to visible state + page_content.css('opacity', '1.0'); + return true; + } + // sidebar already closed + return false; + } + + /* + * Show sidebar. + */ + function show_sidebar() { + if (! page_sidebar.hasClass('active')) { + page_sidebar.toggleClass('active'); + // make page content dimmed + page_content.css('opacity', '0.3'); + return true; + } + return false; + } + +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070294_dialog.spec.js b/pool/shard011/JavaScript/0070294_dialog.spec.js new file mode 100644 index 0000000000000000000000000000000000000000..bf866ea3e5d0c9667e33471b81c66b1b870d2217 --- /dev/null +++ b/pool/shard011/JavaScript/0070294_dialog.spec.js @@ -0,0 +1,51 @@ +'use strict'; +const assert = require('assert'); +const {BotMock, SlackApiMock} = require('../../../lib'); +const {SlackAdapter, SlackMessageTypeMiddleware, SlackEventMiddleware} = require('botbuilder-adapter-slack'); +const fileBeingTested = require('./dialog'); + +describe('create dialog in a thread', () => { + const initController = () => { + const adapter = new SlackAdapter(SlackApiMock.slackAdapterMockParams); + adapter.use(new SlackEventMiddleware()); + adapter.use(new SlackMessageTypeMiddleware()); + + this.controller = new BotMock({ + adapter: adapter, + }); + + SlackApiMock.bindMockApi(this.controller); + + fileBeingTested(this.controller); + }; + + beforeEach(() => { + this.userInfo = { + slackId: 'user123', + channel: 'channel123', + }; + }); + + describe('create_service', () => { + beforeEach(() => { + initController(); + }); + it(`should reply in a correct sequence through message`, async () => { + await this.controller.usersInput([ + { + type: 'message', + user: this.userInfo.slackId, //user required for each direct message + channel: this.userInfo.channel, // user channel required for direct message + messages: [ + { + text: 'create_dialog_service', + isAssertion: true, + } + ] + } + ]); + + assert.strictEqual(this.controller.detailed_answers[this.userInfo.channel][0].text, `Howdy!`); + }); + }); +}); \ No newline at end of file diff --git a/pool/shard011/JavaScript/0070295_calci.js b/pool/shard011/JavaScript/0070295_calci.js new file mode 100644 index 0000000000000000000000000000000000000000..84b7e14c208e9c647700a466d066cd32486c1904 --- /dev/null +++ b/pool/shard011/JavaScript/0070295_calci.js @@ -0,0 +1,114 @@ +var Calci = { + init: function() { + $('#calculator .input').click(function (){ + if (this.dataset.keyType == "digit") { + Calci.handleInput(this.dataset.digit); + } else if (this.dataset.keyType == "operator") { + Calci.handleOperator(this.dataset.operator); + }else if (this.dataset.keyType == "delete") { + Calci.handleDelete(); + }else if (this.dataset.keyType == "equals") { + Calci.evaluateResult(); + } + }); + $('#calculator #delete').dblclick(function() { + Calci.clearPreview(); + Calci.clearResult(); + }); + ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',]. forEach(function(digit){ + $(document).bind('keyup',digit,function() { + Calci.handleInput(digit); + }); + }); + ['/', '*', '+', '-',]. forEach(function(digit){ + $(document).bind('keyup',digit,function() { + Calci.handleOperator(digit); + }); + }); + $(document).bind('keyup', '.' , function() { + lastNumber = Calci.getLastNumber(); + if (lastNumber.indexOf('.') == -1) { + if (lastNumber.length == 0) { + Calci.handleInput(0); + } + Calci.handleInput('.'); + } + }); + $(document).bind('keyup', 'backspace' , function() { + Calci.handleDelete(); + }); + $(document).bind('keyup', 'shift+=' , function() { + Calci.handleOperator('+'); + }); + ['=', 'return'].forEach(function(key) { + $(document).bind('keyup', key , function() { + Calci.evaluateResult('='); + }); + }); + }, + handleInput: function (input) { + $('#preview').html($('#preview').html() + input); + }, + handleOperator: function(operator) { + console.log(operator) + if ($('#preview').html().length == 0) { + if (operator == '-') { + Calci.handleInput('-'); + } + }else { + if (Calci.checkLastCharIsOperator()) { + Calci.handleDelete(); + } + Calci.handleInput(operator); + } + + }, + handleDelete: function() { + $('#preview').html($('#preview').html().slice(0, -1)); + if ($('#preview').html().length==0){ + Calci.clearResult(); + } + }, + evaluateResult: function() { + if (Calci.checkLastCharIsOperator()) { + Calci.handleDelete(); + + } + $('#result').html(eval($('#preview').html())); + }, + clearResult: function(){ + $('#result').html(''); + }, + getLastNumber: function() { + str = $('#preview').html(); + regexp = /[+\-*\/]?([0-9.])*$/ + matches = str.match(regexp); + console.log(matches) + if (matches == null) { + return str; + } else { + return matches[0].slice(1) + } + }, + clearPreview: function() { + $('#preview').html(''); + }, + getLastChar: function() { + str = $('#preview').html(); + console.log("lastChar" + str); + if (str.length == 0) { + return str; + } else { + return str[str.length - 1]; + } + }, + checkLastCharIsOperator: function() { + lastChar = Calci.getLastChar(); + return (['+', '-', '*', '/'].indexOf(lastChar) != -1) + } + + +}; +$(document).ready(function() { + Calci.init(); +}); diff --git a/pool/shard011/JavaScript/0070296_collection-serializer.js b/pool/shard011/JavaScript/0070296_collection-serializer.js new file mode 100644 index 0000000000000000000000000000000000000000..a87121974daeb695aa822c14ccaff1935f1f41a3 --- /dev/null +++ b/pool/shard011/JavaScript/0070296_collection-serializer.js @@ -0,0 +1,16 @@ +'use strict'; +var SerializerUtils = require('./serializer-utils'); + +function CollectionSerializer(payload, collectionName, records, opts) { + payload.data = []; + + records.forEach(function (record) { + var serializerUtils = new SerializerUtils(collectionName, record, payload, + opts); + payload.data.push(serializerUtils.perform()); + }); + + return payload; +} + +module.exports = CollectionSerializer;