text
stringlengths
2
100k
meta
dict
==================================================================== For the license for Meteor itself, see LICENSE.txt in the root of the repository. This file contains the licenses for externally maintained libraries. ==================================================================== ---------- ieee754: https://github.com/feross/ieee754 ---------- The MIT License (MIT) Copyright (c) Feross Aboukhadijeh 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. =========================================== ieee754 originally contained this license: =========================================== Copyright (c) 2008, Fair Oaks Labs, 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 Fair Oaks Labs, 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. Modifications to writeIEEE754 to support negative zeroes made by Brian White.
{ "pile_set_name": "Github" }
package loon; public enum GameType { UNKOWN("Unkown Game"), ACT("Action Game"), STG("Shooting Game"), FTG("Fighting Game"), AVG("Adventure Game"), SLG("Simulation Game"), RPG("Role-playing game"), STRATEGY("Strategy Game"), SPORT("Sports Game"), RACING("Racing Game"), CASUAL("Casual Game"), MUSIC("Music Game"), MMOG("Multiplayer Online Game"); private String name; GameType(String name) { this.name = name; } public static GameType getEnum(int idx) { if (idx < values().length) { return values()[idx]; } else { return null; } } @Override public String toString() { return name; } }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005-2014 Team XBMC * http://xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "system.h" #if defined(HAVE_X11) #include "video/videosync/VideoSyncDRM.h" #include "xf86drm.h" #include <sys/poll.h> #include <sys/time.h> #include "utils/TimeUtils.h" #include "utils/MathUtils.h" #include "windowing/WindowingFactory.h" #include "guilib/GraphicContext.h" #include "utils/log.h" bool CVideoSyncDRM::Setup(PUPDATECLOCK func) { CLog::Log(LOGDEBUG, "CVideoSyncDRM::%s - setting up DRM", __FUNCTION__); UpdateClock = func; m_fd = open("/dev/dri/card0", O_RDWR, 0); if (m_fd < 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - can't open /dev/dri/card0", __FUNCTION__); return false; } drmVBlank vbl; int ret; vbl.request.type = DRM_VBLANK_RELATIVE; vbl.request.sequence = 0; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return false; } m_abort = false; g_Windowing.Register(this); return true; } void CVideoSyncDRM::Run(volatile bool& stop) { drmVBlank vbl; VblInfo info; int ret; int crtc = g_Windowing.GetCrtc(); vbl.request.type = DRM_VBLANK_RELATIVE; if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | (crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK); } vbl.request.sequence = 0; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return; } info.start = CurrentHostCounter(); info.videoSync = this; vbl.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT); if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | (crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK); } vbl.request.sequence = 1; vbl.request.signal = (unsigned long)&info; ret = drmWaitVBlank(m_fd, &vbl); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmWaitVBlank returned error", __FUNCTION__); return; } drmEventContext evctx; memset(&evctx, 0, sizeof evctx); evctx.version = DRM_EVENT_CONTEXT_VERSION; evctx.vblank_handler = EventHandler; evctx.page_flip_handler = NULL; timeval timeout; fd_set fds; FD_ZERO(&fds); FD_SET(m_fd, &fds); while (!stop && !m_abort) { timeout.tv_sec = 1; timeout.tv_usec = 0; ret = select(m_fd + 1, &fds, NULL, NULL, &timeout); if (ret <= 0) { continue; } ret = drmHandleEvent(m_fd, &evctx); if (ret != 0) { CLog::Log(LOGERROR, "CVideoSyncDRM::%s - drmHandleEvent returned error", __FUNCTION__); break; } } } void CVideoSyncDRM::Cleanup() { close(m_fd); g_Windowing.Unregister(this); } void CVideoSyncDRM::EventHandler(int fd, unsigned int frame, unsigned int sec, unsigned int usec, void *data) { drmVBlank vbl; struct timeval end; VblInfo *info = (VblInfo*)data; int crtc = g_Windowing.GetCrtc(); vbl.request.type = (drmVBlankSeqType)(DRM_VBLANK_RELATIVE | DRM_VBLANK_EVENT); if (crtc == 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | DRM_VBLANK_SECONDARY); } else if (crtc > 1) { vbl.request.type = (drmVBlankSeqType)(vbl.request.type | (crtc << DRM_VBLANK_HIGH_CRTC_SHIFT) & DRM_VBLANK_HIGH_CRTC_MASK); } vbl.request.sequence = 1; vbl.request.signal = (unsigned long)data; drmWaitVBlank(info->videoSync->m_fd, &vbl); uint64_t now = CurrentHostCounter(); float diff = (float)(now - info->start)/CurrentHostFrequency(); int vblanks = MathUtils::round_int(diff * info->videoSync->m_fps); info->start = now; info->videoSync->UpdateClock(vblanks, now); } void CVideoSyncDRM::OnResetDevice() { m_abort = true; } float CVideoSyncDRM::GetFps() { m_fps = g_graphicsContext.GetFPS(); return m_fps; } #endif
{ "pile_set_name": "Github" }
select * from t order by id
{ "pile_set_name": "Github" }
2043 1446
{ "pile_set_name": "Github" }
// Boost.Geometry Index // // R-tree implementation // // Copyright (c) 2008 Federico J. Fernandez. // Copyright (c) 2011-2018 Adam Wulkiewicz, Lodz, Poland. // // Use, modification and distribution is 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) #ifndef BOOST_GEOMETRY_INDEX_RTREE_HPP #define BOOST_GEOMETRY_INDEX_RTREE_HPP // STD #include <algorithm> // Boost #include <boost/container/new_allocator.hpp> #include <boost/move/move.hpp> #include <boost/tuple/tuple.hpp> // Boost.Geometry #include <boost/geometry/algorithms/detail/comparable_distance/interface.hpp> #include <boost/geometry/algorithms/detail/covered_by/interface.hpp> #include <boost/geometry/algorithms/detail/disjoint/interface.hpp> #include <boost/geometry/algorithms/detail/equals/interface.hpp> #include <boost/geometry/algorithms/detail/intersects/interface.hpp> #include <boost/geometry/algorithms/detail/overlaps/interface.hpp> #include <boost/geometry/algorithms/detail/touches/interface.hpp> #include <boost/geometry/algorithms/detail/within/interface.hpp> #include <boost/geometry/algorithms/centroid.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/geometries/box.hpp> // Boost.Geometry.Index #include <boost/geometry/index/detail/config_begin.hpp> #include <boost/geometry/index/detail/assert.hpp> #include <boost/geometry/index/detail/exception.hpp> #include <boost/geometry/index/detail/rtree/options.hpp> #include <boost/geometry/index/indexable.hpp> #include <boost/geometry/index/equal_to.hpp> #include <boost/geometry/index/detail/translator.hpp> #include <boost/geometry/index/predicates.hpp> #include <boost/geometry/index/distance_predicates.hpp> #include <boost/geometry/index/detail/rtree/adaptors.hpp> #include <boost/geometry/index/detail/meta.hpp> #include <boost/geometry/index/detail/utilities.hpp> #include <boost/geometry/index/detail/rtree/node/node.hpp> #include <boost/geometry/index/detail/algorithms/is_valid.hpp> #include <boost/geometry/index/detail/rtree/visitors/insert.hpp> #include <boost/geometry/index/detail/rtree/visitors/iterator.hpp> #include <boost/geometry/index/detail/rtree/visitors/remove.hpp> #include <boost/geometry/index/detail/rtree/visitors/copy.hpp> #include <boost/geometry/index/detail/rtree/visitors/destroy.hpp> #include <boost/geometry/index/detail/rtree/visitors/spatial_query.hpp> #include <boost/geometry/index/detail/rtree/visitors/distance_query.hpp> #include <boost/geometry/index/detail/rtree/visitors/count.hpp> #include <boost/geometry/index/detail/rtree/visitors/children_box.hpp> #include <boost/geometry/index/detail/rtree/linear/linear.hpp> #include <boost/geometry/index/detail/rtree/quadratic/quadratic.hpp> #include <boost/geometry/index/detail/rtree/rstar/rstar.hpp> //#include <boost/geometry/extensions/index/detail/rtree/kmeans/kmeans.hpp> #include <boost/geometry/index/detail/rtree/pack_create.hpp> #include <boost/geometry/index/inserter.hpp> #include <boost/geometry/index/detail/rtree/utilities/view.hpp> #include <boost/geometry/index/detail/rtree/iterators.hpp> #include <boost/geometry/index/detail/rtree/query_iterators.hpp> #ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL // serialization #include <boost/geometry/index/detail/serialization.hpp> #endif // TODO change the name to bounding_tree /*! \defgroup rtree_functions R-tree free functions (boost::geometry::index::) */ namespace boost { namespace geometry { namespace index { /*! \brief The R-tree spatial index. This is self-balancing spatial index capable to store various types of Values and balancing algorithms. \par Parameters The user must pass a type defining the Parameters which will be used in rtree creation process. This type is used e.g. to specify balancing algorithm with specific parameters like min and max number of elements in node. \par Predefined algorithms with compile-time parameters are: \li <tt>boost::geometry::index::linear</tt>, \li <tt>boost::geometry::index::quadratic</tt>, \li <tt>boost::geometry::index::rstar</tt>. \par Predefined algorithms with run-time parameters are: \li \c boost::geometry::index::dynamic_linear, \li \c boost::geometry::index::dynamic_quadratic, \li \c boost::geometry::index::dynamic_rstar. \par IndexableGetter The object of IndexableGetter type translates from Value to Indexable each time r-tree requires it. This means that this operation is done for each Value access. Therefore the IndexableGetter should return the Indexable by a reference type. The Indexable should not be calculated since it could harm the performance. The default IndexableGetter can translate all types adapted to Point, Box or Segment concepts (called Indexables). Furthermore, it can handle <tt>std::pair<Indexable, T></tt>, <tt>boost::tuple<Indexable, ...></tt> and <tt>std::tuple<Indexable, ...></tt> when possible. For example, for Value of type <tt>std::pair<Box, int></tt>, the default IndexableGetter translates from <tt>std::pair<Box, int> const&</tt> to <tt>Box const&</tt>. \par EqualTo The object of EqualTo type compares Values and returns <tt>true</tt> if they are equal. It's similar to <tt>std::equal_to<></tt>. The default EqualTo returns the result of <tt>boost::geometry::equals()</tt> for types adapted to some Geometry concept defined in Boost.Geometry and the result of <tt>operator==</tt> for other types. Components of Pairs and Tuples are compared left-to-right. \tparam Value The type of objects stored in the container. \tparam Parameters Compile-time parameters. \tparam IndexableGetter The function object extracting Indexable from Value. \tparam EqualTo The function object comparing objects of type Value. \tparam Allocator The allocator used to allocate/deallocate memory, construct/destroy nodes and Values. */ template < typename Value, typename Parameters, typename IndexableGetter = index::indexable<Value>, typename EqualTo = index::equal_to<Value>, typename Allocator = boost::container::new_allocator<Value> > class rtree { BOOST_COPYABLE_AND_MOVABLE(rtree) public: /*! \brief The type of Value stored in the container. */ typedef Value value_type; /*! \brief R-tree parameters type. */ typedef Parameters parameters_type; /*! \brief The function object extracting Indexable from Value. */ typedef IndexableGetter indexable_getter; /*! \brief The function object comparing objects of type Value. */ typedef EqualTo value_equal; /*! \brief The type of allocator used by the container. */ typedef Allocator allocator_type; // TODO: SHOULD THIS TYPE BE REMOVED? /*! \brief The Indexable type to which Value is translated. */ typedef typename index::detail::indexable_type< detail::translator<IndexableGetter, EqualTo> >::type indexable_type; /*! \brief The Box type used by the R-tree. */ typedef geometry::model::box< geometry::model::point< typename coordinate_type<indexable_type>::type, dimension<indexable_type>::value, typename coordinate_system<indexable_type>::type > > bounds_type; private: typedef detail::translator<IndexableGetter, EqualTo> translator_type; typedef bounds_type box_type; typedef typename detail::rtree::options_type<Parameters>::type options_type; typedef typename options_type::node_tag node_tag; typedef detail::rtree::allocators<allocator_type, value_type, typename options_type::parameters_type, box_type, node_tag> allocators_type; typedef typename detail::rtree::node<value_type, typename options_type::parameters_type, box_type, allocators_type, node_tag>::type node; typedef typename detail::rtree::internal_node<value_type, typename options_type::parameters_type, box_type, allocators_type, node_tag>::type internal_node; typedef typename detail::rtree::leaf<value_type, typename options_type::parameters_type, box_type, allocators_type, node_tag>::type leaf; typedef typename allocators_type::node_pointer node_pointer; typedef ::boost::container::allocator_traits<Allocator> allocator_traits_type; typedef detail::rtree::subtree_destroyer<value_type, options_type, translator_type, box_type, allocators_type> subtree_destroyer; friend class detail::rtree::utilities::view<rtree>; #ifdef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL friend class detail::rtree::private_view<rtree>; friend class detail::rtree::const_private_view<rtree>; #endif public: /*! \brief Type of reference to Value. */ typedef typename allocators_type::reference reference; /*! \brief Type of reference to const Value. */ typedef typename allocators_type::const_reference const_reference; /*! \brief Type of pointer to Value. */ typedef typename allocators_type::pointer pointer; /*! \brief Type of pointer to const Value. */ typedef typename allocators_type::const_pointer const_pointer; /*! \brief Type of difference type. */ typedef typename allocators_type::difference_type difference_type; /*! \brief Unsigned integral type used by the container. */ typedef typename allocators_type::size_type size_type; /*! \brief Type of const iterator, category ForwardIterator. */ typedef index::detail::rtree::iterators::iterator < value_type, options_type, translator_type, box_type, allocators_type > const_iterator; /*! \brief Type of const query iterator, category ForwardIterator. */ typedef index::detail::rtree::iterators::query_iterator < value_type, allocators_type > const_query_iterator; public: /*! \brief The constructor. \param parameters The parameters object. \param getter The function object extracting Indexable from Value. \param equal The function object comparing Values. \par Throws If allocator default constructor throws. */ inline explicit rtree(parameters_type const& parameters = parameters_type(), indexable_getter const& getter = indexable_getter(), value_equal const& equal = value_equal()) : m_members(getter, equal, parameters) {} /*! \brief The constructor. \param parameters The parameters object. \param getter The function object extracting Indexable from Value. \param equal The function object comparing Values. \param allocator The allocator object. \par Throws If allocator copy constructor throws. */ inline rtree(parameters_type const& parameters, indexable_getter const& getter, value_equal const& equal, allocator_type const& allocator) : m_members(getter, equal, parameters, allocator) {} /*! \brief The constructor. The tree is created using packing algorithm. \param first The beginning of the range of Values. \param last The end of the range of Values. \param parameters The parameters object. \param getter The function object extracting Indexable from Value. \param equal The function object comparing Values. \param allocator The allocator object. \par Throws \li If allocator copy constructor throws. \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. */ template<typename Iterator> inline rtree(Iterator first, Iterator last, parameters_type const& parameters = parameters_type(), indexable_getter const& getter = indexable_getter(), value_equal const& equal = value_equal(), allocator_type const& allocator = allocator_type()) : m_members(getter, equal, parameters, allocator) { typedef detail::rtree::pack<value_type, options_type, translator_type, box_type, allocators_type> pack; size_type vc = 0, ll = 0; m_members.root = pack::apply(first, last, vc, ll, m_members.parameters(), m_members.translator(), m_members.allocators()); m_members.values_count = vc; m_members.leafs_level = ll; } /*! \brief The constructor. The tree is created using packing algorithm. \param rng The range of Values. \param parameters The parameters object. \param getter The function object extracting Indexable from Value. \param equal The function object comparing Values. \param allocator The allocator object. \par Throws \li If allocator copy constructor throws. \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. */ template<typename Range> inline explicit rtree(Range const& rng, parameters_type const& parameters = parameters_type(), indexable_getter const& getter = indexable_getter(), value_equal const& equal = value_equal(), allocator_type const& allocator = allocator_type()) : m_members(getter, equal, parameters, allocator) { typedef detail::rtree::pack<value_type, options_type, translator_type, box_type, allocators_type> pack; size_type vc = 0, ll = 0; m_members.root = pack::apply(::boost::begin(rng), ::boost::end(rng), vc, ll, m_members.parameters(), m_members.translator(), m_members.allocators()); m_members.values_count = vc; m_members.leafs_level = ll; } /*! \brief The destructor. \par Throws Nothing. */ inline ~rtree() { this->raw_destroy(*this); } /*! \brief The copy constructor. It uses parameters, translator and allocator from the source tree. \param src The rtree which content will be copied. \par Throws \li If allocator copy constructor throws. \li If Value copy constructor throws. \li If allocation throws or returns invalid value. */ inline rtree(rtree const& src) : m_members(src.m_members.indexable_getter(), src.m_members.equal_to(), src.m_members.parameters(), allocator_traits_type::select_on_container_copy_construction(src.get_allocator())) { this->raw_copy(src, *this, false); } /*! \brief The copy constructor. It uses Parameters and translator from the source tree. \param src The rtree which content will be copied. \param allocator The allocator which will be used. \par Throws \li If allocator copy constructor throws. \li If Value copy constructor throws. \li If allocation throws or returns invalid value. */ inline rtree(rtree const& src, allocator_type const& allocator) : m_members(src.m_members.indexable_getter(), src.m_members.equal_to(), src.m_members.parameters(), allocator) { this->raw_copy(src, *this, false); } /*! \brief The moving constructor. It uses parameters, translator and allocator from the source tree. \param src The rtree which content will be moved. \par Throws Nothing. */ inline rtree(BOOST_RV_REF(rtree) src) : m_members(src.m_members.indexable_getter(), src.m_members.equal_to(), src.m_members.parameters(), boost::move(src.m_members.allocators())) { boost::swap(m_members.values_count, src.m_members.values_count); boost::swap(m_members.leafs_level, src.m_members.leafs_level); boost::swap(m_members.root, src.m_members.root); } /*! \brief The moving constructor. It uses parameters and translator from the source tree. \param src The rtree which content will be moved. \param allocator The allocator. \par Throws \li If allocator copy constructor throws. \li If Value copy constructor throws (only if allocators aren't equal). \li If allocation throws or returns invalid value (only if allocators aren't equal). */ inline rtree(BOOST_RV_REF(rtree) src, allocator_type const& allocator) : m_members(src.m_members.indexable_getter(), src.m_members.equal_to(), src.m_members.parameters(), allocator) { if ( src.m_members.allocators() == allocator ) { boost::swap(m_members.values_count, src.m_members.values_count); boost::swap(m_members.leafs_level, src.m_members.leafs_level); boost::swap(m_members.root, src.m_members.root); } else { this->raw_copy(src, *this, false); } } /*! \brief The assignment operator. It uses parameters and translator from the source tree. \param src The rtree which content will be copied. \par Throws \li If Value copy constructor throws. \li If allocation throws. \li If allocation throws or returns invalid value. */ inline rtree & operator=(BOOST_COPY_ASSIGN_REF(rtree) src) { if ( &src != this ) { allocators_type & this_allocs = m_members.allocators(); allocators_type const& src_allocs = src.m_members.allocators(); // NOTE: if propagate is true for std allocators on darwin 4.2.1, glibc++ // (allocators stored as base classes of members_holder) // copying them changes values_count, in this case it doesn't cause errors since data must be copied typedef boost::mpl::bool_< allocator_traits_type::propagate_on_container_copy_assignment::value > propagate; if ( propagate::value && !(this_allocs == src_allocs) ) this->raw_destroy(*this); detail::assign_cond(this_allocs, src_allocs, propagate()); // It uses m_allocators this->raw_copy(src, *this, true); } return *this; } /*! \brief The moving assignment. It uses parameters and translator from the source tree. \param src The rtree which content will be moved. \par Throws Only if allocators aren't equal. \li If Value copy constructor throws. \li If allocation throws or returns invalid value. */ inline rtree & operator=(BOOST_RV_REF(rtree) src) { if ( &src != this ) { allocators_type & this_allocs = m_members.allocators(); allocators_type & src_allocs = src.m_members.allocators(); if ( this_allocs == src_allocs ) { this->raw_destroy(*this); m_members.indexable_getter() = src.m_members.indexable_getter(); m_members.equal_to() = src.m_members.equal_to(); m_members.parameters() = src.m_members.parameters(); boost::swap(m_members.values_count, src.m_members.values_count); boost::swap(m_members.leafs_level, src.m_members.leafs_level); boost::swap(m_members.root, src.m_members.root); // NOTE: if propagate is true for std allocators on darwin 4.2.1, glibc++ // (allocators stored as base classes of members_holder) // moving them changes values_count typedef boost::mpl::bool_< allocator_traits_type::propagate_on_container_move_assignment::value > propagate; detail::move_cond(this_allocs, src_allocs, propagate()); } else { // TODO - shouldn't here propagate_on_container_copy_assignment be checked like in operator=(const&)? // It uses m_allocators this->raw_copy(src, *this, true); } } return *this; } /*! \brief Swaps contents of two rtrees. Parameters, translator and allocators are swapped as well. \param other The rtree which content will be swapped with this rtree content. \par Throws If allocators swap throws. */ void swap(rtree & other) { boost::swap(m_members.indexable_getter(), other.m_members.indexable_getter()); boost::swap(m_members.equal_to(), other.m_members.equal_to()); boost::swap(m_members.parameters(), other.m_members.parameters()); // NOTE: if propagate is true for std allocators on darwin 4.2.1, glibc++ // (allocators stored as base classes of members_holder) // swapping them changes values_count typedef boost::mpl::bool_< allocator_traits_type::propagate_on_container_swap::value > propagate; detail::swap_cond(m_members.allocators(), other.m_members.allocators(), propagate()); boost::swap(m_members.values_count, other.m_members.values_count); boost::swap(m_members.leafs_level, other.m_members.leafs_level); boost::swap(m_members.root, other.m_members.root); } /*! \brief Insert a value to the index. \param value The value which will be stored in the container. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ inline void insert(value_type const& value) { if ( !m_members.root ) this->raw_create(); this->raw_insert(value); } /*! \brief Insert a range of values to the index. \param first The beginning of the range of values. \param last The end of the range of values. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ template <typename Iterator> inline void insert(Iterator first, Iterator last) { if ( !m_members.root ) this->raw_create(); for ( ; first != last ; ++first ) this->raw_insert(*first); } /*! \brief Insert a value created using convertible object or a range of values to the index. \param conv_or_rng An object of type convertible to value_type or a range of values. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ template <typename ConvertibleOrRange> inline void insert(ConvertibleOrRange const& conv_or_rng) { if ( !m_members.root ) this->raw_create(); typedef boost::mpl::bool_ < boost::is_convertible<ConvertibleOrRange, value_type>::value > is_conv_t; this->insert_dispatch(conv_or_rng, is_conv_t()); } /*! \brief Remove a value from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method this method removes only one value from the container. \param value The value which will be removed from the container. \return 1 if the value was removed, 0 otherwise. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ inline size_type remove(value_type const& value) { if ( !m_members.root ) return 0; return this->raw_remove(value); } /*! \brief Remove a range of values from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method it doesn't take iterators pointing to values stored in this container. It removes values equal to these passed as a range. Furthermore this method removes only one value for each one passed in the range, not all equal values. \param first The beginning of the range of values. \param last The end of the range of values. \return The number of removed values. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ template <typename Iterator> inline size_type remove(Iterator first, Iterator last) { size_type result = 0; if ( !m_members.root ) return result; for ( ; first != last ; ++first ) result += this->raw_remove(*first); return result; } /*! \brief Remove value corresponding to an object convertible to it or a range of values from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method it removes values equal to these passed as a range. Furthermore, this method removes only one value for each one passed in the range, not all equal values. \param conv_or_rng The object of type convertible to value_type or a range of values. \return The number of removed values. \par Throws \li If Value copy constructor or copy assignment throws. \li If allocation throws or returns invalid value. \warning This operation only guarantees that there will be no memory leaks. After an exception is thrown the R-tree may be left in an inconsistent state, elements must not be inserted or removed. Other operations are allowed however some of them may return invalid data. */ template <typename ConvertibleOrRange> inline size_type remove(ConvertibleOrRange const& conv_or_rng) { if ( !m_members.root ) return 0; typedef boost::mpl::bool_ < boost::is_convertible<ConvertibleOrRange, value_type>::value > is_conv_t; return this->remove_dispatch(conv_or_rng, is_conv_t()); } /*! \brief Finds values meeting passed predicates e.g. nearest to some Point and/or intersecting some Box. This query function performs spatial and k-nearest neighbor searches. It allows to pass a set of predicates. Values will be returned only if all predicates are met. <b>Spatial predicates</b> Spatial predicates may be generated by one of the functions listed below: \li \c boost::geometry::index::contains(), \li \c boost::geometry::index::covered_by(), \li \c boost::geometry::index::covers(), \li \c boost::geometry::index::disjoint(), \li \c boost::geometry::index::intersects(), \li \c boost::geometry::index::overlaps(), \li \c boost::geometry::index::within(), It is possible to negate spatial predicates: \li <tt>! boost::geometry::index::contains()</tt>, \li <tt>! boost::geometry::index::covered_by()</tt>, \li <tt>! boost::geometry::index::covers()</tt>, \li <tt>! boost::geometry::index::disjoint()</tt>, \li <tt>! boost::geometry::index::intersects()</tt>, \li <tt>! boost::geometry::index::overlaps()</tt>, \li <tt>! boost::geometry::index::within()</tt> <b>Satisfies predicate</b> This is a special kind of predicate which allows to pass a user-defined function or function object which checks if Value should be returned by the query. It's generated by: \li \c boost::geometry::index::satisfies(). <b>Nearest predicate</b> If the nearest predicate is passed a k-nearest neighbor search will be performed. This query will result in returning k values to the output iterator. Only one nearest predicate may be passed to the query. It may be generated by: \li \c boost::geometry::index::nearest(). <b>Connecting predicates</b> Predicates may be passed together connected with \c operator&&(). \par Example \verbatim // return elements intersecting box tree.query(bgi::intersects(box), std::back_inserter(result)); // return elements intersecting poly but not within box tree.query(bgi::intersects(poly) && !bgi::within(box), std::back_inserter(result)); // return elements overlapping box and meeting my_fun unary predicate tree.query(bgi::overlaps(box) && bgi::satisfies(my_fun), std::back_inserter(result)); // return 5 elements nearest to pt and elements are intersecting box tree.query(bgi::nearest(pt, 5) && bgi::intersects(box), std::back_inserter(result)); // For each found value do_something (it is a type of function object) tree.query(bgi::intersects(box), boost::make_function_output_iterator(do_something())); // For each value stored in the rtree do_something // always_true is a type of function object always returning true tree.query(bgi::satisfies(always_true()), boost::make_function_output_iterator(do_something())); // C++11 (lambda expression) tree.query(bgi::intersects(box), boost::make_function_output_iterator([](value_type const& val){ // do something })); // C++14 (generic lambda expression) tree.query(bgi::intersects(box), boost::make_function_output_iterator([](auto const& val){ // do something })); \endverbatim \par Throws If Value copy constructor or copy assignment throws. If predicates copy throws. \warning Only one \c nearest() predicate may be passed to the query. Passing more of them results in compile-time error. \param predicates Predicates. \param out_it The output iterator, e.g. generated by std::back_inserter(). \return The number of values found. */ template <typename Predicates, typename OutIter> size_type query(Predicates const& predicates, OutIter out_it) const { if ( !m_members.root ) return 0; static const unsigned distance_predicates_count = detail::predicates_count_distance<Predicates>::value; static const bool is_distance_predicate = 0 < distance_predicates_count; BOOST_MPL_ASSERT_MSG((distance_predicates_count <= 1), PASS_ONLY_ONE_DISTANCE_PREDICATE, (Predicates)); return query_dispatch(predicates, out_it, boost::mpl::bool_<is_distance_predicate>()); } /*! \brief Returns a query iterator pointing at the begin of the query range. This method returns an iterator which may be used to perform iterative queries. For the information about predicates which may be passed to this method see query(). \par Example \verbatim for ( Rtree::const_query_iterator it = tree.qbegin(bgi::nearest(pt, 10000)) ; it != tree.qend() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } // C++11 (auto) for ( auto it = tree.qbegin(bgi::nearest(pt, 3)) ; it != tree.qend() ; ++it ) { // do something with value } // C++14 (generic lambda expression) std::for_each(tree.qbegin(bgi::nearest(pt, 3)), tree.qend(), [](auto const& val){ // do something with value }); \endverbatim \par Iterator category ForwardIterator \par Throws If predicates copy throws. If allocation throws. \warning The modification of the rtree may invalidate the iterators. \param predicates Predicates. \return The iterator pointing at the begin of the query range. */ template <typename Predicates> const_query_iterator qbegin(Predicates const& predicates) const { return const_query_iterator(qbegin_(predicates)); } /*! \brief Returns a query iterator pointing at the end of the query range. This method returns an iterator which may be used to check if the query has ended. \par Example \verbatim for ( Rtree::const_query_iterator it = tree.qbegin(bgi::nearest(pt, 10000)) ; it != tree.qend() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } // C++11 (auto) for ( auto it = tree.qbegin(bgi::nearest(pt, 3)) ; it != tree.qend() ; ++it ) { // do something with value } // C++14 (generic lambda expression) std::for_each(tree.qbegin(bgi::nearest(pt, 3)), tree.qend(), [](auto const& val){ // do something with value }); \endverbatim \par Iterator category ForwardIterator \par Throws Nothing \warning The modification of the rtree may invalidate the iterators. \return The iterator pointing at the end of the query range. */ const_query_iterator qend() const { return const_query_iterator(); } #ifndef BOOST_GEOMETRY_INDEX_DETAIL_EXPERIMENTAL private: #endif /*! \brief Returns a query iterator pointing at the begin of the query range. This method returns an iterator which may be used to perform iterative queries. For the information about predicates which may be passed to this method see query(). The type of the returned iterator depends on the type of passed Predicates but the iterator of this type may be assigned to the variable of const_query_iterator type. If you'd like to use the type of the iterator returned by this method you may get the type e.g. by using C++11 decltype or Boost.Typeof library. This iterator may be compared with iterators returned by both versions of qend() method. \par Example \verbatim // Store the result in the container using std::copy() - it requires both iterators of the same type std::copy(tree.qbegin_(bgi::intersects(box)), tree.qend_(bgi::intersects(box)), std::back_inserter(result)); // Store the result in the container using std::copy() and type-erased iterators Rtree::const_query_iterator first = tree.qbegin_(bgi::intersects(box)); Rtree::const_query_iterator last = tree.qend_(); std::copy(first, last, std::back_inserter(result)); // Boost.Typeof typedef BOOST_TYPEOF(tree.qbegin(bgi::nearest(pt, 10000))) Iter; for ( Iter it = tree.qbegin_(bgi::nearest(pt, 10000)) ; it != tree.qend_() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } // C++11 (auto) for ( auto it = tree.qbegin_(bgi::nearest(pt, 10000)) ; it != tree.qend_() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } \endverbatim \par Iterator category ForwardIterator \par Throws If predicates copy throws. If allocation throws. \warning The modification of the rtree may invalidate the iterators. \param predicates Predicates. \return The iterator pointing at the begin of the query range. */ template <typename Predicates> typename boost::mpl::if_c< detail::predicates_count_distance<Predicates>::value == 0, detail::rtree::iterators::spatial_query_iterator<value_type, options_type, translator_type, box_type, allocators_type, Predicates>, detail::rtree::iterators::distance_query_iterator< value_type, options_type, translator_type, box_type, allocators_type, Predicates, detail::predicates_find_distance<Predicates>::value > >::type qbegin_(Predicates const& predicates) const { static const unsigned distance_predicates_count = detail::predicates_count_distance<Predicates>::value; BOOST_MPL_ASSERT_MSG((distance_predicates_count <= 1), PASS_ONLY_ONE_DISTANCE_PREDICATE, (Predicates)); typedef typename boost::mpl::if_c< detail::predicates_count_distance<Predicates>::value == 0, detail::rtree::iterators::spatial_query_iterator<value_type, options_type, translator_type, box_type, allocators_type, Predicates>, detail::rtree::iterators::distance_query_iterator< value_type, options_type, translator_type, box_type, allocators_type, Predicates, detail::predicates_find_distance<Predicates>::value > >::type iterator_type; if ( !m_members.root ) return iterator_type(m_members.translator(), predicates); return iterator_type(m_members.root, m_members.translator(), predicates); } /*! \brief Returns the query iterator pointing at the end of the query range. This method returns the iterator which may be used to perform iterative queries. For the information about the predicates which may be passed to this method see query(). The type of the returned iterator depends on the type of passed Predicates but the iterator of this type may be assigned to the variable of const_query_iterator type. If you'd like to use the type of the iterator returned by this method you may get the type e.g. by using C++11 decltype or Boost.Typeof library. The type of the iterator returned by this method is the same as the one returned by qbegin() to which the same predicates were passed. \par Example \verbatim // Store the result in the container using std::copy() - it requires both iterators of the same type std::copy(tree.qbegin_(bgi::intersects(box)), tree.qend_(bgi::intersects(box)), std::back_inserter(result)); \endverbatim \par Iterator category ForwardIterator \par Throws If predicates copy throws. \warning The modification of the rtree may invalidate the iterators. \param predicates Predicates. \return The iterator pointing at the end of the query range. */ template <typename Predicates> typename boost::mpl::if_c< detail::predicates_count_distance<Predicates>::value == 0, detail::rtree::iterators::spatial_query_iterator<value_type, options_type, translator_type, box_type, allocators_type, Predicates>, detail::rtree::iterators::distance_query_iterator< value_type, options_type, translator_type, box_type, allocators_type, Predicates, detail::predicates_find_distance<Predicates>::value > >::type qend_(Predicates const& predicates) const { static const unsigned distance_predicates_count = detail::predicates_count_distance<Predicates>::value; BOOST_MPL_ASSERT_MSG((distance_predicates_count <= 1), PASS_ONLY_ONE_DISTANCE_PREDICATE, (Predicates)); typedef typename boost::mpl::if_c< detail::predicates_count_distance<Predicates>::value == 0, detail::rtree::iterators::spatial_query_iterator<value_type, options_type, translator_type, box_type, allocators_type, Predicates>, detail::rtree::iterators::distance_query_iterator< value_type, options_type, translator_type, box_type, allocators_type, Predicates, detail::predicates_find_distance<Predicates>::value > >::type iterator_type; return iterator_type(m_members.translator(), predicates); } /*! \brief Returns the query iterator pointing at the end of the query range. This method returns the iterator which may be compared with the iterator returned by qbegin() in order to check if the query has ended. The type of the returned iterator is different than the type returned by qbegin() but the iterator of this type may be assigned to the variable of const_query_iterator type. If you'd like to use the type of the iterator returned by this method, which most certainly will be faster than the type-erased iterator, you may get the type e.g. by using C++11 decltype or Boost.Typeof library. The type of the iterator returned by this method is different than the type returned by qbegin(). \par Example \verbatim // Store the result in the container using std::copy() and type-erased iterators Rtree::const_query_iterator first = tree.qbegin_(bgi::intersects(box)); Rtree::const_query_iterator last = tree.qend_(); std::copy(first, last, std::back_inserter(result)); // Boost.Typeof typedef BOOST_TYPEOF(tree.qbegin(bgi::nearest(pt, 10000))) Iter; for ( Iter it = tree.qbegin_(bgi::nearest(pt, 10000)) ; it != tree.qend_() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } // C++11 (auto) for ( auto it = tree.qbegin_(bgi::nearest(pt, 10000)) ; it != tree.qend_() ; ++it ) { // do something with value if ( has_enough_nearest_values() ) break; } \endverbatim \par Iterator category ForwardIterator \par Throws Nothing \warning The modification of the rtree may invalidate the iterators. \return The iterator pointing at the end of the query range. */ detail::rtree::iterators::end_query_iterator<value_type, allocators_type> qend_() const { return detail::rtree::iterators::end_query_iterator<value_type, allocators_type>(); } public: /*! \brief Returns the iterator pointing at the begin of the rtree values range. This method returns the iterator which may be used to iterate over all values stored in the rtree. \par Example \verbatim // Copy all values into the vector std::copy(tree.begin(), tree.end(), std::back_inserter(vec)); for ( Rtree::const_iterator it = tree.begin() ; it != tree.end() ; ++it ) { // do something with value } // C++11 (auto) for ( auto it = tree.begin() ; it != tree.end() ; ++it ) { // do something with value } // C++14 (generic lambda expression) std::for_each(tree.begin(), tree.end(), [](auto const& val){ // do something with value }) \endverbatim \par Iterator category ForwardIterator \par Throws If allocation throws. \warning The modification of the rtree may invalidate the iterators. \return The iterator pointing at the begin of the range. */ const_iterator begin() const { if ( !m_members.root ) return const_iterator(); return const_iterator(m_members.root); } /*! \brief Returns the iterator pointing at the end of the rtree values range. This method returns the iterator which may be compared with the iterator returned by begin() in order to check if the iteration has ended. \par Example \verbatim for ( Rtree::const_iterator it = tree.begin() ; it != tree.end() ; ++it ) { // do something with value } // C++11 (lambda expression) std::for_each(tree.begin(), tree.end(), [](value_type const& val){ // do something with value }) \endverbatim \par Iterator category ForwardIterator \par Throws Nothing. \warning The modification of the rtree may invalidate the iterators. \return The iterator pointing at the end of the range. */ const_iterator end() const { return const_iterator(); } /*! \brief Returns the number of stored values. \return The number of stored values. \par Throws Nothing. */ inline size_type size() const { return m_members.values_count; } /*! \brief Query if the container is empty. \return true if the container is empty. \par Throws Nothing. */ inline bool empty() const { return 0 == m_members.values_count; } /*! \brief Removes all values stored in the container. \par Throws Nothing. */ inline void clear() { this->raw_destroy(*this); } /*! \brief Returns the box able to contain all values stored in the container. Returns the box able to contain all values stored in the container. If the container is empty the result of \c geometry::assign_inverse() is returned. \return The box able to contain all values stored in the container or an invalid box if there are no values in the container. \par Throws Nothing. */ inline bounds_type bounds() const { bounds_type result; // in order to suppress the uninitialized variable warnings geometry::assign_inverse(result); if ( m_members.root ) { detail::rtree::visitors::children_box<value_type, options_type, translator_type, box_type, allocators_type> box_v(result, m_members.translator()); detail::rtree::apply_visitor(box_v, *m_members.root); } return result; } /*! \brief Count Values or Indexables stored in the container. For indexable_type it returns the number of values which indexables equals the parameter. For value_type it returns the number of values which equals the parameter. \param vori The value or indexable which will be counted. \return The number of values found. \par Throws Nothing. */ template <typename ValueOrIndexable> size_type count(ValueOrIndexable const& vori) const { if ( !m_members.root ) return 0; // the input should be convertible to Value or Indexable type enum { as_val = 0, as_ind, dont_know }; typedef boost::mpl::int_ < boost::is_same<ValueOrIndexable, value_type>::value ? as_val : boost::is_same<ValueOrIndexable, indexable_type>::value ? as_ind : boost::is_convertible<ValueOrIndexable, indexable_type>::value ? as_ind : boost::is_convertible<ValueOrIndexable, value_type>::value ? as_val : dont_know > variant; BOOST_MPL_ASSERT_MSG((variant::value != dont_know), PASSED_OBJECT_NOT_CONVERTIBLE_TO_VALUE_NOR_INDEXABLE_TYPE, (ValueOrIndexable)); typedef typename boost::mpl::if_c < variant::value == as_val, value_type, indexable_type >::type value_or_indexable; // NOTE: If an object of convertible but not the same type is passed // into the function, here a temporary will be created. return this->template raw_count<value_or_indexable>(vori); } /*! \brief Returns parameters. \return The parameters object. \par Throws Nothing. */ inline parameters_type parameters() const { return m_members.parameters(); } /*! \brief Returns function retrieving Indexable from Value. \return The indexable_getter object. \par Throws Nothing. */ indexable_getter indexable_get() const { return m_members.indexable_getter(); } /*! \brief Returns function comparing Values \return The value_equal function. \par Throws Nothing. */ value_equal value_eq() const { return m_members.equal_to(); } /*! \brief Returns allocator used by the rtree. \return The allocator. \par Throws If allocator copy constructor throws. */ allocator_type get_allocator() const { return m_members.allocators().allocator(); } private: /*! \brief Returns the translator object. \return The translator object. \par Throws Nothing. */ inline translator_type translator() const { return m_members.translator(); } /*! \brief Apply a visitor to the nodes structure in order to perform some operator. This function is not a part of the 'official' interface. However it makes possible e.g. to pass a visitor drawing the tree structure. \param visitor The visitor object. \par Throws If Visitor::operator() throws. */ template <typename Visitor> inline void apply_visitor(Visitor & visitor) const { if ( m_members.root ) detail::rtree::apply_visitor(visitor, *m_members.root); } /*! \brief Returns the depth of the R-tree. This function is not a part of the 'official' interface. \return The depth of the R-tree. \par Throws Nothing. */ inline size_type depth() const { return m_members.leafs_level; } private: /*! \pre Root node must exist - m_root != 0. \brief Insert a value to the index. \param value The value which will be stored in the container. \par Exception-safety basic */ inline void raw_insert(value_type const& value) { BOOST_GEOMETRY_INDEX_ASSERT(m_members.root, "The root must exist"); // CONSIDER: alternative - ignore invalid indexable or throw an exception BOOST_GEOMETRY_INDEX_ASSERT(detail::is_valid(m_members.translator()(value)), "Indexable is invalid"); detail::rtree::visitors::insert< value_type, value_type, options_type, translator_type, box_type, allocators_type, typename options_type::insert_tag > insert_v(m_members.root, m_members.leafs_level, value, m_members.parameters(), m_members.translator(), m_members.allocators()); detail::rtree::apply_visitor(insert_v, *m_members.root); // TODO // Think about this: If exception is thrown, may the root be removed? // Or it is just cleared? // TODO // If exception is thrown, m_values_count may be invalid ++m_members.values_count; } /*! \brief Remove the value from the container. \param value The value which will be removed from the container. \par Exception-safety basic */ inline size_type raw_remove(value_type const& value) { // TODO: awulkiew - assert for correct value (indexable) ? BOOST_GEOMETRY_INDEX_ASSERT(m_members.root, "The root must exist"); detail::rtree::visitors::remove< value_type, options_type, translator_type, box_type, allocators_type > remove_v(m_members.root, m_members.leafs_level, value, m_members.parameters(), m_members.translator(), m_members.allocators()); detail::rtree::apply_visitor(remove_v, *m_members.root); // If exception is thrown, m_values_count may be invalid if ( remove_v.is_value_removed() ) { BOOST_GEOMETRY_INDEX_ASSERT(0 < m_members.values_count, "unexpected state"); --m_members.values_count; return 1; } return 0; } /*! \brief Create an empty R-tree i.e. new empty root node and clear other attributes. \par Exception-safety strong */ inline void raw_create() { BOOST_GEOMETRY_INDEX_ASSERT(0 == m_members.root, "the tree is already created"); m_members.root = detail::rtree::create_node<allocators_type, leaf>::apply(m_members.allocators()); // MAY THROW (N: alloc) m_members.values_count = 0; m_members.leafs_level = 0; } /*! \brief Destroy the R-tree i.e. all nodes and clear attributes. \param t The container which is going to be destroyed. \par Exception-safety nothrow */ inline void raw_destroy(rtree & t) { if ( t.m_members.root ) { detail::rtree::visitors::destroy<value_type, options_type, translator_type, box_type, allocators_type> del_v(t.m_members.root, t.m_members.allocators()); detail::rtree::apply_visitor(del_v, *t.m_members.root); t.m_members.root = 0; } t.m_members.values_count = 0; t.m_members.leafs_level = 0; } /*! \brief Copy the R-tree i.e. whole nodes structure, values and other attributes. It uses destination's allocators to create the new structure. \param src The source R-tree. \param dst The destination R-tree. \param copy_tr_and_params If true, translator and parameters will also be copied. \par Exception-safety strong */ inline void raw_copy(rtree const& src, rtree & dst, bool copy_tr_and_params) const { detail::rtree::visitors::copy<value_type, options_type, translator_type, box_type, allocators_type> copy_v(dst.m_members.allocators()); if ( src.m_members.root ) detail::rtree::apply_visitor(copy_v, *src.m_members.root); // MAY THROW (V, E: alloc, copy, N: alloc) if ( copy_tr_and_params ) { dst.m_members.indexable_getter() = src.m_members.indexable_getter(); dst.m_members.equal_to() = src.m_members.equal_to(); dst.m_members.parameters() = src.m_members.parameters(); } // TODO use subtree_destroyer if ( dst.m_members.root ) { detail::rtree::visitors::destroy<value_type, options_type, translator_type, box_type, allocators_type> del_v(dst.m_members.root, dst.m_members.allocators()); detail::rtree::apply_visitor(del_v, *dst.m_members.root); dst.m_members.root = 0; } dst.m_members.root = copy_v.result; dst.m_members.values_count = src.m_members.values_count; dst.m_members.leafs_level = src.m_members.leafs_level; } /*! \brief Insert a value corresponding to convertible object into the index. \param val_conv The object convertible to value. \par Exception-safety basic */ template <typename ValueConvertible> inline void insert_dispatch(ValueConvertible const& val_conv, boost::mpl::bool_<true> const& /*is_convertible*/) { this->raw_insert(val_conv); } /*! \brief Insert a range of values into the index. \param rng The range of values. \par Exception-safety basic */ template <typename Range> inline void insert_dispatch(Range const& rng, boost::mpl::bool_<false> const& /*is_convertible*/) { BOOST_MPL_ASSERT_MSG((detail::is_range<Range>::value), PASSED_OBJECT_IS_NOT_CONVERTIBLE_TO_VALUE_NOR_A_RANGE, (Range)); typedef typename boost::range_const_iterator<Range>::type It; for ( It it = boost::const_begin(rng); it != boost::const_end(rng) ; ++it ) this->raw_insert(*it); } /*! \brief Remove a value corresponding to convertible object from the index. \param val_conv The object convertible to value. \par Exception-safety basic */ template <typename ValueConvertible> inline size_type remove_dispatch(ValueConvertible const& val_conv, boost::mpl::bool_<true> const& /*is_convertible*/) { return this->raw_remove(val_conv); } /*! \brief Remove a range of values from the index. \param rng The range of values which will be removed from the container. \par Exception-safety basic */ template <typename Range> inline size_type remove_dispatch(Range const& rng, boost::mpl::bool_<false> const& /*is_convertible*/) { BOOST_MPL_ASSERT_MSG((detail::is_range<Range>::value), PASSED_OBJECT_IS_NOT_CONVERTIBLE_TO_VALUE_NOR_A_RANGE, (Range)); size_type result = 0; typedef typename boost::range_const_iterator<Range>::type It; for ( It it = boost::const_begin(rng); it != boost::const_end(rng) ; ++it ) result += this->raw_remove(*it); return result; } /*! \brief Return values meeting predicates. \par Exception-safety strong */ template <typename Predicates, typename OutIter> size_type query_dispatch(Predicates const& predicates, OutIter out_it, boost::mpl::bool_<false> const& /*is_distance_predicate*/) const { detail::rtree::visitors::spatial_query<value_type, options_type, translator_type, box_type, allocators_type, Predicates, OutIter> find_v(m_members.translator(), predicates, out_it); detail::rtree::apply_visitor(find_v, *m_members.root); return find_v.found_count; } /*! \brief Perform nearest neighbour search. \par Exception-safety strong */ template <typename Predicates, typename OutIter> size_type query_dispatch(Predicates const& predicates, OutIter out_it, boost::mpl::bool_<true> const& /*is_distance_predicate*/) const { BOOST_GEOMETRY_INDEX_ASSERT(m_members.root, "The root must exist"); static const unsigned distance_predicate_index = detail::predicates_find_distance<Predicates>::value; detail::rtree::visitors::distance_query< value_type, options_type, translator_type, box_type, allocators_type, Predicates, distance_predicate_index, OutIter > distance_v(m_members.parameters(), m_members.translator(), predicates, out_it); detail::rtree::apply_visitor(distance_v, *m_members.root); return distance_v.finish(); } /*! \brief Count elements corresponding to value or indexable. \par Exception-safety strong */ template <typename ValueOrIndexable> size_type raw_count(ValueOrIndexable const& vori) const { BOOST_GEOMETRY_INDEX_ASSERT(m_members.root, "The root must exist"); detail::rtree::visitors::count < ValueOrIndexable, value_type, options_type, translator_type, box_type, allocators_type > count_v(vori, m_members.translator()); detail::rtree::apply_visitor(count_v, *m_members.root); return count_v.found_count; } struct members_holder : public translator_type , public Parameters , public allocators_type { private: members_holder(members_holder const&); members_holder & operator=(members_holder const&); public: template <typename IndGet, typename ValEq, typename Alloc> members_holder(IndGet const& ind_get, ValEq const& val_eq, Parameters const& parameters, BOOST_FWD_REF(Alloc) alloc) : translator_type(ind_get, val_eq) , Parameters(parameters) , allocators_type(boost::forward<Alloc>(alloc)) , values_count(0) , leafs_level(0) , root(0) {} template <typename IndGet, typename ValEq> members_holder(IndGet const& ind_get, ValEq const& val_eq, Parameters const& parameters) : translator_type(ind_get, val_eq) , Parameters(parameters) , allocators_type() , values_count(0) , leafs_level(0) , root(0) {} translator_type const& translator() const { return *this; } IndexableGetter const& indexable_getter() const { return *this; } IndexableGetter & indexable_getter() { return *this; } EqualTo const& equal_to() const { return *this; } EqualTo & equal_to() { return *this; } Parameters const& parameters() const { return *this; } Parameters & parameters() { return *this; } allocators_type const& allocators() const { return *this; } allocators_type & allocators() { return *this; } size_type values_count; size_type leafs_level; node_pointer root; }; members_holder m_members; }; /*! \brief Insert a value to the index. It calls <tt>rtree::insert(value_type const&)</tt>. \ingroup rtree_functions \param tree The spatial index. \param v The value which will be stored in the index. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline void insert(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, Value const& v) { tree.insert(v); } /*! \brief Insert a range of values to the index. It calls <tt>rtree::insert(Iterator, Iterator)</tt>. \ingroup rtree_functions \param tree The spatial index. \param first The beginning of the range of values. \param last The end of the range of values. */ template<typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename Iterator> inline void insert(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, Iterator first, Iterator last) { tree.insert(first, last); } /*! \brief Insert a value created using convertible object or a range of values to the index. It calls <tt>rtree::insert(ConvertibleOrRange const&)</tt>. \ingroup rtree_functions \param tree The spatial index. \param conv_or_rng The object of type convertible to value_type or a range of values. */ template<typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename ConvertibleOrRange> inline void insert(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, ConvertibleOrRange const& conv_or_rng) { tree.insert(conv_or_rng); } /*! \brief Remove a value from the container. Remove a value from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method this function removes only one value from the container. It calls <tt>rtree::remove(value_type const&)</tt>. \ingroup rtree_functions \param tree The spatial index. \param v The value which will be removed from the index. \return 1 if value was removed, 0 otherwise. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::size_type remove(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, Value const& v) { return tree.remove(v); } /*! \brief Remove a range of values from the container. Remove a range of values from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method it doesn't take iterators pointing to values stored in this container. It removes values equal to these passed as a range. Furthermore this function removes only one value for each one passed in the range, not all equal values. It calls <tt>rtree::remove(Iterator, Iterator)</tt>. \ingroup rtree_functions \param tree The spatial index. \param first The beginning of the range of values. \param last The end of the range of values. \return The number of removed values. */ template<typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename Iterator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::size_type remove(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, Iterator first, Iterator last) { return tree.remove(first, last); } /*! \brief Remove a value corresponding to an object convertible to it or a range of values from the container. Remove a value corresponding to an object convertible to it or a range of values from the container. In contrast to the \c std::set or <tt>std::map erase()</tt> method it removes values equal to these passed as a range. Furthermore this method removes only one value for each one passed in the range, not all equal values. It calls <tt>rtree::remove(ConvertibleOrRange const&)</tt>. \ingroup rtree_functions \param tree The spatial index. \param conv_or_rng The object of type convertible to value_type or the range of values. \return The number of removed values. */ template<typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename ConvertibleOrRange> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::size_type remove(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree, ConvertibleOrRange const& conv_or_rng) { return tree.remove(conv_or_rng); } /*! \brief Finds values meeting passed predicates e.g. nearest to some Point and/or intersecting some Box. This query function performs spatial and k-nearest neighbor searches. It allows to pass a set of predicates. Values will be returned only if all predicates are met. <b>Spatial predicates</b> Spatial predicates may be generated by one of the functions listed below: \li \c boost::geometry::index::contains(), \li \c boost::geometry::index::covered_by(), \li \c boost::geometry::index::covers(), \li \c boost::geometry::index::disjoint(), \li \c boost::geometry::index::intersects(), \li \c boost::geometry::index::overlaps(), \li \c boost::geometry::index::within(), It is possible to negate spatial predicates: \li <tt>! boost::geometry::index::contains()</tt>, \li <tt>! boost::geometry::index::covered_by()</tt>, \li <tt>! boost::geometry::index::covers()</tt>, \li <tt>! boost::geometry::index::disjoint()</tt>, \li <tt>! boost::geometry::index::intersects()</tt>, \li <tt>! boost::geometry::index::overlaps()</tt>, \li <tt>! boost::geometry::index::within()</tt> <b>Satisfies predicate</b> This is a special kind of predicate which allows to pass a user-defined function or function object which checks if Value should be returned by the query. It's generated by: \li \c boost::geometry::index::satisfies(). <b>Nearest predicate</b> If the nearest predicate is passed a k-nearest neighbor search will be performed. This query will result in returning k values to the output iterator. Only one nearest predicate may be passed to the query. It may be generated by: \li \c boost::geometry::index::nearest(). <b>Connecting predicates</b> Predicates may be passed together connected with \c operator&&(). \par Example \verbatim // return elements intersecting box bgi::query(tree, bgi::intersects(box), std::back_inserter(result)); // return elements intersecting poly but not within box bgi::query(tree, bgi::intersects(poly) && !bgi::within(box), std::back_inserter(result)); // return elements overlapping box and meeting my_fun value predicate bgi::query(tree, bgi::overlaps(box) && bgi::satisfies(my_fun), std::back_inserter(result)); // return 5 elements nearest to pt and elements are intersecting box bgi::query(tree, bgi::nearest(pt, 5) && bgi::intersects(box), std::back_inserter(result)); // For each found value do_something (it is a type of function object) tree.query(bgi::intersects(box), boost::make_function_output_iterator(do_something())); \endverbatim \par Throws If Value copy constructor or copy assignment throws. \warning Only one \c nearest() predicate may be passed to the query. Passing more of them results in compile-time error. \ingroup rtree_functions \param tree The rtree. \param predicates Predicates. \param out_it The output iterator, e.g. generated by std::back_inserter(). \return The number of values found. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename Predicates, typename OutIter> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::size_type query(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree, Predicates const& predicates, OutIter out_it) { return tree.query(predicates, out_it); } /*! \brief Returns the query iterator pointing at the begin of the query range. This method returns the iterator which may be used to perform iterative queries. For the information about the predicates which may be passed to this method see query(). \par Example \verbatim std::for_each(bgi::qbegin(tree, bgi::nearest(pt, 3)), bgi::qend(tree), do_something()); \endverbatim \par Iterator category ForwardIterator \par Throws If predicates copy throws. If allocation throws. \warning The modification of the rtree may invalidate the iterators. \ingroup rtree_functions \param tree The rtree. \param predicates Predicates. \return The iterator pointing at the begin of the query range. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator, typename Predicates> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::const_query_iterator qbegin(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree, Predicates const& predicates) { return tree.qbegin(predicates); } /*! \brief Returns the query iterator pointing at the end of the query range. This method returns the iterator which may be used to check if the query has ended. \par Example \verbatim std::for_each(bgi::qbegin(tree, bgi::nearest(pt, 3)), bgi::qend(tree), do_something()); \endverbatim \par Iterator category ForwardIterator \par Throws Nothing \warning The modification of the rtree may invalidate the iterators. \ingroup rtree_functions \return The iterator pointing at the end of the query range. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::const_query_iterator qend(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.qend(); } /*! \brief Returns the iterator pointing at the begin of the rtree values range. This method returns the iterator which may be used to iterate over all values stored in the rtree. \par Example \verbatim std::for_each(bgi::begin(tree), bgi::end(tree), do_something()); // the same as std::for_each(boost::begin(tree), boost::end(tree), do_something()); \endverbatim \par Iterator category ForwardIterator \par Throws If allocation throws. \warning The modification of the rtree may invalidate the iterators. \ingroup rtree_functions \return The iterator pointing at the begin of the range. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::const_iterator begin(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.begin(); } /*! \brief Returns the iterator pointing at the end of the rtree values range. This method returns the iterator which may be compared with the iterator returned by begin() in order to check if the iteration has ended. \par Example \verbatim std::for_each(bgi::begin(tree), bgi::end(tree), do_something()); // the same as std::for_each(boost::begin(tree), boost::end(tree), do_something()); \endverbatim \par Iterator category ForwardIterator \par Throws Nothing. \warning The modification of the rtree may invalidate the iterators. \ingroup rtree_functions \return The iterator pointing at the end of the range. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::const_iterator end(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.end(); } /*! \brief Remove all values from the index. It calls \c rtree::clear(). \ingroup rtree_functions \param tree The spatial index. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline void clear(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & tree) { return tree.clear(); } /*! \brief Get the number of values stored in the index. It calls \c rtree::size(). \ingroup rtree_functions \param tree The spatial index. \return The number of values stored in the index. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline size_t size(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.size(); } /*! \brief Query if there are no values stored in the index. It calls \c rtree::empty(). \ingroup rtree_functions \param tree The spatial index. \return true if there are no values in the index. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline bool empty(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.bounds(); } /*! \brief Get the box containing all stored values or an invalid box if the index has no values. It calls \c rtree::envelope(). \ingroup rtree_functions \param tree The spatial index. \return The box containing all stored values or an invalid box. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline typename rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator>::bounds_type bounds(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> const& tree) { return tree.bounds(); } /*! \brief Exchanges the contents of the container with those of other. It calls \c rtree::swap(). \ingroup rtree_functions \param l The first rtree. \param r The second rtree. */ template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> inline void swap(rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & l, rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> & r) { return l.swap(r); } }}} // namespace boost::geometry::index // Boost.Range adaptation namespace boost { template <typename Value, typename Parameters, typename IndexableGetter, typename EqualTo, typename Allocator> struct range_mutable_iterator < boost::geometry::index::rtree<Value, Parameters, IndexableGetter, EqualTo, Allocator> > { typedef typename boost::geometry::index::rtree < Value, Parameters, IndexableGetter, EqualTo, Allocator >::const_iterator type; }; } // namespace boost #include <boost/geometry/index/detail/config_end.hpp> #endif // BOOST_GEOMETRY_INDEX_RTREE_HPP
{ "pile_set_name": "Github" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2016 Dmitry Vyukov <[email protected]> // // 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/. #ifndef EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H #define EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H namespace Eigen { template <typename Environment> class NonBlockingThreadPoolTempl : public Eigen::ThreadPoolInterface { public: typedef typename Environment::Task Task; typedef RunQueue<Task, 1024> Queue; NonBlockingThreadPoolTempl(int num_threads, Environment env = Environment()) : env_(env), threads_(num_threads), queues_(num_threads), coprimes_(num_threads), waiters_(num_threads), blocked_(0), spinning_(0), done_(false), ec_(waiters_) { waiters_.resize(num_threads); // Calculate coprimes of num_threads. // Coprimes are used for a random walk over all threads in Steal // and NonEmptyQueueIndex. Iteration is based on the fact that if we take // a walk starting thread index t and calculate num_threads - 1 subsequent // indices as (t + coprime) % num_threads, we will cover all threads without // repetitions (effectively getting a presudo-random permutation of thread // indices). for (int i = 1; i <= num_threads; i++) { unsigned a = i; unsigned b = num_threads; // If GCD(a, b) == 1, then a and b are coprimes. while (b != 0) { unsigned tmp = a; a = b; b = tmp % b; } if (a == 1) { coprimes_.push_back(i); } } for (int i = 0; i < num_threads; i++) { queues_.push_back(new Queue()); } for (int i = 0; i < num_threads; i++) { threads_.push_back(env_.CreateThread([this, i]() { WorkerLoop(i); })); } } ~NonBlockingThreadPoolTempl() { done_ = true; // Now if all threads block without work, they will start exiting. // But note that threads can continue to work arbitrary long, // block, submit new work, unblock and otherwise live full life. ec_.Notify(true); // Join threads explicitly to avoid destruction order issues. for (size_t i = 0; i < threads_.size(); i++) delete threads_[i]; for (size_t i = 0; i < threads_.size(); i++) delete queues_[i]; } void Schedule(std::function<void()> fn) { Task t = env_.CreateTask(std::move(fn)); PerThread* pt = GetPerThread(); if (pt->pool == this) { // Worker thread of this pool, push onto the thread's queue. Queue* q = queues_[pt->thread_id]; t = q->PushFront(std::move(t)); } else { // A free-standing thread (or worker of another pool), push onto a random // queue. Queue* q = queues_[Rand(&pt->rand) % queues_.size()]; t = q->PushBack(std::move(t)); } // Note: below we touch this after making w available to worker threads. // Strictly speaking, this can lead to a racy-use-after-free. Consider that // Schedule is called from a thread that is neither main thread nor a worker // thread of this pool. Then, execution of w directly or indirectly // completes overall computations, which in turn leads to destruction of // this. We expect that such scenario is prevented by program, that is, // this is kept alive while any threads can potentially be in Schedule. if (!t.f) ec_.Notify(false); else env_.ExecuteTask(t); // Push failed, execute directly. } int NumThreads() const final { return static_cast<int>(threads_.size()); } int CurrentThreadId() const final { const PerThread* pt = const_cast<NonBlockingThreadPoolTempl*>(this)->GetPerThread(); if (pt->pool == this) { return pt->thread_id; } else { return -1; } } private: typedef typename Environment::EnvThread Thread; struct PerThread { constexpr PerThread() : pool(NULL), rand(0), thread_id(-1) { } NonBlockingThreadPoolTempl* pool; // Parent pool, or null for normal threads. uint64_t rand; // Random generator state. int thread_id; // Worker thread index in pool. }; Environment env_; MaxSizeVector<Thread*> threads_; MaxSizeVector<Queue*> queues_; MaxSizeVector<unsigned> coprimes_; MaxSizeVector<EventCount::Waiter> waiters_; std::atomic<unsigned> blocked_; std::atomic<bool> spinning_; std::atomic<bool> done_; EventCount ec_; // Main worker thread loop. void WorkerLoop(int thread_id) { PerThread* pt = GetPerThread(); pt->pool = this; pt->rand = std::hash<std::thread::id>()(std::this_thread::get_id()); pt->thread_id = thread_id; Queue* q = queues_[thread_id]; EventCount::Waiter* waiter = &waiters_[thread_id]; for (;;) { Task t = q->PopFront(); if (!t.f) { t = Steal(); if (!t.f) { // Leave one thread spinning. This reduces latency. // TODO(dvyukov): 1000 iterations is based on fair dice roll, tune it. // Also, the time it takes to attempt to steal work 1000 times depends // on the size of the thread pool. However the speed at which the user // of the thread pool submit tasks is independent of the size of the // pool. Consider a time based limit instead. if (!spinning_ && !spinning_.exchange(true)) { for (int i = 0; i < 1000 && !t.f; i++) { t = Steal(); } spinning_ = false; } if (!t.f) { if (!WaitForWork(waiter, &t)) { return; } } } } if (t.f) { env_.ExecuteTask(t); } } } // Steal tries to steal work from other worker threads in best-effort manner. Task Steal() { PerThread* pt = GetPerThread(); const size_t size = queues_.size(); unsigned r = Rand(&pt->rand); unsigned inc = coprimes_[r % coprimes_.size()]; unsigned victim = r % size; for (unsigned i = 0; i < size; i++) { Task t = queues_[victim]->PopBack(); if (t.f) { return t; } victim += inc; if (victim >= size) { victim -= size; } } return Task(); } // WaitForWork blocks until new work is available (returns true), or if it is // time to exit (returns false). Can optionally return a task to execute in t // (in such case t.f != nullptr on return). bool WaitForWork(EventCount::Waiter* waiter, Task* t) { eigen_assert(!t->f); // We already did best-effort emptiness check in Steal, so prepare for // blocking. ec_.Prewait(waiter); // Now do a reliable emptiness check. int victim = NonEmptyQueueIndex(); if (victim != -1) { ec_.CancelWait(waiter); *t = queues_[victim]->PopBack(); return true; } // Number of blocked threads is used as termination condition. // If we are shutting down and all worker threads blocked without work, // that's we are done. blocked_++; if (done_ && blocked_ == threads_.size()) { ec_.CancelWait(waiter); // Almost done, but need to re-check queues. // Consider that all queues are empty and all worker threads are preempted // right after incrementing blocked_ above. Now a free-standing thread // submits work and calls destructor (which sets done_). If we don't // re-check queues, we will exit leaving the work unexecuted. if (NonEmptyQueueIndex() != -1) { // Note: we must not pop from queues before we decrement blocked_, // otherwise the following scenario is possible. Consider that instead // of checking for emptiness we popped the only element from queues. // Now other worker threads can start exiting, which is bad if the // work item submits other work. So we just check emptiness here, // which ensures that all worker threads exit at the same time. blocked_--; return true; } // Reached stable termination state. ec_.Notify(true); return false; } ec_.CommitWait(waiter); blocked_--; return true; } int NonEmptyQueueIndex() { PerThread* pt = GetPerThread(); const size_t size = queues_.size(); unsigned r = Rand(&pt->rand); unsigned inc = coprimes_[r % coprimes_.size()]; unsigned victim = r % size; for (unsigned i = 0; i < size; i++) { if (!queues_[victim]->Empty()) { return victim; } victim += inc; if (victim >= size) { victim -= size; } } return -1; } static EIGEN_STRONG_INLINE PerThread* GetPerThread() { EIGEN_THREAD_LOCAL PerThread per_thread_; PerThread* pt = &per_thread_; return pt; } static EIGEN_STRONG_INLINE unsigned Rand(uint64_t* state) { uint64_t current = *state; // Update the internal state *state = current * 6364136223846793005ULL + 0xda3e39cb94b95bdbULL; // Generate the random output (using the PCG-XSH-RS scheme) return static_cast<unsigned>((current ^ (current >> 22)) >> (22 + (current >> 61))); } }; typedef NonBlockingThreadPoolTempl<StlThreadEnvironment> NonBlockingThreadPool; } // namespace Eigen #endif // EIGEN_CXX11_THREADPOOL_NONBLOCKING_THREAD_POOL_H
{ "pile_set_name": "Github" }
<resources>> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <item name="android:windowDrawsSystemBarBackgrounds">true</item> <item name="android:statusBarColor">@android:color/transparent</item> </style> </resources>
{ "pile_set_name": "Github" }
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #import "ios/web/web_state/ui/crw_touch_tracking_recognizer.h" @interface CRWTouchTrackingRecognizer () <UIGestureRecognizerDelegate> { id<CRWTouchTrackingDelegate> _delegate; // weak } @end @implementation CRWTouchTrackingRecognizer @synthesize touchTrackingDelegate = _delegate; - (id)initWithDelegate:(id<CRWTouchTrackingDelegate>)delegate { if ((self = [super init])) { _delegate = delegate; self.delegate = self; } return self; } #pragma mark - #pragma mark UIGestureRecognizer Methods - (void)reset { [super reset]; } - (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { [super touchesBegan:touches withEvent:event]; [_delegate touched:YES]; } - (void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { [super touchesMoved:touches withEvent:event]; } - (void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event { [super touchesEnded:touches withEvent:event]; self.state = UIGestureRecognizerStateFailed; [_delegate touched:NO]; } - (void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event { [super touchesCancelled:touches withEvent:event]; [_delegate touched:NO]; } #pragma mark - #pragma mark UIGestureRecognizerDelegate Method - (BOOL)gestureRecognizer:(UIGestureRecognizer*)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer: (UIGestureRecognizer*)otherGestureRecognizer { return YES; } @end
{ "pile_set_name": "Github" }
A : "a" B ; : "b" A ; B : "a" B ; : "b" "a" "a" ;
{ "pile_set_name": "Github" }
#ifndef MICROSOFT_PE_H_ #define MICROSOFT_PE_H_ // This is a generated file! Please edit source .ksy file and use // kaitai-struct-compiler to rebuild #include <kaitai/kaitaistream.h> #include <kaitai/kaitaistruct.h> #include <cstdint> #include <vector> namespace veles { namespace kaitai { namespace microsoft_pe { class microsoft_pe_t : public kaitai::kstruct { public: class optional_header_windows_t; class optional_header_data_dirs_t; class data_dir_t; class optional_header_t; class section_t; class mz_placeholder_t; class optional_header_std_t; class coff_header_t; explicit microsoft_pe_t(kaitai::kstream* p_io, kaitai::kstruct* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~microsoft_pe_t(); class optional_header_windows_t : public kaitai::kstruct { public: enum subsystem_t { SUBSYSTEM_UNKNOWN = 0, SUBSYSTEM_NATIVE = 1, SUBSYSTEM_WINDOWS_GUI = 2, SUBSYSTEM_WINDOWS_CUI = 3, SUBSYSTEM_POSIX_CUI = 7, SUBSYSTEM_WINDOWS_CE_GUI = 9, SUBSYSTEM_EFI_APPLICATION = 10, SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, SUBSYSTEM_EFI_ROM = 13, SUBSYSTEM_XBOX = 14 }; explicit optional_header_windows_t( kaitai::kstream* p_io, microsoft_pe_t::optional_header_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~optional_header_windows_t(); private: uint32_t m_image_base; bool n_image_base; public: bool _is_null_image_base() { image_base(); return n_image_base; }; private: uint64_t m_image_base2; bool n_image_base2; public: bool _is_null_image_base2() { image_base2(); return n_image_base2; }; private: uint32_t m_section_alignment; uint32_t m_file_alignment; uint16_t m_major_operating_system_version; uint16_t m_minor_operating_system_version; uint16_t m_major_image_version; uint16_t m_minor_image_version; uint16_t m_major_subsystem_version; uint16_t m_minor_subsystem_version; uint32_t m_win32_version_value; uint32_t m_size_of_image; uint32_t m_size_of_headers; uint32_t m_check_sum; subsystem_t m_subsystem; uint16_t m_dll_characteristics; uint32_t m_size_of_stack_reserve; bool n_size_of_stack_reserve; public: bool _is_null_size_of_stack_reserve() { size_of_stack_reserve(); return n_size_of_stack_reserve; }; private: uint64_t m_size_of_stack_reserve2; bool n_size_of_stack_reserve2; public: bool _is_null_size_of_stack_reserve2() { size_of_stack_reserve2(); return n_size_of_stack_reserve2; }; private: uint32_t m_size_of_stack_commit; bool n_size_of_stack_commit; public: bool _is_null_size_of_stack_commit() { size_of_stack_commit(); return n_size_of_stack_commit; }; private: uint64_t m_size_of_stack_commit2; bool n_size_of_stack_commit2; public: bool _is_null_size_of_stack_commit2() { size_of_stack_commit2(); return n_size_of_stack_commit2; }; private: uint32_t m_size_of_heap_reserve; bool n_size_of_heap_reserve; public: bool _is_null_size_of_heap_reserve() { size_of_heap_reserve(); return n_size_of_heap_reserve; }; private: uint64_t m_size_of_heap_reserve2; bool n_size_of_heap_reserve2; public: bool _is_null_size_of_heap_reserve2() { size_of_heap_reserve2(); return n_size_of_heap_reserve2; }; private: uint32_t m_size_of_heap_commit; bool n_size_of_heap_commit; public: bool _is_null_size_of_heap_commit() { size_of_heap_commit(); return n_size_of_heap_commit; }; private: uint64_t m_size_of_heap_commit2; bool n_size_of_heap_commit2; public: bool _is_null_size_of_heap_commit2() { size_of_heap_commit2(); return n_size_of_heap_commit2; }; private: uint32_t m_loader_flags; uint32_t m_number_of_rva_and_sizes; microsoft_pe_t* m__root; microsoft_pe_t::optional_header_t* m__parent; public: uint32_t image_base() const { return m_image_base; } uint64_t image_base2() const { return m_image_base2; } uint32_t section_alignment() const { return m_section_alignment; } uint32_t file_alignment() const { return m_file_alignment; } uint16_t major_operating_system_version() const { return m_major_operating_system_version; } uint16_t minor_operating_system_version() const { return m_minor_operating_system_version; } uint16_t major_image_version() const { return m_major_image_version; } uint16_t minor_image_version() const { return m_minor_image_version; } uint16_t major_subsystem_version() const { return m_major_subsystem_version; } uint16_t minor_subsystem_version() const { return m_minor_subsystem_version; } uint32_t win32_version_value() const { return m_win32_version_value; } uint32_t size_of_image() const { return m_size_of_image; } uint32_t size_of_headers() const { return m_size_of_headers; } uint32_t check_sum() const { return m_check_sum; } subsystem_t subsystem() const { return m_subsystem; } uint16_t dll_characteristics() const { return m_dll_characteristics; } uint32_t size_of_stack_reserve() const { return m_size_of_stack_reserve; } uint64_t size_of_stack_reserve2() const { return m_size_of_stack_reserve2; } uint32_t size_of_stack_commit() const { return m_size_of_stack_commit; } uint64_t size_of_stack_commit2() const { return m_size_of_stack_commit2; } uint32_t size_of_heap_reserve() const { return m_size_of_heap_reserve; } uint64_t size_of_heap_reserve2() const { return m_size_of_heap_reserve2; } uint32_t size_of_heap_commit() const { return m_size_of_heap_commit; } uint64_t size_of_heap_commit2() const { return m_size_of_heap_commit2; } uint32_t loader_flags() const { return m_loader_flags; } uint32_t number_of_rva_and_sizes() const { return m_number_of_rva_and_sizes; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t::optional_header_t* _parent() const { return m__parent; } }; class optional_header_data_dirs_t : public kaitai::kstruct { public: explicit optional_header_data_dirs_t( kaitai::kstream* p_io, microsoft_pe_t::optional_header_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~optional_header_data_dirs_t(); private: data_dir_t* m_export_table; data_dir_t* m_import_table; data_dir_t* m_resource_table; data_dir_t* m_exception_table; data_dir_t* m_certificate_table; data_dir_t* m_base_relocation_table; data_dir_t* m_debug; data_dir_t* m_architecture; data_dir_t* m_global_ptr; data_dir_t* m_tls_table; data_dir_t* m_load_config_table; data_dir_t* m_bound_import; data_dir_t* m_iat; data_dir_t* m_delay_import_descriptor; data_dir_t* m_clr_runtime_header; microsoft_pe_t* m__root; microsoft_pe_t::optional_header_t* m__parent; public: data_dir_t* export_table() const { return m_export_table; } data_dir_t* import_table() const { return m_import_table; } data_dir_t* resource_table() const { return m_resource_table; } data_dir_t* exception_table() const { return m_exception_table; } data_dir_t* certificate_table() const { return m_certificate_table; } data_dir_t* base_relocation_table() const { return m_base_relocation_table; } data_dir_t* debug() const { return m_debug; } data_dir_t* architecture() const { return m_architecture; } data_dir_t* global_ptr() const { return m_global_ptr; } data_dir_t* tls_table() const { return m_tls_table; } data_dir_t* load_config_table() const { return m_load_config_table; } data_dir_t* bound_import() const { return m_bound_import; } data_dir_t* iat() const { return m_iat; } data_dir_t* delay_import_descriptor() const { return m_delay_import_descriptor; } data_dir_t* clr_runtime_header() const { return m_clr_runtime_header; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t::optional_header_t* _parent() const { return m__parent; } }; class data_dir_t : public kaitai::kstruct { public: explicit data_dir_t( kaitai::kstream* p_io, microsoft_pe_t::optional_header_data_dirs_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~data_dir_t(); private: uint32_t m_virtual_address; uint32_t m_size; microsoft_pe_t* m__root; microsoft_pe_t::optional_header_data_dirs_t* m__parent; public: uint32_t virtual_address() const { return m_virtual_address; } uint32_t size() const { return m_size; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t::optional_header_data_dirs_t* _parent() const { return m__parent; } }; class optional_header_t : public kaitai::kstruct { public: explicit optional_header_t(kaitai::kstream* p_io, microsoft_pe_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~optional_header_t(); private: optional_header_std_t* m_std; optional_header_windows_t* m_windows; optional_header_data_dirs_t* m_data_dirs; microsoft_pe_t* m__root; microsoft_pe_t* m__parent; public: optional_header_std_t* std() const { return m_std; } optional_header_windows_t* windows() const { return m_windows; } optional_header_data_dirs_t* data_dirs() const { return m_data_dirs; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t* _parent() const { return m__parent; } }; class section_t : public kaitai::kstruct { public: explicit section_t(kaitai::kstream* p_io, microsoft_pe_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~section_t(); private: bool f_body; std::vector<uint8_t> m_body; public: std::vector<uint8_t> body(); private: std::string m_name; uint32_t m_virtual_size; uint32_t m_virtual_address; uint32_t m_size_of_raw_data; uint32_t m_pointer_to_raw_data; uint32_t m_pointer_to_relocations; uint32_t m_pointer_to_linenumbers; uint16_t m_number_of_relocations; uint16_t m_number_of_linenumbers; uint32_t m_characteristics; microsoft_pe_t* m__root; microsoft_pe_t* m__parent; public: std::string name() const { return m_name; } uint32_t virtual_size() const { return m_virtual_size; } uint32_t virtual_address() const { return m_virtual_address; } uint32_t size_of_raw_data() const { return m_size_of_raw_data; } uint32_t pointer_to_raw_data() const { return m_pointer_to_raw_data; } uint32_t pointer_to_relocations() const { return m_pointer_to_relocations; } uint32_t pointer_to_linenumbers() const { return m_pointer_to_linenumbers; } uint16_t number_of_relocations() const { return m_number_of_relocations; } uint16_t number_of_linenumbers() const { return m_number_of_linenumbers; } uint32_t characteristics() const { return m_characteristics; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t* _parent() const { return m__parent; } }; class mz_placeholder_t : public kaitai::kstruct { public: explicit mz_placeholder_t(kaitai::kstream* p_io, microsoft_pe_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~mz_placeholder_t(); private: std::vector<uint8_t> m_magic; std::vector<uint8_t> m_data1; uint32_t m_header_size; microsoft_pe_t* m__root; microsoft_pe_t* m__parent; public: std::vector<uint8_t> magic() const { return m_magic; } std::vector<uint8_t> data1() const { return m_data1; } uint32_t header_size() const { return m_header_size; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t* _parent() const { return m__parent; } }; class optional_header_std_t : public kaitai::kstruct { public: enum pe_formatx_t { PE_FORMATX_ROM_IMAGE = 263, PE_FORMATX_PE32 = 267, PE_FORMATX_PE32_PLUS = 523 }; explicit optional_header_std_t( kaitai::kstream* p_io, microsoft_pe_t::optional_header_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~optional_header_std_t(); private: uint16_t m_format; uint8_t m_major_linker_version; uint8_t m_minor_linker_version; uint32_t m_size_of_code; uint32_t m_size_of_initialized_data; uint32_t m_size_of_uninitialized_data; uint32_t m_address_of_entry_point; uint32_t m_base_of_code; uint32_t m_base_of_data; bool n_base_of_data; public: bool _is_null_base_of_data() { base_of_data(); return n_base_of_data; }; private: microsoft_pe_t* m__root; microsoft_pe_t::optional_header_t* m__parent; public: uint16_t format() const { return m_format; } uint8_t major_linker_version() const { return m_major_linker_version; } uint8_t minor_linker_version() const { return m_minor_linker_version; } uint32_t size_of_code() const { return m_size_of_code; } uint32_t size_of_initialized_data() const { return m_size_of_initialized_data; } uint32_t size_of_uninitialized_data() const { return m_size_of_uninitialized_data; } uint32_t address_of_entry_point() const { return m_address_of_entry_point; } uint32_t base_of_code() const { return m_base_of_code; } uint32_t base_of_data() const { return m_base_of_data; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t::optional_header_t* _parent() const { return m__parent; } }; class coff_header_t : public kaitai::kstruct { public: enum machine_type_t { MACHINE_TYPE_UNKNOWN = 0, MACHINE_TYPE_I386 = 332, MACHINE_TYPE_R4000 = 358, MACHINE_TYPE_WCEMIPSV2 = 361, MACHINE_TYPE_SH3 = 418, MACHINE_TYPE_SH3DSP = 419, MACHINE_TYPE_SH4 = 422, MACHINE_TYPE_SH5 = 424, MACHINE_TYPE_ARM = 448, MACHINE_TYPE_THUMB = 450, MACHINE_TYPE_ARMNT = 452, MACHINE_TYPE_AM33 = 467, MACHINE_TYPE_POWERPC = 496, MACHINE_TYPE_POWERPCFP = 497, MACHINE_TYPE_IA64 = 512, MACHINE_TYPE_MIPS16 = 614, MACHINE_TYPE_MIPSFPU = 870, MACHINE_TYPE_MIPSFPU16 = 1126, MACHINE_TYPE_EBC = 3772, MACHINE_TYPE_RISCV32 = 20530, MACHINE_TYPE_RISCV64 = 20580, MACHINE_TYPE_RISCV128 = 20776, MACHINE_TYPE_AMD64 = 34404, MACHINE_TYPE_M32R = 36929 }; explicit coff_header_t(kaitai::kstream* p_io, microsoft_pe_t* p_parent = nullptr, microsoft_pe_t* p_root = nullptr); veles::dbif::ObjectHandle veles_obj; ~coff_header_t(); private: machine_type_t m_machine; uint16_t m_number_of_sections; uint32_t m_time_date_stamp; uint32_t m_pointer_to_symbol_table; uint32_t m_number_of_symbols; uint16_t m_size_of_optional_header; uint16_t m_characteristics; microsoft_pe_t* m__root; microsoft_pe_t* m__parent; public: machine_type_t machine() const { return m_machine; } uint16_t number_of_sections() const { return m_number_of_sections; } uint32_t time_date_stamp() const { return m_time_date_stamp; } uint32_t pointer_to_symbol_table() const { return m_pointer_to_symbol_table; } uint32_t number_of_symbols() const { return m_number_of_symbols; } uint16_t size_of_optional_header() const { return m_size_of_optional_header; } uint16_t characteristics() const { return m_characteristics; } microsoft_pe_t* _root() const { return m__root; } microsoft_pe_t* _parent() const { return m__parent; } }; private: mz_placeholder_t* m_mz1; std::vector<uint8_t> m_mz2; std::vector<uint8_t> m_pe_signature; coff_header_t* m_coff_header; optional_header_t* m_optional_header; std::vector<section_t*>* m_sections; microsoft_pe_t* m__root; kaitai::kstruct* m__parent; std::vector<uint8_t> m__skip_me_optional_header; kaitai::kstream* m__io__skip_me_optional_header; public: mz_placeholder_t* mz1() const { return m_mz1; } std::vector<uint8_t> mz2() const { return m_mz2; } std::vector<uint8_t> pe_signature() const { return m_pe_signature; } coff_header_t* coff_header() const { return m_coff_header; } optional_header_t* optional_header() const { return m_optional_header; } std::vector<section_t*>* sections() const { return m_sections; } microsoft_pe_t* _root() const { return m__root; } kaitai::kstruct* _parent() const { return m__parent; } std::vector<uint8_t> _skip_me_optional_header() const { return m__skip_me_optional_header; } kaitai::kstream* _io__skip_me_optional_header() const { return m__io__skip_me_optional_header; } }; } // namespace microsoft_pe } // namespace kaitai } // namespace veles #endif // MICROSOFT_PE_H_
{ "pile_set_name": "Github" }
/* main.c - Application main entry point */ /* * Copyright (c) 2019 Nordic Semiconductor ASA * * SPDX-License-Identifier: LicenseRef-BSD-5-Clause-Nordic */ #include <zephyr/types.h> #include <stddef.h> #include <stdbool.h> #include <string.h> #include <zephyr.h> #include <sys/printk.h> #include <sys/byteorder.h> #include <st25r3911b_nfca.h> #include <nfc/t4t/ndef_file.h> #include <nfc/ndef/msg_parser.h> #include <nfc/ndef/text_rec.h> #include <nfc/t4t/isodep.h> #include <nfc/t4t/hl_procedure.h> #include <nfc/tnep/poller.h> #define NFC_TNEP_MAX_RECORD 2 #define NFC_TNEP_DATA_SIZE 256 #define NFC_TNEP_SVC_NAME_MAX_LEN 30 #define MAX_TLV_BLOCKS 10 #define MAX_NDEF_RECORDS 10 #define NFC_T4T_ISODEP_FSD 256 #define NFC_T4T_ISODEP_RX_DATA_MAX_SIZE 1024 #define NFC_T4T_APDU_MAX_SIZE 1024 #define NFC_TX_DATA_LEN NFC_T4T_ISODEP_FSD #define NFC_RX_DATA_LEN NFC_T4T_ISODEP_FSD #define TRANSMIT_DELAY 3000 #define ALL_REQ_DELAY 2000 static uint8_t tx_data[NFC_TX_DATA_LEN]; static uint8_t rx_data[NFC_RX_DATA_LEN]; static struct k_poll_event events[ST25R3911B_NFCA_EVENT_CNT]; static struct k_delayed_work transmit_work; NFC_NDEF_MSG_DEF(poller_msg, NFC_TNEP_MAX_RECORD); NFC_T4T_CC_DESC_DEF(t4t_cc, MAX_TLV_BLOCKS); static uint8_t tnep_tx_data[NFC_TNEP_DATA_SIZE]; static uint8_t tnep_rx_data[NFC_TNEP_DATA_SIZE]; static const struct nfc_tnep_buf tnep_tx_buf = { .data = tnep_tx_data, .size = sizeof(tnep_tx_data) }; static struct nfc_tnep_buf tnep_rx_buf = { .data = tnep_rx_data, .size = sizeof(tnep_rx_data) }; static struct st25r3911b_nfca_buf tx_buf = { .data = tx_data, .len = sizeof(tx_data) }; static const struct st25r3911b_nfca_buf rx_buf = { .data = rx_data, .len = sizeof(rx_data) }; struct t4t_tag { uint8_t data[NFC_T4T_ISODEP_RX_DATA_MAX_SIZE]; uint8_t ndef[MAX_TLV_BLOCKS][NFC_T4T_APDU_MAX_SIZE]; uint8_t tlv_index; }; static enum nfc_tnep_tag_type tag_type; static struct t4t_tag t4t; static struct nfc_ndef_tnep_rec_svc_param services[2]; static uint32_t tnep_msg_max_size; static bool tnep_mode; /* Text message in English with its language code. */ static const uint8_t en_payload[] = { 'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!' }; static const uint8_t en_code[] = {'e', 'n'}; /* Text message in Polish with its language code. */ static const uint8_t pl_payload[] = { 'W', 'i', 't', 'a', 'j', ' ', 0xc5, 0x9a, 'w', 'i', 'e', 'c', 'i', 'e', '!' }; static const uint8_t pl_code[] = {'P', 'L'}; static void nfc_tag_detect(bool all_request) { int err; enum st25r3911b_nfca_detect_cmd cmd; tag_type = NFC_TNEP_TAG_TYPE_UNSUPPORTED; tnep_mode = false; cmd = all_request ? ST25R3911B_NFCA_DETECT_CMD_ALL_REQ : ST25R3911B_NFCA_DETECT_CMD_SENS_REQ; err = st25r3911b_nfca_tag_detect(cmd); if (err) { printk("Tag detect error: %d.\n", err); } } static bool tnep_data_search(const uint8_t *ndef_msg_buff, size_t nfc_data_len) { int err; uint8_t desc_buf[NFC_NDEF_PARSER_REQIRED_MEMO_SIZE_CALC(MAX_NDEF_RECORDS)]; size_t desc_buf_len = sizeof(desc_buf); uint8_t cnt = ARRAY_SIZE(services); err = nfc_ndef_msg_parse(desc_buf, &desc_buf_len, ndef_msg_buff, &nfc_data_len); if (err) { printk("Error during parsing a NDEF message, err: %d.\n", err); return false; } err = nfc_tnep_poller_svc_search((struct nfc_ndef_msg_desc *) desc_buf, services, &cnt); if (err) { printk("Service search err: %d\n", err); return false; } printk("TNEP Service count: %u\n", cnt); if (cnt > 0) { tnep_mode = true; return true; } return false; } static void transfer_handler(struct k_work *work) { nfc_tag_detect(false); } static int tnep_ndef_read(uint8_t *ndef_buff, uint16_t ndef_len) { return nfc_t4t_hl_procedure_ndef_read(&NFC_T4T_CC_DESC(t4t_cc), ndef_buff, ndef_len); } static int tnep_ndef_update(const uint8_t *ndef_buff, uint16_t ndef_len) { return nfc_t4t_hl_procedure_ndef_update(&NFC_T4T_CC_DESC(t4t_cc), (uint8_t *)ndef_buff, ndef_len); } static struct nfc_tnep_poller_ndef_api tnep_ndef_api = { .ndef_read = tnep_ndef_read, .ndef_update = tnep_ndef_update }; static void nfc_field_on(void) { printk("NFC field on.\n"); nfc_tag_detect(false); } static void nfc_timeout(bool tag_sleep) { if (tag_sleep) { printk("Tag sleep or no detected, sending ALL Request.\n"); } else if (tag_type == NFC_TNEP_TAG_TYPE_T4T) { nfc_t4t_isodep_on_timeout(); return; } /* Sleep will block processing loop. Accepted as it is short. */ k_sleep(K_MSEC(ALL_REQ_DELAY)); nfc_tag_detect(true); } static void nfc_field_off(void) { printk("NFC field off.\n"); } static void tag_detected(const struct st25r3911b_nfca_sens_resp *sens_resp) { int err; printk("Anticollision: 0x%x Platform: 0x%x.\n", sens_resp->anticollison, sens_resp->platform_info); err = st25r3911b_nfca_anticollision_start(); if (err) { printk("Anticollision error: %d.\n", err); } } static void anticollision_completed(const struct st25r3911b_nfca_tag_info *tag_info, int err) { if (err) { printk("Error during anticollision avoidance.\n"); nfc_tag_detect(false); return; } printk("Tag info, type: %d.\n", tag_info->type); if (tag_info->type == ST25R3911B_NFCA_TAG_TYPE_T4T) { printk("Type 4 Tag.\n"); tag_type = NFC_TNEP_TAG_TYPE_T4T; err = nfc_tnep_poller_api_set(&tnep_ndef_api, NFC_TNEP_TAG_TYPE_T4T); if (err) { printk("TNEP API set error: %d\n", err); return; } /* Send RATS command */ err = nfc_t4t_isodep_rats_send(NFC_T4T_ISODEP_FSD_256, 0); if (err) { printk("Type 4 Tag RATS sending error %d.\n", err); } } else { printk("Unsupported tag type.\n"); tag_type = NFC_TNEP_TAG_TYPE_UNSUPPORTED; nfc_tag_detect(false); return; } } static void transfer_completed(const uint8_t *data, size_t len, int err) { if (err) { printk("NFC Transfer error: %d.\n", err); return; } err = nfc_t4t_isodep_data_received(data, len, err); if (err) { printk("NFC-A T4T read error: %d.\n", err); } } static void tag_sleep(void) { printk("Tag entered the Sleep state.\n"); } static const struct st25r3911b_nfca_cb cb = { .field_on = nfc_field_on, .field_off = nfc_field_off, .tag_detected = tag_detected, .anticollision_completed = anticollision_completed, .rx_timeout = nfc_timeout, .transfer_completed = transfer_completed, .tag_sleep = tag_sleep }; static void t4t_isodep_selected(const struct nfc_t4t_isodep_tag *t4t_tag) { int err; printk("NFC T4T selected.\n"); if ((t4t_tag->lp_divisor != 0) && (t4t_tag->lp_divisor != t4t_tag->pl_divisor)) { printk("Unsupported bitrate divisor by Reader/Writer.\n"); } err = nfc_t4t_hl_procedure_ndef_tag_app_select(); if (err) { printk("NFC T4T app select err %d.\n", err); return; } } static void t4t_isodep_error(int err) { printk("ISO-DEP Protocol error %d.\n", err); nfc_tag_detect(false); } static void t4t_isodep_data_send(uint8_t *data, size_t data_len, uint32_t ftd) { int err; tx_buf.data = data; tx_buf.len = data_len; err = st25r3911b_nfca_transfer_with_crc(&tx_buf, &rx_buf, ftd); if (err) { printk("NFC T4T ISO-DEP transfer error: %d.\n", err); } } static void t4t_isodep_received(const uint8_t *data, size_t data_len) { int err; err = nfc_t4t_hl_procedure_on_data_received(data, data_len); if (err) { printk("NFC Type 4 Tag HL data received error: %d.\n", err); } } static void t4t_isodep_deselected(void) { st25r3911b_nfca_tag_sleep(); k_delayed_work_submit(&transmit_work, K_MSEC(TRANSMIT_DELAY)); } static const struct nfc_t4t_isodep_cb t4t_isodep_cb = { .selected = t4t_isodep_selected, .deselected = t4t_isodep_deselected, .error = t4t_isodep_error, .ready_to_send = t4t_isodep_data_send, .data_received = t4t_isodep_received }; static void t4t_hl_selected(enum nfc_t4t_hl_procedure_select type) { int err = 0; switch (type) { case NFC_T4T_HL_PROCEDURE_NDEF_APP_SELECT: printk("NFC T4T NDEF Application selected.\n"); err = nfc_t4t_hl_procedure_cc_select(); if (err) { printk("NFC T4T Capability Container select error: %d.\n", err); } break; case NFC_T4T_HL_PROCEDURE_CC_SELECT: printk("NFC T4T Capability Container file selected.\n"); err = nfc_t4t_hl_procedure_cc_read(&NFC_T4T_CC_DESC(t4t_cc)); if (err) { printk("Capability Container read error: %d.\n", err); } break; case NFC_T4T_HL_PROCEDURE_NDEF_FILE_SELECT: if (tnep_mode) { printk("NFC T4T NDEF file contains the TNEP Initial Message selected.\n"); /* Select first service. */ err = nfc_tnep_poller_svc_select(&tnep_rx_buf, services, tnep_msg_max_size); if (err) { printk("Service select err: %d\n", err); } return; } printk("NFC T4T NDEF file selected.\n"); err = nfc_t4t_hl_procedure_ndef_read(&NFC_T4T_CC_DESC(t4t_cc), t4t.ndef[t4t.tlv_index], NFC_T4T_APDU_MAX_SIZE); if (err) { printk("NFC T4T NDEF file read error %d.\n", err); } break; default: break; } if (err) { st25r3911b_nfca_tag_sleep(); k_delayed_work_submit(&transmit_work, K_MSEC(TRANSMIT_DELAY)); } } static void t4t_hl_cc_read(struct nfc_t4t_cc_file *cc) { int err; struct nfc_t4t_tlv_block *tlv_block; printk("NFC T4T Capability Container file read.\n"); for (size_t i = 0; i < cc->tlv_count; i++) { tlv_block = &cc->tlv_block_array[i]; if ((tlv_block->type == NFC_T4T_TLV_BLOCK_TYPE_NDEF_FILE_CONTROL_TLV) && (tlv_block->value.read_access == NFC_T4T_TLV_BLOCK_CONTROL_FILE_READ_ACCESS_GRANTED)) { err = nfc_t4t_hl_procedure_ndef_file_select(tlv_block->value.file_id); if (err) { printk("NFC T4T NDEF file select error: %d.\n", err); } return; } } printk("No NDEF File TLV in Capability Container."); } static void t4t_hl_ndef_read(uint16_t file_id, const uint8_t *data, size_t len) { int err; struct nfc_t4t_cc_file *cc; struct nfc_t4t_tlv_block *tlv_block; printk("NDEF file read, id: 0x%x.\n", file_id); if (tnep_mode) { err = nfc_tnep_poller_on_ndef_read(nfc_t4t_ndef_file_msg_get(data), nfc_t4t_ndef_file_msg_size_get(len)); if (err) { printk("TNEP Read data error: %d\n", err); } return; } t4t.tlv_index++; cc = &NFC_T4T_CC_DESC(t4t_cc); for (size_t i = t4t.tlv_index; i < cc->tlv_count; i++) { tlv_block = &cc->tlv_block_array[i]; if ((tlv_block->type == NFC_T4T_TLV_BLOCK_TYPE_NDEF_FILE_CONTROL_TLV) && (tlv_block->value.read_access == NFC_T4T_TLV_BLOCK_CONTROL_FILE_READ_ACCESS_GRANTED)) { err = nfc_t4t_hl_procedure_ndef_file_select(tlv_block->value.file_id); if (err) { printk("NFC T4T NDEF file select error: %d.\n", err); } return; } t4t.tlv_index++; } t4t.tlv_index = 0; nfc_t4t_cc_file_printout(cc); tlv_block = cc->tlv_block_array; for (size_t i = 0; i < cc->tlv_count; i++) { if ((tlv_block[i].type == NFC_T4T_TLV_BLOCK_TYPE_NDEF_FILE_CONTROL_TLV) || (tlv_block[i].value.file.content != NULL)) { /* Look for first message contains TNEP Service * Parameter Records. */ if (tnep_data_search(nfc_t4t_ndef_file_msg_get(tlv_block[i].value.file.content), nfc_t4t_ndef_file_msg_size_get(tlv_block[i].value.file.len))) { tnep_msg_max_size = tlv_block[i].value.max_file_size; /* In case when NFC Tag device contains more * than one NDEF Message, select the * NDEF file which contains it. */ err = nfc_t4t_hl_procedure_ndef_file_select(tlv_block->value.file_id); if (err) { printk("TNEP Initial NDEF Message select error: %d.\n", err); } return; } } } err = nfc_t4t_isodep_tag_deselect(); if (err) { printk("NFC T4T Deselect error: %d.\n", err); } } static void t4t_hl_ndef_update(uint16_t file_id) { if (tnep_mode) { nfc_tnep_poller_on_ndef_write(); } } static const struct nfc_t4t_hl_procedure_cb t4t_hl_procedure_cb = { .selected = t4t_hl_selected, .cc_read = t4t_hl_cc_read, .ndef_read = t4t_hl_ndef_read, .ndef_updated = t4t_hl_ndef_update }; void tnep_svc_selected(const struct nfc_ndef_tnep_rec_svc_param *param, const struct nfc_tnep_poller_msg *msg, bool timeout) { int err; char name[NFC_TNEP_SVC_NAME_MAX_LEN]; NFC_NDEF_MSG_DEF(update_msg, NFC_TNEP_MAX_RECORD); NFC_NDEF_TEXT_RECORD_DESC_DEF(nfc_en_text_rec, UTF_8, en_code, sizeof(en_code) - 1, en_payload, sizeof(en_payload) - 1); NFC_NDEF_TEXT_RECORD_DESC_DEF(nfc_pl_text_rec, UTF_8, pl_code, sizeof(pl_code) - 1, pl_payload, sizeof(pl_payload) - 1); if (timeout) { err = nfc_tnep_poller_svc_deselect(); if (err) { printk("TNEP service deselect error: %d.\n", err); } return; } strncpy(name, param->uri, param->uri_length); printk("TNEP Service selected. Service URI: %s.\n", name); printk("Service status: %d.\n", msg->status); if (msg->status != 0) { printk("Service status indicates TNEP protocol or service error.\n"); return; } if (msg->msg->record_count == 1) { printk("Service data contains only status record. Communication is finished.\n"); printk("Deselecting service.\n"); err = nfc_tnep_poller_svc_deselect(); if (err) { printk("TNEP service deselect error: %d.\n", err); } return; } printk("Service message:\n"); nfc_ndef_msg_printout(msg->msg); /* Add text records to NDEF text message */ err = nfc_ndef_msg_record_add(&NFC_NDEF_MSG(update_msg), &NFC_NDEF_TEXT_RECORD_DESC(nfc_en_text_rec)); if (err) { printk("Cannot add first record to TNEP update message!\n"); return; } err = nfc_ndef_msg_record_add(&NFC_NDEF_MSG(update_msg), &NFC_NDEF_TEXT_RECORD_DESC(nfc_pl_text_rec)); if (err) { printk("Cannot add second record to TNEP update message!\n"); return; } /* Update Service data. */ err = nfc_tnep_poller_svc_write(&NFC_NDEF_MSG(update_msg), &tnep_rx_buf); if (err) { printk("Service Update error: %d.\n", err); } } void tnep_svc_deselected(void) { int err; printk("TNEP Service deselected.\n"); err = nfc_t4t_isodep_tag_deselect(); if (err) { printk("NFC T4T Deselect error: %d.\n", err); } } void tnep_svc_sent(const struct nfc_ndef_tnep_rec_svc_param *param, const struct nfc_tnep_poller_msg *rsp_msg, bool timeout) { int err; if (timeout) { err = nfc_tnep_poller_svc_deselect(); if (err) { printk("TNEP service deselect error: %d.\n", err); } return; } printk("TNEP service updated.\n"); if (rsp_msg->status != 0) { printk("TNEP protocol or service error.\n"); return; } if (rsp_msg->msg->record_count == 1) { printk("Service data contains only status record. Communication is finished. Deselecting service.\n"); } err = nfc_tnep_poller_svc_deselect(); if (err) { printk("TNEP service deselect error: %d.\n", err); } } void tnep_error(int err) { printk("TNEP error: %d.\n", err); } static struct nfc_tnep_poller_cb tnep_cb = { .svc_selected = tnep_svc_selected, .svc_deselected = tnep_svc_deselected, .svc_sent = tnep_svc_sent, .error = tnep_error }; void main(void) { int err; printk("NFC TNEP Poller sample started.\n"); nfc_t4t_hl_procedure_cb_register(&t4t_hl_procedure_cb); k_delayed_work_init(&transmit_work, transfer_handler); err = nfc_tnep_poller_init(&tnep_tx_buf, &tnep_cb); if (err) { printk("NFC TNEP Protocol initialization err: %d\n", err); return; } err = nfc_t4t_isodep_init(tx_data, sizeof(tx_data), t4t.data, sizeof(t4t.data), &t4t_isodep_cb); if (err) { printk("NFC T4T ISO-DEP Protocol initialization failed err: %d.\n", err); return; } err = st25r3911b_nfca_init(events, ARRAY_SIZE(events), &cb); if (err) { printk("NFCA initialization failed err: %d.\n", err); return; } err = st25r3911b_nfca_field_on(); if (err) { printk("Field on error %d.", err); return; } while (true) { k_poll(events, ARRAY_SIZE(events), K_FOREVER); err = st25r3911b_nfca_process(); if (err) { printk("NFC-A process failed, err: %d.\n", err); return; } } }
{ "pile_set_name": "Github" }
--- systemd: units: - name: docker.service enable: true dropins: - name: 40-docker-opts.conf contents: | [Service] Environment="DOCKER_OPTS=--insecure-registry hub.mirror.kubermesh:5000 --insecure-registry quay.mirror.kubermesh:5001 --insecure-registry gcr.mirror.kubermesh:5002" - name: installer.service enable: true contents: | [Unit] Requires=network-online.target After=network-online.target [Service] Type=oneshot ExecStart=/opt/installer # Signal error state ExecStopPost=-/usr/bin/docker run --rm --device /dev/bus/usb/ hub.mirror.kubermesh:5000/mikebryant/alpine-blink1 blink1-tool --playpattern '1,#aaaa00,0,2,#cc0000,0,1' ExecStopPost=/bin/systemctl --force reboot [Install] WantedBy=multi-user.target storage: files: - path: /opt/installer filesystem: root mode: 0500 contents: inline: | #!/bin/bash -ex # Signal initial state docker run --rm --device /dev/bus/usb/ hub.mirror.kubermesh:5000/mikebryant/alpine-blink1 blink1-tool --playpattern '1,#aaaa00,0,2,#aa7700,0,1' || true curl -f "{{.ignition_endpoint}}?{{.request.raw_query}}&os=installed&board_name=`cat /sys/devices/virtual/dmi/id/board_name`&sys_vendor=`cat /sys/devices/virtual/dmi/id/sys_vendor`" -o ignition.json curl -f "{{.kubeconfig}}" -o kubeconfig FIRST_DISK=`lsblk --output NAME -e 1,7 --nodeps --noheadings | sort | head -n 1` coreos-install -d /dev/${FIRST_DISK} -C {{.coreos_channel}} -V {{.coreos_version}} -i ignition.json {{if index . "baseurl"}}-b {{.baseurl}}{{end}} udevadm settle mount /dev/${FIRST_DISK}9 /mnt/ mkdir -p /mnt/etc/kubernetes/ cp kubeconfig /mnt/etc/kubernetes/kubeconfig docker run --rm --device /dev/bus/usb/ hub.mirror.kubermesh:5000/mikebryant/alpine-blink1 blink1-tool --playpattern '1,#aaaa00,0,2,#006666,0,1' || true /bin/systemctl reboot /bin/sleep 10 - path: /etc/hosts filesystem: root mode: 0644 contents: inline: | 127.0.0.1 localhost ::1 localhost fd65:7b9c:569:680:98eb:c508:eb8c:1b80 apiserver.kubermesh fd65:7b9c:569:680:98eb:c508:ea6b:b0b2 etcd.kubermesh fd65:7b9c:569:680:98e8:1762:7b6e:83f6 hub.mirror.kubermesh fd65:7b9c:569:680:98e8:1762:7b6e:61d3 gcr.mirror.kubermesh fd65:7b9c:569:680:98e8:1762:7abd:e0b7 quay.mirror.kubermesh {{ if index . "ssh_authorized_keys" }} passwd: users: - name: core password_hash: "{{ .password_hash }}" ssh_authorized_keys: {{ range $element := .ssh_authorized_keys }} - {{$element}} {{end}} {{end}}
{ "pile_set_name": "Github" }
/* Copyright 2015 The Kubernetes 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. */ package node import ( "reflect" "testing" "time" "k8s.io/kubernetes/pkg/util/flowcontrol" "k8s.io/kubernetes/pkg/util/sets" ) func CheckQueueEq(lhs []string, rhs TimedQueue) bool { for i := 0; i < len(lhs); i++ { if rhs[i].Value != lhs[i] { return false } } return true } func CheckSetEq(lhs, rhs sets.String) bool { return lhs.HasAll(rhs.List()...) && rhs.HasAll(lhs.List()...) } func TestAddNode(t *testing.T) { evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") queuePattern := []string{"first", "second", "third"} if len(evictor.queue.queue) != len(queuePattern) { t.Fatalf("Queue %v should have length %d", evictor.queue.queue, len(queuePattern)) } if !CheckQueueEq(queuePattern, evictor.queue.queue) { t.Errorf("Invalid queue. Got %v, expected %v", evictor.queue.queue, queuePattern) } setPattern := sets.NewString("first", "second", "third") if len(evictor.queue.set) != len(setPattern) { t.Fatalf("Map %v should have length %d", evictor.queue.set, len(setPattern)) } if !CheckSetEq(setPattern, evictor.queue.set) { t.Errorf("Invalid map. Got %v, expected %v", evictor.queue.set, setPattern) } } func TestDelNode(t *testing.T) { defer func() { now = time.Now }() var tick int64 now = func() time.Time { t := time.Unix(tick, 0) tick++ return t } evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") evictor.Remove("first") queuePattern := []string{"second", "third"} if len(evictor.queue.queue) != len(queuePattern) { t.Fatalf("Queue %v should have length %d", evictor.queue.queue, len(queuePattern)) } if !CheckQueueEq(queuePattern, evictor.queue.queue) { t.Errorf("Invalid queue. Got %v, expected %v", evictor.queue.queue, queuePattern) } setPattern := sets.NewString("second", "third") if len(evictor.queue.set) != len(setPattern) { t.Fatalf("Map %v should have length %d", evictor.queue.set, len(setPattern)) } if !CheckSetEq(setPattern, evictor.queue.set) { t.Errorf("Invalid map. Got %v, expected %v", evictor.queue.set, setPattern) } evictor = NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") evictor.Remove("second") queuePattern = []string{"first", "third"} if len(evictor.queue.queue) != len(queuePattern) { t.Fatalf("Queue %v should have length %d", evictor.queue.queue, len(queuePattern)) } if !CheckQueueEq(queuePattern, evictor.queue.queue) { t.Errorf("Invalid queue. Got %v, expected %v", evictor.queue.queue, queuePattern) } setPattern = sets.NewString("first", "third") if len(evictor.queue.set) != len(setPattern) { t.Fatalf("Map %v should have length %d", evictor.queue.set, len(setPattern)) } if !CheckSetEq(setPattern, evictor.queue.set) { t.Errorf("Invalid map. Got %v, expected %v", evictor.queue.set, setPattern) } evictor = NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") evictor.Remove("third") queuePattern = []string{"first", "second"} if len(evictor.queue.queue) != len(queuePattern) { t.Fatalf("Queue %v should have length %d", evictor.queue.queue, len(queuePattern)) } if !CheckQueueEq(queuePattern, evictor.queue.queue) { t.Errorf("Invalid queue. Got %v, expected %v", evictor.queue.queue, queuePattern) } setPattern = sets.NewString("first", "second") if len(evictor.queue.set) != len(setPattern) { t.Fatalf("Map %v should have length %d", evictor.queue.set, len(setPattern)) } if !CheckSetEq(setPattern, evictor.queue.set) { t.Errorf("Invalid map. Got %v, expected %v", evictor.queue.set, setPattern) } } func TestTry(t *testing.T) { evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") evictor.Remove("second") deletedMap := sets.NewString() evictor.Try(func(value TimedValue) (bool, time.Duration) { deletedMap.Insert(value.Value) return true, 0 }) setPattern := sets.NewString("first", "third") if len(deletedMap) != len(setPattern) { t.Fatalf("Map %v should have length %d", evictor.queue.set, len(setPattern)) } if !CheckSetEq(setPattern, deletedMap) { t.Errorf("Invalid map. Got %v, expected %v", deletedMap, setPattern) } } func TestTryOrdering(t *testing.T) { defer func() { now = time.Now }() current := time.Unix(0, 0) delay := 0 // the current time is incremented by 1ms every time now is invoked now = func() time.Time { if delay > 0 { delay-- } else { current = current.Add(time.Millisecond) } t.Logf("time %d", current.UnixNano()) return current } evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") order := []string{} count := 0 hasQueued := false evictor.Try(func(value TimedValue) (bool, time.Duration) { count++ t.Logf("eviction %d", count) if value.ProcessAt.IsZero() { t.Fatalf("processAt should not be zero") } switch value.Value { case "first": if !value.AddedAt.Equal(time.Unix(0, time.Millisecond.Nanoseconds())) { t.Fatalf("added time for %s is %d", value.Value, value.AddedAt) } case "second": if !value.AddedAt.Equal(time.Unix(0, 2*time.Millisecond.Nanoseconds())) { t.Fatalf("added time for %s is %d", value.Value, value.AddedAt) } if hasQueued { if !value.ProcessAt.Equal(time.Unix(0, 6*time.Millisecond.Nanoseconds())) { t.Fatalf("process time for %s is %d", value.Value, value.ProcessAt) } break } hasQueued = true delay = 1 t.Logf("going to delay") return false, 2 * time.Millisecond case "third": if !value.AddedAt.Equal(time.Unix(0, 3*time.Millisecond.Nanoseconds())) { t.Fatalf("added time for %s is %d", value.Value, value.AddedAt) } } order = append(order, value.Value) return true, 0 }) if !reflect.DeepEqual(order, []string{"first", "third"}) { t.Fatalf("order was wrong: %v", order) } if count != 3 { t.Fatalf("unexpected iterations: %d", count) } } func TestTryRemovingWhileTry(t *testing.T) { evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") processing := make(chan struct{}) wait := make(chan struct{}) order := []string{} count := 0 queued := false // while the Try function is processing "second", remove it from the queue // we should not see "second" retried. go func() { <-processing evictor.Remove("second") close(wait) }() evictor.Try(func(value TimedValue) (bool, time.Duration) { count++ if value.AddedAt.IsZero() { t.Fatalf("added should not be zero") } if value.ProcessAt.IsZero() { t.Fatalf("next should not be zero") } if !queued && value.Value == "second" { queued = true close(processing) <-wait return false, time.Millisecond } order = append(order, value.Value) return true, 0 }) if !reflect.DeepEqual(order, []string{"first", "third"}) { t.Fatalf("order was wrong: %v", order) } if count != 3 { t.Fatalf("unexpected iterations: %d", count) } } func TestClear(t *testing.T) { evictor := NewRateLimitedTimedQueue(flowcontrol.NewFakeAlwaysRateLimiter()) evictor.Add("first") evictor.Add("second") evictor.Add("third") evictor.Clear() if len(evictor.queue.queue) != 0 { t.Fatalf("Clear should remove all elements from the queue.") } }
{ "pile_set_name": "Github" }
/* * Marvell UMI head file * * Copyright 2011 Marvell. <[email protected]> * * This file is licensed under GPLv2. * * 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; version 2 of the * License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ #ifndef MVUMI_H #define MVUMI_H #define MAX_BASE_ADDRESS 6 #define VER_MAJOR 1 #define VER_MINOR 1 #define VER_OEM 0 #define VER_BUILD 1500 #define MV_DRIVER_NAME "mvumi" #define PCI_VENDOR_ID_MARVELL_2 0x1b4b #define PCI_DEVICE_ID_MARVELL_MV9143 0x9143 #define MVUMI_INTERNAL_CMD_WAIT_TIME 45 #define IS_DMA64 (sizeof(dma_addr_t) == 8) enum mvumi_qc_result { MV_QUEUE_COMMAND_RESULT_SENT = 0, MV_QUEUE_COMMAND_RESULT_NO_RESOURCE, }; enum { /*******************************************/ /* ARM Mbus Registers Map */ /*******************************************/ CPU_MAIN_INT_CAUSE_REG = 0x20200, CPU_MAIN_IRQ_MASK_REG = 0x20204, CPU_MAIN_FIQ_MASK_REG = 0x20208, CPU_ENPOINTA_MASK_REG = 0x2020C, CPU_ENPOINTB_MASK_REG = 0x20210, INT_MAP_COMAERR = 1 << 6, INT_MAP_COMAIN = 1 << 7, INT_MAP_COMAOUT = 1 << 8, INT_MAP_COMBERR = 1 << 9, INT_MAP_COMBIN = 1 << 10, INT_MAP_COMBOUT = 1 << 11, INT_MAP_COMAINT = (INT_MAP_COMAOUT | INT_MAP_COMAERR), INT_MAP_COMBINT = (INT_MAP_COMBOUT | INT_MAP_COMBIN | INT_MAP_COMBERR), INT_MAP_DL_PCIEA2CPU = 1 << 0, INT_MAP_DL_CPU2PCIEA = 1 << 1, /***************************************/ /* ARM Doorbell Registers Map */ /***************************************/ CPU_PCIEA_TO_ARM_DRBL_REG = 0x20400, CPU_PCIEA_TO_ARM_MASK_REG = 0x20404, CPU_ARM_TO_PCIEA_DRBL_REG = 0x20408, CPU_ARM_TO_PCIEA_MASK_REG = 0x2040C, DRBL_HANDSHAKE = 1 << 0, DRBL_SOFT_RESET = 1 << 1, DRBL_BUS_CHANGE = 1 << 2, DRBL_EVENT_NOTIFY = 1 << 3, DRBL_MU_RESET = 1 << 4, DRBL_HANDSHAKE_ISR = DRBL_HANDSHAKE, CPU_PCIEA_TO_ARM_MSG0 = 0x20430, CPU_PCIEA_TO_ARM_MSG1 = 0x20434, CPU_ARM_TO_PCIEA_MSG0 = 0x20438, CPU_ARM_TO_PCIEA_MSG1 = 0x2043C, /*******************************************/ /* ARM Communication List Registers Map */ /*******************************************/ CLA_INB_LIST_BASEL = 0x500, CLA_INB_LIST_BASEH = 0x504, CLA_INB_AVAL_COUNT_BASEL = 0x508, CLA_INB_AVAL_COUNT_BASEH = 0x50C, CLA_INB_DESTI_LIST_BASEL = 0x510, CLA_INB_DESTI_LIST_BASEH = 0x514, CLA_INB_WRITE_POINTER = 0x518, CLA_INB_READ_POINTER = 0x51C, CLA_OUTB_LIST_BASEL = 0x530, CLA_OUTB_LIST_BASEH = 0x534, CLA_OUTB_SOURCE_LIST_BASEL = 0x538, CLA_OUTB_SOURCE_LIST_BASEH = 0x53C, CLA_OUTB_COPY_POINTER = 0x544, CLA_OUTB_READ_POINTER = 0x548, CLA_ISR_CAUSE = 0x560, CLA_ISR_MASK = 0x564, INT_MAP_MU = (INT_MAP_DL_CPU2PCIEA | INT_MAP_COMAINT), CL_POINTER_TOGGLE = 1 << 12, CLIC_IN_IRQ = 1 << 0, CLIC_OUT_IRQ = 1 << 1, CLIC_IN_ERR_IRQ = 1 << 8, CLIC_OUT_ERR_IRQ = 1 << 12, CL_SLOT_NUM_MASK = 0xFFF, /* * Command flag is the flag for the CDB command itself */ /* 1-non data; 0-data command */ CMD_FLAG_NON_DATA = 1 << 0, CMD_FLAG_DMA = 1 << 1, CMD_FLAG_PIO = 1 << 2, /* 1-host read data */ CMD_FLAG_DATA_IN = 1 << 3, /* 1-host write data */ CMD_FLAG_DATA_OUT = 1 << 4, SCSI_CMD_MARVELL_SPECIFIC = 0xE1, CDB_CORE_SHUTDOWN = 0xB, }; #define APICDB0_EVENT 0xF4 #define APICDB1_EVENT_GETEVENT 0 #define MAX_EVENTS_RETURNED 6 struct mvumi_driver_event { u32 time_stamp; u32 sequence_no; u32 event_id; u8 severity; u8 param_count; u16 device_id; u32 params[4]; u8 sense_data_length; u8 Reserved1; u8 sense_data[30]; }; struct mvumi_event_req { unsigned char count; unsigned char reserved[3]; struct mvumi_driver_event events[MAX_EVENTS_RETURNED]; }; struct mvumi_events_wq { struct work_struct work_q; struct mvumi_hba *mhba; unsigned int event; void *param; }; #define MVUMI_MAX_SG_ENTRY 32 #define SGD_EOT (1L << 27) struct mvumi_sgl { u32 baseaddr_l; u32 baseaddr_h; u32 flags; u32 size; }; struct mvumi_res { struct list_head entry; dma_addr_t bus_addr; void *virt_addr; unsigned int size; unsigned short type; /* enum Resource_Type */ }; /* Resource type */ enum resource_type { RESOURCE_CACHED_MEMORY = 0, RESOURCE_UNCACHED_MEMORY }; struct mvumi_sense_data { u8 error_eode:7; u8 valid:1; u8 segment_number; u8 sense_key:4; u8 reserved:1; u8 incorrect_length:1; u8 end_of_media:1; u8 file_mark:1; u8 information[4]; u8 additional_sense_length; u8 command_specific_information[4]; u8 additional_sense_code; u8 additional_sense_code_qualifier; u8 field_replaceable_unit_code; u8 sense_key_specific[3]; }; /* Request initiator must set the status to REQ_STATUS_PENDING. */ #define REQ_STATUS_PENDING 0x80 struct mvumi_cmd { struct list_head queue_pointer; struct mvumi_msg_frame *frame; struct scsi_cmnd *scmd; atomic_t sync_cmd; void *data_buf; unsigned short request_id; unsigned char cmd_status; }; /* * the function type of the in bound frame */ #define CL_FUN_SCSI_CMD 0x1 struct mvumi_msg_frame { u16 device_id; u16 tag; u8 cmd_flag; u8 req_function; u8 cdb_length; u8 sg_counts; u32 data_transfer_length; u16 request_id; u16 reserved1; u8 cdb[MAX_COMMAND_SIZE]; u32 payload[1]; }; /* * the respond flag for data_payload of the out bound frame */ #define CL_RSP_FLAG_NODATA 0x0 #define CL_RSP_FLAG_SENSEDATA 0x1 struct mvumi_rsp_frame { u16 device_id; u16 tag; u8 req_status; u8 rsp_flag; /* Indicates the type of Data_Payload.*/ u16 request_id; u32 payload[1]; }; struct mvumi_ob_data { struct list_head list; unsigned char data[0]; }; struct version_info { u32 ver_major; u32 ver_minor; u32 ver_oem; u32 ver_build; }; #define FW_MAX_DELAY 30 #define MVUMI_FW_BUSY (1U << 0) #define MVUMI_FW_ATTACH (1U << 1) #define MVUMI_FW_ALLOC (1U << 2) /* * State is the state of the MU */ #define FW_STATE_IDLE 0 #define FW_STATE_STARTING 1 #define FW_STATE_HANDSHAKING 2 #define FW_STATE_STARTED 3 #define FW_STATE_ABORT 4 #define HANDSHAKE_SIGNATURE 0x5A5A5A5AL #define HANDSHAKE_READYSTATE 0x55AA5AA5L #define HANDSHAKE_DONESTATE 0x55AAA55AL /* HandShake Status definition */ #define HS_STATUS_OK 1 #define HS_STATUS_ERR 2 #define HS_STATUS_INVALID 3 /* HandShake State/Cmd definition */ #define HS_S_START 1 #define HS_S_RESET 2 #define HS_S_PAGE_ADDR 3 #define HS_S_QUERY_PAGE 4 #define HS_S_SEND_PAGE 5 #define HS_S_END 6 #define HS_S_ABORT 7 #define HS_PAGE_VERIFY_SIZE 128 #define HS_GET_STATE(a) (a & 0xFFFF) #define HS_GET_STATUS(a) ((a & 0xFFFF0000) >> 16) #define HS_SET_STATE(a, b) (a |= (b & 0xFFFF)) #define HS_SET_STATUS(a, b) (a |= ((b & 0xFFFF) << 16)) /* handshake frame */ struct mvumi_hs_frame { u16 size; /* host information */ u8 host_type; u8 reserved_1[1]; struct version_info host_ver; /* bios or driver version */ /* controller information */ u32 system_io_bus; u32 slot_number; u32 intr_level; u32 intr_vector; /* communication list configuration */ u32 ib_baseaddr_l; u32 ib_baseaddr_h; u32 ob_baseaddr_l; u32 ob_baseaddr_h; u8 ib_entry_size; u8 ob_entry_size; u8 ob_depth; u8 ib_depth; /* system time */ u64 seconds_since1970; }; struct mvumi_hs_header { u8 page_code; u8 checksum; u16 frame_length; u32 frame_content[1]; }; /* * the page code type of the handshake header */ #define HS_PAGE_FIRM_CAP 0x1 #define HS_PAGE_HOST_INFO 0x2 #define HS_PAGE_FIRM_CTL 0x3 #define HS_PAGE_CL_INFO 0x4 #define HS_PAGE_TOTAL 0x5 #define HSP_SIZE(i) sizeof(struct mvumi_hs_page##i) #define HSP_MAX_SIZE ({ \ int size, m1, m2; \ m1 = max(HSP_SIZE(1), HSP_SIZE(3)); \ m2 = max(HSP_SIZE(2), HSP_SIZE(4)); \ size = max(m1, m2); \ size; \ }) /* The format of the page code for Firmware capability */ struct mvumi_hs_page1 { u8 pagecode; u8 checksum; u16 frame_length; u16 number_of_ports; u16 max_devices_support; u16 max_io_support; u16 umi_ver; u32 max_transfer_size; struct version_info fw_ver; u8 cl_in_max_entry_size; u8 cl_out_max_entry_size; u8 cl_inout_list_depth; u8 total_pages; u16 capability; u16 reserved1; }; /* The format of the page code for Host information */ struct mvumi_hs_page2 { u8 pagecode; u8 checksum; u16 frame_length; u8 host_type; u8 reserved[3]; struct version_info host_ver; u32 system_io_bus; u32 slot_number; u32 intr_level; u32 intr_vector; u64 seconds_since1970; }; /* The format of the page code for firmware control */ struct mvumi_hs_page3 { u8 pagecode; u8 checksum; u16 frame_length; u16 control; u8 reserved[2]; u32 host_bufferaddr_l; u32 host_bufferaddr_h; u32 host_eventaddr_l; u32 host_eventaddr_h; }; struct mvumi_hs_page4 { u8 pagecode; u8 checksum; u16 frame_length; u32 ib_baseaddr_l; u32 ib_baseaddr_h; u32 ob_baseaddr_l; u32 ob_baseaddr_h; u8 ib_entry_size; u8 ob_entry_size; u8 ob_depth; u8 ib_depth; }; struct mvumi_tag { unsigned short *stack; unsigned short top; unsigned short size; }; struct mvumi_hba { void *base_addr[MAX_BASE_ADDRESS]; void *mmio; struct list_head cmd_pool; struct Scsi_Host *shost; wait_queue_head_t int_cmd_wait_q; struct pci_dev *pdev; unsigned int unique_id; atomic_t fw_outstanding; struct mvumi_instance_template *instancet; void *ib_list; dma_addr_t ib_list_phys; void *ob_list; dma_addr_t ob_list_phys; void *ib_shadow; dma_addr_t ib_shadow_phys; void *ob_shadow; dma_addr_t ob_shadow_phys; void *handshake_page; dma_addr_t handshake_page_phys; unsigned int global_isr; unsigned int isr_status; unsigned short max_sge; unsigned short max_target_id; unsigned char *target_map; unsigned int max_io; unsigned int list_num_io; unsigned int ib_max_size; unsigned int ob_max_size; unsigned int ib_max_size_setting; unsigned int ob_max_size_setting; unsigned int max_transfer_size; unsigned char hba_total_pages; unsigned char fw_flag; unsigned char request_id_enabled; unsigned short hba_capability; unsigned short io_seq; unsigned int ib_cur_slot; unsigned int ob_cur_slot; unsigned int fw_state; struct list_head ob_data_list; struct list_head free_ob_list; struct list_head res_list; struct list_head waiting_req_list; struct mvumi_tag tag_pool; struct mvumi_cmd **tag_cmd; }; struct mvumi_instance_template { void (*fire_cmd)(struct mvumi_hba *, struct mvumi_cmd *); void (*enable_intr)(void *) ; void (*disable_intr)(void *); int (*clear_intr)(void *); unsigned int (*read_fw_status_reg)(void *); }; extern struct timezone sys_tz; #endif
{ "pile_set_name": "Github" }
recipe 'remacs-git-snapshot' do git 'https://github.com/Wilfred/remacs.git' osx do option '--with-ns' option '--without-x' option '--without-dbus' end linux do option '--prefix', installation_path option '--without-gif' end install do autogen configure make 'bootstrap' make 'install' osx do copy File.join(build_path, 'nextstep', 'Emacs.app'), installation_path end end end
{ "pile_set_name": "Github" }
sphinx -e git+https://github.com/hagenw/sphinxcontrib-katex.git#egg=sphinxcontrib.katex -e git+https://github.com/szymonmaszke/torchstar-docs.git#egg=pytorch_sphinx_theme
{ "pile_set_name": "Github" }
/* $NoKeywords:$ */ /** * @file * * mfParallelTraining.h * * Header file for the parallel training feature * * @xrefitem bom "File Content Label" "Release Content" * @e project: AGESA * @e sub-project: (Mem) * @e \$Revision: 84150 $ @e \$Date: 2012-12-12 15:46:25 -0600 (Wed, 12 Dec 2012) $ * **/ /***************************************************************************** * * Copyright (c) 2008 - 2013, Advanced Micro Devices, 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 Advanced Micro Devices, 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 ADVANCED MICRO DEVICES, INC. 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. * *************************************************************************** * */ #ifndef _MFPARALLELTRAINING_H_ #define _MFPARALLELTRAINING_H_ /*---------------------------------------------------------------------------- * Mixed (DEFINITIONS AND MACROS / TYPEDEFS, STRUCTURES, ENUMS) * *---------------------------------------------------------------------------- */ /*----------------------------------------------------------------------------- * DEFINITIONS AND MACROS * *----------------------------------------------------------------------------- */ /*---------------------------------------------------------------------------- * TYPEDEFS, STRUCTURES, ENUMS * *---------------------------------------------------------------------------- */ typedef BOOLEAN (*REMOTE_NBBLOCK_CONSTRUCTOR) ( IN OUT MEM_NB_BLOCK *NBPtr, IN DIE_STRUCT *MCTPtr, IN MEM_FEAT_BLOCK_NB *FeatPtr ); ///< This structure defines the environment on the AP for parallel training typedef struct _REMOTE_TRAINING_ENV { IN OUT AMD_CONFIG_PARAMS StdHeader; ///< Config pointer of BSP IN OUT AGESA_STATUS (*GetPlatformCfg[MAX_PLATFORM_TYPES]) (struct _MEM_DATA_STRUCT *MemData, UINT8 SocketID, CH_DEF_STRUCT *CurrentChannel); ///< look-up platform info IN OUT BOOLEAN (*ErrorHandling)(struct _DIE_STRUCT *MCTPtr, UINT8 DCT, UINT16 ChipSelMask, AMD_CONFIG_PARAMS *StdHeader); ///< Error Handling IN REMOTE_NBBLOCK_CONSTRUCTOR NBBlockCtor; ///< NB Block constructor IN MEM_FEAT_BLOCK_NB *FeatPtr; ///< Feature block pointer IN UINT8 *TableBasedAlterations; ///< Point to an array of data bytes describing desired modifications to register settings IN PSO_TABLE *PlatformMemoryConfiguration; ///< Point to platform config table IN UINT32 HoleBase; ///< Used for Memtyping IN UINT32 UmaSize; ///< Used for Memtyping IN UINT16 BottomIo; ///< Used for Memtyping IN UINT32 SysLimit; ///< Used for Memtyping IN UINT8 BspSocket; ///< Socket number of BSP IN UINT8 BspCore; ///< Core number of BSP IN DIE_STRUCT DieStruct; ///< Remote copy of Die Struct } REMOTE_TRAINING_ENV; ///< This structure defines Die information typedef struct _DIE_INFO { IN OUT UINT8 Socket; ///< Socket number IN OUT UINT8 Core; ///< Core number IN OUT BOOLEAN Training; ///< Training Flag, 1 = Training has been started on this core } DIE_INFO; /*---------------------------------------------------------------------------- * FUNCTIONS PROTOTYPE * *---------------------------------------------------------------------------- */ #endif /* _MFPARALLELTRAINING_H_ */
{ "pile_set_name": "Github" }
PaddleX GUI ======================================= PaddleX GUI是基于PaddleX实现的可视化开发客户端。开发者以点选、键入的方式快速体验深度学习模型开发的全流程。不仅可以作为您提升深度学习模型开发效率的工具,更可以作为您们应用PaddleX API搭建专属的行业软件/应用的示例参照。 PaddleX GUI 当前提供Windows,Mac,Ubuntu三种版本一键绿色安装的方式。请至飞桨官网:https://www.paddlepaddle.org.cn/paddle/paddleX 下载您需要的版本。 功能简介 --------------------------------------- PaddleX GUI是PaddleX API的衍生品,它在集成API功能的基础上,额外提供了可视化分析、评估等附加功能,致力于为开发者带来极致顺畅的开发体验。其拥有以下独特的功能: 全流程打通 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> PaddleX GUI覆盖深度学习模型开发必经的 **数据处理** 、 **超参配置** 、 **模型训练及优化** 、 **模型发布** 全流程,无需开发一行代码,即可得到高性深度学习推理模型。 数据集智能分析 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 详细的数据结构说明,并提供 **数据标签自动校验** 。支持 **可视化数据预览** 、 **数据分布图表展示** 、 **一键数据集切分** 等实用功能 自动超参推荐 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 集成飞桨团队长时间产业实践经验,根据用户选择的模型类别、骨架网络等,提供多种针对性优化的 **预训练模型** ,并 **提供推荐超参配置** ,可 **一键开启多种优化策略** 可视化模型评估 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 集成 **可视化分析工具:VisualDL** , 以线性图表的形式展示acc、lr等关键参数在训练过程中的变化趋势。提供 **混淆矩阵** 等实用方法,帮助快速定位问题,加速调参。模型评估报告一键导出,方便项目复盘分析。 模型裁剪及量化 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 一键启动模型裁剪、量化,在不同阶段为开发者提供模型优化的策略,满足不同环境对模型性能的需求。 预训练模型管理 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 可对历史训练模型进行保存及管理,未进行裁剪的模型可以保存为预训练模型,在后续任务中使用。 可视化模型测试 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 客户端直接展示模型预测效果,无需上线即可进行效果评估 模型多端部署 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> 点选式选择模型发布平台、格式,一键导出预测模型,并匹配完善的模型预测部署说明文档,贴心助力产业端到端项目落地 .. toctree:: :maxdepth: 2 :caption: 文档目录 download.md how_to_use.md faq.md * PaddleX GUI版本: v1.0 * 项目官网: http://www.paddlepaddle.org.cn/paddle/paddlex * 项目GitHub: https://github.com/PaddlePaddle/PaddleX/tree/develop * 官方QQ用户群: 1045148026 * GitHub Issue反馈: http://www.github.com/PaddlePaddle/PaddleX/issues
{ "pile_set_name": "Github" }
/* apps/cms.c */ /* Written by Dr Stephen N Henson ([email protected]) for the OpenSSL * project. */ /* ==================================================================== * Copyright (c) 2008 The OpenSSL 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: * * 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * [email protected]. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== */ /* CMS utility function */ #include <stdio.h> #include <string.h> #include "apps.h" #ifndef OPENSSL_NO_CMS #include <openssl/crypto.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/x509_vfy.h> #include <openssl/x509v3.h> #include <openssl/cms.h> #undef PROG #define PROG cms_main static int save_certs(char *signerfile, STACK_OF(X509) *signers); static int cms_cb(int ok, X509_STORE_CTX *ctx); static void receipt_request_print(BIO *out, CMS_ContentInfo *cms); static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from); #define SMIME_OP 0x10 #define SMIME_IP 0x20 #define SMIME_SIGNERS 0x40 #define SMIME_ENCRYPT (1 | SMIME_OP) #define SMIME_DECRYPT (2 | SMIME_IP) #define SMIME_SIGN (3 | SMIME_OP | SMIME_SIGNERS) #define SMIME_VERIFY (4 | SMIME_IP) #define SMIME_CMSOUT (5 | SMIME_IP | SMIME_OP) #define SMIME_RESIGN (6 | SMIME_IP | SMIME_OP | SMIME_SIGNERS) #define SMIME_DATAOUT (7 | SMIME_IP) #define SMIME_DATA_CREATE (8 | SMIME_OP) #define SMIME_DIGEST_VERIFY (9 | SMIME_IP) #define SMIME_DIGEST_CREATE (10 | SMIME_OP) #define SMIME_UNCOMPRESS (11 | SMIME_IP) #define SMIME_COMPRESS (12 | SMIME_OP) #define SMIME_ENCRYPTED_DECRYPT (13 | SMIME_IP) #define SMIME_ENCRYPTED_ENCRYPT (14 | SMIME_OP) #define SMIME_SIGN_RECEIPT (15 | SMIME_IP | SMIME_OP) #define SMIME_VERIFY_RECEIPT (16 | SMIME_IP) int verify_err = 0; int MAIN(int, char **); int MAIN(int argc, char **argv) { ENGINE *e = NULL; int operation = 0; int ret = 0; char **args; const char *inmode = "r", *outmode = "w"; char *infile = NULL, *outfile = NULL, *rctfile = NULL; char *signerfile = NULL, *recipfile = NULL; STACK_OF(OPENSSL_STRING) *sksigners = NULL, *skkeys = NULL; char *certfile = NULL, *keyfile = NULL, *contfile=NULL; char *certsoutfile = NULL; const EVP_CIPHER *cipher = NULL; CMS_ContentInfo *cms = NULL, *rcms = NULL; X509_STORE *store = NULL; X509 *cert = NULL, *recip = NULL, *signer = NULL; EVP_PKEY *key = NULL; STACK_OF(X509) *encerts = NULL, *other = NULL; BIO *in = NULL, *out = NULL, *indata = NULL, *rctin = NULL; int badarg = 0; int flags = CMS_DETACHED, noout = 0, print = 0; int verify_retcode = 0; int rr_print = 0, rr_allorfirst = -1; STACK_OF(OPENSSL_STRING) *rr_to = NULL, *rr_from = NULL; CMS_ReceiptRequest *rr = NULL; char *to = NULL, *from = NULL, *subject = NULL; char *CAfile = NULL, *CApath = NULL; char *passargin = NULL, *passin = NULL; char *inrand = NULL; int need_rand = 0; const EVP_MD *sign_md = NULL; int informat = FORMAT_SMIME, outformat = FORMAT_SMIME; int rctformat = FORMAT_SMIME, keyform = FORMAT_PEM; #ifndef OPENSSL_NO_ENGINE char *engine=NULL; #endif unsigned char *secret_key = NULL, *secret_keyid = NULL; size_t secret_keylen = 0, secret_keyidlen = 0; ASN1_OBJECT *econtent_type = NULL; X509_VERIFY_PARAM *vpm = NULL; args = argv + 1; ret = 1; apps_startup(); if (bio_err == NULL) { if ((bio_err = BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err, stderr, BIO_NOCLOSE|BIO_FP_TEXT); } if (!load_config(bio_err, NULL)) goto end; while (!badarg && *args && *args[0] == '-') { if (!strcmp (*args, "-encrypt")) operation = SMIME_ENCRYPT; else if (!strcmp (*args, "-decrypt")) operation = SMIME_DECRYPT; else if (!strcmp (*args, "-sign")) operation = SMIME_SIGN; else if (!strcmp (*args, "-sign_receipt")) operation = SMIME_SIGN_RECEIPT; else if (!strcmp (*args, "-resign")) operation = SMIME_RESIGN; else if (!strcmp (*args, "-verify")) operation = SMIME_VERIFY; else if (!strcmp (*args, "-verify_retcode")) verify_retcode = 1; else if (!strcmp(*args,"-verify_receipt")) { operation = SMIME_VERIFY_RECEIPT; if (!args[1]) goto argerr; args++; rctfile = *args; } else if (!strcmp (*args, "-cmsout")) operation = SMIME_CMSOUT; else if (!strcmp (*args, "-data_out")) operation = SMIME_DATAOUT; else if (!strcmp (*args, "-data_create")) operation = SMIME_DATA_CREATE; else if (!strcmp (*args, "-digest_verify")) operation = SMIME_DIGEST_VERIFY; else if (!strcmp (*args, "-digest_create")) operation = SMIME_DIGEST_CREATE; else if (!strcmp (*args, "-compress")) operation = SMIME_COMPRESS; else if (!strcmp (*args, "-uncompress")) operation = SMIME_UNCOMPRESS; else if (!strcmp (*args, "-EncryptedData_decrypt")) operation = SMIME_ENCRYPTED_DECRYPT; else if (!strcmp (*args, "-EncryptedData_encrypt")) operation = SMIME_ENCRYPTED_ENCRYPT; #ifndef OPENSSL_NO_DES else if (!strcmp (*args, "-des3")) cipher = EVP_des_ede3_cbc(); else if (!strcmp (*args, "-des")) cipher = EVP_des_cbc(); #endif #ifndef OPENSSL_NO_SEED else if (!strcmp (*args, "-seed")) cipher = EVP_seed_cbc(); #endif #ifndef OPENSSL_NO_RC2 else if (!strcmp (*args, "-rc2-40")) cipher = EVP_rc2_40_cbc(); else if (!strcmp (*args, "-rc2-128")) cipher = EVP_rc2_cbc(); else if (!strcmp (*args, "-rc2-64")) cipher = EVP_rc2_64_cbc(); #endif #ifndef OPENSSL_NO_AES else if (!strcmp(*args,"-aes128")) cipher = EVP_aes_128_cbc(); else if (!strcmp(*args,"-aes192")) cipher = EVP_aes_192_cbc(); else if (!strcmp(*args,"-aes256")) cipher = EVP_aes_256_cbc(); #endif #ifndef OPENSSL_NO_CAMELLIA else if (!strcmp(*args,"-camellia128")) cipher = EVP_camellia_128_cbc(); else if (!strcmp(*args,"-camellia192")) cipher = EVP_camellia_192_cbc(); else if (!strcmp(*args,"-camellia256")) cipher = EVP_camellia_256_cbc(); #endif else if (!strcmp (*args, "-text")) flags |= CMS_TEXT; else if (!strcmp (*args, "-nointern")) flags |= CMS_NOINTERN; else if (!strcmp (*args, "-noverify") || !strcmp (*args, "-no_signer_cert_verify")) flags |= CMS_NO_SIGNER_CERT_VERIFY; else if (!strcmp (*args, "-nocerts")) flags |= CMS_NOCERTS; else if (!strcmp (*args, "-noattr")) flags |= CMS_NOATTR; else if (!strcmp (*args, "-nodetach")) flags &= ~CMS_DETACHED; else if (!strcmp (*args, "-nosmimecap")) flags |= CMS_NOSMIMECAP; else if (!strcmp (*args, "-binary")) flags |= CMS_BINARY; else if (!strcmp (*args, "-keyid")) flags |= CMS_USE_KEYID; else if (!strcmp (*args, "-nosigs")) flags |= CMS_NOSIGS; else if (!strcmp (*args, "-no_content_verify")) flags |= CMS_NO_CONTENT_VERIFY; else if (!strcmp (*args, "-no_attr_verify")) flags |= CMS_NO_ATTR_VERIFY; else if (!strcmp (*args, "-stream")) flags |= CMS_STREAM; else if (!strcmp (*args, "-indef")) flags |= CMS_STREAM; else if (!strcmp (*args, "-noindef")) flags &= ~CMS_STREAM; else if (!strcmp (*args, "-nooldmime")) flags |= CMS_NOOLDMIMETYPE; else if (!strcmp (*args, "-crlfeol")) flags |= CMS_CRLFEOL; else if (!strcmp (*args, "-noout")) noout = 1; else if (!strcmp (*args, "-receipt_request_print")) rr_print = 1; else if (!strcmp (*args, "-receipt_request_all")) rr_allorfirst = 0; else if (!strcmp (*args, "-receipt_request_first")) rr_allorfirst = 1; else if (!strcmp(*args,"-receipt_request_from")) { if (!args[1]) goto argerr; args++; if (!rr_from) rr_from = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(rr_from, *args); } else if (!strcmp(*args,"-receipt_request_to")) { if (!args[1]) goto argerr; args++; if (!rr_to) rr_to = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(rr_to, *args); } else if (!strcmp (*args, "-print")) { noout = 1; print = 1; } else if (!strcmp(*args,"-secretkey")) { long ltmp; if (!args[1]) goto argerr; args++; secret_key = string_to_hex(*args, &ltmp); if (!secret_key) { BIO_printf(bio_err, "Invalid key %s\n", *args); goto argerr; } secret_keylen = (size_t)ltmp; } else if (!strcmp(*args,"-secretkeyid")) { long ltmp; if (!args[1]) goto argerr; args++; secret_keyid = string_to_hex(*args, &ltmp); if (!secret_keyid) { BIO_printf(bio_err, "Invalid id %s\n", *args); goto argerr; } secret_keyidlen = (size_t)ltmp; } else if (!strcmp(*args,"-econtent_type")) { if (!args[1]) goto argerr; args++; econtent_type = OBJ_txt2obj(*args, 0); if (!econtent_type) { BIO_printf(bio_err, "Invalid OID %s\n", *args); goto argerr; } } else if (!strcmp(*args,"-rand")) { if (!args[1]) goto argerr; args++; inrand = *args; need_rand = 1; } #ifndef OPENSSL_NO_ENGINE else if (!strcmp(*args,"-engine")) { if (!args[1]) goto argerr; engine = *++args; } #endif else if (!strcmp(*args,"-passin")) { if (!args[1]) goto argerr; passargin = *++args; } else if (!strcmp (*args, "-to")) { if (!args[1]) goto argerr; to = *++args; } else if (!strcmp (*args, "-from")) { if (!args[1]) goto argerr; from = *++args; } else if (!strcmp (*args, "-subject")) { if (!args[1]) goto argerr; subject = *++args; } else if (!strcmp (*args, "-signer")) { if (!args[1]) goto argerr; /* If previous -signer argument add signer to list */ if (signerfile) { if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); if (!keyfile) keyfile = signerfile; if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(skkeys, keyfile); keyfile = NULL; } signerfile = *++args; } else if (!strcmp (*args, "-recip")) { if (!args[1]) goto argerr; recipfile = *++args; } else if (!strcmp (*args, "-certsout")) { if (!args[1]) goto argerr; certsoutfile = *++args; } else if (!strcmp (*args, "-md")) { if (!args[1]) goto argerr; sign_md = EVP_get_digestbyname(*++args); if (sign_md == NULL) { BIO_printf(bio_err, "Unknown digest %s\n", *args); goto argerr; } } else if (!strcmp (*args, "-inkey")) { if (!args[1]) goto argerr; /* If previous -inkey arument add signer to list */ if (keyfile) { if (!signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto argerr; } if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); signerfile = NULL; if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(skkeys, keyfile); } keyfile = *++args; } else if (!strcmp (*args, "-keyform")) { if (!args[1]) goto argerr; keyform = str2fmt(*++args); } else if (!strcmp (*args, "-rctform")) { if (!args[1]) goto argerr; rctformat = str2fmt(*++args); } else if (!strcmp (*args, "-certfile")) { if (!args[1]) goto argerr; certfile = *++args; } else if (!strcmp (*args, "-CAfile")) { if (!args[1]) goto argerr; CAfile = *++args; } else if (!strcmp (*args, "-CApath")) { if (!args[1]) goto argerr; CApath = *++args; } else if (!strcmp (*args, "-in")) { if (!args[1]) goto argerr; infile = *++args; } else if (!strcmp (*args, "-inform")) { if (!args[1]) goto argerr; informat = str2fmt(*++args); } else if (!strcmp (*args, "-outform")) { if (!args[1]) goto argerr; outformat = str2fmt(*++args); } else if (!strcmp (*args, "-out")) { if (!args[1]) goto argerr; outfile = *++args; } else if (!strcmp (*args, "-content")) { if (!args[1]) goto argerr; contfile = *++args; } else if (args_verify(&args, NULL, &badarg, bio_err, &vpm)) continue; else if ((cipher = EVP_get_cipherbyname(*args + 1)) == NULL) badarg = 1; args++; } if (((rr_allorfirst != -1) || rr_from) && !rr_to) { BIO_puts(bio_err, "No Signed Receipts Recipients\n"); goto argerr; } if (!(operation & SMIME_SIGNERS) && (rr_to || rr_from)) { BIO_puts(bio_err, "Signed receipts only allowed with -sign\n"); goto argerr; } if (!(operation & SMIME_SIGNERS) && (skkeys || sksigners)) { BIO_puts(bio_err, "Multiple signers or keys not allowed\n"); goto argerr; } if (operation & SMIME_SIGNERS) { if (keyfile && !signerfile) { BIO_puts(bio_err, "Illegal -inkey without -signer\n"); goto argerr; } /* Check to see if any final signer needs to be appended */ if (signerfile) { if (!sksigners) sksigners = sk_OPENSSL_STRING_new_null(); sk_OPENSSL_STRING_push(sksigners, signerfile); if (!skkeys) skkeys = sk_OPENSSL_STRING_new_null(); if (!keyfile) keyfile = signerfile; sk_OPENSSL_STRING_push(skkeys, keyfile); } if (!sksigners) { BIO_printf(bio_err, "No signer certificate specified\n"); badarg = 1; } signerfile = NULL; keyfile = NULL; need_rand = 1; } else if (operation == SMIME_DECRYPT) { if (!recipfile && !keyfile && !secret_key) { BIO_printf(bio_err, "No recipient certificate or key specified\n"); badarg = 1; } } else if (operation == SMIME_ENCRYPT) { if (!*args && !secret_key) { BIO_printf(bio_err, "No recipient(s) certificate(s) specified\n"); badarg = 1; } need_rand = 1; } else if (!operation) badarg = 1; if (badarg) { argerr: BIO_printf (bio_err, "Usage cms [options] cert.pem ...\n"); BIO_printf (bio_err, "where options are\n"); BIO_printf (bio_err, "-encrypt encrypt message\n"); BIO_printf (bio_err, "-decrypt decrypt encrypted message\n"); BIO_printf (bio_err, "-sign sign message\n"); BIO_printf (bio_err, "-verify verify signed message\n"); BIO_printf (bio_err, "-cmsout output CMS structure\n"); #ifndef OPENSSL_NO_DES BIO_printf (bio_err, "-des3 encrypt with triple DES\n"); BIO_printf (bio_err, "-des encrypt with DES\n"); #endif #ifndef OPENSSL_NO_SEED BIO_printf (bio_err, "-seed encrypt with SEED\n"); #endif #ifndef OPENSSL_NO_RC2 BIO_printf (bio_err, "-rc2-40 encrypt with RC2-40 (default)\n"); BIO_printf (bio_err, "-rc2-64 encrypt with RC2-64\n"); BIO_printf (bio_err, "-rc2-128 encrypt with RC2-128\n"); #endif #ifndef OPENSSL_NO_AES BIO_printf (bio_err, "-aes128, -aes192, -aes256\n"); BIO_printf (bio_err, " encrypt PEM output with cbc aes\n"); #endif #ifndef OPENSSL_NO_CAMELLIA BIO_printf (bio_err, "-camellia128, -camellia192, -camellia256\n"); BIO_printf (bio_err, " encrypt PEM output with cbc camellia\n"); #endif BIO_printf (bio_err, "-nointern don't search certificates in message for signer\n"); BIO_printf (bio_err, "-nosigs don't verify message signature\n"); BIO_printf (bio_err, "-noverify don't verify signers certificate\n"); BIO_printf (bio_err, "-nocerts don't include signers certificate when signing\n"); BIO_printf (bio_err, "-nodetach use opaque signing\n"); BIO_printf (bio_err, "-noattr don't include any signed attributes\n"); BIO_printf (bio_err, "-binary don't translate message to text\n"); BIO_printf (bio_err, "-certfile file other certificates file\n"); BIO_printf (bio_err, "-certsout file certificate output file\n"); BIO_printf (bio_err, "-signer file signer certificate file\n"); BIO_printf (bio_err, "-recip file recipient certificate file for decryption\n"); BIO_printf (bio_err, "-skeyid use subject key identifier\n"); BIO_printf (bio_err, "-in file input file\n"); BIO_printf (bio_err, "-inform arg input format SMIME (default), PEM or DER\n"); BIO_printf (bio_err, "-inkey file input private key (if not signer or recipient)\n"); BIO_printf (bio_err, "-keyform arg input private key format (PEM or ENGINE)\n"); BIO_printf (bio_err, "-out file output file\n"); BIO_printf (bio_err, "-outform arg output format SMIME (default), PEM or DER\n"); BIO_printf (bio_err, "-content file supply or override content for detached signature\n"); BIO_printf (bio_err, "-to addr to address\n"); BIO_printf (bio_err, "-from ad from address\n"); BIO_printf (bio_err, "-subject s subject\n"); BIO_printf (bio_err, "-text include or delete text MIME headers\n"); BIO_printf (bio_err, "-CApath dir trusted certificates directory\n"); BIO_printf (bio_err, "-CAfile file trusted certificates file\n"); BIO_printf (bio_err, "-crl_check check revocation status of signer's certificate using CRLs\n"); BIO_printf (bio_err, "-crl_check_all check revocation status of signer's certificate chain using CRLs\n"); #ifndef OPENSSL_NO_ENGINE BIO_printf (bio_err, "-engine e use engine e, possibly a hardware device.\n"); #endif BIO_printf (bio_err, "-passin arg input file pass phrase source\n"); BIO_printf(bio_err, "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR); BIO_printf(bio_err, " load the file (or the files in the directory) into\n"); BIO_printf(bio_err, " the random number generator\n"); BIO_printf (bio_err, "cert.pem recipient certificate(s) for encryption\n"); goto end; } #ifndef OPENSSL_NO_ENGINE e = setup_engine(bio_err, engine, 0); #endif if (!app_passwd(bio_err, passargin, NULL, &passin, NULL)) { BIO_printf(bio_err, "Error getting password\n"); goto end; } if (need_rand) { app_RAND_load_file(NULL, bio_err, (inrand != NULL)); if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); } ret = 2; if (!(operation & SMIME_SIGNERS)) flags &= ~CMS_DETACHED; if (operation & SMIME_OP) { if (outformat == FORMAT_ASN1) outmode = "wb"; } else { if (flags & CMS_BINARY) outmode = "wb"; } if (operation & SMIME_IP) { if (informat == FORMAT_ASN1) inmode = "rb"; } else { if (flags & CMS_BINARY) inmode = "rb"; } if (operation == SMIME_ENCRYPT) { if (!cipher) { #ifndef OPENSSL_NO_DES cipher = EVP_des_ede3_cbc(); #else BIO_printf(bio_err, "No cipher selected\n"); goto end; #endif } if (secret_key && !secret_keyid) { BIO_printf(bio_err, "No secret key id\n"); goto end; } if (*args) encerts = sk_X509_new_null(); while (*args) { if (!(cert = load_cert(bio_err,*args,FORMAT_PEM, NULL, e, "recipient certificate file"))) goto end; sk_X509_push(encerts, cert); cert = NULL; args++; } } if (certfile) { if (!(other = load_certs(bio_err,certfile,FORMAT_PEM, NULL, e, "certificate file"))) { ERR_print_errors(bio_err); goto end; } } if (recipfile && (operation == SMIME_DECRYPT)) { if (!(recip = load_cert(bio_err,recipfile,FORMAT_PEM,NULL, e, "recipient certificate file"))) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_SIGN_RECEIPT) { if (!(signer = load_cert(bio_err,signerfile,FORMAT_PEM,NULL, e, "receipt signer certificate file"))) { ERR_print_errors(bio_err); goto end; } } if (operation == SMIME_DECRYPT) { if (!keyfile) keyfile = recipfile; } else if ((operation == SMIME_SIGN) || (operation == SMIME_SIGN_RECEIPT)) { if (!keyfile) keyfile = signerfile; } else keyfile = NULL; if (keyfile) { key = load_key(bio_err, keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; } if (infile) { if (!(in = BIO_new_file(infile, inmode))) { BIO_printf (bio_err, "Can't open input file %s\n", infile); goto end; } } else in = BIO_new_fp(stdin, BIO_NOCLOSE); if (operation & SMIME_IP) { if (informat == FORMAT_SMIME) cms = SMIME_read_CMS(in, &indata); else if (informat == FORMAT_PEM) cms = PEM_read_bio_CMS(in, NULL, NULL, NULL); else if (informat == FORMAT_ASN1) cms = d2i_CMS_bio(in, NULL); else { BIO_printf(bio_err, "Bad input format for CMS file\n"); goto end; } if (!cms) { BIO_printf(bio_err, "Error reading S/MIME message\n"); goto end; } if (contfile) { BIO_free(indata); if (!(indata = BIO_new_file(contfile, "rb"))) { BIO_printf(bio_err, "Can't read content file %s\n", contfile); goto end; } } if (certsoutfile) { STACK_OF(X509) *allcerts; allcerts = CMS_get1_certs(cms); if (!save_certs(certsoutfile, allcerts)) { BIO_printf(bio_err, "Error writing certs to %s\n", certsoutfile); ret = 5; goto end; } sk_X509_pop_free(allcerts, X509_free); } } if (rctfile) { char *rctmode = (rctformat == FORMAT_ASN1) ? "rb" : "r"; if (!(rctin = BIO_new_file(rctfile, rctmode))) { BIO_printf (bio_err, "Can't open receipt file %s\n", rctfile); goto end; } if (rctformat == FORMAT_SMIME) rcms = SMIME_read_CMS(rctin, NULL); else if (rctformat == FORMAT_PEM) rcms = PEM_read_bio_CMS(rctin, NULL, NULL, NULL); else if (rctformat == FORMAT_ASN1) rcms = d2i_CMS_bio(rctin, NULL); else { BIO_printf(bio_err, "Bad input format for receipt\n"); goto end; } if (!rcms) { BIO_printf(bio_err, "Error reading receipt\n"); goto end; } } if (outfile) { if (!(out = BIO_new_file(outfile, outmode))) { BIO_printf (bio_err, "Can't open output file %s\n", outfile); goto end; } } else { out = BIO_new_fp(stdout, BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } if ((operation == SMIME_VERIFY) || (operation == SMIME_VERIFY_RECEIPT)) { if (!(store = setup_verify(bio_err, CAfile, CApath))) goto end; X509_STORE_set_verify_cb(store, cms_cb); if (vpm) X509_STORE_set1_param(store, vpm); } ret = 3; if (operation == SMIME_DATA_CREATE) { cms = CMS_data_create(in, flags); } else if (operation == SMIME_DIGEST_CREATE) { cms = CMS_digest_create(in, sign_md, flags); } else if (operation == SMIME_COMPRESS) { cms = CMS_compress(in, -1, flags); } else if (operation == SMIME_ENCRYPT) { flags |= CMS_PARTIAL; cms = CMS_encrypt(encerts, in, cipher, flags); if (!cms) goto end; if (secret_key) { if (!CMS_add0_recipient_key(cms, NID_undef, secret_key, secret_keylen, secret_keyid, secret_keyidlen, NULL, NULL, NULL)) goto end; /* NULL these because call absorbs them */ secret_key = NULL; secret_keyid = NULL; } if (!(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } else if (operation == SMIME_ENCRYPTED_ENCRYPT) { cms = CMS_EncryptedData_encrypt(in, cipher, secret_key, secret_keylen, flags); } else if (operation == SMIME_SIGN_RECEIPT) { CMS_ContentInfo *srcms = NULL; STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; sis = CMS_get0_SignerInfos(cms); if (!sis) goto end; si = sk_CMS_SignerInfo_value(sis, 0); srcms = CMS_sign_receipt(si, signer, key, other, flags); if (!srcms) goto end; CMS_ContentInfo_free(cms); cms = srcms; } else if (operation & SMIME_SIGNERS) { int i; /* If detached data content we enable streaming if * S/MIME output format. */ if (operation == SMIME_SIGN) { if (flags & CMS_DETACHED) { if (outformat == FORMAT_SMIME) flags |= CMS_STREAM; } flags |= CMS_PARTIAL; cms = CMS_sign(NULL, NULL, other, in, flags); if (!cms) goto end; if (econtent_type) CMS_set1_eContentType(cms, econtent_type); if (rr_to) { rr = make_receipt_request(rr_to, rr_allorfirst, rr_from); if (!rr) { BIO_puts(bio_err, "Signed Receipt Request Creation Error\n"); goto end; } } } else flags |= CMS_REUSE_DIGEST; for (i = 0; i < sk_OPENSSL_STRING_num(sksigners); i++) { CMS_SignerInfo *si; signerfile = sk_OPENSSL_STRING_value(sksigners, i); keyfile = sk_OPENSSL_STRING_value(skkeys, i); signer = load_cert(bio_err, signerfile,FORMAT_PEM, NULL, e, "signer certificate"); if (!signer) goto end; key = load_key(bio_err, keyfile, keyform, 0, passin, e, "signing key file"); if (!key) goto end; si = CMS_add1_signer(cms, signer, key, sign_md, flags); if (!si) goto end; if (rr && !CMS_add1_ReceiptRequest(si, rr)) goto end; X509_free(signer); signer = NULL; EVP_PKEY_free(key); key = NULL; } /* If not streaming or resigning finalize structure */ if ((operation == SMIME_SIGN) && !(flags & CMS_STREAM)) { if (!CMS_final(cms, in, NULL, flags)) goto end; } } if (!cms) { BIO_printf(bio_err, "Error creating CMS structure\n"); goto end; } ret = 4; if (operation == SMIME_DECRYPT) { if (secret_key) { if (!CMS_decrypt_set1_key(cms, secret_key, secret_keylen, secret_keyid, secret_keyidlen)) { BIO_puts(bio_err, "Error decrypting CMS using secret key\n"); goto end; } } if (key) { if (!CMS_decrypt_set1_pkey(cms, key, recip)) { BIO_puts(bio_err, "Error decrypting CMS using private key\n"); goto end; } } if (!CMS_decrypt(cms, NULL, NULL, indata, out, flags)) { BIO_printf(bio_err, "Error decrypting CMS structure\n"); goto end; } } else if (operation == SMIME_DATAOUT) { if (!CMS_data(cms, out, flags)) goto end; } else if (operation == SMIME_UNCOMPRESS) { if (!CMS_uncompress(cms, indata, out, flags)) goto end; } else if (operation == SMIME_DIGEST_VERIFY) { if (CMS_digest_verify(cms, indata, out, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else if (operation == SMIME_ENCRYPTED_DECRYPT) { if (!CMS_EncryptedData_decrypt(cms, secret_key, secret_keylen, indata, out, flags)) goto end; } else if (operation == SMIME_VERIFY) { if (CMS_verify(cms, other, store, indata, out, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); if (verify_retcode) ret = verify_err + 32; goto end; } if (signerfile) { STACK_OF(X509) *signers; signers = CMS_get0_signers(cms); if (!save_certs(signerfile, signers)) { BIO_printf(bio_err, "Error writing signers to %s\n", signerfile); ret = 5; goto end; } sk_X509_free(signers); } if (rr_print) receipt_request_print(bio_err, cms); } else if (operation == SMIME_VERIFY_RECEIPT) { if (CMS_verify_receipt(rcms, cms, other, store, flags) > 0) BIO_printf(bio_err, "Verification successful\n"); else { BIO_printf(bio_err, "Verification failure\n"); goto end; } } else { if (noout) { if (print) CMS_ContentInfo_print_ctx(out, cms, 0, NULL); } else if (outformat == FORMAT_SMIME) { if (to) BIO_printf(out, "To: %s\n", to); if (from) BIO_printf(out, "From: %s\n", from); if (subject) BIO_printf(out, "Subject: %s\n", subject); if (operation == SMIME_RESIGN) ret = SMIME_write_CMS(out, cms, indata, flags); else ret = SMIME_write_CMS(out, cms, in, flags); } else if (outformat == FORMAT_PEM) ret = PEM_write_bio_CMS_stream(out, cms, in, flags); else if (outformat == FORMAT_ASN1) ret = i2d_CMS_bio_stream(out,cms, in, flags); else { BIO_printf(bio_err, "Bad output format for CMS file\n"); goto end; } if (ret <= 0) { ret = 6; goto end; } } ret = 0; end: if (ret) ERR_print_errors(bio_err); if (need_rand) app_RAND_write_file(NULL, bio_err); sk_X509_pop_free(encerts, X509_free); sk_X509_pop_free(other, X509_free); if (vpm) X509_VERIFY_PARAM_free(vpm); if (sksigners) sk_OPENSSL_STRING_free(sksigners); if (skkeys) sk_OPENSSL_STRING_free(skkeys); if (secret_key) OPENSSL_free(secret_key); if (secret_keyid) OPENSSL_free(secret_keyid); if (econtent_type) ASN1_OBJECT_free(econtent_type); if (rr) CMS_ReceiptRequest_free(rr); if (rr_to) sk_OPENSSL_STRING_free(rr_to); if (rr_from) sk_OPENSSL_STRING_free(rr_from); X509_STORE_free(store); X509_free(cert); X509_free(recip); X509_free(signer); EVP_PKEY_free(key); CMS_ContentInfo_free(cms); CMS_ContentInfo_free(rcms); BIO_free(rctin); BIO_free(in); BIO_free(indata); BIO_free_all(out); if (passin) OPENSSL_free(passin); return (ret); } static int save_certs(char *signerfile, STACK_OF(X509) *signers) { int i; BIO *tmp; if (!signerfile) return 1; tmp = BIO_new_file(signerfile, "w"); if (!tmp) return 0; for(i = 0; i < sk_X509_num(signers); i++) PEM_write_bio_X509(tmp, sk_X509_value(signers, i)); BIO_free(tmp); return 1; } /* Minimal callback just to output policy info (if any) */ static int cms_cb(int ok, X509_STORE_CTX *ctx) { int error; error = X509_STORE_CTX_get_error(ctx); verify_err = error; if ((error != X509_V_ERR_NO_EXPLICIT_POLICY) && ((error != X509_V_OK) || (ok != 2))) return ok; policies_print(NULL, ctx); return ok; } static void gnames_stack_print(BIO *out, STACK_OF(GENERAL_NAMES) *gns) { STACK_OF(GENERAL_NAME) *gens; GENERAL_NAME *gen; int i, j; for (i = 0; i < sk_GENERAL_NAMES_num(gns); i++) { gens = sk_GENERAL_NAMES_value(gns, i); for (j = 0; j < sk_GENERAL_NAME_num(gens); j++) { gen = sk_GENERAL_NAME_value(gens, j); BIO_puts(out, " "); GENERAL_NAME_print(out, gen); BIO_puts(out, "\n"); } } return; } static void receipt_request_print(BIO *out, CMS_ContentInfo *cms) { STACK_OF(CMS_SignerInfo) *sis; CMS_SignerInfo *si; CMS_ReceiptRequest *rr; int allorfirst; STACK_OF(GENERAL_NAMES) *rto, *rlist; ASN1_STRING *scid; int i, rv; sis = CMS_get0_SignerInfos(cms); for (i = 0; i < sk_CMS_SignerInfo_num(sis); i++) { si = sk_CMS_SignerInfo_value(sis, i); rv = CMS_get1_ReceiptRequest(si, &rr); BIO_printf(bio_err, "Signer %d:\n", i + 1); if (rv == 0) BIO_puts(bio_err, " No Receipt Request\n"); else if (rv < 0) { BIO_puts(bio_err, " Receipt Request Parse Error\n"); ERR_print_errors(bio_err); } else { char *id; int idlen; CMS_ReceiptRequest_get0_values(rr, &scid, &allorfirst, &rlist, &rto); BIO_puts(out, " Signed Content ID:\n"); idlen = ASN1_STRING_length(scid); id = (char *)ASN1_STRING_data(scid); BIO_dump_indent(out, id, idlen, 4); BIO_puts(out, " Receipts From"); if (rlist) { BIO_puts(out, " List:\n"); gnames_stack_print(out, rlist); } else if (allorfirst == 1) BIO_puts(out, ": First Tier\n"); else if (allorfirst == 0) BIO_puts(out, ": All\n"); else BIO_printf(out, " Unknown (%d)\n", allorfirst); BIO_puts(out, " Receipts To:\n"); gnames_stack_print(out, rto); } if (rr) CMS_ReceiptRequest_free(rr); } } static STACK_OF(GENERAL_NAMES) *make_names_stack(STACK_OF(OPENSSL_STRING) *ns) { int i; STACK_OF(GENERAL_NAMES) *ret; GENERAL_NAMES *gens = NULL; GENERAL_NAME *gen = NULL; ret = sk_GENERAL_NAMES_new_null(); if (!ret) goto err; for (i = 0; i < sk_OPENSSL_STRING_num(ns); i++) { char *str = sk_OPENSSL_STRING_value(ns, i); gen = a2i_GENERAL_NAME(NULL, NULL, NULL, GEN_EMAIL, str, 0); if (!gen) goto err; gens = GENERAL_NAMES_new(); if (!gens) goto err; if (!sk_GENERAL_NAME_push(gens, gen)) goto err; gen = NULL; if (!sk_GENERAL_NAMES_push(ret, gens)) goto err; gens = NULL; } return ret; err: if (ret) sk_GENERAL_NAMES_pop_free(ret, GENERAL_NAMES_free); if (gens) GENERAL_NAMES_free(gens); if (gen) GENERAL_NAME_free(gen); return NULL; } static CMS_ReceiptRequest *make_receipt_request(STACK_OF(OPENSSL_STRING) *rr_to, int rr_allorfirst, STACK_OF(OPENSSL_STRING) *rr_from) { STACK_OF(GENERAL_NAMES) *rct_to, *rct_from; CMS_ReceiptRequest *rr; rct_to = make_names_stack(rr_to); if (!rct_to) goto err; if (rr_from) { rct_from = make_names_stack(rr_from); if (!rct_from) goto err; } else rct_from = NULL; rr = CMS_ReceiptRequest_create0(NULL, -1, rr_allorfirst, rct_from, rct_to); return rr; err: return NULL; } #endif
{ "pile_set_name": "Github" }
#%RAML 1.0 title: Test /url: post: body: application/json: properties: name:
{ "pile_set_name": "Github" }
set(_cmake_oldestSupported "(__GNUC__ * 100 + __GNUC_MINOR__) >= 304") # GNU 4.7 correctly sets __STDC_VERSION__ to 201112L, but GNU 4.6 sets it # to 201000L. As the former is strictly greater than the latter, test only # for the latter. If in the future CMake learns about a C feature which was # introduced with GNU 4.7, that should test for the correct version, similar # to the distinction between __cplusplus and __GXX_EXPERIMENTAL_CXX0X__ tests. set(GNU46_C11 "(__GNUC__ * 100 + __GNUC_MINOR__) >= 406 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201000L") set(_cmake_feature_test_c_static_assert "${GNU46_C11}") # Since 3.4 at least: set(GNU34_C99 "(__GNUC__ * 100 + __GNUC_MINOR__) >= 304 && defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L") set(_cmake_feature_test_c_restrict "${GNU34_C99}") set(_cmake_feature_test_c_variadic_macros "${GNU34_C99}") set(GNU_C90 "${_cmake_oldestSupported}") set(_cmake_feature_test_c_function_prototypes "${GNU_C90}")
{ "pile_set_name": "Github" }
// notty is a new kind of terminal emulator. // Copyright (C) 2015 without boats // // 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 <http://www.gnu.org/licenses/>. use cairo; use pango_sys as pango; #[link(name = "pangocairo-1.0")] extern { pub fn pango_cairo_create_layout(cr: *mut cairo::cairo_t) -> *mut pango::PangoLayout; pub fn pango_cairo_show_layout(cr: *mut cairo::cairo_t, layout: *mut pango::PangoLayout); }
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard. // #import "WAReportBaseItem.h" @class NSString; @interface WAReportKFSessionOpItem : WAReportBaseItem { unsigned int _actionTime; unsigned long long _enterScene; NSString *_sceneID; unsigned long long _action; } @property(nonatomic) unsigned int actionTime; // @synthesize actionTime=_actionTime; @property(nonatomic) unsigned long long action; // @synthesize action=_action; @property(copy, nonatomic) NSString *sceneID; // @synthesize sceneID=_sceneID; @property(nonatomic) unsigned long long enterScene; // @synthesize enterScene=_enterScene; - (void).cxx_destruct; - (id)reportString; @end
{ "pile_set_name": "Github" }
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ //$Id$ package org.hibernate.jpa.test.pack.spacepar; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Bug { @Id @GeneratedValue private Long id; private String subject; @Column(name="`comment`") private String comment; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } }
{ "pile_set_name": "Github" }
[package] name = "aesm-client" version = "0.5.0" authors = ["Fortanix, Inc."] license = "MPL-2.0" description = """ RPC client for Intel SGX AESM (Architectural Enclave Service Manager). With this client, applications can obtain launch tokens for enclaves and turn attestation reports into quotes. """ repository = "https://github.com/fortanix/rust-sgx" documentation = "https://edp.fortanix.com/docs/api/aesm_client/" homepage = "https://edp.fortanix.com/" keywords = ["sgx", "enclave", "psw", "aesm", "aesmd"] categories = ["api-bindings"] autotests = true [[test]] name = "live_quote" required-features = ["test-sgx", "sgxs"] [features] # Enable tests that can only be run on an SGX-enabled environment test-sgx = [] [dependencies] # Project dependencies sgxs = { version = "0.7.0", path = "../sgxs", optional = true } sgx-isa = { version = "0.3.0", path = "../sgx-isa"} # External dependencies byteorder = "1.0" # Unlicense/MIT lazy_static = "1" # MIT/Apache-2.0 protobuf = "2.8.0" # MIT/Apache-2.0 failure = "0.1.1" # MIT/Apache-2.0 failure_derive = "0.1.1" # MIT/Apache-2.0 [target.'cfg(unix)'.dependencies] # We require a version of unix-socket with the following change: # https://github.com/rust-lang-nursery/unix-socket/pull/30 . Alternatively, in # the future, https://github.com/rust-lang/rust/issues/42048 might provide std # support. In addition, we need UnixStream::connect_timeout, which may be # provided by https://github.com/rust-lang/rust/issues/53615. unix_socket2 = "0.5.4" # MIT/Apache-2.0 [target.'cfg(windows)'.dependencies] # External dependencies winapi = { version = "0.3.7", features = ["combaseapi", "enclaveapi", "memoryapi", "objbase"] } libloading = "0.5.2" [build-dependencies] protoc-rust = "2.8.0" # MIT/Apache-2.0 [dev-dependencies] sgx-isa = { version = "0.3.0", path = "../sgx-isa" } "report-test" = { version = "0.3.1", path = "../report-test" } "sgxs-loaders" = { version = "0.3.0", path = "../sgxs-loaders" }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2011, The University of Southampton and the individual contributors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the University of Southampton 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. */ package org.openimaj.util.parallel.partition; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * A {@link GrowingChunkPartitioner} dynamically partitions data into chunks. * The partitioner does not need to know about the length of the data apriori. * The size of the chunks grows over time exponentially. * * @author Jonathon Hare ([email protected]) * * @param <T> Type of object in the partition */ public class GrowingChunkPartitioner<T> implements Partitioner<T> { private static final int NUM_HW_THREADS = Runtime.getRuntime().availableProcessors(); private Iterator<T> objects; /** * Construct with data in the form of an {@link Iterable}. * * @param objects the {@link Iterable} representing the data. */ public GrowingChunkPartitioner(Iterable<T> objects) { this.objects = objects.iterator(); } @Override public Iterator<Iterator<T>> getPartitions() { return new Iterator<Iterator<T>>() { private int currentIteration = 0; private int chunkSize = 2; @Override public boolean hasNext() { synchronized (objects) { return objects.hasNext(); } } @Override public Iterator<T> next() { synchronized (objects) { if (!objects.hasNext()) return null; if (currentIteration % NUM_HW_THREADS == 0) { chunkSize = (int)Math.pow(2, (currentIteration/NUM_HW_THREADS) + 1); } List<T> list = new ArrayList<T>(chunkSize); int i=0; while (objects.hasNext() && i<chunkSize) { list.add(objects.next()); i++; } currentIteration++; return list.iterator(); } } @Override public void remove() { throw new UnsupportedOperationException("Not supported"); } }; } }
{ "pile_set_name": "Github" }
uuid: 4d69c89b-0373-4f55-80f5-97f99a02f5d2 langcode: en status: true dependencies: config: - field.storage.paragraph.field_overview_url - paragraphs.paragraphs_type.docs_and_apis _core: default_config_hash: Xnd_8kIDpyUaGKz3IjlP8tzvh6wdtbJDj0ZR76v50FY id: paragraph.docs_and_apis.field_overview_url field_name: field_overview_url entity_type: paragraph bundle: docs_and_apis label: Url description: 'Used to build the URL for the sub pages. <strong>DO NOT CHANGE</strong>' required: false translatable: true default_value: - value: 'Docs and APIs' default_value_callback: '' settings: { } field_type: string
{ "pile_set_name": "Github" }
#include "llvm/Support/ScopedPrinter.h" #include "llvm/Support/Format.h" #include <cctype> using namespace llvm::support; namespace llvm { raw_ostream &operator<<(raw_ostream &OS, const HexNumber &Value) { OS << "0x" << to_hexString(Value.Value); return OS; } const std::string to_hexString(uint64_t Value, bool UpperCase) { std::string number; llvm::raw_string_ostream stream(number); stream << format_hex_no_prefix(Value, 1, UpperCase); return stream.str(); } void ScopedPrinter::printBinaryImpl(StringRef Label, StringRef Str, ArrayRef<uint8_t> Data, bool Block, uint32_t StartOffset) { if (Data.size() > 16) Block = true; if (Block) { startLine() << Label; if (!Str.empty()) OS << ": " << Str; OS << " (\n"; if (!Data.empty()) OS << format_bytes_with_ascii(Data, StartOffset, 16, 4, (IndentLevel + 1) * 2, true) << "\n"; startLine() << ")\n"; } else { startLine() << Label << ":"; if (!Str.empty()) OS << " " << Str; OS << " (" << format_bytes(Data, None, Data.size(), 1, 0, true) << ")\n"; } } } // namespace llvm
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Flat UI Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Loading Bootstrap --> <link href="css/vendor/bootstrap.min.css" rel="stylesheet"> <!-- Loading Flat UI Pro --> <link href="css/flat-ui.css" rel="stylesheet"> </head> <body> <div class="container"> <h1>Hello, world!</h1> </div> <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!-- Bootstrap 4 requires Popper.js --> <script src="https://unpkg.com/[email protected]/dist/umd/popper.min.js" crossorigin="anonymous"></script> <script src="http://vjs.zencdn.net/6.6.3/video.js"></script> <script src="scripts/flat-ui.js"></script> </body> </html>
{ "pile_set_name": "Github" }
SET @sName = 'bx_invites'; SET @iCategId = (SELECT `id` FROM `sys_options_categories` WHERE `name`=@sName LIMIT 1); DELETE FROM `sys_options` WHERE `name`='bx_invites_enable_reg_by_inv' LIMIT 1; INSERT INTO `sys_options` (`name`, `value`, `category_id`, `caption`, `type`, `check`, `check_error`, `extra`, `order`) VALUES ('bx_invites_enable_reg_by_inv', 'on', @iCategId, '_bx_invites_option_enable_reg_by_inv', 'checkbox', '', '', '', 5);
{ "pile_set_name": "Github" }
K 25 svn:wc:ra_dav:version-url V 41 /svn/!svn/ver/253/trunk/samples/tutorial1 END tutorial1.cpp K 25 svn:wc:ra_dav:version-url V 55 /svn/!svn/ver/253/trunk/samples/tutorial1/tutorial1.cpp END tutorial1.vcproj K 25 svn:wc:ra_dav:version-url V 58 /svn/!svn/ver/235/trunk/samples/tutorial1/tutorial1.vcproj END Makefile K 25 svn:wc:ra_dav:version-url V 50 /svn/!svn/ver/235/trunk/samples/tutorial1/Makefile END
{ "pile_set_name": "Github" }
%---------------------------------------------------------------------------% % vim: ft=mercury ts=4 sw=4 et %---------------------------------------------------------------------------% % Copyright (C) 1995-1997, 2000-2001, 2004-2006, 2011 The University of Melbourne. % This file may only be copied under the terms of the GNU General % Public License - see the file COPYING in the Mercury distribution. %---------------------------------------------------------------------------% % % File: options.m. % Main author: fjh. % % This defines the stuff necessary so that getopt.m can parse the command line % options. % %---------------------------------------------------------------------------% %---------------------------------------------------------------------------% :- module options. :- interface. :- import_module bool. :- import_module getopt. :- import_module io. %---------------------------------------------------------------------------% :- type option % Verbosity options ---> verbose ; very_verbose % Profiler options ; dynamic_cg ; call_graph ; profile ; profile_time ; profile_memory_words ; profile_memory_cells ; demangle % Filename options ; countfile ; pairfile ; declfile ; libraryfile % Snapshot (memory attribution profiling) options ; snapshots ; snapshots_file ; snapshots_by_type ; snapshots_brief ; snapshots_include_runtime ; snapshots_recalc_size % developers only % Miscellaneous Options ; help. :- type option_table == option_table(option). :- pred short_option(character::in, option::out) is semidet. :- pred long_option(string::in, option::out) is semidet. :- pred option_default(option::out, option_data::out) is multi. :- pred special_handler(option::in, special_data::in, option_table::in, maybe_option_table(option)::out) is semidet. :- pred options_help(io::di, io::uo) is det. % A couple of misc utilities :- pred maybe_write_string(bool::input, string::input, io::di, io::uo) is det. :- pred maybe_flush_output(bool::in, io::di, io::uo) is det. %---------------------------------------------------------------------------% %---------------------------------------------------------------------------% :- implementation. :- import_module map. %---------------------------------------------------------------------------% % please keep this in alphabetic order short_option('b', snapshots_brief). short_option('C', countfile). short_option('c', call_graph). short_option('d', dynamic_cg). short_option('D', declfile). short_option('h', help). short_option('L', libraryfile). short_option('m', profile_memory_words). short_option('M', profile_memory_cells). short_option('p', profile). short_option('P', pairfile). short_option('r', snapshots_include_runtime). short_option('s', snapshots). short_option('t', profile_time). short_option('T', snapshots_by_type). short_option('v', verbose). short_option('V', very_verbose). long_option("call-pair-file", pairfile). long_option("call-graph", call_graph). long_option("count-file", countfile). long_option("declaration-file", declfile). long_option("demangle", demangle). long_option("help", help). % XXX: what is this doing here? long_option("library-callgraph", help). long_option("profile", profile). long_option("profile-memory-words", profile_memory_words). long_option("profile-memory-cells", profile_memory_cells). long_option("profile-time", profile_time). long_option("snapshots", snapshots). long_option("snapshots-brief", snapshots_brief). long_option("snapshots-by-type", snapshots_by_type). long_option("snapshots-file", snapshots_file). long_option("snapshots-include-runtime", snapshots_include_runtime). long_option("snapshots-recalc-size", snapshots_recalc_size). long_option("use-dynamic", dynamic_cg). long_option("verbose", verbose). long_option("very-verbose", very_verbose). % Verbosity Options option_default(verbose, bool(no)). option_default(very_verbose, bool(no)). % General profiler options option_default(dynamic_cg, bool(no)). option_default(call_graph, bool(no)). option_default(profile, string_special). option_default(profile_time, special). option_default(profile_memory_words, special). option_default(profile_memory_cells, special). option_default(countfile, string("Prof.Counts")). option_default(pairfile, string("Prof.CallPair")). option_default(declfile, string("Prof.Decl")). option_default(libraryfile, string("")). option_default(demangle, bool(yes)). option_default(snapshots, bool(no)). option_default(snapshots_file, string("Prof.Snapshots")). option_default(snapshots_by_type, bool(no)). option_default(snapshots_brief, bool(no)). option_default(snapshots_include_runtime, bool(no)). option_default(snapshots_recalc_size, bool(yes)). % Miscellaneous Options option_default(help, bool(no)). special_handler(profile, string(WhatToProfile), !.OptionTable, Result) :- ( if valid_profile_option(WhatToProfile, CountFile) then map.set(countfile, string(CountFile), !OptionTable), Result = ok(!.OptionTable) else Result = error("Invalid argument to `--profile' or `-p' option") ). special_handler(profile_memory_words, _, !.OptionTable, ok(!:OptionTable)) :- map.set(countfile, string("Prof.MemoryWords"), !OptionTable). special_handler(profile_memory_cells, _, !.OptionTable, ok(!:OptionTable)) :- map.set(countfile, string("Prof.MemoryCells"), !OptionTable). special_handler(profile_time, _, !.OptionTable, ok(!:OptionTable)) :- map.set(countfile, string("Prof.Counts"), !OptionTable). :- pred valid_profile_option(string::in, string::out) is semidet. valid_profile_option("memory-words", "Prof.MemoryWords"). valid_profile_option("memory-cells", "Prof.MemoryCells"). valid_profile_option("time", "Prof.Counts"). options_help --> io.write_string("\t-h, --help\n"), io.write_string("\t\tPrint this usage message.\n"), io.write_string("\nProfiler Options:\n"), io.write_string("\t-c, --call-graph\n"), io.write_string("\t\tInclude the call graph profile.\n"), io.write_string("\t-d, --use-dynamic\n"), io.write_string("\t\tBuild the call graph dynamically.\n"), io.write_string("\t-p, --profile {time, memory-words, memory-cells}\n"), io.write_string("\t\tSelect what to profile: time, amount of memory allocated, or\n"), io.write_string("\t\tnumber of memory allocations (regardless of size).\n"), io.write_string("\t-m\n"), io.write_string("\t\tSame as `--profile memory-words'\n"), io.write_string("\t-M\n"), io.write_string("\t\tSame as `--profile memory-cells'.\n"), io.write_string("\t-t\n"), io.write_string("\t\tSame as `--profile time'.\n"), io.write_string("\t--no-demangle\n"), io.write_string("\t\tOutput the mangled predicate and function names.\n"), io.write_string("\nFilename Options:\n"), io.write_string("\t-C <file>, --count-file <file>\n"), io.write_string("\t\tName of the count file. Usually `Prof.Counts',\n"), io.write_string("\t\t`Prof.MemoryWords', or `Prof.MemoryCells'.\n"), io.write_string("\t-D <file>, --declaration-file <file>\n"), io.write_string("\t\tName of the declaration file. Usually `Prof.Decl'.\n"), io.write_string("\t-P <file>, --call-pair-file <file>\n"), io.write_string("\t\tName of the call-pair file. Usually `Prof.CallPair'.\n"), io.write_string("\t-L <file>, --library-callgraph <file>\n"), io.write_string("\t\tName of the file which contains the call graph for\n"), io.write_string("\t\tthe library modules.\n"), io.write_string("\nSnapshot options:\n"), io.write_string("\t-s, --snapshots\n"), io.write_string("\t\tShow summary of heap objects at the times\n"), io.write_string("\t\t`benchmarking.report_memory_attribution' was called.\n"), io.write_string("\t\tThis overrides other profiler modes.\n"), io.write_string("\t--snapshots-file <file>\n"), io.write_string("\t\tName of the snapshots file. Usually `Prof.Snapshots'.\n"), io.write_string("\t-T, --snapshots-by-type\n"), io.write_string("\t\tGroup results by type.\n"), io.write_string("\t-b, --snapshots-brief\n"), io.write_string("\t\tGenerate a brief profile.\n"), io.write_string("\t-r, --snapshots-include-runtime\n"), io.write_string("\t\tInclude internal Mercury runtime structures in the\n"), io.write_string("\t\tprofile. These are excluded by default.\n"), io.write_string("\nVerbosity Options:\n"), io.write_string("\t-v, --verbose\n"), io.write_string("\t\tOutput progress messages at each stage.\n"), io.write_string("\t-V, --very-verbose\n"), io.write_string("\t\tOutput very verbose progress messages.\n"). %---------------------------------------------------------------------------% maybe_write_string(yes, String, !IO) :- io.write_string(String, !IO). maybe_write_string(no, _, !IO). maybe_flush_output(yes, !IO) :- io.flush_output(!IO). maybe_flush_output(no, !IO). %---------------------------------------------------------------------------% :- end_module options. %---------------------------------------------------------------------------%
{ "pile_set_name": "Github" }
/* eslint-disable max-len */ import { nativeImage } from 'electron'; import { fixPathForAsarUnpack } from 'electron-util'; import * as path from 'path'; declare const __static; const searchEngine = [ { name: 'Google', search: 'https://www.google.com/search?ie=UTF-8&q={queryString}', autocomplete: 'https://www.google.com/complete/search?client=chrome&q={queryString}', }, { name: 'Bing', search: 'http://www.bing.com/search?setmkt={language}&q={queryString}', autocomplete: 'http://api.bing.com/osjson.aspx?query={queryString}&language={language}', }, { name: 'Yahoo!', search: 'http://search.yahoo.com/search?ei=UTF-8&fr=crmas&p={queryString}', autocomplete: 'http://ff.search.yahoo.com/gossip?output=fxjson&command={queryString}', }, { name: 'Yahoo! UK & Ireland', search: 'http://uk.search.yahoo.com/search?ei=UTF-8&fr=crmas&p={queryString}', autocomplete: 'http://uk-sayt.ff.search.yahoo.com/gossip-uk-sayt?output=fxjson&command={queryString}', }, { name: 'Yahoo! JAPAN', search: 'http://search.yahoo.co.jp/search?ei=UTF-8&fr=crmas&p={queryString}', autocomplete: 'http://search.yahooapis.jp/AssistSearchService/V2/webassistSearch?appid=oQsoxcyxg66enp0TYoirkKoryq6rF8bK76mW0KYxZ0v0WPLtn.Lix6wy8F_LwGWHUII-&output=iejson&p={queryString}', }, { name: 'Daum', search: 'http://search.daum.net/search?q={queryString}', autocomplete: 'http://sug.search.daum.net/search_nsuggest?mod=fxjson&q={queryString}', }, { name: 'Naver', search: 'http://search.naver.com/search.naver?ie=UTF-8&query={queryString}', autocomplete: 'http://ac.search.naver.com/nx/ac?of=os&ie=utf-8&q={queryString}', }, { name: 'StartPage', search: 'https://www.startpage.com/do/dsearch?prfe=36c84513558a2d34bf0d89ea505333ad9c86bd6598735d590adc2e9be9271a9b5065027ac0acf3048b0efafd7d93a95c&query={queryString}', autocomplete: 'https://www.startpage.com/do/suggest?limit=10&format=json&query={queryString}&prfe=36c84513558a2d34bf0d89ea505333ad9c86bd6598735d590adc2e9be9271a9b5065027ac0acf3048b0efafd7d93a95c', }, ]; const homepage = 'https://github.com/LulumiProject/lulumi-browser'; const pdfViewer = 'pdf-viewer'; const tabConfig: Lulumi.Store.TabConfig = { dummyTabObject: { webContentsId: -1, id: -1, index: -1, windowId: -1, highlighted: false, active: false, pinned: false, url: 'about:newtab', title: null, favIconUrl: null, status: null, incognito: false, statusText: false, isLoading: false, didNavigate: false, isSearching: false, canGoBack: false, canGoForward: false, canRefresh: false, error: false, hasMedia: false, isAudioMuted: false, pageActionMapping: {}, extensionsMetadata: {}, }, lulumiDefault: { systemFavicon: nativeImage .createFromPath(fixPathForAsarUnpack(path.join(__static, 'icons', 'icon.png'))) .toDataURL(), tabFavicon: 'document', commandPalette: { browsingHistory: 'reading', onlineSearch: 'view', }, }, }; const proxyConfig: Electron.Config = { pacScript: '', proxyRules: '', proxyBypassRules: '', }; // Top 500 alexa sites sorted by popularity const recommendTopSite: Lulumi.Renderer.SuggestionItem[] = [ { title: 'Gmail', value: 'gmail.com', url: 'gmail.com', icon: 'document', }, { title: 'Google', value: 'google.com', url: 'google.com', icon: 'document', }, { title: 'Gmail', value: 'mail.google.com', url: 'mail.google.com', icon: 'document', }, { title: 'Google Calendar', value: 'calendar.google.com', url: 'calendar.google.com', icon: 'document', }, { title: 'Facebook', value: 'facebook.com', url: 'facebook.com', icon: 'document', }, { title: 'Youtube', value: 'youtube.com', url: 'youtube.com', icon: 'document', }, { title: 'Yahoo', value: 'yahoo.com', url: 'yahoo.com', icon: 'document', }, { title: 'Baidu', value: 'baidu.com', url: 'baidu.com', icon: 'document', }, { title: 'Wikipedia', value: 'wikipedia.com', url: 'wikipedia.com', icon: 'document', }, { title: 'Twitter', value: 'twitter.com', url: 'twitter.com', icon: 'document', }, { title: 'Linkedin', value: 'linkedin.com', url: 'linkedin.com', icon: 'document', }, { title: 'Pinterest', value: 'pinterest.com', url: 'pinterest.com', icon: 'document', }, { title: 'Tumblr', value: 'tumblr.com', url: 'tumblr.com', icon: 'document', }, { title: 'Apple', value: 'apple.com', url: 'apple.com', icon: 'document', }, { title: 'Imgur', value: 'imgur.com', url: 'imgur.com', icon: 'document', }, { title: 'Stack Overflow', value: 'stackoverflow.com', url: 'stackoverflow.com', icon: 'document', }, { title: 'Reddit', value: 'reddit.com', url: 'reddit.com', icon: 'document', }, { title: 'FC2', value: 'fc2.com', url: 'fc2.com', icon: 'document', }, { title: 'Flickr', value: 'flickr.com', url: 'flickr.com', icon: 'document', }, { title: 'Netflix', value: 'netflix.com', url: 'netflix.com', icon: 'document', }, { title: 'Dropbox', value: 'dropbox.com', url: 'dropbox.com', icon: 'document', }, { title: 'Google Taiwan', value: 'google.com.tw', url: 'google.com.tw', icon: 'document', }, { title: 'Github', value: 'github.com', url: 'github.com', icon: 'document', }, { title: 'PHP', value: 'php.net', url: 'php.net', icon: 'document', }, { title: 'Twitch', value: 'twitch.tv', url: 'twitch.tv', icon: 'document', }, { title: '9GAG', value: '9gag.com', url: '9gag.com', icon: 'document', }, { title: 'eyny', value: 'eyny.com', url: 'eyny.com', icon: 'document', }, { title: 'Quora', value: 'quora.com', url: 'quora.com', icon: 'document', }, { title: 'CTFtime', value: 'ctftime.org', url: 'ctftime.org', icon: 'document', }, { title: '巴哈姆特電玩資訊站', value: 'gamer.com.tw', url: 'gamer.com.tw', icon: 'document', }, ]; export default { tabConfig, proxyConfig, searchEngine, homepage, pdfViewer, recommendTopSite, lulumiPagesCustomProtocol: 'lulumi', aboutPages: { about: 'List of about pages', }, currentSearchEngine: searchEngine[0], autoFetch: false, };
{ "pile_set_name": "Github" }
/* $Id: base64.c,v 1.4 2001/03/15 08:32:59 dugsong Exp $ * * Copyright (c) 1996 by Internet Software Consortium. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS * SOFTWARE. */ /* * Portions Copyright (c) 1995 by International Business Machines, Inc. * * International Business Machines, Inc. (hereinafter called IBM) grants * permission under its copyrights to use, copy, modify, and distribute this * Software with or without fee, provided that the above copyright notice and * all paragraphs of this notice appear in all copies, and that the name of IBM * not be used in connection with the marketing of any product incorporating * the Software or modifications thereof, without specific, written prior * permission. * * To the extent it has a right to do so, IBM grants an immunity from suit * under its patents, if any, for the use, sale or manufacture of products to * the extent that such products are used for performing Domain Name System * dynamic updates in TCP/IP networks by means of the Software. No immunity is * granted for any product per se or for any other function of any product. * * THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL, * DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN * IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES. */ #include <sys/types.h> #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "base64.h" #define Assert(Cond) if (!(Cond)) abort() static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static const char Pad64 = '='; /* (From RFC1521 and draft-ietf-dnssec-secext-03.txt) The following encoding technique is taken from RFC 1521 by Borenstein and Freed. It is reproduced here in a slightly edited form for convenience. A 65-character subset of US-ASCII is used, enabling 6 bits to be represented per printable character. (The extra 65th character, "=", is used to signify a special processing function.) The encoding process represents 24-bit groups of input bits as output strings of 4 encoded characters. Proceeding from left to right, a 24-bit input group is formed by concatenating 3 8-bit input groups. These 24 bits are then treated as 4 concatenated 6-bit groups, each of which is translated into a single digit in the base64 alphabet. Each 6-bit group is used as an index into an array of 64 printable characters. The character referenced by the index is placed in the output string. Table 1: The Base64 Alphabet Value Encoding Value Encoding Value Encoding Value Encoding 0 A 17 R 34 i 51 z 1 B 18 S 35 j 52 0 2 C 19 T 36 k 53 1 3 D 20 U 37 l 54 2 4 E 21 V 38 m 55 3 5 F 22 W 39 n 56 4 6 G 23 X 40 o 57 5 7 H 24 Y 41 p 58 6 8 I 25 Z 42 q 59 7 9 J 26 a 43 r 60 8 10 K 27 b 44 s 61 9 11 L 28 c 45 t 62 + 12 M 29 d 46 u 63 / 13 N 30 e 47 v 14 O 31 f 48 w (pad) = 15 P 32 g 49 x 16 Q 33 h 50 y Special processing is performed if fewer than 24 bits are available at the end of the data being encoded. A full encoding quantum is always completed at the end of a quantity. When fewer than 24 input bits are available in an input group, zero bits are added (on the right) to form an integral number of 6-bit groups. Padding at the end of the data is performed using the '=' character. Since all base64 input is an integral number of octets, only the ------------------------------------------------- following cases can arise: (1) the final quantum of encoding input is an integral multiple of 24 bits; here, the final unit of encoded output will be an integral multiple of 4 characters with no "=" padding, (2) the final quantum of encoding input is exactly 8 bits; here, the final unit of encoded output will be two characters followed by two "=" padding characters, or (3) the final quantum of encoding input is exactly 16 bits; here, the final unit of encoded output will be three characters followed by one "=" padding character. */ /* skips all whitespace anywhere. converts characters, four at a time, starting at (or after) src from base - 64 numbers into three 8 bit bytes in the target area. it returns the number of data bytes stored at the target, or -1 on error. */ int base64_pton(src, target, targsize) char const *src; u_char *target; size_t targsize; { int tarindex, state, ch; char *pos; state = 0; tarindex = 0; while ((ch = *src++) != '\0') { if (isspace(ch)) /* Skip whitespace anywhere. */ continue; if (ch == Pad64) break; pos = strchr(Base64, ch); if (pos == 0) /* A non-base64 character. */ return (-1); switch (state) { case 0: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] = (pos - Base64) << 2; } state = 1; break; case 1: if (target) { if (tarindex + 1 >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 4; target[tarindex+1] = ((pos - Base64) & 0x0f) << 4 ; } tarindex++; state = 2; break; case 2: if (target) { if (tarindex + 1 >= targsize) return (-1); target[tarindex] |= (pos - Base64) >> 2; target[tarindex+1] = ((pos - Base64) & 0x03) << 6; } tarindex++; state = 3; break; case 3: if (target) { if (tarindex >= targsize) return (-1); target[tarindex] |= (pos - Base64); } tarindex++; state = 0; break; } } /* * We are done decoding Base-64 chars. Let's see if we ended * on a byte boundary, and/or with erroneous trailing characters. */ if (ch == Pad64) { /* We got a pad char. */ ch = *src++; /* Skip it, get next. */ switch (state) { case 0: /* Invalid = in first position */ case 1: /* Invalid = in second position */ return (-1); case 2: /* Valid, means one byte of info */ /* Skip any number of spaces. */ for (; ch != '\0'; ch = *src++) if (!isspace(ch)) break; /* Make sure there is another trailing = sign. */ if (ch != Pad64) return (-1); ch = *src++; /* Skip the = */ /* Fall through to "single trailing =" case. */ /* FALLTHROUGH */ case 3: /* Valid, means two bytes of info */ /* * We know this char is an =. Is there anything but * whitespace after it? */ for (; ch != '\0'; ch = *src++) if (!isspace(ch)) return (-1); /* * Now make sure for cases 2 and 3 that the "extra" * bits that slopped past the last full byte were * zeros. If we don't check them, they become a * subliminal channel. */ if (target && target[tarindex] != 0) return (-1); } } else { /* * We ended by seeing the end of the string. Make sure we * have no partial bytes lying around. */ if (state != 0) return (-1); } return (tarindex); }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013 Cameron White * * 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/>. */ #ifndef SCORE_FILEVERSION_H #define SCORE_FILEVERSION_H #include <cstdint> enum class FileVersion : int { /// Initial version from the beginning of development. INITIAL_VERSION = 1, /// Added floating text items. TEXT_ITEMS = 2, /// Removed the Staff::myViewType member and added view filters. VIEW_FILTERS = 3, /// Added left hand fingering numbers to notes. LEFT_HAND_FINGERING = 4, /// Added a thumb option to left hand fingerings. LEFT_HAND_FINGERING_THUMB = 5, /// Added a subtitle to the score info. SONG_SUBTITLE = 6, /// Added volume swells. VOLUME_SWELLS = 7, LATEST_VERSION = VOLUME_SWELLS }; #endif
{ "pile_set_name": "Github" }
xLearn Python Package Guide ^^^^^^^^^^^^^^^^^^^^^^^^^^^ xLearn supports very easy-to-use Python API for users. Once you install the xLearn Python package successfully, you can try it. Type ``python`` in your shell and type the following Python code to check your installation: :: import xlearn as xl xl.hello() If you install xLearn Python package successfully, you will see :: ------------------------------------------------------------------------- _ | | __ _| | ___ __ _ _ __ _ __ \ \/ / | / _ \/ _` | '__| '_ \ > <| |___| __/ (_| | | | | | | /_/\_\_____/\___|\__,_|_| |_| |_| xLearn -- 0.44 Version -- ------------------------------------------------------------------------- Quick Start ---------------------------------------- Here is a simple Python demo to demonstrate how to use xLearn. You can checkout the demo data (``small_train.txt`` and ``small_test.txt``) from the path ``demo/classification/criteo_ctr``. .. code-block:: python import xlearn as xl # Training task ffm_model = xl.create_ffm() # Use field-aware factorization machine ffm_model.setTrain("./small_train.txt") # Training data ffm_model.setValidate("./small_test.txt") # Validation data # param: # 0. binary classification # 1. learning rate : 0.2 # 2. regular lambda : 0.002 param = {'task':'binary', 'lr':0.2, 'lambda':0.002} # Train model ffm_model.fit(param, "./model.out") A portion of the xLearn's output :: Start to train ... Epoch Train log_loss Test log_loss Time cost (sec) 1 0.593750 0.535847 0.00 2 0.539226 0.543829 0.00 3 0.520034 0.531732 0.00 4 0.505186 0.537418 0.00 5 0.494089 0.533448 0.00 6 0.483678 0.534629 0.00 7 0.470848 0.528086 0.00 8 0.466330 0.533253 0.00 9 0.456660 0.535635 0.00 Early-stopping at epoch 7 Start to save model ... In this example, xLearn uses *field-ware factorization machines* (ffm) to train our model for solving a binary classification task. If you want train a model for regression task. You can reset the ``task`` parameter to ``reg``. :: param = {'task':'reg', 'lr':0.2, 'lambda':0.002} We can see that a new file called ``model.out`` has been generated in the current directory. This file stores the trained model checkpoint, and we can use this model file to make prediction in the future: :: ffm_model.setTest("./small_test.txt") ffm_model.predict("./model.out", "./output.txt") After we run this Python code, we can get a new file called ``output.txt`` in current directory. This is output prediction. Here we show the first five lines of this output by using the following command :: head -n 5 ./output.txt -1.66107 -0.616408 -0.815918 -0.608931 -1.30794 These lines of data are the prediction score calculated for examples in the test set. The negative data represents the negative example and positive data represents the positive example. In xLearn, you can convert the score to (0-1) by using ``setSigmoid()`` option: :: ffm_model.setTest("./small_test.txt") ffm_model.setSigmoid() ffm_model.predict("./model.out", "./output.txt") and then we can get the result :: head -n 5 ./output.txt 0.158613 0.354297 0.310193 0.357449 0.220061 We can also convert the score to binary result ``(0 and 1)`` by using ``setSign()`` API :: # Prediction task ffm_model.setTest("./small_test.txt") ffm_model.setSign() ffm_model.predict("./model.out", "./output.txt") and then we can get the result :: head -n 5 ./output.txt 0 0 0 0 0 Also, users can save the model in txt format by using ``setTXTModel()`` API. For example: :: ffm_model.setTXTModel("./model.txt") After that, we get a new file called ``model.txt``, which stores the trained model in txt format.:: head -n 5 ./model.txt -0.688182 0.458082 0 0 0 For the linear and bias term, we store each parameter in each line. For FM and FFM, we store one vector of the latent factor in each line. Choose Machine Learning Algorithm ---------------------------------------- For now, xLearn can support three different machine learning algorithms, including LR, FM and FFM. Users can choose different machine learning algorithms by using ``create_xxx()`` API: :: import xlearn as xl ffm_model = xl.create_ffm() fm_model = xl.create_fm() lr_model = xl.create_lr() For LR and FM, the input data format can be ``CSV`` or ``libsvm``. For FFM, the input data should be the ``libffm`` format. :: libsvm format: label index_1:value_1 index_2:value_2 ... index_n:value_n CSV format: value_1 value_2 .. value_n label libffm format: label field_1:index_1:value_1 field_2:index_2:value_2 ... Users can also give a libffm file to LR and FM. At that time, xLearn will treat this data as libsvm format. Set Validation Dataset ---------------------------------------- A validation dataset is used to tune the hyperparameters of a machine learning model. In xLearn, users can use ``setValdiate()`` API to set the validation dataset. For example: :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.setValidate("./small_test.txt") param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.fit(param, "./model.out") A portion of xLearn's output: :: Epoch Train log_loss Test log_loss Time cost (sec) 1 0.598814 0.536327 0.00 2 0.539872 0.542924 0.00 3 0.521035 0.531595 0.00 4 0.505414 0.536246 0.00 5 0.492150 0.532070 0.00 6 0.482229 0.536482 0.00 7 0.470457 0.528871 0.00 8 0.464445 0.534550 0.00 9 0.456061 0.537320 0.00 Here we can see that the training loss continuously goes down. But the validation loss (test loss) goes down first, and then goes up. This is because our model has already overfitted current training dataset. By default, xLearn will calculate the validation loss in each epoch, while users can also set different evaluation metrics by using ``metric`` parameter. For classification problems, the metric can be : ``acc`` (accuracy), ``prec`` (precision), ``f1`` (f1 score), and ``auc`` (AUC score). For example: :: param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'metric': 'acc'} param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'metric': 'prec'} param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'metric': 'f1'} param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'metric': 'auc'} For regression problems, the metric can be ``mae``, ``mape``, and ``rmsd`` (rmse). For example: :: param = {'task':'reg', 'lr':0.2, 'lambda':0.002, 'metric': 'rmse'} param = {'task':'reg', 'lr':0.2, 'lambda':0.002, 'metric': 'mae'} param = {'task':'reg', 'lr':0.2, 'lambda':0.002, 'metric': 'mape'} Cross-Validation ---------------------------------------- Cross-validation, sometimes called rotation estimation, is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent dataset. In xLearn, users can use the ``cv()`` API to use this technique. For example: :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.cv(param) On default, xLearn uses 5-folds cross validation, and users can set the number of fold by using the ``fold`` parameter: :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'fold':3} ffm_model.cv(param) Here we set the number of folds to 3. The xLearn will calculate the average validation loss at the end of its output message. :: [------------] Average log_loss: 0.547632 [ ACTION ] Finish Cross-Validation [ ACTION ] Clear the xLearn environment ... [------------] Total time cost: 0.05 (sec) Choose Optimization Method ---------------------------------------- In xLearn, users can choose different optimization methods by using ``opt`` parameter. For now, users can choose ``sgd``, ``adagrad``, and ``ftrl`` method. By default, xLearn uses the ``adagrad`` method. For example: :: param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'opt':'sgd'} param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'opt':'adagrad'} param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'opt':'ftrl'} Compared to traditional sgd method, adagrad adapts the learning rate to the parameters, performing larger updates for infrequent and smaller updates for frequent parameters. For this reason, it is well-suited for dealing with sparse data. In addition, sgd is more sensitive to the learning rate compared with adagrad. FTRL (Follow-the-Regularized-Leader) is also a famous method that has been widely used in the large-scale sparse problem. To use FTRL, users need to tune more hyperparameters compared with sgd and adagard. Hyperparameter Tuning ---------------------------------------- In machine learning, a *hyperparameter* is a parameter whose value is set before the learning process begins. By contrast, the value of other parameters is derived via training. Hyperparameter tuning is the problem of choosing a set of optimal hyperparameters for a learning algorithm. First, the ``learning rate`` is one of the most important hyperparameters used in machine learning. By default, this value is set to 0.2, and we can tune this value by using ``lr`` parameter: :: param = {'task':'binary', 'lr':0.2} param = {'task':'binary', 'lr':0.5} param = {'task':'binary', 'lr':0.01} We can also use the ``lambda`` parameter to perform regularization. By default, xLearn uses L2 regularization, and the *regular_lambda* has been set to ``0.00002``. :: param = {'task':'binary', 'lr':0.2, 'lambda':0.01} param = {'task':'binary', 'lr':0.2, 'lambda':0.02} param = {'task':'binary', 'lr':0.2, 'lambda':0.002} For the FTRL method, we also need to tune another four hyperparameters, including ``alpha``, ``beta``, ``lambda_1``, and ``lambda_2``. For example: :: param = {'alpha':0.002, 'beta':0.8, 'lambda_1':0.001, 'lambda_2': 1.0} For FM and FFM, users also need to set the size of latent factor by using ``k`` parameter. By default, xLearn uses ``4`` for this value. :: param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'k':2} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'k':4} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'k':5} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'k':8} xLearn uses *SSE* instruction to accelerate vector operation, and hence the time cost for ``k=2`` and ``k=4`` are the same. For FM and FFM, users can also set the parameter ``init`` for model initialization. By default, this value is set to ``0.66``. param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'init':0.5} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'init':0.8} Set Epoch Number and Early-Stopping ---------------------------------------- For machine learning, one epoch consists of one full training cycle on the training set. In xLearn, users can set the number of epoch for training by using ``epoch`` option. :: param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'epoch':3} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'epoch':5} param = {'task':'binary', 'lr':0.2, 'lambda':0.01, 'epoch':10} If you set the validation data, xLearn will perform early-stopping by default. For example: :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.setValidate("./small_test.txt") param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'epoch':10} ffm_model.fit(param, "./model.out") Here, we set epoch number to ``10``, but xLearn stopped at epoch ``7`` because we get the best model at that epoch (you may get different a stopping number on your machine) :: Early-stopping at epoch 7 Start to save model ... Users can set stop window for early-stopping by using ``stop_window`` parameter :: param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'epoch':10, 'stop_window':3} ffm_model.fit(param, "./model.out") Users can disable early-stopping by using ``disableEarlyStop()`` API: :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.setValidate("./small_test.txt") ffm_model.disableEarlyStop(); param = {'task':'binary', 'lr':0.2, 'lambda':0.002, 'epoch':10} ffm_model.fit(param, "./model.out") At this time, xLearn performed 10 epoch for training. Lock-Free Training ---------------------------------------- By default, xLearn performs *Hogwild! lock-free* training, which takes advantages of multiple cores to accelerate training task. But lock-free training is *non-deterministic*. For example, if we run the following Python code multiple times, we may get different loss value at each epoch. :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.fit(param, "./model.out") The 1st time: 0.449056 The 2nd time: 0.449302 The 3nd time: 0.449185 Users can disable lock-free training by using ``disableLockFree()`` API. :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.disableLockFree() param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.fit(param, "./model.out") In this time, our result are *deterministic*. :: The 1st time: 0.449172 The 2nd time: 0.449172 The 3nd time: 0.449172 The disadvantage of ``disableLockFree()`` is that it is much slower than lock-free training. Instance-wise Normalization ---------------------------------------- For FM and FFM, xLearn uses instance-wise normalization by default. In some scenes like CTR prediction, this technique is very useful. But sometimes it hurts model performance. Users can disable *instance-wise normalization* by using ``disableNorm()`` API. :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.disableNorm() param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.fit(param, "./model.out") Note that we usually use ``disableNorm`` in regression tasks. Quiet Training ---------------------------------------- When using ``setQuiet()`` API, xLearn will not calculate any evaluation information during the training, and it just train the model quietly :: import xlearn as xl # Training task ffm_model = xl.create_ffm() ffm_model.setTrain("./small_train.txt") ffm_model.setQuiet() param = {'task':'binary', 'lr':0.2, 'lambda':0.002} ffm_model.fit(param, "./model.out") In this way, xLearn can accelerate its training speed. Scikit-learn api for xLearn ---------------------------------------- xLearn can support scikit-learn-like api for users. Here is an example: :: import numpy as np import xlearn as xl from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split # Load dataset iris_data = load_iris() X = iris_data['data'] y = (iris_data['target'] == 2) X_train, \ X_val, \ y_train, \ y_val = train_test_split(X, y, test_size=0.3, random_state=0) # param: # 0. binary classification # 1. model scale: 0.1 # 2. epoch number: 10 (auto early-stop) # 3. learning rate: 0.1 # 4. regular lambda: 1.0 # 5. use sgd optimization method linear_model = xl.LRModel(task='binary', init=0.1, epoch=10, lr=0.1, reg_lambda=1.0, opt='sgd') # Start to train linear_model.fit(X_train, y_train, eval_set=[X_val, y_val], is_lock_free=False) # Generate predictions y_pred = linear_model.predict(X_val) In this example, we use linear model to train a binary classifier. We can also create FM and FFM by using ``xl.FMModel()`` and ``xl.FMModel()`` . Please see the details of these examples in (`Link`__) .. __: https://github.com/aksnzhy/xlearn/tree/master/demo/classification/scikit_learn_demo .. toctree:: :hidden:
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/bottom_button" style="@style/Widget.AppCompat.Button.Colored" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:enabled="true" android:text="Do not press" /> </RelativeLayout> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="325dp" android:fitsSystemWindows="true" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <com.google.android.material.appbar.CollapsingToolbarLayout android:layout_width="match_parent" android:layout_height="match_parent" app:contentScrim="?colorPrimary" app:expandedTitleMarginStart="48dp" app:layout_scrollFlags="scroll|exitUntilCollapsed"> <androidx.appcompat.widget.Toolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" app:layout_collapseMode="pin"> </androidx.appcompat.widget.Toolbar> </com.google.android.material.appbar.CollapsingToolbarLayout> </com.google.android.material.appbar.AppBarLayout> </androidx.coordinatorlayout.widget.CoordinatorLayout>
{ "pile_set_name": "Github" }
浦野美波最新番号 【MMV-140】初脱ぎ熟女 59</a>2008-01-07クリスタル映像$$$MADAM MANI119分钟
{ "pile_set_name": "Github" }
; ; udata is a bit special we have to copy it on a task switch as we've ; got almost no common memory space on the simple board design ; .file "commonmem" .mode mshort ; exported symbols .globl _ub .globl udata .globl kstack_top .globl istack_top .globl istack_switched_sp .sect .udata .comm udata,512,1 .comm kstack_top,0,1 .comm istack_base,254,1 .comm istack_top,2,1 .comm istack_switched_sp,2,1
{ "pile_set_name": "Github" }
// // Generated by class-dump 3.5 (64 bit) (Debug version compiled Jun 9 2015 22:53:21). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2014 by Steve Nygard. // #import "MacBuddyViewController.h" @class IASUnifiedProgressClient, NSString, NSTimer; @interface ProgressViewController : MacBuddyViewController { float _progressValue; NSString *_progressMessage; IASUnifiedProgressClient *_progressClient; NSTimer *_shutdownTimer; } @property(retain) NSTimer *shutdownTimer; // @synthesize shutdownTimer=_shutdownTimer; @property(retain) IASUnifiedProgressClient *progressClient; // @synthesize progressClient=_progressClient; @property float progressValue; // @synthesize progressValue=_progressValue; @property(retain) NSString *progressMessage; // @synthesize progressMessage=_progressMessage; - (void).cxx_destruct; - (void)forwardPaneWithHandler:(CDUnknownBlockType)arg1; - (void)performEOSHealing; - (void)didBecomeVisible; - (void)willBecomeVisible; - (id)nextViewIdentifier; - (id)manager; - (id)init; @end
{ "pile_set_name": "Github" }
package com.haoxy.thymeleaf.controller; import com.haoxy.thymeleaf.model.Message; import com.haoxy.thymeleaf.repository.MessageRepository; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.validation.Valid; /** * Created by hxy on 2018/6/13. * E-mail:[email protected] * github:https://github.com/haoxiaoyong1014 */ @Controller @RequestMapping("/") public class MessageController { private final MessageRepository messageRepository; public MessageController(MessageRepository messageRepository) { this.messageRepository = messageRepository; } @GetMapping public ModelAndView list() { Iterable<Message> messages = this.messageRepository.findAll(); return new ModelAndView("messages/list", "messages", messages); } @GetMapping("{id}") public ModelAndView view(@PathVariable("id") Message message) { return new ModelAndView("messages/view", "message", message); } @GetMapping(params = "form") public String createForm(@ModelAttribute Message message) { return "messages/form"; } @PostMapping(value = "add") public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) { if (result.hasErrors()) { return new ModelAndView("messages/form", "formErrors", result.getAllErrors()); } message = this.messageRepository.save(message); redirect.addFlashAttribute("globalMessage", "Successfully created a new message"); return new ModelAndView("redirect:/{message.id}", "message.id", message.getId()); } @RequestMapping("foo") public String foo() { throw new RuntimeException("Expected exception in controller"); } @GetMapping(value = "delete/{id}") public ModelAndView delete(@PathVariable("id") Long id) { this.messageRepository.deleteMessage(id); Iterable<Message> messages = this.messageRepository.findAll(); return new ModelAndView("messages/list", "messages", messages); } @GetMapping(value = "modify/{id}") public ModelAndView modifyForm(@PathVariable("id") Message message) { return new ModelAndView("messages/form", "message", message); } }
{ "pile_set_name": "Github" }
using System; using System.Threading.Tasks; using OpenTracing; namespace OpenTracing.Examples.MultipleCallbacks { public class Client { private readonly ITracer _tracer; public Client(ITracer tracer) { _tracer = tracer; } public async Task<string> Send<T>(T message, long milliseconds) { using (IScope scope = _tracer.BuildSpan("subtask").StartActive(finishSpanOnDispose:true)) { await Task.Delay(TimeSpan.FromMilliseconds(milliseconds)); } return message + "::response"; } } }
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.Json; namespace Jazz2.Migrations { public class MetadataV1ToV2 { private class MetadataV1Json { public class GraphicsSection { public string filename { get; set; } public IList<int> states { get; set; } public int frameOffset { get; set; } public object frameCount { get; set; } public object fps { get; set; } public bool onlyOnce { get; set; } public IList<int> color { get; set; } public string shader { get; set; } } public class SoundsSection { public IList<string> filenames { get; set; } } public IDictionary<string, GraphicsSection> graphics { get; set; } public IDictionary<string, SoundsSection> sounds { get; set; } public IList<string> children { get; set; } public IList<int> boundingBox { get; set; } } private class MetadataV2JsonStub { public class VersionSection { public string Target { get; set; } } public VersionSection Version { get; set; } } public static bool Convert(string path) { JsonParser jsonParser = new JsonParser(); MetadataV2JsonStub jsonV2; using (Stream s = File.Open(path, FileMode.Open)) { jsonV2 = jsonParser.Parse<MetadataV2JsonStub>(s); } if (jsonV2.Version != null && !string.IsNullOrEmpty(jsonV2.Version.Target)) { return false; } MetadataV1Json jsonV1; using (Stream s = File.Open(path, FileMode.Open)) { jsonV1 = jsonParser.Parse<MetadataV1Json>(s); } if (jsonV1.graphics == null && jsonV1.sounds == null && jsonV1.children == null) { Console.WriteLine("[ERROR] Corrupted or empty metadata!"); return false; } using (Stream so = File.Create(path)) using (StreamWriter w = new StreamWriter(so, new UTF8Encoding(false))) { w.WriteLine("{"); w.WriteLine(" \"Version\": {"); w.WriteLine(" \"Target\": \"Jazz² Resurrection\""); w.Write(" }"); // Misc. if (jsonV1.boundingBox != null) { w.WriteLine(","); w.WriteLine(); w.Write(" \"BoundingBox\": [ " + string.Join(", ", jsonV1.boundingBox) + " ]"); //Console.WriteLine("[WARNING] Metadata has a BoundingBox!"); if (jsonV1.boundingBox.Count != 2) { Console.WriteLine("[ERROR] BoundingBox has " + jsonV1.boundingBox.Count + " items!"); } } // Animations if (jsonV1.graphics != null && jsonV1.graphics.Count > 0) { w.WriteLine(","); w.WriteLine(); w.WriteLine(" \"Animations\": {"); bool isFirst = true; foreach (var graphic in jsonV1.graphics) { if (isFirst) { isFirst = false; } else { w.WriteLine(","); } w.WriteLine(" \"" + graphic.Key + "\": {"); w.Write(" \"Path\": \"" + graphic.Value.filename + "\""); int flags = 0; if (graphic.Value.onlyOnce) { flags |= 1; } if (flags != 0) { w.WriteLine(","); w.Write(" \"Flags\": " + flags + ""); } if (graphic.Value.frameOffset > 0) { w.WriteLine(","); w.Write(" \"FrameOffset\": " + graphic.Value.frameOffset + ""); } if (graphic.Value.frameCount != null) { w.WriteLine(","); w.Write(" \"FrameCount\": " + graphic.Value.frameCount + ""); } if (graphic.Value.fps != null) { w.WriteLine(","); w.Write(" \"FrameRate\": " + graphic.Value.fps + ""); } if (graphic.Value.states != null && graphic.Value.states.Count > 0) { w.WriteLine(","); w.Write(" \"States\": [ " + string.Join(", ", graphic.Value.states) + " ]"); } if (!string.IsNullOrEmpty(graphic.Value.shader)) { w.WriteLine(","); w.Write(" \"Shader\": \"" + string.Join(", ", graphic.Value.shader) + "\""); } if (graphic.Value.color != null) { w.WriteLine(","); w.Write(" \"ShaderColor\": [ " + string.Join(", ", graphic.Value.color) + " ]"); if (graphic.Value.color.Count != 4) { Console.WriteLine("[ERROR] Animations[\"" + graphic.Key + "\"].ShaderColor has " + graphic.Value.color.Count + " items!"); } } w.WriteLine(); w.Write(" }"); } w.WriteLine(); w.Write(" }"); } // Sounds if (jsonV1.sounds != null && jsonV1.sounds.Count > 0) { w.WriteLine(","); w.WriteLine(); w.WriteLine(" \"Sounds\": {"); bool isFirst = true; foreach (var sound in jsonV1.sounds) { if (sound.Value.filenames == null || sound.Value.filenames.Count == 0) { Console.WriteLine("[ERROR] Sounds[\"" + sound.Key + "\"] has no paths!"); continue; } if (isFirst) { isFirst = false; } else { w.WriteLine(","); } w.WriteLine(" \"" + sound.Key + "\": {"); w.WriteLine(" \"Paths\": [ " + string.Join("", sound.Value.filenames.Select((p, i) => (i == 0 || sound.Value.filenames.Count == 1) ? "\"" + p + "\"" : ", \"" + p + "\"")) + " ]"); w.Write(" }"); } w.WriteLine(); w.Write(" }"); } // Preload if (jsonV1.children != null && jsonV1.children.Count > 0) { w.WriteLine(","); w.WriteLine(); w.WriteLine(" \"Preload\": ["); w.WriteLine(" " + string.Join("", jsonV1.children.Select((p, i) => (i == 0 || jsonV1.children.Count == 1) ? "\"" + p + "\"" : ", \"" + p + "\"")) + ""); w.Write(" ]"); } w.WriteLine(); w.Write("}"); } return true; } } }
{ "pile_set_name": "Github" }
$whmcs_api_key = "jCteD6q91a3"; $whmcs_api_host = "www.whmcs.com"; $whmcs_api_port = 80; $whmcs_api_ssl = 0; $whmcs_api_prefix = "/licenseapi/validate.php"; # script_whmcs_desc() sub script_whmcs_desc { return "WHMCS"; } sub script_whmcs_uses { return ( "php" ); } sub script_whmcs_longdesc { return "WHMCS is an all-in-one client management, billing & support solution for online businesses."; } # script_whmcs_versions() sub script_whmcs_versions { return ( "6.3.2", "7.7.1" ); } sub script_whmcs_gpl { return 1; } sub script_whmcs_release { return 7; # To fix download URL } sub script_whmcs_category { return "Commerce"; } sub script_whmcs_php_vers { return ( 5 ); } # script_whmcs_depends(&domain, version) sub script_whmcs_depends { local ($d, $ver, $sinfo, $phpver) = @_; if ($ver >= 7) { local $phpv = &get_php_version($phpver || 5, $d); if (!$phpv) { return ("Could not work out exact PHP version"); } if (&compare_versions($phpv, "5.6") < 0) { return ("WHMCS requires PHP version 5.6 or later"); } } return ( ); } sub script_whmcs_php_modules { return ("mysql", "curl", "gd"); } sub script_whmcs_dbs { return ("mysql"); } # script_whmcs_params(&domain, version, &upgrade-info) # Returns HTML for table rows for options for installing WHMCS sub script_whmcs_params { local ($d, $ver, $upgrade) = @_; local $rv; local $hdir = &public_html_dir($d, 1); if ($upgrade) { # Options are fixed when upgrading local ($dbtype, $dbname) = split(/_/, $upgrade->{'opts'}->{'db'}, 2); $rv .= &ui_table_row("Database for WHMCS tables", $dbname); local $dir = $upgrade->{'opts'}->{'dir'}; $dir =~ s/^$d->{'home'}\///; $rv .= &ui_table_row("Install directory", $dir); $rv .= &ui_table_row("WHMCS licence key", $upgrade->{'opts'}->{'licensekey'}); } else { # Show editable install options local @dbs = &domain_databases($d, [ "mysql", "postgres" ]); $rv .= &ui_table_row("Database for WHMCS tables", &ui_database_select("db", undef, \@dbs, $d, "whmcs")); $rv .= &ui_table_row("Install sub-directory under <tt>$hdir</tt>", &ui_opt_textbox("dir", &substitute_scriptname_template("whmcs", $d), 30, "At top level")); $rv .= &ui_table_row("WHMCS license key", &ui_textbox("licensekey", undef, 30)); $rv .= &ui_table_row(" ", "You must purchase an <a href='https://www.whmcs.com/members/aff.php?aff=4115' target=_blank>WHMCS license</a> before installing this script"); } return $rv; } # script_whmcs_parse(&domain, version, &in, &upgrade-info) # Returns either a hash ref of parsed options, or an error string sub script_whmcs_parse { local ($d, $ver, $in, $upgrade) = @_; if ($upgrade) { # Options are always the same return $upgrade->{'opts'}; } else { local $hdir = &public_html_dir($d, 0); $in{'dir_def'} || $in{'dir'} =~ /\S/ && $in{'dir'} !~ /\.\./ || return "Missing or invalid installation directory"; local $dir = $in{'dir_def'} ? $hdir : "$hdir/$in{'dir'}"; local ($newdb) = ($in->{'db'} =~ s/^\*//); $in{'licensekey'} =~ s/^\s*//; $in{'licensekey'} =~ s/\s*$//; $in{'licensekey'} =~ /^\S+$/ || return "Missing or invalid-looking licence key - should be ". "like Owned-a8f06f0510547d80704b"; return { 'db' => $in->{'db'}, 'newdb' => $newdb, 'dir' => $dir, 'path' => $in{'dir_def'} ? "/" : "/$in{'dir'}", 'licensekey' => $in{'licensekey'}, }; } } # script_whmcs_check(&domain, version, &opts, &upgrade-info) # Returns an error message if a required option is missing or invalid sub script_whmcs_check { local ($d, $ver, $opts, $upgrade) = @_; $opts->{'licensekey'} || return "Missing licensekey option - licenses can be purchased at http://www.whmcs.com/members/aff.php?aff=4115"; $opts->{'dir'} =~ /^\// || return "Missing or invalid install directory"; $opts->{'db'} || return "Missing database"; if (-r "$opts->{'dir'}/configuration.php") { return "WHMCS appears to be already installed in the selected directory"; } local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2); local $clash = &find_database_table($dbtype, $dbname, "tbl"); $clash && return "WHMCS appears to be already using the selected database (table $clash)"; # Check for PHP mode &get_domain_php_mode($d) eq "mod_php" && return "WHMCS cannot be installed when PHP is being run via mod_php"; # Check if ioncube loader can be found local $io = &script_whmcs_get_ioncube_type(); $io || return "No ionCube loader for your operating system and CPU ". "architecture could be found"; # Validate the licence local $params = "key=".&urlize($whmcs_api_key). "&licensekey=".&urlize($opts->{'licensekey'}). "&domain=".&urlize($d->{'dom'}). "&ipaddress=".&urlize($d->{'ip'}). "&directory=".&urlize($opts->{'dir'}); local ($out, $err); &http_download($whmcs_api_host, $whmcs_api_port, $whmcs_api_prefix."?".$params, \$out, \$err, undef, $whmcs_api_ssl, undef, undef, undef, 0, 1); if ($err) { return "WHMCS licence check failed : $err"; } elsif ($out =~ /invalidkey/) { return "WHMCS API is invalid"; } elsif ($out =~ /licensekeynotfound/) { return "WHMCS licence key was not found"; } elsif ($out =~ /expired/) { return "WHMCS licence key has expired"; } elsif ($out =~ /suspended/) { return "WHMCS licence key has been suspended"; } elsif ($out =~ /invalid/) { return "WHMCS license key is registered to another IP address or directory. For more information, or to reissue your WHMCS license, please see 'My Licenses and Services' in the Client Area at whmcs.com."; } elsif ($out !~ /valid/) { return "Unknown WHMCS licence check code : $out"; } return undef; } # script_whmcs_files(&domain, version, &opts, &upgrade-info) # Returns a list of files needed by WHMCS, each of which is a hash ref # containing a name, filename and URL sub script_whmcs_files { local ($d, $ver, $opts, $upgrade) = @_; local $shortver = $ver; $shortver =~ s/\.//g; local @files = ( { 'name' => "source", 'file' => "whmcs_v$shortver.zip", 'url' => "http://scripts.virtualmin.com/whmcs_v${shortver}.zip" } ); local $io = &script_whmcs_get_ioncube_type(); push(@files, { 'name' => "ioncube", 'file' => "ioncube_loaders.zip", 'url' => "http://downloads3.ioncube.com/". "loader_downloads/ioncube_loaders_$io.zip" }); if (&compare_versions($ver, "4.5.2") <= 0) { # Also need security patch push(@files, { 'name' => 'patch', 'file' => 'patch.zip', 'url' => 'http://www.whmcs.com/go/21/download' }); } if (&compare_versions($ver, "4.5.2") <= 0) { # New security patch push(@files, { 'name' => 'patch2', 'file' => 'patch2.zip', 'url' => 'http://www.whmcs.com/members/dl.php?type=d&id=112' }); } if (&compare_versions($ver, "5.0.3") <= 0) { # SQL injection path push(@files, { 'name' => 'patch3', 'file' => 'patch3.zip', 'url' => 'http://www.whmcs.com/members/dl.php?type=d&id=126' }); } if (&compare_versions($ver, "5.1.2") <= 0) { # Patch for Boleto module push(@files, { 'name' => 'patch4', 'file' => 'patch4.zip', 'url' => 'http://www.whmcs.com/members/dl.php?type=d&id=138' }); } return @files; } sub script_whmcs_get_ioncube_type { local $io; local $arch = &backquote_command("uname -m"); if ($gconfig{'os_type'} eq 'solaris' && $arch =~ /sparc/) { $io = "sun_sparc"; } elsif ($gconfig{'os_type'} eq 'solaris' && $arch =~ /86/) { $io = "sun_x86"; } elsif ($gconfig{'os_type'} eq 'freebsd' && $arch =~ /64/) { $io = "fre_".int($gconfig{'os_version'})."_x86-64"; } elsif ($gconfig{'os_type'} eq 'freebsd' && $arch !~ /64/) { $io = "fre_".int($gconfig{'os_version'})."_x86"; } elsif ($gconfig{'os_type'} eq 'macos' && $arch =~ /64/) { $io = "dar_x86-64"; } elsif ($gconfig{'os_type'} eq 'macos' && $arch !~ /64/) { $io = "dar_x86"; } elsif ($gconfig{'os_type'} =~ /-linux/ && $arch =~ /x86_64/) { $io = "lin_x86-64"; } elsif ($gconfig{'os_type'} =~ /-linux/ && $arch =~ /i[0-9]86/) { $io = "lin_x86"; } elsif ($gconfig{'os_type'} =~ /-linux/ && $arch =~ /ppc/) { $io = "lin_ppc"; } return $io; } sub script_whmcs_commands { return ("unzip"); } # script_whmcs_install(&domain, version, &opts, &files, &upgrade-info, # username, password) # Actually installs WHMCS, and returns either 1 and an informational # message, or 0 and an error sub script_whmcs_install { local ($d, $version, $opts, $files, $upgrade, $domuser, $dompass) = @_; # Get DB details local ($out, $ex); if ($opts->{'newdb'} && !$upgrade) { local $err = &create_script_database($d, $opts->{'db'}); return (0, "Database creation failed : $err") if ($err); } local ($dbtype, $dbname) = split(/_/, $opts->{'db'}, 2); local $dbuser = $dbtype eq "mysql" ? &mysql_user($d) : &postgres_user($d); local $dbpass = $dbtype eq "mysql" ? &mysql_pass($d) : &postgres_pass($d, 1); local $dbphptype = $dbtype eq "mysql" ? "mysql" : "psql"; local $dbhost = &get_database_host($dbtype, $d); local $dberr = &check_script_db_connection($dbtype, $dbname, $dbuser, $dbpass); return (0, "Database connection failed : $dberr") if ($dberr); # Extract ioncube loader local $iotemp = &transname(); local $err = &extract_script_archive($files->{'ioncube'}, $iotemp, $d); $err && return (0, "Failed to extract ionCube files : $err"); local $io = &script_whmcs_get_ioncube_type(); local $phpver = &get_php_version($opts->{'phpver'}); $phpver =~ s/^(\d+\.\d+)\..*$/$1/; local ($sofile) = glob("$iotemp/ioncube/ioncube_loader_*_$phpver.so"); $sofile || return (0, "No ionCube loader for PHP version $phpver found in file"); # Extract tar file to temp dir and copy to target local $temp = &transname(); local $cfile = "$opts->{'dir'}/configuration.php"; local $cfilesrc = "$opts->{'dir'}/configuration.php.new"; local $err = &extract_script_archive($files->{'source'}, $temp, $d, $opts->{'dir'}, "whmcs"); $err && return (0, "Failed to extract source : $err"); # Apply security patches, if needed foreach my $k (keys %$files) { if ($k =~ /^patch/) { local $ptemp = &transname(); local $err = &extract_script_archive($files->{$k}, $ptemp, $d, $opts->{'dir'}); $err && return (0, "Failed to extract patch source : $err"); } } # Copy loader to ~/etc , adjust php.ini local $inifile = &get_domain_php_ini($d, $opts->{'phpver'}); $inifile && -r $inifile || return (0, "PHP configuration file was not found!"); $sofile =~ /\/([^\/]+)$/; local $sodest = "$d->{'home'}/etc/$1"; &copy_source_dest_as_domain_user($d, $sofile, $sodest); &foreign_require("phpini", "phpini-lib.pl"); local $conf = &phpini::get_config($inifile); local @allzends = grep { $_->{'name'} eq 'zend_extension' } @$conf; local @zends = grep { $_->{'enabled'} } @allzends; local ($got) = grep { $_->{'value'} eq $sodest } @zends; if (!$got) { # Needs to be enabled local $lref = &read_file_lines($inifile); if (@zends) { # After current extensions splice(@$lref, $zends[$#zends]->{'line'}+1, 0, "zend_extension=$sodest"); } elsif (@allexts) { # After commented out extensions splice(@$lref, $allzends[$#allzends]->{'line'}+1, 0, "zend_extension=$sodest"); } else { # At end of file (should never happen, but..) push(@$lref, "zend_extension=$sodest"); } &write_as_domain_user($d, sub { &flush_file_lines($inifile) }); undef($phpini::get_config_cache{$inifile}); } # Apply apache config now, for later wgets &push_all_print(); &restart_apache(); &pop_all_print(); if (!-r $cfile) { if (-r $cfilesrc) { # Use template config file &copy_source_dest_as_domain_user($d, $cfilesrc, $cfile); } else { # Create empty config file &open_tempfile_as_domain_user($d, CFILE, ">$cfile"); &close_tempfile_as_domain_user($d, CFILE); } &make_file_php_writable($d, $cfile); } # Run install script local $ipath = $opts->{'path'}."/install/install.php"; if (!$upgrade) { # Fetch config check page local ($out, $err); &get_http_connection($d, $ipath."?step=2", \$out, \$err); if ($err) { return (-1, "Failed to fetch system check page : $err"); } elsif ($out !~ /Continue|Begin\s+Installation/i) { return (-1, "System check failed"); } # Post to DB setup page local @params = ( [ "licenseKey", $opts->{'licensekey'} ], [ "databaseHost", $dbhost ], [ "databasePort", 3306 ], [ "databaseUsername", $dbuser ], [ "databasePassword", $dbpass ], [ "databaseName", $dbname ], ); local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params); local ($out, $err); &post_http_connection($d, $ipath."?step=4", $params, \$out, \$err); if ($err) { return (-1, "Database setup page failed : $err"); } elsif ($out !~ /Setup\s+Administrator\s+Account/i) { return (-1, "Database setup did not succeed"); } # Post to user creation page local $firstname = $d->{'owner'}; $firstname =~ s/\s.*$//; $firstname =~ s/['"]//g; $firstname ||= $d->{'dom'}; if (length($dompass) <= 5) { $dompass .= "12345"; } local @params = ( [ "firstName", $firstname ], [ "lastName", "Virtualmin" ], [ "email", $d->{'emailto_addr'} ], [ "username", $domuser ], [ "password", $dompass ], [ "confirmPassword", $dompass ], ); local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params); local ($out, $err); &post_http_connection($d, $ipath."?step=5", $params, \$out, \$err); if ($err) { return (-1, "Account creation page failed : $err"); } elsif ($out !~ /Installation\s+Complete/i) { return (-1, "Account creation did not succeed"); } } else { # Fetch config check page local ($out, $err); &get_http_connection($d, $ipath."?step=2", \$out, \$err); if ($err) { return (-1, "Failed to fetch upgrade check page : $err"); } elsif ($out !~ /Perform\s+Upgrade|already\s+running/) { return (-1, "Upgrade check failed"); } # Post to DB upgrade page local $oldver = $upgrade->{'version'}; $oldver =~ s/\.//g; local @params = ( [ "step", "upgrade" ], [ "version", $oldver ], [ "confirmbackup", 1 ], ); local $params = join("&", map { $_->[0]."=".&urlize($_->[1]) } @params); local ($out, $err); &post_http_connection($d, $ipath, $params, \$out, \$err); if ($err) { return (-1, "Database upgrade page failed : $err"); } elsif ($out !~ /Upgrade\s+Complete/i) { return (-1, "Database upgrade did not succeed"); } } # Setup cron job local $url = &script_path_url($d, $opts); if (!$upgrade) { &create_script_wget_job($d, $url."admin/cron.php", '0', int(rand()*24), 1); } # Delete install folder &unlink_file_as_domain_user($d, "$opts->{'dir'}/install"); # Return a URL for the user local $rp = $opts->{'dir'}; $rp =~ s/^$d->{'home'}\///; local $adminurl = $url."admin/"; return (1, "WHMCS installation complete. It can be accessed at <a href=$url target=_blank>$url</a> and managed at <a href=$adminurl target=_blank>$adminurl</a>. For more information, see <a href=http://wiki.whmcs.com/Installing_WHMCS target=_blank>http://wiki.whmcs.com/Installing_WHMCS</a> and <a href=http://wiki.whmcs.com/Virtualmin_Pro target=_blank>http://wiki.whmcs.com/Virtualmin_Pro</a>.", "Under $rp using $dbphptype database $dbname", $url, $domuser, $dompass); } # script_whmcs_uninstall(&domain, version, &opts) # Un-installs a WHMCS installation, by deleting the directory and database. # Returns 1 on success and a message, or 0 on failure and an error sub script_whmcs_uninstall { local ($d, $version, $opts) = @_; # Remove tbl* tables from the database &cleanup_script_database($d, $opts->{'db'}, "(tbl|mod_)"); # Delete the cron job &delete_script_wget_job($d, $sinfo->{'url'}."admin/cron.php"); # Remove the contents of the target directory local $derr = &delete_script_install_directory($d, $opts); return (0, $derr) if ($derr); # Take out the DB if ($opts->{'newdb'}) { &delete_script_database($d, $opts->{'db'}); } return (1, "WHMCS directory and tables deleted."); } #sub script_whmcs_latest #{ #local ($ver) = @_; #local $sfx = $ver =~ /^(\d+)\.(\d+)\.(\d+)$/ ? ".$3" : ""; #return ( "http://www.whmcs.com/whats-new/#download", # "WHMCS\\s+V(\\S+)\\s+Stable", # undef, $sfx ); #} sub script_whmcs_site { return 'http://www.whmcs.com/members/aff.php?aff=4115'; } sub script_whmcs_passmode { return 1; } 1;
{ "pile_set_name": "Github" }
require('../../../modules/es6.array.slice'); module.exports = require('../../../modules/_entry-virtual')('Array').slice;
{ "pile_set_name": "Github" }
choose-mirror-bin mirror/http/proxy string d-i base-installer/kernel/override-image string linux-server d-i clock-setup/utc boolean true d-i clock-setup/utc-auto boolean true d-i finish-install/reboot_in_progress note d-i grub-installer/only_debian boolean true d-i grub-installer/with_other_os boolean true d-i mirror/country string manual d-i mirror/http/directory string /ubuntu/ d-i mirror/http/hostname string archive.ubuntu.com d-i mirror/http/proxy string d-i partman-auto-lvm/guided_size string max d-i partman-auto/choose_recipe select atomic d-i partman-auto/method string lvm d-i partman-lvm/confirm boolean true d-i partman-lvm/confirm boolean true d-i partman-lvm/confirm_nooverwrite boolean true d-i partman-lvm/device_remove_lvm boolean true d-i partman/choose_partition select finish d-i partman/confirm boolean true d-i partman/confirm_nooverwrite boolean true d-i partman/confirm_write_new_label boolean true d-i passwd/user-fullname string vagrant d-i passwd/user-uid string 1000 d-i passwd/user-password password vagrant d-i passwd/user-password-again password vagrant d-i passwd/username string vagrant d-i pkgsel/include string openssh-server cryptsetup build-essential libssl-dev libreadline-dev zlib1g-dev linux-source dkms nfs-common linux-headers-$(uname -r) perl cifs-utils software-properties-common rsync ifupdown d-i pkgsel/install-language-support boolean false d-i pkgsel/update-policy select none d-i pkgsel/upgrade select full-upgrade d-i time/zone string UTC d-i user-setup/allow-password-weak boolean true d-i user-setup/encrypt-home boolean false tasksel tasksel/first multiselect standard, server
{ "pile_set_name": "Github" }
/* $Id: optimized-sort.h,v 1.1 2008/06/07 22:30:24 depetrini Exp $ * Adopted from GNU glibc by Mjt. * See stdlib/qsort.c in glibc */ /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Douglas C. Schmidt ([email protected]). The GNU C 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 GNU C 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 the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ /* in-line qsort implementation. Differs from traditional qsort() routine * in that it is a macro, not a function, and instead of passing an address * of a comparision routine to the function, it is possible to inline * comparision routine, thus speed up sorting alot. * * Usage: * #include "iqsort.h" * #define islt(a,b) (strcmp((*a),(*b))<0) * char *arr[]; * int n; * QSORT(char*, arr, n, islt); * * The "prototype" and 4 arguments are: * QSORT(TYPE,BASE,NELT,ISLT) * 1) type of each element, TYPE, * 2) address of the beginning of the array, of type TYPE*, * 3) number of elements in the array, and * 4) comparision routine. * Array pointer and number of elements are referenced only once. * This is similar to a call * qsort(BASE,NELT,sizeof(TYPE),ISLT) * with the difference in last parameter. * Note the islt macro/routine (it receives pointers to two elements): * the only condition of interest is whenever one element is less than * another, no other conditions (greather than, equal to etc) are tested. * So, for example, to define integer sort, use: * #define islt(a,b) ((*a)<(*b)) * QSORT(int, arr, n, islt) * * The macro could be used to implement a sorting function (see examples * below), or to implement the sorting algorithm inline. That is, either * create a sorting function and use it whenever you want to sort something, * or use QSORT() macro directly instead a call to such routine. Note that * the macro expands to quite some code (compiled size of int qsort on x86 * is about 700..800 bytes). * * Using this macro directly it isn't possible to implement traditional * qsort() routine, because the macro assumes sizeof(element) == sizeof(TYPE), * while qsort() allows element size to be different. * * Several ready-to-use examples: * * Sorting array of integers: * void int_qsort(int *arr, unsigned n) { * #define int_lt(a,b) ((*a)<(*b)) * QSORT(int, arr, n, int_lt); * } * * Sorting array of string pointers: * void str_qsort(char *arr[], unsigned n) { * #define str_lt(a,b) (strcmp((*a),(*b)) < 0) * QSORT(char*, arr, n, str_lt); * } * * Sorting array of structures: * * struct elt { * int key; * ... * }; * void elt_qsort(struct elt *arr, unsigned n) { * #define elt_lt(a,b) ((a)->key < (b)->key) * QSORT(struct elt, arr, n, elt_lt); * } * * And so on. */ /* Swap two items pointed to by A and B using temporary buffer t. */ #define _QSORT_SWAP(a, b, t) ((void)((t = *a), (*a = *b), (*b = t))) /* Discontinue quicksort algorithm when partition gets below this size. This particular magic number was chosen to work best on a Sun 4/260. */ #define _QSORT_MAX_THRESH 4 /* Stack node declarations used to store unfulfilled partition obligations * (inlined in QSORT). typedef struct { QSORT_TYPE *_lo, *_hi; } qsort_stack_node; */ /* The next 4 #defines implement a very fast in-line stack abstraction. */ /* The stack needs log (total_elements) entries (we could even subtract log(MAX_THRESH)). Since total_elements has type unsigned, we get as upper bound for log (total_elements): bits per byte (CHAR_BIT) * sizeof(unsigned). */ #define _QSORT_STACK_SIZE (8 * sizeof(unsigned)) #define _QSORT_PUSH(top, low, high) \ (((top->_lo = (low)), (top->_hi = (high)), ++top)) #define _QSORT_POP(low, high, top) \ ((--top, (low = top->_lo), (high = top->_hi))) #define _QSORT_STACK_NOT_EMPTY (_stack < _top) /* Order size using quicksort. This implementation incorporates four optimizations discussed in Sedgewick: 1. Non-recursive, using an explicit stack of pointer that store the next array partition to sort. To save time, this maximum amount of space required to store an array of SIZE_MAX is allocated on the stack. Assuming a 32-bit (64 bit) integer for size_t, this needs only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes). Pretty cheap, actually. 2. Chose the pivot element using a median-of-three decision tree. This reduces the probability of selecting a bad pivot value and eliminates certain extraneous comparisons. 3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving insertion sort to order the MAX_THRESH items within each partition. This is a big win, since insertion sort is faster for small, mostly sorted array segments. 4. The larger of the two sub-partitions is always pushed onto the stack first, with the algorithm then concentrating on the smaller partition. This *guarantees* no more than log (total_elems) stack size is needed (actually O(1) in this case)! */ /* The main code starts here... */ #define QSORT(QSORT_TYPE,QSORT_BASE,QSORT_NELT,QSORT_LT) \ { \ QSORT_TYPE *const _base = (QSORT_BASE); \ const unsigned _elems = (QSORT_NELT); \ QSORT_TYPE _hold; \ \ /* Don't declare two variables of type QSORT_TYPE in a single \ * statement: eg `TYPE a, b;', in case if TYPE is a pointer, \ * expands to `type* a, b;' wich isn't what we want. \ */ \ \ if (_elems > _QSORT_MAX_THRESH) { \ QSORT_TYPE *_lo = _base; \ QSORT_TYPE *_hi = _lo + _elems - 1; \ struct { \ QSORT_TYPE *_hi; QSORT_TYPE *_lo; \ } _stack[_QSORT_STACK_SIZE], *_top = _stack + 1; \ \ while (_QSORT_STACK_NOT_EMPTY) { \ QSORT_TYPE *_left_ptr; QSORT_TYPE *_right_ptr; \ \ /* Select median value from among LO, MID, and HI. Rearrange \ LO and HI so the three values are sorted. This lowers the \ probability of picking a pathological pivot value and \ skips a comparison for both the LEFT_PTR and RIGHT_PTR in \ the while loops. */ \ \ QSORT_TYPE *_mid = _lo + ((_hi - _lo) >> 1); \ \ if (QSORT_LT (_mid, _lo)) \ _QSORT_SWAP (_mid, _lo, _hold); \ if (QSORT_LT (_hi, _mid)) \ _QSORT_SWAP (_mid, _hi, _hold); \ else \ goto _jump_over; \ if (QSORT_LT (_mid, _lo)) \ _QSORT_SWAP (_mid, _lo, _hold); \ _jump_over:; \ \ _left_ptr = _lo + 1; \ _right_ptr = _hi - 1; \ \ /* Here's the famous ``collapse the walls'' section of quicksort. \ Gotta like those tight inner loops! They are the main reason \ that this algorithm runs much faster than others. */ \ do { \ while (QSORT_LT (_left_ptr, _mid)) \ ++_left_ptr; \ \ while (QSORT_LT (_mid, _right_ptr)) \ --_right_ptr; \ \ if (_left_ptr < _right_ptr) { \ _QSORT_SWAP (_left_ptr, _right_ptr, _hold); \ if (_mid == _left_ptr) \ _mid = _right_ptr; \ else if (_mid == _right_ptr) \ _mid = _left_ptr; \ ++_left_ptr; \ --_right_ptr; \ } \ else if (_left_ptr == _right_ptr) { \ ++_left_ptr; \ --_right_ptr; \ break; \ } \ } while (_left_ptr <= _right_ptr); \ \ /* Set up pointers for next iteration. First determine whether \ left and right partitions are below the threshold size. If so, \ ignore one or both. Otherwise, push the larger partition's \ bounds on the stack and continue sorting the smaller one. */ \ \ if (_right_ptr - _lo <= _QSORT_MAX_THRESH) { \ if (_hi - _left_ptr <= _QSORT_MAX_THRESH) \ /* Ignore both small partitions. */ \ _QSORT_POP (_lo, _hi, _top); \ else \ /* Ignore small left partition. */ \ _lo = _left_ptr; \ } \ else if (_hi - _left_ptr <= _QSORT_MAX_THRESH) \ /* Ignore small right partition. */ \ _hi = _right_ptr; \ else if (_right_ptr - _lo > _hi - _left_ptr) { \ /* Push larger left partition indices. */ \ _QSORT_PUSH (_top, _lo, _right_ptr); \ _lo = _left_ptr; \ } \ else { \ /* Push larger right partition indices. */ \ _QSORT_PUSH (_top, _left_ptr, _hi); \ _hi = _right_ptr; \ } \ } \ } \ \ /* Once the BASE array is partially sorted by quicksort the rest \ is completely sorted using insertion sort, since this is efficient \ for partitions below MAX_THRESH size. BASE points to the \ beginning of the array to sort, and END_PTR points at the very \ last element in the array (*not* one beyond it!). */ \ \ { \ QSORT_TYPE *const _end_ptr = _base + _elems - 1; \ QSORT_TYPE *_tmp_ptr = _base; \ register QSORT_TYPE *_run_ptr; \ QSORT_TYPE *_thresh; \ \ _thresh = _base + _QSORT_MAX_THRESH; \ if (_thresh > _end_ptr) \ _thresh = _end_ptr; \ \ /* Find smallest element in first threshold and place it at the \ array's beginning. This is the smallest array element, \ and the operation speeds up insertion sort's inner loop. */ \ \ for (_run_ptr = _tmp_ptr + 1; _run_ptr <= _thresh; ++_run_ptr) \ if (QSORT_LT (_run_ptr, _tmp_ptr)) \ _tmp_ptr = _run_ptr; \ \ if (_tmp_ptr != _base) \ _QSORT_SWAP (_tmp_ptr, _base, _hold); \ \ /* Insertion sort, running from left-hand-side \ * up to right-hand-side. */ \ \ _run_ptr = _base + 1; \ while (++_run_ptr <= _end_ptr) { \ _tmp_ptr = _run_ptr - 1; \ while (QSORT_LT (_run_ptr, _tmp_ptr)) \ --_tmp_ptr; \ \ ++_tmp_ptr; \ if (_tmp_ptr != _run_ptr) { \ QSORT_TYPE *_trav = _run_ptr + 1; \ while (--_trav >= _run_ptr) { \ QSORT_TYPE *_hi; QSORT_TYPE *_lo; \ _hold = *_trav; \ \ for (_hi = _lo = _trav; --_lo >= _tmp_ptr; _hi = _lo) \ *_hi = *_lo; \ *_hi = _hold; \ } \ } \ } \ } \ \ }
{ "pile_set_name": "Github" }
/* * 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'; function noop() {} module.exports = noop;
{ "pile_set_name": "Github" }
#template = int(2) #template = ''' 愚公移山 太行,王屋二山的北面,住了一個九十歲的老翁,名叫愚公。二山佔地廣闊,擋住去路,使他和家人往來極為不便。 一天,愚公召集家人說:「讓我們各盡其力,剷平二山,開條道路,直通豫州,你們認為怎樣?」 大家都異口同聲贊成,只有他的妻子表示懷疑,並說:「你連開鑿一個小丘的力量都沒有,怎可能剷平太行、王屋二山呢?況且,鑿出的土石又丟到哪裏去呢?」 大家都熱烈地說:「把土石丟進渤海裏。」 於是愚公就和兒孫,一起開挖土,把土石搬運到渤海去。 愚公的鄰居是個寡婦,有個兒子八歲也興致勃勃地走來幫忙。 寒來暑往,他們要一年才能往返渤海一次。 住在黃河河畔的智叟,看見他們這樣辛苦,取笑愚公說:「你不是很愚蠢嗎?你已一把年紀了,就是用盡你的氣力,也不能挖去山的一角呢?」 愚公歎息道:「你有這樣的成見,是不會明白的。你比那寡婦的小兒子還不如呢!就算我死了,還有我的兒子,我的孫子,我的曾孫子,他們一直傳下去。而這二山是不會加大的,總有一天,我們會把它們剷平。」 智叟聽了,無話可說: 二山的守護神被愚公的堅毅精神嚇倒,便把此事奏知天帝。天帝佩服愚公的精神,就命兩位大力神揹走二山。 How The Foolish Old Man Moved Mountains Yugong was a ninety-year-old man who lived at the north of two high mountains, Mount Taixing and Mount Wangwu. Stretching over a wide expanse of land, the mountains blocked yugong’s way making it inconvenient for him and his family to get around. One day yugong gathered his family together and said,”Let’s do our best to level these two mountains. We shall open a road that leads to Yuzhou. What do you think?” All but his wife agreed with him. “You don’t have the strength to cut even a small mound,” muttered his wife. “How on earth do you suppose you can level Mount Taixin and Mount Wanwu? Moreover, where will all the earth and rubble go?” “Dump them into the Sea of Bohai!” said everyone. So Yugong, his sons, and his grandsons started to break up rocks and remove the earth. They transported the earth and rubble to the Sea of Bohai. Now Yugong’s neighbour was a widow who had an only child eight years old. Evening the young boy offered his help eagerly. Summer went by and winter came. It took Yugong and his crew a full year to travel back and forth once. On the bank of the Yellow River dwelled an old man much respected for his wisdom. When he saw their back-breaking labour, he ridiculed Yugong saying,”Aren’t you foolish, my friend? You are very old now, and with whatever remains of your waning strength, you won’t be able to remove even a corner of the mountain.” Yugong uttered a sigh and said,”A biased person like you will never understand. You can’t even compare with the widow’s little boy!” “Even if I were dead, there will still be my children, my grandchildren, my great grandchildren, my great great grandchildren. They descendants will go on forever. But these mountains will not grow any taler. We shall level them one day!” he declared with confidence. The wise old man was totally silenced. When the guardian gods of the mountains saw how determined Yugong and his crew were, they were struck with fear and reported the incident to the Emperor of Heavens. Filled with admiration for Yugong, the Emperor of Heavens ordered two mighty gods to carry the mountains away. ''' '''导入stats_word模块''' import stats_word '''读取唐诗300首''' with open('tang300.json') as f: template = f.read() f.closed '''使用','调用join函数根据"contents"组合一个新的string''' #return ', '.join(d['contents'] for d in list1) '''try…except捕获异常''' try: '''调用stats_word模块中的stats_text函数''' print(stats_word.stats_text(template)) except ValueError: print(ValueError, ':你输入的参数类型不是string!')
{ "pile_set_name": "Github" }
// +build !ignore_autogenerated /* Copyright The Kubernetes 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. */ // Code generated by deepcopy-gen. DO NOT EDIT. package runtime // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RawExtension) DeepCopyInto(out *RawExtension) { *out = *in if in.Raw != nil { in, out := &in.Raw, &out.Raw *out = make([]byte, len(*in)) copy(*out, *in) } if in.Object != nil { out.Object = in.Object.DeepCopyObject() } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new RawExtension. func (in *RawExtension) DeepCopy() *RawExtension { if in == nil { return nil } out := new(RawExtension) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Unknown) DeepCopyInto(out *Unknown) { *out = *in out.TypeMeta = in.TypeMeta if in.Raw != nil { in, out := &in.Raw, &out.Raw *out = make([]byte, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Unknown. func (in *Unknown) DeepCopy() *Unknown { if in == nil { return nil } out := new(Unknown) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new Object. func (in *Unknown) DeepCopyObject() Object { if c := in.DeepCopy(); c != nil { return c } return nil } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *VersionedObjects) DeepCopyInto(out *VersionedObjects) { *out = *in if in.Objects != nil { in, out := &in.Objects, &out.Objects *out = make([]Object, len(*in)) for i := range *in { if (*in)[i] != nil { (*out)[i] = (*in)[i].DeepCopyObject() } } } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new VersionedObjects. func (in *VersionedObjects) DeepCopy() *VersionedObjects { if in == nil { return nil } out := new(VersionedObjects) in.DeepCopyInto(out) return out } // DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new Object. func (in *VersionedObjects) DeepCopyObject() Object { if c := in.DeepCopy(); c != nil { return c } return nil }
{ "pile_set_name": "Github" }
/* * This file is part of Applied Energistics 2. * Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved. * * Applied Energistics 2 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. * * Applied Energistics 2 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 Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>. */ package appeng.core.features.registries; import java.util.Collection; import java.util.HashSet; import java.util.Set; import net.minecraft.util.ResourceLocation; import appeng.api.parts.IPartModels; public class PartModels implements IPartModels { private final Set<ResourceLocation> models = new HashSet<>(); private boolean initialized = false; @Override public void registerModels(Collection<ResourceLocation> partModels) { if (this.initialized) { throw new IllegalStateException("Cannot register models after the pre-initialization phase!"); } this.models.addAll(partModels); } public Set<ResourceLocation> getModels() { return this.models; } public void setInitialized(boolean initialized) { this.initialized = initialized; } }
{ "pile_set_name": "Github" }
Filter 1: ON PK Fc 31 Hz Gain -8.6 dB Q 1.41 Filter 2: ON PK Fc 62 Hz Gain -5.4 dB Q 1.41 Filter 3: ON PK Fc 125 Hz Gain -5.1 dB Q 1.41 Filter 4: ON PK Fc 250 Hz Gain -3.6 dB Q 1.41 Filter 5: ON PK Fc 500 Hz Gain 1.1 dB Q 1.41 Filter 6: ON PK Fc 1000 Hz Gain 3.4 dB Q 1.41 Filter 7: ON PK Fc 2000 Hz Gain 1.3 dB Q 1.41 Filter 8: ON PK Fc 4000 Hz Gain -4.1 dB Q 1.41 Filter 9: ON PK Fc 8000 Hz Gain 8.6 dB Q 1.41 Filter 10: ON PK Fc 16000 Hz Gain 4.9 dB Q 1.41
{ "pile_set_name": "Github" }
/* * OpenPBS (Portable Batch System) v2.3 Software License * * Copyright (c) 1999-2000 Veridian Information Solutions, Inc. * All rights reserved. * * --------------------------------------------------------------------------- * For a license to use or redistribute the OpenPBS software under conditions * other than those described below, or to purchase support for this software, * please contact Veridian Systems, PBS Products Department ("Licensor") at: * * www.OpenPBS.org +1 650 967-4675 [email protected] * 877 902-4PBS (US toll-free) * --------------------------------------------------------------------------- * * This license covers use of the OpenPBS v2.3 software (the "Software") at * your site or location, and, for certain users, redistribution of the * Software to other sites and locations. Use and redistribution of * OpenPBS v2.3 in source and binary forms, with or without modification, * are permitted provided that all of the following conditions are met. * After December 31, 2001, only conditions 3-6 must be met: * * 1. Commercial and/or non-commercial use of the Software is permitted * provided a current software registration is on file at www.OpenPBS.org. * If use of this software contributes to a publication, product, or * service, proper attribution must be given; see www.OpenPBS.org/credit.html * * 2. Redistribution in any form is only permitted for non-commercial, * non-profit purposes. There can be no charge for the Software or any * software incorporating the Software. Further, there can be no * expectation of revenue generated as a consequence of redistributing * the Software. * * 3. Any Redistribution of source code must retain the above copyright notice * and the acknowledgment contained in paragraph 6, this list of conditions * and the disclaimer contained in paragraph 7. * * 4. Any Redistribution in binary form must reproduce the above copyright * notice and the acknowledgment contained in paragraph 6, this list of * conditions and the disclaimer contained in paragraph 7 in the * documentation and/or other materials provided with the distribution. * * 5. Redistributions in any form must be accompanied by information on how to * obtain complete source code for the OpenPBS software and any * modifications and/or additions to the OpenPBS software. The source code * must either be included in the distribution or be available for no more * than the cost of distribution plus a nominal fee, and all modifications * and additions to the Software must be freely redistributable by any party * (including Licensor) without restriction. * * 6. All advertising materials mentioning features or use of the Software must * display the following acknowledgment: * * "This product includes software developed by NASA Ames Research Center, * Lawrence Livermore National Laboratory, and Veridian Information * Solutions, Inc. * Visit www.OpenPBS.org for OpenPBS software support, * products, and information." * * 7. DISCLAIMER OF WARRANTY * * THIS SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT * ARE EXPRESSLY DISCLAIMED. * * IN NO EVENT SHALL VERIDIAN CORPORATION, ITS AFFILIATED COMPANIES, OR THE * U.S. GOVERNMENT OR ANY OF ITS AGENCIES BE LIABLE FOR ANY DIRECT OR INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This license will be governed by the laws of the Commonwealth of Virginia, * without reference to its choice of law rules. */ /* pbs_rlsjob.c Release a hold on a job. really just an instance of the "manager" request. */ #include <pbs_config.h> /* the master config generated by configure */ #include <stdio.h> #include "libpbs.h" int pbs_rlsjob_err( int c, const char *jobid, const char *holdtype, char *extend, int *local_errno) { struct attropl aopl; if ((jobid == (char *)0) || (*jobid == '\0') || c < 0) return (PBSE_IVALREQ); aopl.name = (char *)ATTR_h; aopl.resource = (char *)NULL; if ((holdtype == (char *)NULL) || (*holdtype == '\0')) aopl.value = (char *)"u"; else aopl.value = (char *)holdtype; aopl.op = SET; aopl.next = (struct attropl *)NULL; return PBSD_manager(c, PBS_BATCH_ReleaseJob, MGR_CMD_SET, MGR_OBJ_JOB, jobid, &aopl, extend, local_errno); } /* pbs_rlsjob_err() */ int pbs_rlsjob( int c, char *jobid, char *holdtype, char *extend) { pbs_errno = 0; return(pbs_rlsjob_err(c, (const char *)jobid, (const char *)holdtype, extend, &pbs_errno)); } /* END pbs_rlsjob() */
{ "pile_set_name": "Github" }
/*------------------------------------------------------------------------- * * nodeIndexonlyscan.h * * * * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group * Portions Copyright (c) 1994, Regents of the University of California * * src/include/executor/nodeIndexonlyscan.h * *------------------------------------------------------------------------- */ #ifndef NODEINDEXONLYSCAN_H #define NODEINDEXONLYSCAN_H #include "nodes/execnodes.h" extern IndexOnlyScanState *ExecInitIndexOnlyScan(IndexOnlyScan *node, EState *estate, int eflags); extern TupleTableSlot *ExecIndexOnlyScan(IndexOnlyScanState *node); extern void ExecEndIndexOnlyScan(IndexOnlyScanState *node); extern void ExecIndexOnlyMarkPos(IndexOnlyScanState *node); extern void ExecIndexOnlyRestrPos(IndexOnlyScanState *node); extern void ExecReScanIndexOnlyScan(IndexOnlyScanState *node); #endif /* NODEINDEXONLYSCAN_H */
{ "pile_set_name": "Github" }
:020000023000CC :10FC000001C0F3C0112484B790E890936100109272 :10FC10006100882369F0982F9A70923049F081FF33 :10FC200002C097EF94BF282E80E002D10C94000010 :10FC300085E08093810082E08093C80088E1809312 :10FC4000C90084E08093CC0086E08093CA008EE0F7 :10FC5000EFD0259A84E02CE33BEF91E030938500D0 :10FC60002093840096BBB09BFECF1D9AA89540912F :10FC7000C80047FD02C0815089F7CED0813479F4A5 :10FC8000CBD0C82FDBD0C23811F480E004C088E0AC :10FC9000C13809F083E0B9D080E1B7D0EECF82342B :10FCA00019F484E1D3D0F8CF853411F485E0FACF8C :10FCB000853581F4B1D0E82EAFD0F82E87FF07C08C :10FCC0008BB781608BBFEE0CFF1CB8D0E5CF8BB734 :10FCD0008E7FF8CF863579F49FD08D3451F49CD047 :10FCE000CBB79AD0C170880F8C2B8BBF81E0AED080 :10FCF000CCCF83E0FCCF843609F046C08DD0C82F2E :10FD0000D0E0DC2FCC2788D0C82B86D0D82E5E013F :10FD10008EEFB81A00E012E04801EFEF8E1A9E0A4B :10FD20007BD0F801808384018A149B04A9F786D0D4 :10FD3000F5E410E000E0DF1609F150E040E063E098 :10FD4000C70153D08701C12C92E0D92EF601419111 :10FD500051916F0161E0C80148D00E5F1F4F22979B :10FD6000A9F750E040E065E0C7013FD095CF608142 :10FD7000C8018E0D9F1D79D00F5F1F4FF801FE5FE8 :10FD8000C017D107A1F788CF843701F545D0C82F18 :10FD9000D0E0DC2FCC2740D0C82B3ED0D82E4ED080 :10FDA0008701F5E4DF120BC0CE0DDF1DC80155D071 :10FDB0002CD00F5F1F4FC017D107C1F76DCFF801CF :10FDC00087918F0122D02197D1F766CF853739F4FB :10FDD00035D08EE11AD088E918D082E05CCF813529 :10FDE00009F073CF88E024D070CFFC010A0167BF0F :10FDF000E895112407B600FCFDCF667029F0452B6D :10FE000019F481E187BFE89508959091C80095FFA6 :10FE1000FCCF8093CE0008958091C80087FFFCCF6F :10FE20008091C80084FD01C0A8958091CE000895FE :10FE3000E0E6F0E098E1908380830895EDDF803282 :10FE400019F088E0F5DFFFCF84E1DFCFCF93C82F33 :10FE5000E3DFC150E9F7CF91F1CFF999FECF92BD21 :10FE600081BDF89A992780B50895262FF999FECF7C :10FE70001FBA92BD81BD20BD0FB6F894FA9AF99AC7 :06FE80000FBE019608957B :02FFFE000008F9 :040000033000FC00CD :00000001FF
{ "pile_set_name": "Github" }
/** * 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. */ #pragma once #include <string> #include "hurricane/base/Variant.h" namespace hurricane { namespace base { class NetAddress : public Serializable { public: inline NetAddress(); inline NetAddress(const std::string& host, int32_t port); inline void Serialize(Variants& variants) const override; inline void Deserialize(Variants::const_iterator& it) override; const std::string& GetHost() const { return _host; } void SetHost(const std::string& host) { _host = host; } int32_t GetPort() const { return _port; } void SetPort(int32_t port) { _port = port; } private: std::string _host; int32_t _port; }; } } #include "hurricane/base/NetAddress.tcc"
{ "pile_set_name": "Github" }
-- ************************************************************** -- -- Common definitions -- -- ************************************************************** S1AP-CommonDataTypes { itu-t (0) identified-organization (4) etsi (0) mobileDomain (0) eps-Access (21) modules (3) s1ap (1) version1 (1) s1ap-CommonDataTypes (3) } DEFINITIONS AUTOMATIC TAGS ::= BEGIN Criticality ::= ENUMERATED { reject, ignore, notify } Presence ::= ENUMERATED { optional, conditional, mandatory } PrivateIE-ID ::= CHOICE { local INTEGER (0..65535), global OBJECT IDENTIFIER } ProcedureCode ::= INTEGER (0..255) ProtocolExtensionID ::= INTEGER (0..65535) ProtocolIE-ID ::= INTEGER (0..65535) TriggeringMessage ::= ENUMERATED { initiating-message, successful-outcome, unsuccessfull-outcome } END
{ "pile_set_name": "Github" }
require('../../modules/es6.function.bind'); module.exports = require('../../modules/_core').Function.bind;
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Plain &lt;div&gt; with role "link" and no states or properties</title> </head> <body> <div role="link" id="test">Placeholder content</div> </body> </html>
{ "pile_set_name": "Github" }
// SPDX-License-Identifier: GPL-2.0 /* * Process version 2 NFS requests. * * Copyright (C) 1995-1997 Olaf Kirch <[email protected]> */ #include <linux/namei.h> #include "cache.h" #include "xdr.h" #include "vfs.h" typedef struct svc_rqst svc_rqst; typedef struct svc_buf svc_buf; #define NFSDDBG_FACILITY NFSDDBG_PROC static __be32 nfsd_proc_null(struct svc_rqst *rqstp) { return nfs_ok; } static __be32 nfsd_return_attrs(__be32 err, struct nfsd_attrstat *resp) { if (err) return err; return fh_getattr(&resp->fh, &resp->stat); } static __be32 nfsd_return_dirop(__be32 err, struct nfsd_diropres *resp) { if (err) return err; return fh_getattr(&resp->fh, &resp->stat); } /* * Get a file's attributes * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_getattr(struct svc_rqst *rqstp) { struct nfsd_fhandle *argp = rqstp->rq_argp; struct nfsd_attrstat *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: GETATTR %s\n", SVCFH_fmt(&argp->fh)); fh_copy(&resp->fh, &argp->fh); nfserr = fh_verify(rqstp, &resp->fh, 0, NFSD_MAY_NOP | NFSD_MAY_BYPASS_GSS_ON_ROOT); return nfsd_return_attrs(nfserr, resp); } /* * Set a file's attributes * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_setattr(struct svc_rqst *rqstp) { struct nfsd_sattrargs *argp = rqstp->rq_argp; struct nfsd_attrstat *resp = rqstp->rq_resp; struct iattr *iap = &argp->attrs; struct svc_fh *fhp; __be32 nfserr; dprintk("nfsd: SETATTR %s, valid=%x, size=%ld\n", SVCFH_fmt(&argp->fh), argp->attrs.ia_valid, (long) argp->attrs.ia_size); fhp = fh_copy(&resp->fh, &argp->fh); /* * NFSv2 does not differentiate between "set-[ac]time-to-now" * which only requires access, and "set-[ac]time-to-X" which * requires ownership. * So if it looks like it might be "set both to the same time which * is close to now", and if setattr_prepare fails, then we * convert to "set to now" instead of "set to explicit time" * * We only call setattr_prepare as the last test as technically * it is not an interface that we should be using. */ #define BOTH_TIME_SET (ATTR_ATIME_SET | ATTR_MTIME_SET) #define MAX_TOUCH_TIME_ERROR (30*60) if ((iap->ia_valid & BOTH_TIME_SET) == BOTH_TIME_SET && iap->ia_mtime.tv_sec == iap->ia_atime.tv_sec) { /* * Looks probable. * * Now just make sure time is in the right ballpark. * Solaris, at least, doesn't seem to care what the time * request is. We require it be within 30 minutes of now. */ time_t delta = iap->ia_atime.tv_sec - get_seconds(); nfserr = fh_verify(rqstp, fhp, 0, NFSD_MAY_NOP); if (nfserr) goto done; if (delta < 0) delta = -delta; if (delta < MAX_TOUCH_TIME_ERROR && setattr_prepare(fhp->fh_dentry, iap) != 0) { /* * Turn off ATTR_[AM]TIME_SET but leave ATTR_[AM]TIME. * This will cause notify_change to set these times * to "now" */ iap->ia_valid &= ~BOTH_TIME_SET; } } nfserr = nfsd_setattr(rqstp, fhp, iap, 0, (time_t)0); done: return nfsd_return_attrs(nfserr, resp); } /* * Look up a path name component * Note: the dentry in the resp->fh may be negative if the file * doesn't exist yet. * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_lookup(struct svc_rqst *rqstp) { struct nfsd_diropargs *argp = rqstp->rq_argp; struct nfsd_diropres *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: LOOKUP %s %.*s\n", SVCFH_fmt(&argp->fh), argp->len, argp->name); fh_init(&resp->fh, NFS_FHSIZE); nfserr = nfsd_lookup(rqstp, &argp->fh, argp->name, argp->len, &resp->fh); fh_put(&argp->fh); return nfsd_return_dirop(nfserr, resp); } /* * Read a symlink. */ static __be32 nfsd_proc_readlink(struct svc_rqst *rqstp) { struct nfsd_readlinkargs *argp = rqstp->rq_argp; struct nfsd_readlinkres *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: READLINK %s\n", SVCFH_fmt(&argp->fh)); /* Read the symlink. */ resp->len = NFS_MAXPATHLEN; nfserr = nfsd_readlink(rqstp, &argp->fh, argp->buffer, &resp->len); fh_put(&argp->fh); return nfserr; } /* * Read a portion of a file. * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_read(struct svc_rqst *rqstp) { struct nfsd_readargs *argp = rqstp->rq_argp; struct nfsd_readres *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: READ %s %d bytes at %d\n", SVCFH_fmt(&argp->fh), argp->count, argp->offset); /* Obtain buffer pointer for payload. 19 is 1 word for * status, 17 words for fattr, and 1 word for the byte count. */ if (NFSSVC_MAXBLKSIZE_V2 < argp->count) { char buf[RPC_MAX_ADDRBUFLEN]; printk(KERN_NOTICE "oversized read request from %s (%d bytes)\n", svc_print_addr(rqstp, buf, sizeof(buf)), argp->count); argp->count = NFSSVC_MAXBLKSIZE_V2; } svc_reserve_auth(rqstp, (19<<2) + argp->count + 4); resp->count = argp->count; nfserr = nfsd_read(rqstp, fh_copy(&resp->fh, &argp->fh), argp->offset, rqstp->rq_vec, argp->vlen, &resp->count); if (nfserr) return nfserr; return fh_getattr(&resp->fh, &resp->stat); } /* * Write data to a file * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_write(struct svc_rqst *rqstp) { struct nfsd_writeargs *argp = rqstp->rq_argp; struct nfsd_attrstat *resp = rqstp->rq_resp; __be32 nfserr; unsigned long cnt = argp->len; dprintk("nfsd: WRITE %s %d bytes at %d\n", SVCFH_fmt(&argp->fh), argp->len, argp->offset); nfserr = nfsd_write(rqstp, fh_copy(&resp->fh, &argp->fh), argp->offset, rqstp->rq_vec, argp->vlen, &cnt, NFS_DATA_SYNC); return nfsd_return_attrs(nfserr, resp); } /* * CREATE processing is complicated. The keyword here is `overloaded.' * The parent directory is kept locked between the check for existence * and the actual create() call in compliance with VFS protocols. * N.B. After this call _both_ argp->fh and resp->fh need an fh_put */ static __be32 nfsd_proc_create(struct svc_rqst *rqstp) { struct nfsd_createargs *argp = rqstp->rq_argp; struct nfsd_diropres *resp = rqstp->rq_resp; svc_fh *dirfhp = &argp->fh; svc_fh *newfhp = &resp->fh; struct iattr *attr = &argp->attrs; struct inode *inode; struct dentry *dchild; int type, mode; __be32 nfserr; int hosterr; dev_t rdev = 0, wanted = new_decode_dev(attr->ia_size); dprintk("nfsd: CREATE %s %.*s\n", SVCFH_fmt(dirfhp), argp->len, argp->name); /* First verify the parent file handle */ nfserr = fh_verify(rqstp, dirfhp, S_IFDIR, NFSD_MAY_EXEC); if (nfserr) goto done; /* must fh_put dirfhp even on error */ /* Check for NFSD_MAY_WRITE in nfsd_create if necessary */ nfserr = nfserr_exist; if (isdotent(argp->name, argp->len)) goto done; hosterr = fh_want_write(dirfhp); if (hosterr) { nfserr = nfserrno(hosterr); goto done; } fh_lock_nested(dirfhp, I_MUTEX_PARENT); dchild = lookup_one_len(argp->name, dirfhp->fh_dentry, argp->len); if (IS_ERR(dchild)) { nfserr = nfserrno(PTR_ERR(dchild)); goto out_unlock; } fh_init(newfhp, NFS_FHSIZE); nfserr = fh_compose(newfhp, dirfhp->fh_export, dchild, dirfhp); if (!nfserr && d_really_is_negative(dchild)) nfserr = nfserr_noent; dput(dchild); if (nfserr) { if (nfserr != nfserr_noent) goto out_unlock; /* * If the new file handle wasn't verified, we can't tell * whether the file exists or not. Time to bail ... */ nfserr = nfserr_acces; if (!newfhp->fh_dentry) { printk(KERN_WARNING "nfsd_proc_create: file handle not verified\n"); goto out_unlock; } } inode = d_inode(newfhp->fh_dentry); /* Unfudge the mode bits */ if (attr->ia_valid & ATTR_MODE) { type = attr->ia_mode & S_IFMT; mode = attr->ia_mode & ~S_IFMT; if (!type) { /* no type, so if target exists, assume same as that, * else assume a file */ if (inode) { type = inode->i_mode & S_IFMT; switch(type) { case S_IFCHR: case S_IFBLK: /* reserve rdev for later checking */ rdev = inode->i_rdev; attr->ia_valid |= ATTR_SIZE; /* FALLTHROUGH */ case S_IFIFO: /* this is probably a permission check.. * at least IRIX implements perm checking on * echo thing > device-special-file-or-pipe * by doing a CREATE with type==0 */ nfserr = nfsd_permission(rqstp, newfhp->fh_export, newfhp->fh_dentry, NFSD_MAY_WRITE|NFSD_MAY_LOCAL_ACCESS); if (nfserr && nfserr != nfserr_rofs) goto out_unlock; } } else type = S_IFREG; } } else if (inode) { type = inode->i_mode & S_IFMT; mode = inode->i_mode & ~S_IFMT; } else { type = S_IFREG; mode = 0; /* ??? */ } attr->ia_valid |= ATTR_MODE; attr->ia_mode = mode; /* Special treatment for non-regular files according to the * gospel of sun micro */ if (type != S_IFREG) { if (type != S_IFBLK && type != S_IFCHR) { rdev = 0; } else if (type == S_IFCHR && !(attr->ia_valid & ATTR_SIZE)) { /* If you think you've seen the worst, grok this. */ type = S_IFIFO; } else { /* Okay, char or block special */ if (!rdev) rdev = wanted; } /* we've used the SIZE information, so discard it */ attr->ia_valid &= ~ATTR_SIZE; /* Make sure the type and device matches */ nfserr = nfserr_exist; if (inode && type != (inode->i_mode & S_IFMT)) goto out_unlock; } nfserr = 0; if (!inode) { /* File doesn't exist. Create it and set attrs */ nfserr = nfsd_create_locked(rqstp, dirfhp, argp->name, argp->len, attr, type, rdev, newfhp); } else if (type == S_IFREG) { dprintk("nfsd: existing %s, valid=%x, size=%ld\n", argp->name, attr->ia_valid, (long) attr->ia_size); /* File already exists. We ignore all attributes except * size, so that creat() behaves exactly like * open(..., O_CREAT|O_TRUNC|O_WRONLY). */ attr->ia_valid &= ATTR_SIZE; if (attr->ia_valid) nfserr = nfsd_setattr(rqstp, newfhp, attr, 0, (time_t)0); } out_unlock: /* We don't really need to unlock, as fh_put does it. */ fh_unlock(dirfhp); fh_drop_write(dirfhp); done: fh_put(dirfhp); return nfsd_return_dirop(nfserr, resp); } static __be32 nfsd_proc_remove(struct svc_rqst *rqstp) { struct nfsd_diropargs *argp = rqstp->rq_argp; __be32 nfserr; dprintk("nfsd: REMOVE %s %.*s\n", SVCFH_fmt(&argp->fh), argp->len, argp->name); /* Unlink. -SIFDIR means file must not be a directory */ nfserr = nfsd_unlink(rqstp, &argp->fh, -S_IFDIR, argp->name, argp->len); fh_put(&argp->fh); return nfserr; } static __be32 nfsd_proc_rename(struct svc_rqst *rqstp) { struct nfsd_renameargs *argp = rqstp->rq_argp; __be32 nfserr; dprintk("nfsd: RENAME %s %.*s -> \n", SVCFH_fmt(&argp->ffh), argp->flen, argp->fname); dprintk("nfsd: -> %s %.*s\n", SVCFH_fmt(&argp->tfh), argp->tlen, argp->tname); nfserr = nfsd_rename(rqstp, &argp->ffh, argp->fname, argp->flen, &argp->tfh, argp->tname, argp->tlen); fh_put(&argp->ffh); fh_put(&argp->tfh); return nfserr; } static __be32 nfsd_proc_link(struct svc_rqst *rqstp) { struct nfsd_linkargs *argp = rqstp->rq_argp; __be32 nfserr; dprintk("nfsd: LINK %s ->\n", SVCFH_fmt(&argp->ffh)); dprintk("nfsd: %s %.*s\n", SVCFH_fmt(&argp->tfh), argp->tlen, argp->tname); nfserr = nfsd_link(rqstp, &argp->tfh, argp->tname, argp->tlen, &argp->ffh); fh_put(&argp->ffh); fh_put(&argp->tfh); return nfserr; } static __be32 nfsd_proc_symlink(struct svc_rqst *rqstp) { struct nfsd_symlinkargs *argp = rqstp->rq_argp; struct svc_fh newfh; __be32 nfserr; dprintk("nfsd: SYMLINK %s %.*s -> %.*s\n", SVCFH_fmt(&argp->ffh), argp->flen, argp->fname, argp->tlen, argp->tname); fh_init(&newfh, NFS_FHSIZE); /* * Crazy hack: the request fits in a page, and already-decoded * attributes follow argp->tname, so it's safe to just write a * null to ensure it's null-terminated: */ argp->tname[argp->tlen] = '\0'; nfserr = nfsd_symlink(rqstp, &argp->ffh, argp->fname, argp->flen, argp->tname, &newfh); fh_put(&argp->ffh); fh_put(&newfh); return nfserr; } /* * Make directory. This operation is not idempotent. * N.B. After this call resp->fh needs an fh_put */ static __be32 nfsd_proc_mkdir(struct svc_rqst *rqstp) { struct nfsd_createargs *argp = rqstp->rq_argp; struct nfsd_diropres *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: MKDIR %s %.*s\n", SVCFH_fmt(&argp->fh), argp->len, argp->name); if (resp->fh.fh_dentry) { printk(KERN_WARNING "nfsd_proc_mkdir: response already verified??\n"); } argp->attrs.ia_valid &= ~ATTR_SIZE; fh_init(&resp->fh, NFS_FHSIZE); nfserr = nfsd_create(rqstp, &argp->fh, argp->name, argp->len, &argp->attrs, S_IFDIR, 0, &resp->fh); fh_put(&argp->fh); return nfsd_return_dirop(nfserr, resp); } /* * Remove a directory */ static __be32 nfsd_proc_rmdir(struct svc_rqst *rqstp) { struct nfsd_diropargs *argp = rqstp->rq_argp; __be32 nfserr; dprintk("nfsd: RMDIR %s %.*s\n", SVCFH_fmt(&argp->fh), argp->len, argp->name); nfserr = nfsd_unlink(rqstp, &argp->fh, S_IFDIR, argp->name, argp->len); fh_put(&argp->fh); return nfserr; } /* * Read a portion of a directory. */ static __be32 nfsd_proc_readdir(struct svc_rqst *rqstp) { struct nfsd_readdirargs *argp = rqstp->rq_argp; struct nfsd_readdirres *resp = rqstp->rq_resp; int count; __be32 nfserr; loff_t offset; dprintk("nfsd: READDIR %s %d bytes at %d\n", SVCFH_fmt(&argp->fh), argp->count, argp->cookie); /* Shrink to the client read size */ count = (argp->count >> 2) - 2; /* Make sure we've room for the NULL ptr & eof flag */ count -= 2; if (count < 0) count = 0; resp->buffer = argp->buffer; resp->offset = NULL; resp->buflen = count; resp->common.err = nfs_ok; /* Read directory and encode entries on the fly */ offset = argp->cookie; nfserr = nfsd_readdir(rqstp, &argp->fh, &offset, &resp->common, nfssvc_encode_entry); resp->count = resp->buffer - argp->buffer; if (resp->offset) *resp->offset = htonl(offset); fh_put(&argp->fh); return nfserr; } /* * Get file system info */ static __be32 nfsd_proc_statfs(struct svc_rqst *rqstp) { struct nfsd_fhandle *argp = rqstp->rq_argp; struct nfsd_statfsres *resp = rqstp->rq_resp; __be32 nfserr; dprintk("nfsd: STATFS %s\n", SVCFH_fmt(&argp->fh)); nfserr = nfsd_statfs(rqstp, &argp->fh, &resp->stats, NFSD_MAY_BYPASS_GSS_ON_ROOT); fh_put(&argp->fh); return nfserr; } /* * NFSv2 Server procedures. * Only the results of non-idempotent operations are cached. */ struct nfsd_void { int dummy; }; #define ST 1 /* status */ #define FH 8 /* filehandle */ #define AT 18 /* attributes */ static const struct svc_procedure nfsd_procedures2[18] = { [NFSPROC_NULL] = { .pc_func = nfsd_proc_null, .pc_decode = nfssvc_decode_void, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_void), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST, }, [NFSPROC_GETATTR] = { .pc_func = nfsd_proc_getattr, .pc_decode = nfssvc_decode_fhandle, .pc_encode = nfssvc_encode_attrstat, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_fhandle), .pc_ressize = sizeof(struct nfsd_attrstat), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST+AT, }, [NFSPROC_SETATTR] = { .pc_func = nfsd_proc_setattr, .pc_decode = nfssvc_decode_sattrargs, .pc_encode = nfssvc_encode_attrstat, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_sattrargs), .pc_ressize = sizeof(struct nfsd_attrstat), .pc_cachetype = RC_REPLBUFF, .pc_xdrressize = ST+AT, }, [NFSPROC_ROOT] = { .pc_decode = nfssvc_decode_void, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_void), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST, }, [NFSPROC_LOOKUP] = { .pc_func = nfsd_proc_lookup, .pc_decode = nfssvc_decode_diropargs, .pc_encode = nfssvc_encode_diropres, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_diropargs), .pc_ressize = sizeof(struct nfsd_diropres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST+FH+AT, }, [NFSPROC_READLINK] = { .pc_func = nfsd_proc_readlink, .pc_decode = nfssvc_decode_readlinkargs, .pc_encode = nfssvc_encode_readlinkres, .pc_argsize = sizeof(struct nfsd_readlinkargs), .pc_ressize = sizeof(struct nfsd_readlinkres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST+1+NFS_MAXPATHLEN/4, }, [NFSPROC_READ] = { .pc_func = nfsd_proc_read, .pc_decode = nfssvc_decode_readargs, .pc_encode = nfssvc_encode_readres, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_readargs), .pc_ressize = sizeof(struct nfsd_readres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST+AT+1+NFSSVC_MAXBLKSIZE_V2/4, }, [NFSPROC_WRITECACHE] = { .pc_decode = nfssvc_decode_void, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_void), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST, }, [NFSPROC_WRITE] = { .pc_func = nfsd_proc_write, .pc_decode = nfssvc_decode_writeargs, .pc_encode = nfssvc_encode_attrstat, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_writeargs), .pc_ressize = sizeof(struct nfsd_attrstat), .pc_cachetype = RC_REPLBUFF, .pc_xdrressize = ST+AT, }, [NFSPROC_CREATE] = { .pc_func = nfsd_proc_create, .pc_decode = nfssvc_decode_createargs, .pc_encode = nfssvc_encode_diropres, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_createargs), .pc_ressize = sizeof(struct nfsd_diropres), .pc_cachetype = RC_REPLBUFF, .pc_xdrressize = ST+FH+AT, }, [NFSPROC_REMOVE] = { .pc_func = nfsd_proc_remove, .pc_decode = nfssvc_decode_diropargs, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_diropargs), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_REPLSTAT, .pc_xdrressize = ST, }, [NFSPROC_RENAME] = { .pc_func = nfsd_proc_rename, .pc_decode = nfssvc_decode_renameargs, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_renameargs), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_REPLSTAT, .pc_xdrressize = ST, }, [NFSPROC_LINK] = { .pc_func = nfsd_proc_link, .pc_decode = nfssvc_decode_linkargs, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_linkargs), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_REPLSTAT, .pc_xdrressize = ST, }, [NFSPROC_SYMLINK] = { .pc_func = nfsd_proc_symlink, .pc_decode = nfssvc_decode_symlinkargs, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_symlinkargs), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_REPLSTAT, .pc_xdrressize = ST, }, [NFSPROC_MKDIR] = { .pc_func = nfsd_proc_mkdir, .pc_decode = nfssvc_decode_createargs, .pc_encode = nfssvc_encode_diropres, .pc_release = nfssvc_release_fhandle, .pc_argsize = sizeof(struct nfsd_createargs), .pc_ressize = sizeof(struct nfsd_diropres), .pc_cachetype = RC_REPLBUFF, .pc_xdrressize = ST+FH+AT, }, [NFSPROC_RMDIR] = { .pc_func = nfsd_proc_rmdir, .pc_decode = nfssvc_decode_diropargs, .pc_encode = nfssvc_encode_void, .pc_argsize = sizeof(struct nfsd_diropargs), .pc_ressize = sizeof(struct nfsd_void), .pc_cachetype = RC_REPLSTAT, .pc_xdrressize = ST, }, [NFSPROC_READDIR] = { .pc_func = nfsd_proc_readdir, .pc_decode = nfssvc_decode_readdirargs, .pc_encode = nfssvc_encode_readdirres, .pc_argsize = sizeof(struct nfsd_readdirargs), .pc_ressize = sizeof(struct nfsd_readdirres), .pc_cachetype = RC_NOCACHE, }, [NFSPROC_STATFS] = { .pc_func = nfsd_proc_statfs, .pc_decode = nfssvc_decode_fhandle, .pc_encode = nfssvc_encode_statfsres, .pc_argsize = sizeof(struct nfsd_fhandle), .pc_ressize = sizeof(struct nfsd_statfsres), .pc_cachetype = RC_NOCACHE, .pc_xdrressize = ST+5, }, }; static unsigned int nfsd_count2[ARRAY_SIZE(nfsd_procedures2)]; const struct svc_version nfsd_version2 = { .vs_vers = 2, .vs_nproc = 18, .vs_proc = nfsd_procedures2, .vs_count = nfsd_count2, .vs_dispatch = nfsd_dispatch, .vs_xdrsize = NFS2_SVC_XDRSIZE, }; /* * Map errnos to NFS errnos. */ __be32 nfserrno (int errno) { static struct { __be32 nfserr; int syserr; } nfs_errtbl[] = { { nfs_ok, 0 }, { nfserr_perm, -EPERM }, { nfserr_noent, -ENOENT }, { nfserr_io, -EIO }, { nfserr_nxio, -ENXIO }, { nfserr_fbig, -E2BIG }, { nfserr_acces, -EACCES }, { nfserr_exist, -EEXIST }, { nfserr_xdev, -EXDEV }, { nfserr_mlink, -EMLINK }, { nfserr_nodev, -ENODEV }, { nfserr_notdir, -ENOTDIR }, { nfserr_isdir, -EISDIR }, { nfserr_inval, -EINVAL }, { nfserr_fbig, -EFBIG }, { nfserr_nospc, -ENOSPC }, { nfserr_rofs, -EROFS }, { nfserr_mlink, -EMLINK }, { nfserr_nametoolong, -ENAMETOOLONG }, { nfserr_notempty, -ENOTEMPTY }, #ifdef EDQUOT { nfserr_dquot, -EDQUOT }, #endif { nfserr_stale, -ESTALE }, { nfserr_jukebox, -ETIMEDOUT }, { nfserr_jukebox, -ERESTARTSYS }, { nfserr_jukebox, -EAGAIN }, { nfserr_jukebox, -EWOULDBLOCK }, { nfserr_jukebox, -ENOMEM }, { nfserr_io, -ETXTBSY }, { nfserr_notsupp, -EOPNOTSUPP }, { nfserr_toosmall, -ETOOSMALL }, { nfserr_serverfault, -ESERVERFAULT }, { nfserr_serverfault, -ENFILE }, { nfserr_io, -EUCLEAN }, { nfserr_perm, -ENOKEY }, }; int i; for (i = 0; i < ARRAY_SIZE(nfs_errtbl); i++) { if (nfs_errtbl[i].syserr == errno) return nfs_errtbl[i].nfserr; } WARN_ONCE(1, "nfsd: non-standard errno: %d\n", errno); return nfserr_io; }
{ "pile_set_name": "Github" }
<template> <div class="ow-select" :style="selectStyles" v-click-outside="close"> <div class="ow-select-input-wrapper"> <input :disabled="disabled" @click="toggle" type="text" :value="selectedLabel" readonly> <ow-icon color="white" name="down"></ow-icon> </div> <ul v-if="isShowDropdown" :style="dropdownStyles" class="ow-select-dropdown"> <ow-option v-for="option in options" :key="option.value" :label="option.label" :value="option.value" :img-url="option.img" :disabled="option.disabled" :selected="option.selected || option.label === selectedLabel" @click="onClickOption(option)"> </ow-option> </ul> </div> </template> <script> import ClickOutside from '../../directives/ClickOutside' import OwIcon from '../Icon/OwIcon' import OwOption from './OwOption' export default { name: "OwSelect", props: { value: { type: [Number, String, Boolean, Object], required: true }, options: { type: Array, required: true }, disabled: { type: Boolean, default: false }, maxHeight: { type: Number, }, width: { type: Number, default: 200 } }, data() { return { isShowDropdown: false } }, computed: { selectedLabel() { const selectedOption = this.options.find((option) => option.value === this.value) return (selectedOption && selectedOption.label) ? selectedOption.label : '' }, selectStyles() { return { width: this.width + 'px' } }, dropdownStyles() { return { maxHeight: this.maxHeight + 'px' } } }, directives: { ClickOutside }, components: { OwOption, OwIcon }, methods: { open() { this.isShowDropdown = true }, close() { this.isShowDropdown = false }, toggle() { if (this.isShowDropdown) { this.close() } else { this.open() } }, onClickOption(option) { if (this.disabled || option.disabled) { return } this.$emit('update:value', option.value) this.$emit('input', option.value) // Close dropdown this.close() } } } </script> <style scoped lang="scss"> .ow-select { position: relative; display: inline-block; vertical-align: top; &-input-wrapper { display: flex; align-items: center; padding: 0 8px; height: $--input-height; background: $--color-opacity-primary; border: 1px solid $--color-opacity-primary; transition: all .3s; > input { padding: 0 5px; height: 100%; width: 100%; border: none; background: transparent; outline: none; color: $--select-input-color; font-size: $--select-input-font-size; } &:hover { background: $--color-primary; border-color: $--select-border-color-hover; } } &-dropdown { position: absolute; top: $--input-height; left: 0; margin-top: 2px; padding: $--select-dropdown-padding; width: 100%; max-height: $--select-dropdown-max-height; border-radius: 2px; background: $--select-dropdown-background; overflow: auto; z-index: 1; } } </style>
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>ol-ext Class: Delete</title> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/sunlight.default.css"> <link type="text/css" rel="stylesheet" href="styles/site.cerulean.css"> </head> <body> <div class="navbar navbar-default navbar-fixed-top "> <div class="container"> <div class="navbar-header"> <a class="navbar-brand" href="index.html"><img class="branding-logo" src="https://openlayers.org/en/latest/examples/resources/logo-70x70.png" alt="logo"/>ol-ext</a> <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#topNavigation"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> <div class="navbar-collapse collapse" id="topNavigation"> <ul class="nav navbar-nav"> <li class="dropdown"> <a href="namespaces.list.html" class="dropdown-toggle" data-toggle="dropdown">Namespaces<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="CanvasRenderingContext2D.html">CanvasRenderingContext2D</a></li><li><a href="ol.html">ol</a></li><li><a href="ol.control.html">ol.control</a></li><li><a href="ol.control.Control.html">ol.control.Control</a></li><li><a href="ol.coordinate.html">ol.coordinate</a></li><li><a href="ol.easing.html">ol.easing</a></li><li><a href="ol.ext.html">ol.ext</a></li><li><a href="ol.filter.html">ol.filter</a></li><li><a href="ol.geom.html">ol.geom</a></li><li><a href="ol.geom.Geometry.html">ol.geom.Geometry</a></li><li><a href="ol.geom.LineString.html">ol.geom.LineString</a></li><li><a href="ol.geom.MultiPolygon.html">ol.geom.MultiPolygon</a></li><li><a href="ol.geom.Point.html">ol.geom.Point</a></li><li><a href="ol.geom.Polygon.html">ol.geom.Polygon</a></li><li><a href="ol.graph.html">ol.graph</a></li><li><a href="ol.interaction.html">ol.interaction</a></li><li><a href="ol.layer.html">ol.layer</a></li><li><a href="ol.layer.Base.html">ol.layer.Base</a></li><li><a href="ol.layer.Group.html">ol.layer.Group</a></li><li><a href="ol.layer.Vector.html">ol.layer.Vector</a></li><li><a href="ol.Map.html">ol.Map</a></li><li><a href="ol.ordering.html">ol.ordering</a></li><li><a href="ol.Overlay.html">ol.Overlay</a></li><li><a href="ol.source.html">ol.source</a></li><li><a href="ol.source.Vector.html">ol.source.Vector</a></li><li><a href="ol.style.html">ol.style</a></li><li><a href="ol.style.Image.html">ol.style.Image</a></li> </ul> </li> <li class="dropdown"> <a href="classes.list.html" class="dropdown-toggle" data-toggle="dropdown">Classes<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="ol.control.Bar.html">ol.control.Bar</a></li><li><a href="ol.control.Button.html">ol.control.Button</a></li><li><a href="ol.control.CanvasAttribution.html">ol.control.CanvasAttribution</a></li><li><a href="ol.control.CanvasBase.html">ol.control.CanvasBase</a></li><li><a href="ol.control.CanvasScaleLine.html">ol.control.CanvasScaleLine</a></li><li><a href="ol.control.CanvasTitle.html">ol.control.CanvasTitle</a></li><li><a href="ol.control.CenterPosition.html">ol.control.CenterPosition</a></li><li><a href="ol.control.Compass.html">ol.control.Compass</a></li><li><a href="ol.control.Dialog.html">ol.control.Dialog</a></li><li><a href="ol.control.Disable.html">ol.control.Disable</a></li><li><a href="ol.control.EditBar.html">ol.control.EditBar</a></li><li><a href="ol.control.Gauge.html">ol.control.Gauge</a></li><li><a href="ol.control.GeoBookmark.html">ol.control.GeoBookmark</a></li><li><a href="ol.control.GeolocationBar.html">ol.control.GeolocationBar</a></li><li><a href="ol.control.Globe.html">ol.control.Globe</a></li><li><a href="ol.control.Graticule.html">ol.control.Graticule</a></li><li><a href="ol.control.GridReference.html">ol.control.GridReference</a></li><li><a href="ol.control.Imageline.html">ol.control.Imageline</a></li><li><a href="ol.control.IsochroneGeoportail.html">ol.control.IsochroneGeoportail</a></li><li><a href="ol.control.LayerPopup.html">ol.control.LayerPopup</a></li><li><a href="ol.control.LayerSwitcher.html">ol.control.LayerSwitcher</a></li><li><a href="ol.control.LayerSwitcherImage.html">ol.control.LayerSwitcherImage</a></li><li><a href="ol.control.Legend.html">ol.control.Legend</a></li><li><a href="ol.control.MapZone.html">ol.control.MapZone</a></li><li><a href="ol.control.Notification.html">ol.control.Notification</a></li><li><a href="ol.control.Overlay.html">ol.control.Overlay</a></li><li><a href="ol.control.Overview.html">ol.control.Overview</a></li><li><a href="ol.control.Permalink.html">ol.control.Permalink</a></li><li><a href="ol.control.Print.html">ol.control.Print</a></li><li><a href="ol.control.Profil.html">ol.control.Profil</a></li><li><a href="ol.control.RoutingGeoportail.html">ol.control.RoutingGeoportail</a></li><li><a href="ol.control.Scale.html">ol.control.Scale</a></li><li><a href="ol.control.Search.html">ol.control.Search</a></li><li><a href="ol.control.SearchBAN.html">ol.control.SearchBAN</a></li><li><a href="ol.control.SearchDFCI.html">ol.control.SearchDFCI</a></li><li><a href="ol.control.SearchFeature.html">ol.control.SearchFeature</a></li><li><a href="ol.control.SearchGeoportail.html">ol.control.SearchGeoportail</a></li><li><a href="ol.control.SearchGeoportailParcelle.html">ol.control.SearchGeoportailParcelle</a></li><li><a href="ol.control.SearchGPS.html">ol.control.SearchGPS</a></li><li><a href="ol.control.SearchJSON.html">ol.control.SearchJSON</a></li><li><a href="ol.control.SearchNominatim.html">ol.control.SearchNominatim</a></li><li><a href="ol.control.SearchPhoton.html">ol.control.SearchPhoton</a></li><li><a href="ol.control.SearchWikipedia.html">ol.control.SearchWikipedia</a></li><li><a href="ol.control.Select.html">ol.control.Select</a></li><li><a href="ol.control.SelectBase.html">ol.control.SelectBase</a></li><li><a href="ol.control.SelectCheck.html">ol.control.SelectCheck</a></li><li><a href="ol.control.SelectCondition.html">ol.control.SelectCondition</a></li><li><a href="ol.control.SelectFulltext.html">ol.control.SelectFulltext</a></li><li><a href="ol.control.SelectMulti.html">ol.control.SelectMulti</a></li><li><a href="ol.control.SelectPopup.html">ol.control.SelectPopup</a></li><li><a href="ol.control.Status.html">ol.control.Status</a></li><li><a href="ol.control.Storymap.html">ol.control.Storymap</a></li><li><a href="ol.control.Swipe.html">ol.control.Swipe</a></li><li><a href="ol.control.Target.html">ol.control.Target</a></li><li><a href="ol.control.TextButton.html">ol.control.TextButton</a></li><li><a href="ol.control.Timeline.html">ol.control.Timeline</a></li><li><a href="ol.control.Toggle.html">ol.control.Toggle</a></li><li><a href="ol.featureAnimation.html">ol.featureAnimation</a></li><li><a href="ol.featureAnimation.Blink.html">ol.featureAnimation.Blink</a></li><li><a href="ol.featureAnimation.Bounce.html">ol.featureAnimation.Bounce</a></li><li><a href="ol.featureAnimation.Drop.html">ol.featureAnimation.Drop</a></li><li><a href="ol.featureAnimation.Fade.html">ol.featureAnimation.Fade</a></li><li><a href="ol.featureAnimation.None.html">ol.featureAnimation.None</a></li><li><a href="ol.featureAnimation.Null.html">ol.featureAnimation.Null</a></li><li><a href="ol.featureAnimation.Path.html">ol.featureAnimation.Path</a></li><li><a href="ol.featureAnimation.Shake.html">ol.featureAnimation.Shake</a></li><li><a href="ol.featureAnimation.Show.html">ol.featureAnimation.Show</a></li><li><a href="ol.featureAnimation.Slide.html">ol.featureAnimation.Slide</a></li><li><a href="ol.featureAnimation.Teleport.html">ol.featureAnimation.Teleport</a></li><li><a href="ol.featureAnimation.Throw.html">ol.featureAnimation.Throw</a></li><li><a href="ol.featureAnimation.Zoom.html">ol.featureAnimation.Zoom</a></li><li><a href="ol.featureAnimation.ZoomOut.html">ol.featureAnimation.ZoomOut</a></li><li><a href="ol.filter.Base.html">ol.filter.Base</a></li><li><a href="ol.filter.Clip.html">ol.filter.Clip</a></li><li><a href="ol.filter.Colorize.html">ol.filter.Colorize</a></li><li><a href="ol.filter.Composite.html">ol.filter.Composite</a></li><li><a href="ol.filter.Crop.html">ol.filter.Crop</a></li><li><a href="ol.filter.Fold.html">ol.filter.Fold</a></li><li><a href="ol.filter.Lego.html">ol.filter.Lego</a></li><li><a href="ol.filter.Mask.html">ol.filter.Mask</a></li><li><a href="ol.filter.Texture.html">ol.filter.Texture</a></li><li><a href="ol.fromat.GeoRSS.html">ol.fromat.GeoRSS</a></li><li><a href="ol.graph.Dijskra.html">ol.graph.Dijskra</a></li><li><a href="ol.HexGrid.html">ol.HexGrid</a></li><li><a href="ol.InseeGrid.html">ol.InseeGrid</a></li><li><a href="ol.interaction.CenterTouch.html">ol.interaction.CenterTouch</a></li><li><a href="ol.interaction.Clip.html">ol.interaction.Clip</a></li><li><a href="ol.interaction.CopyPaste.html">ol.interaction.CopyPaste</a></li><li><a href="ol.interaction.Delete.html">ol.interaction.Delete</a></li><li><a href="ol.interaction.DragOverlay.html">ol.interaction.DragOverlay</a></li><li><a href="ol.interaction.DrawHole.html">ol.interaction.DrawHole</a></li><li><a href="ol.interaction.DrawRegular.html">ol.interaction.DrawRegular</a></li><li><a href="ol.interaction.DrawTouch.html">ol.interaction.DrawTouch</a></li><li><a href="ol.interaction.DropFile.html">ol.interaction.DropFile</a></li><li><a href="ol.interaction.FillAttribute.html">ol.interaction.FillAttribute</a></li><li><a href="ol.interaction.Flashlight.html">ol.interaction.Flashlight</a></li><li><a href="ol.interaction.FocusMap.html">ol.interaction.FocusMap</a></li><li><a href="ol.interaction.GeolocationDraw.html">ol.interaction.GeolocationDraw</a></li><li><a href="ol.interaction.Hover.html">ol.interaction.Hover</a></li><li><a href="ol.interaction.LongTouch.html">ol.interaction.LongTouch</a></li><li><a href="ol.interaction.ModifyFeature.html">ol.interaction.ModifyFeature</a></li><li><a href="ol.interaction.ModifyTouch.html">ol.interaction.ModifyTouch</a></li><li><a href="ol.interaction.Offset.html">ol.interaction.Offset</a></li><li><a href="ol.interaction.Ripple.html">ol.interaction.Ripple</a></li><li><a href="ol.interaction.SelectCluster.html">ol.interaction.SelectCluster</a></li><li><a href="ol.interaction.SnapGuides.html">ol.interaction.SnapGuides</a></li><li><a href="ol.interaction.Split.html">ol.interaction.Split</a></li><li><a href="ol.interaction.Splitter.html">ol.interaction.Splitter</a></li><li><a href="ol.interaction.Synchronize.html">ol.interaction.Synchronize</a></li><li><a href="ol.interaction.TinkerBell.html">ol.interaction.TinkerBell</a></li><li><a href="ol.interaction.TouchCompass.html">ol.interaction.TouchCompass</a></li><li><a href="ol.interaction.Transform.html">ol.interaction.Transform</a></li><li><a href="ol.interaction.UndoRedo.html">ol.interaction.UndoRedo</a></li><li><a href="ol.layer.AnimatedCluster.html">ol.layer.AnimatedCluster</a></li><li><a href="ol.layer.Geoportail.html">ol.layer.Geoportail</a></li><li><a href="ol.layer.Vector3D.html">ol.layer.Vector3D</a></li><li><a href="ol.Overlay.AnimatedCanvas.html">ol.Overlay.AnimatedCanvas</a></li><li><a href="ol.Overlay.Magnify.html">ol.Overlay.Magnify</a></li><li><a href="ol.Overlay.Placemark.html">ol.Overlay.Placemark</a></li><li><a href="ol.Overlay.Popup.html">ol.Overlay.Popup</a></li><li><a href="ol.Overlay.PopupFeature.html">ol.Overlay.PopupFeature</a></li><li><a href="ol.Overlay.Tooltip.html">ol.Overlay.Tooltip</a></li><li><a href="ol.particule.Base.html">ol.particule.Base</a></li><li><a href="ol.particule.Bird.html">ol.particule.Bird</a></li><li><a href="ol.particule.Cloud.html">ol.particule.Cloud</a></li><li><a href="ol.particule.Rain.html">ol.particule.Rain</a></li><li><a href="ol.particule.RainDrop.html">ol.particule.RainDrop</a></li><li><a href="ol.particule.Snow.html">ol.particule.Snow</a></li><li><a href="ol.render3D.html">ol.render3D</a></li><li><a href="ol.source.BinBase.html">ol.source.BinBase</a></li><li><a href="ol.source.DayNight.html">ol.source.DayNight</a></li><li><a href="ol.source.DBPedia.html">ol.source.DBPedia</a></li><li><a href="ol.source.DFCI.html">ol.source.DFCI</a></li><li><a href="ol.source.FeatureBin.html">ol.source.FeatureBin</a></li><li><a href="ol.source.GeoImage.html">ol.source.GeoImage</a></li><li><a href="ol.source.Geoportail.html">ol.source.Geoportail</a></li><li><a href="ol.source.GeoRSS.html">ol.source.GeoRSS</a></li><li><a href="ol.source.GridBin.html">ol.source.GridBin</a></li><li><a href="ol.source.HexBin.html">ol.source.HexBin</a></li><li><a href="ol.source.InseeBin.html">ol.source.InseeBin</a></li><li><a href="ol.source.Mapillary.html">ol.source.Mapillary</a></li><li><a href="ol.source.Overpass.html">ol.source.Overpass</a></li><li><a href="ol.source.WikiCommons.html">ol.source.WikiCommons</a></li><li><a href="ol.style.Chart.html">ol.style.Chart</a></li><li><a href="ol.style.FillPattern.html">ol.style.FillPattern</a></li><li><a href="ol.style.FontSymbol.html">ol.style.FontSymbol</a></li><li><a href="ol.style.Photo.html">ol.style.Photo</a></li><li><a href="ol.style.Shadow.html">ol.style.Shadow</a></li><li><a href="ol.style.StrokePattern.html">ol.style.StrokePattern</a></li><li><a href="ol.style.TextPath.html">ol.style.TextPath</a></li> </ul> </li> <li class="dropdown"> <a href="global.html" class="dropdown-toggle" data-toggle="dropdown">Global<b class="caret"></b></a> <ul class="dropdown-menu "> <li><a href="global.html">Global</a></li> </ul> </li> </ul> <div class="col-sm-3 col-md-3"> <form class="navbar-form" role="search"> <div class="input-group"> <input type="text" class="form-control" placeholder="Search" name="q" id="search-input"> <div class="input-group-btn"> <button class="btn btn-default" id="search-submit"><i class="glyphicon glyphicon-search"></i></button> </div> </div> </form> </div> </div> </div> </div> <div class="container" id="toc-content"> <div class="row"> <div class="col-md-8"> <div id="main"> <h1 class="page-title">Class: Delete</h1> <section> <header> <h2> <span class="ancestors"><a href="ol.html">ol</a><a href="ol.interaction.html">.interaction</a>.</span> Delete </h2> </header> <article> <div class="container-overview"> <hr> <dt> <h4 class="name" id="Delete"><span class="type-signature"></span>new Delete(options)</h4> </dt> <dd> <div class="description"> <p>A Select interaction to delete features on click.</p> </div> <h5>Parameters:</h5> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>options</code></td> <td class="type"> <span class="param-type">*</span> </td> <td class="description last"><p>ol.interaction.Select options</p></td> </tr> </tbody> </table> <dl class="details"> </dl> <h5>Fires:</h5> <ul> <li>event:deletestart</li> <li>event:deleteend</li> </ul> </dd> </div> <h3 class="subsection-title">Extends</h3> <ul> <li>ol.interaction.Interaction</li> </ul> <h3 class="subsection-title">Methods</h3> <dl> <hr> <dt> <h4 class="name" id="_getSources"><span class="type-signature"></span>_getSources()</h4> </dt> <dd> <div class="description"> <p>Get vector source of the map</p> </div> <dl class="details"> </dl> <h5>Returns:</h5> <dl> <dt> Type </dt> <dd> <span class="param-type">Array.&lt;<a href="ol.source.Vector.html">ol.source.Vector</a>></span> </dd> </dl> </dd> <hr> <dt> <h4 class="name" id="delete"><span class="type-signature"></span>delete(features)</h4> </dt> <dd> <div class="description"> <p>Delete features: remove the features from the map (from all layers in the map)</p> </div> <h5>Parameters:</h5> <table class="params table table-striped"> <thead> <tr> <th>Name</th> <th>Type</th> <th class="last">Description</th> </tr> </thead> <tbody> <tr> <td class="name"><code>features</code></td> <td class="type"> <span class="param-type">ol.Collection.&lt;ol.Feature></span> | <span class="param-type">Array.&lt;ol.Feature></span> </td> <td class="description last"><p>The features to delete</p></td> </tr> </tbody> </table> <dl class="details"> </dl> </dd> </dl> </article> </section> </div> </div> <div class="clearfix"></div> <div class="col-md-3"> <div id="toc" class="col-md-3 hidden-xs hidden-sm hidden-md"></div> </div> </div> </div> <div class="modal fade" id="searchResults"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Search results</h4> </div> <div class="modal-body"></div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div><!-- /.modal-content --> </div><!-- /.modal-dialog --> </div> <footer> <span class="jsdoc-message"> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.6.3</a> using the <a href="https://github.com/docstrap/docstrap">DocStrap template</a>. </span> </footer> <script src="scripts/docstrap.lib.js"></script> <script src="scripts/toc.js"></script> <script type="text/javascript" src="scripts/fulltext-search-ui.js"></script> <script> $( function () { $( "[id*='$']" ).each( function () { var $this = $( this ); $this.attr( "id", $this.attr( "id" ).replace( "$", "__" ) ); } ); $( ".tutorial-section pre, .readme-section pre, pre.prettyprint.source" ).each( function () { var $this = $( this ); var example = $this.find( "code" ); exampleText = example.html(); var lang = /{@lang (.*?)}/.exec( exampleText ); if ( lang && lang[1] ) { exampleText = exampleText.replace( lang[0], "" ); example.html( exampleText ); lang = lang[1]; } else { var langClassMatch = example.parent()[0].className.match(/lang\-(\S+)/); lang = langClassMatch ? langClassMatch[1] : "javascript"; } if ( lang ) { $this .addClass( "sunlight-highlight-" + lang ) .addClass( "linenums" ) .html( example.html() ); } } ); Sunlight.highlightAll( { lineNumbers : true, showMenu : true, enableDoclinks : true } ); $.catchAnchorLinks( { navbarOffset: 10 } ); $( "#toc" ).toc( { anchorName : function ( i, heading, prefix ) { return $( heading ).attr( "id" ) || ( prefix + i ); }, selectors : "#toc-content h1,#toc-content h2,#toc-content h3,#toc-content h4", showAndHide : false, smoothScrolling: true } ); $( "#main span[id^='toc']" ).addClass( "toc-shim" ); $( '.dropdown-toggle' ).dropdown(); $( "table" ).each( function () { var $this = $( this ); $this.addClass('table'); } ); } ); </script> <!--Navigation and Symbol Display--> <!--Google Analytics--> <script type="text/javascript"> $(document).ready(function() { SearcherDisplay.init(); }); </script> </body> </html>
{ "pile_set_name": "Github" }
/* * Copyright 2003-2019 JetBrains s.r.o. * * 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. */ package jetbrains.mps.workbench.findusages; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.indexing.DataIndexer; import com.intellij.util.indexing.DefaultFileTypeSpecificInputFilter; import com.intellij.util.indexing.FileBasedIndex; import com.intellij.util.indexing.FileBasedIndex.InputFilter; import com.intellij.util.indexing.FileContent; import com.intellij.util.indexing.ID; import com.intellij.util.indexing.ScalarIndexExtension; import com.intellij.util.io.KeyDescriptor; import jetbrains.mps.core.platform.Platform; import jetbrains.mps.extapi.persistence.ModelFactoryService; import jetbrains.mps.fileTypes.MPSFileTypeFactory; import jetbrains.mps.ide.MPSCoreComponents; import jetbrains.mps.persistence.IndexAwareModelFactory; import jetbrains.mps.persistence.IndexAwareModelFactory.Callback; import jetbrains.mps.smodel.adapter.ids.SConceptId; import jetbrains.mps.workbench.findusages.UsageEntry.ConceptInstance; import jetbrains.mps.workbench.findusages.UsageEntry.ModelUse; import jetbrains.mps.workbench.findusages.UsageEntry.NodeUse; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.model.SModelReference; import org.jetbrains.mps.openapi.model.SNodeId; import org.jetbrains.mps.openapi.persistence.ModelFactory; import org.jetbrains.mps.openapi.persistence.datasource.DataSourceType; import org.jetbrains.mps.openapi.persistence.datasource.FileExtensionDataSourceType; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * Bridge {@link IndexAwareModelFactory} to IDEA file-backed indexing mechanism */ public class MPSModelsIndexer extends ScalarIndexExtension<UsageEntry> { private static final ID<UsageEntry, Void> NAME = ID.create("mps.NodeUsage"); private final Map<FileType, IndexAwareModelFactory> myIndexAwareFileTypes = new HashMap<>(); public static Collection<VirtualFile> getContainingFiles(UsageEntry entry, GlobalSearchScope allFiles) { return FileBasedIndex.getInstance().getContainingFiles(NAME, entry, allFiles); } public MPSModelsIndexer() { final Platform mpsPlatform = ApplicationManager.getApplication().getComponent(MPSCoreComponents.class).getPlatform(); for (ModelFactory mf : mpsPlatform.findComponent(ModelFactoryService.class).getFactories()) { if (mf instanceof IndexAwareModelFactory) { for (DataSourceType type : mf.getPreferredDataSourceTypes()) { if (type instanceof FileExtensionDataSourceType) { String fileExt = ((FileExtensionDataSourceType) type).getFileExtension(); final FileType ft = MPSFileTypeFactory.findByExtension(fileExt); if (ft != null) { myIndexAwareFileTypes.put(ft, (IndexAwareModelFactory) mf); } } } } } IndexAwareModelFactory mf = myIndexAwareFileTypes.get(MPSFileTypeFactory.MPS_FILE_TYPE); if (mf != null) { // ModelFactory is registered for the 'primary' extension name only, duplicate for 'auxiliary' extensions as well myIndexAwareFileTypes.put(MPSFileTypeFactory.MPS_HEADER_FILE_TYPE, mf); myIndexAwareFileTypes.put(MPSFileTypeFactory.MPS_ROOT_FILE_TYPE, mf); } } @NotNull @Override public ID<UsageEntry, Void> getName() { return NAME; } @NotNull @Override public DataIndexer<UsageEntry, Void, FileContent> getIndexer() { return new ModelIndexer(); } @NotNull @Override public KeyDescriptor<UsageEntry> getKeyDescriptor() { return new UsageEntryKeyDescriptor(); } @NotNull @Override public InputFilter getInputFilter() { return new DefaultFileTypeSpecificInputFilter(myIndexAwareFileTypes.keySet().toArray(new FileType[0])); } @Override public boolean dependsOnFileContent() { return true; } @Override public int getVersion() { return 1; } private static class IndexCallback implements Callback { private final Map<UsageEntry, Void> myResult = new HashMap<>(128); public Map<UsageEntry, Void> getResult() { return myResult; } @Override public void instances(@NotNull SConceptId concept) { myResult.put(new ConceptInstance(concept), null); } @Override public void imports(@NotNull SModelReference modelRef) { myResult.put(new ModelUse(modelRef), null); } @Override public void externalNodeRef(@NotNull SNodeId node) { myResult.put(new NodeUse(node), null); } @Override public void localNodeRef(@NotNull SNodeId node) { myResult.put(new NodeUse(node), null); } } private class ModelIndexer implements DataIndexer<UsageEntry, Void, FileContent> { @NotNull @Override public Map<UsageEntry, Void> map(@NotNull FileContent inputData) { IndexAwareModelFactory mf = myIndexAwareFileTypes.get(inputData.getFileType()); if (mf == null) { return Collections.emptyMap(); } final byte[] content = inputData.getContent(); final IndexCallback cb = new IndexCallback(); try { mf.index(new ByteArrayInputStream(content), cb); } catch (IOException ex) { Logger.getLogger(MPSModelsIndexer.class).warn(String.format("Indexing failed: %s", ex), ex); } return cb.getResult(); } } }
{ "pile_set_name": "Github" }
package Paws::WorkSpaces::ModifyClientProperties; use Moose; has ClientProperties => (is => 'ro', isa => 'Paws::WorkSpaces::ClientProperties', required => 1); has ResourceId => (is => 'ro', isa => 'Str', required => 1); use MooseX::ClassAttribute; class_has _api_call => (isa => 'Str', is => 'ro', default => 'ModifyClientProperties'); class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::WorkSpaces::ModifyClientPropertiesResult'); class_has _result_key => (isa => 'Str', is => 'ro'); 1; ### main pod documentation begin ### =head1 NAME Paws::WorkSpaces::ModifyClientProperties - Arguments for method ModifyClientProperties on L<Paws::WorkSpaces> =head1 DESCRIPTION This class represents the parameters used for calling the method ModifyClientProperties on the L<Amazon WorkSpaces|Paws::WorkSpaces> service. Use the attributes of this class as arguments to method ModifyClientProperties. You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to ModifyClientProperties. =head1 SYNOPSIS my $workspaces = Paws->service('WorkSpaces'); my $ModifyClientPropertiesResult = $workspaces->ModifyClientProperties( ClientProperties => { ReconnectEnabled => 'ENABLED', # values: ENABLED, DISABLED; OPTIONAL }, ResourceId => 'MyNonEmptyString', ); Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object. For the AWS API documentation, see L<https://docs.aws.amazon.com/goto/WebAPI/workspaces/ModifyClientProperties> =head1 ATTRIBUTES =head2 B<REQUIRED> ClientProperties => L<Paws::WorkSpaces::ClientProperties> Information about the Amazon WorkSpaces client. =head2 B<REQUIRED> ResourceId => Str The resource identifiers, in the form of directory IDs. =head1 SEE ALSO This class forms part of L<Paws>, documenting arguments for method ModifyClientProperties in L<Paws::WorkSpaces> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
{ "pile_set_name": "Github" }
@model SpecificationAttributeModel @{ //page title ViewBag.Title = T("Admin.Catalog.Attributes.SpecificationAttributes.EditAttributeDetails").Text; } <form asp-area="@Constants.AreaAdmin" asp-controller="SpecificationAttribute" asp-action="Edit" method="post" id="specificationattribute-form"> <div class="row"> <div class="col-md-12"> <div class="x_panel light form-fit"> <div class="x_title"> <div class="caption"> <i class="fa fa-list-alt"></i> @T("Admin.Catalog.Attributes.SpecificationAttributes.EditAttributeDetails") - @Model.Name <small><i class="fa fa-arrow-circle-left"></i>@Html.ActionLink(T("Admin.Catalog.Attributes.SpecificationAttributes.BackToList").Text, "List") </small> </div> <div class="actions"> <div class="btn-group btn-group-devided"> <button class="btn btn-success" type="submit" name="save"><i class="fa fa-check"></i> @T("Admin.Common.Save") </button> <button class="btn btn-success" type="submit" name="save-continue"><i class="fa fa-check-circle"></i> @T("Admin.Common.SaveContinue") </button> <span id="specificationattribute-delete" class="btn red"><i class="fa fa-trash-o"></i> @T("Admin.Common.Delete")</span> <vc:admin-widget widget-zone="specification_attribute_details_buttons" additional-data="Model" /> </div> </div> </div> <div class="x_content form"> <partial name="_CreateOrUpdate" model="Model" /> </div> </div> </div> </div> </form> <admin-delete-confirmation button-id="specificationattribute-delete"/>
{ "pile_set_name": "Github" }
#ifndef TEXT_AREA_INCLUDED #define TEXT_AREA_INCLUDED #include "TextField.h" // fires action performed when ENTER hit inside area // (can be toggled to fire on every text change or every focus loss) class TextArea : public TextField { public: // label text and char maps copied internally TextArea( Font *inLabelFont, Font *inDisplayFont, double inX, double inY, double inWide, double inHigh, char inForceCaps = false, const char *inLabelText = NULL, const char *inAllowedChars = NULL, const char *inForbiddenChars = NULL ); virtual ~TextArea(); // defaults to false void enableSpellCheck( char inSpellCheckOn ); virtual void draw(); virtual void step(); virtual void specialKeyDown( int inKeyCode ); virtual void specialKeyUp( int inKeyCode ); virtual void pointerDown( float inX, float inY ); virtual void pointerDrag( float inX, float inY ); virtual void pointerUp( float inX, float inY ); protected: double mWide, mHigh; Font *mLabelFont; char mSpellCheckOn; int mCurrentLine; SimpleVector<char*> mLineStrings; // one per line, to help cursor move up and down evenly // absolute positions in mText SimpleVector<int> mCursorTargetPositions; // relative positions in each line's string SimpleVector<int> mCursorTargetLinePositions; char *mLastDrawnText; char mRecomputeCursorPositions; char *mLastComputedCursorText; int mHoldVertArrowSteps[2]; char mFirstVertArrowRepeatDone[2]; void upHit(); void downHit(); void clearVertArrowRepeat(); double mVertSlideOffset; char mSmoothSlidingUp, mSmoothSlidingDown; // override smooth movement for HOME and END and PAGE keys char mSnapMove; float mTopShadingFade, mBottomShadingFade; int mMaxLinesShown; int mFirstVisibleLine; int mLastVisibleLine; char mPointerDownInside; int mStepsSinceTextChanged; char mEverDrawn; int getClickHitCursorIndex( float inX, float inY ); // starts adjusting selection if shift held void cursorUpFromKey(); void cursorDownFromKey(); }; #endif
{ "pile_set_name": "Github" }
# Event 156 - AudStreamSink_RecreateAudioStream_Task ###### Version: 0 ## Description None ## Data Dictionary |Standard Name|Field Name|Type|Description|Sample Value| |---|---|---|---|---| |TBD|object|Pointer|None|`None`| |TBD|bDeviceChange|Boolean|None|`None`| |TBD|hnsNewStreamStartTime|Int64|None|`None`| ## Tags * etw_level_Informational * etw_opcode_Start * etw_task_AudStreamSink_RecreateAudioStream_Task
{ "pile_set_name": "Github" }
#ifdef RCSID static char RCSid[] = "$Header$"; #endif /* Copyright (c) 2010 by Michael J. Roberts. All Rights Reserved. */ /* Name osnet-connect.cpp - Win32 command-line UI connection Function Launches a local Web browser to connect to the Web UI Notes Modified 05/12/10 MJRoberts - Creation */ #include <string.h> #include <stdlib.h> #include "t3std.h" #include "os.h" #include "osifcnet.h" #include "vmnet.h" #include "vmvsn.h" #include "vmglob.h" #include "vmimage.h" #include "osnet-comm.h" /* ------------------------------------------------------------------------ */ /* * The Web UI communicator thread - specialization for the VM side of the * channel. */ class WebUICommThreadVM: public WebUICommThread { public: WebUICommThreadVM(TadsMessageQueue *mq, HANDLE proc, HANDLE pipe) : WebUICommThread(proc, pipe) { /* remember the message queue object */ (msg_queue = mq)->add_ref(); } ~WebUICommThreadVM() { /* release the message queue */ msg_queue->release_ref(); } virtual void process_request(int id, char *cmd) { /* check for close/disconnect messages */ if (memcmp(cmd, "disconnect", 10) == 0 || memcmp(cmd, "close", 5) == 0) { /* post a UI Close event */ if (msg_queue != 0) msg_queue->post(new TadsUICloseEvent(0)); } /* inherit the base class handling */ WebUICommThread::process_request(id, cmd); } /* the application-wide network message queue */ TadsMessageQueue *msg_queue; }; static WebUICommThreadVM *comm_thread = 0; /* ------------------------------------------------------------------------ */ /* * Launch a local "tadsweb" customized browser as a separate process, and * navigate it to the given start page on our internal HTTP server. This * handles the Web UI connection when we're running in the local * stand-alone configuration, where the user launches the game from the * Windows desktop or command line. */ static int launch_tadsweb(VMG_ const char *addr, int port, const char *path, char **errmsg) { STARTUPINFO si; PROCESS_INFORMATION pi; char dir[OSFNMAX], exe[OSFNMAX]; char *rootname; int ok; HANDLE pipe = INVALID_HANDLE_VALUE; char pipe_name[128]; char cmdline[1024]; /* presume failure, but we don't have an error message yet */ ok = FALSE; *errmsg = 0; /* initialize the process descriptor structures */ memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); /* if the URL path starts with a '/', skip it */ if (path != 0 && *path == '/') ++path; /* * if there's already a process running, try connecting the current * process to the new path */ if (comm_thread != 0) { /* try sending a 'connect' message */ char *reply; ok = (comm_thread->send_cmd( 2500, reply, "connect http://%s:%d/%s", addr, port, path) && strcmp(reply, "ok") == 0); /* free the reply message */ lib_free_str(reply); /* check the result */ if (ok) { /* success - we're now showing the new UI */ return TRUE; } else { /* * the re-connect attempt failed; shut down the old UI and * proceed to start a new one */ osnet_disconnect_webui(TRUE); } } /* get the current executable directory */ GetModuleFileName(0, dir, sizeof(dir)); /* * build the full path to the tadsweb executable, looking in the same * directory that contains the current process's executable */ rootname = os_get_root_name(dir); *(rootname != 0 ? rootname : dir) = '\0'; os_build_full_path(exe, sizeof(exe), dir, "tadsweb.exe"); /* open a named pipe for communication with the server */ sprintf(pipe_name, "\\\\.\\pipe\\tadsweb.%lx", (long)GetCurrentProcessId()); pipe = CreateNamedPipe( pipe_name, PIPE_ACCESS_DUPLEX | FILE_FLAG_FIRST_PIPE_INSTANCE | FILE_FLAG_OVERLAPPED | FILE_FLAG_WRITE_THROUGH, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE, 1, 4096, 4096, 0, 0); /* check to make sure we created the pipe */ if (pipe == INVALID_HANDLE_VALUE) goto done; /* set up the command line */ _snprintf(cmdline, sizeof(cmdline), " url=http://%s:%d/%s pipe=%s ppid=%ld", addr, port, path, pipe_name, (long)GetCurrentProcessId()); /* try launching the process */ if (CreateProcess(exe, cmdline, 0, 0, TRUE, 0, 0, 0, &si, &pi)) { char *reply = 0; /* * success */ /* set the success status */ ok = TRUE; /* we don't need the webui's main thread handle */ CloseHandle(pi.hThread); /* if there's a previous communicator thread, forget it */ if (comm_thread != 0) comm_thread->release_ref(); /* create a new communicator thread */ comm_thread = new WebUICommThreadVM(G_net_queue, pi.hProcess, pipe); /* set up an overlapped I/O wait for the client to connect */ OVERLAPPED ov; memset(&ov, 0, sizeof(ov)); ov.hEvent = CreateEvent(0, TRUE, FALSE, 0); if (ConnectNamedPipe(pipe, &ov) || GetLastError() == ERROR_PIPE_CONNECTED) { /* success/already connected */ } else if (GetLastError() == ERROR_IO_PENDING) { /* wait for that to complete, but not too long */ ok = (WaitForSingleObject(ov.hEvent, 30000) == WAIT_OBJECT_0); } else { /* failed */ ok = FALSE; } /* done with the overlapped I/O event */ CloseHandle(ov.hEvent); /* if the client didn't start up, abort */ if (!ok) { *errmsg = lib_copy_str("Timed out waiting for client to connect"); goto done; } /* launch the thread */ if (!comm_thread->launch()) { /* couldn't launch the thread, so release the thread object */ comm_thread->release_ref(); comm_thread = 0; /* flag the error and abort */ ok = FALSE; *errmsg = lib_copy_str("Unable to launch monitor thread"); goto done; } /* send it the TADS version string */ if (comm_thread->send_cmd(500, reply, "tadsver %s", T3VM_VSN_STRING)) lib_free_str(reply); /* send the game directory */ if (comm_thread->send_cmd(500, reply, "gamedir %s", G_image_loader->get_path())) lib_free_str(reply); /* send the default saved game extension, if any */ const char *ext = os_get_save_ext(); if (ext != 0 && comm_thread->send_cmd(500, reply, "saveext %s", ext)) lib_free_str(reply); } else { /* failed */ *errmsg = lib_copy_str("Unable to open game window"); } done: /* if an error occurred, clean up partial resources */ if (!ok) { /* if we opened the pipe, close it */ if (pipe != INVALID_HANDLE_VALUE) CloseHandle(pipe); /* if we created a process, close the handle */ if (pi.hProcess != 0) CloseHandle(pi.hProcess); } /* return the status indication */ return ok; } /* * Connect to the client UI. A Web-based game calls this after starting * its internal HTTP server, to send instructions back to the client on how * the client UI can connect to the game. * * There are two very different configurations we can run in: * * - Local, stand-alone mode. This is the "old fashioned" configuration * where everything's installed on the local PC: the user has a copy of the * TADS Player Kit installed, and has a downloaded copy of the game on the * local hard disk. In this mode, everything should behave as much as * possible like the conventional Windows version of TADS. To launch the * game, the user double-clicks the game file on the Windows desktop, or * enters a t3run command line. There's no browser involved in the launch * process, so to connect to the UI, we actually have to create the UI. In * principle, this *could* simply launch a regular Web browser, but that's * not what our implementation does. Instead, to provide a more integrated * appearance to the UI, we launch a special TADS window that's basically * an IE control wrapped in a custom app frame. This lets us decorate the * app frame so that it looks roughly like a traditional HTML TADS window. * * - Client/server mode. In this mode, the local machine is set up with * t3run plus a conventional Web server (e.g., Apache), with the TADS web * launch scripts installed. The user is on a remote machine. The user * opens a Web browser and connects to our Apache server by requesting (via * HTTP) our launch page. The launch page is typically our t3launch.php * script. That page executes t3run (that's us) as a subprocess. Before * t3launch.php sends a reply back to the client, it waits to hear from the * t3run subprocess (that's us again): we have to send the game connection * information, so that t3launch.php can relay the information back to the * client as its reply to the launch page request. The php page sends the * address back as an HTTP 301 redirect, so the client automatically * navigates to the game's start page. * * We can tell which mode we're running in by checking for a "hostname" * variable in the net config object. If there's no hostname variable * setting, we're in local mode. If there's a hostname setting, we're in * client/server mode, and the hostname gives the address of the network * adapter our HTTP listener binds to. */ int osnet_connect_webui(VMG_ const char *addr, int port, const char *path, char **errmsg) { /* get the host name from the network configuration, if any */ const char *hostname = (G_net_config != 0 ? G_net_config->get("hostname") : 0); /* * If we have host name in the network configuration, we're running in * Web server mode - the host name parameter means that we were * launched by a web server in response to an incoming launch request * from a remote client. In this mode, we need to send the connection * information back to the web server's launcher, which is our parent * process; we send the information back via stdout. * * If we don't have a host name, it means that the user must have * launched the interpreter from the Windows desktop or command shell, * in which case they want to run the game as a local, stand-alone * application. In local mode, we have to display our own user * interface. */ if (hostname != 0) { /* * Web server mode. We were launched by the local Web server in * response to a new game request from a Web client. Our parent * process is the Web server running the php launch page. The php * page has a pipe connection to our stdout. Send the start page * information back to the php page simply by writing the * information to stdout. */ printf("connectWebUI:http://%s:%d%s\n", addr, port, path); fflush(stdout); #if 0 // $$$ for testing only if (strcmp(hostname, "localhost") == 0) { char buf[4096]; _snprintf(buf, sizeof(buf), "http://%s:%d%s\n", addr, port, path); ShellExecute(0, "open", buf, 0, 0, SW_SHOWNORMAL); } #endif /* success */ *errmsg = 0; return TRUE; } else { /* * Local stand-alone mode. In this mode, we have to launch our own * user interface, since the user directly ran the TADS interpreter * from the Windows desktop or command shell, and so far we haven't * presented any UI. Our UI in this mode is the "tadsweb" custom * browser. This is similar to an ordinary browser, but it has a * customized frame (menus, toolbar, etc) that makes it look more * like a regular HTML TADS window, and it has a special control * channel (via a pipe) that tightly couples it to the intepreter. */ return launch_tadsweb(vmg_ addr, port, path, errmsg); } } /* ------------------------------------------------------------------------ */ /* * Disconnect from the web UI, in preparation for program termination */ void osnet_disconnect_webui(int close) { /* if the web ui process is running, send it a shutdown message */ if (comm_thread != 0) { /* send a 'shutdown' message */ comm_thread->disconnect(close); /* wait for the comm thread to finish (but not forever) */ comm_thread->wait(15000); /* we're done with the thread */ comm_thread->release_ref(); comm_thread = 0; } /* unload dynamically linked libraries */ tads_unlink_user32(); } /* ------------------------------------------------------------------------ */ /* * Negotiate foreground status for the Web UI */ /* ask the Web UI to yield the foreground to the current process */ void osnet_webui_yield_foreground() { if (comm_thread != 0) { /* send the request to yield the foreground to the current PID */ char *reply; if (comm_thread->send_cmd(2500, reply, "yield-fg %ld", GetCurrentProcessId())) lib_free_str(reply); } } /* bring the Web UI to the foreground */ void osnet_webui_to_foreground() { if (comm_thread != 0) { /* explicitly yield the foreground to the webui process */ tads_AllowSetForegroundWindow(GetProcessId(comm_thread->proc)); /* tell the web ui to set itself as the foreground window */ char *reply; if (comm_thread->send_cmd(1000, reply, "to-fg")) lib_free_str(reply); } } /* ------------------------------------------------------------------------ */ /* * Quote the askfile prompt - escape commas and percent signs with '%' */ static size_t quote_askfile_prompt(char *dst, const char *src) { size_t len; for (len = 0 ; *src != '\0' ; ++src) { switch (*src) { case ',': case '%': /* we need to quote these */ len += 2; if (dst != 0) { *dst++ = '%'; *dst++ = *src; } break; default: /* everything else goes as is */ len += 1; if (dst != 0) *dst++ = *src; break; } } /* null-terminate the string */ if (dst != 0) *dst = '\0'; /* return the length */ return len; } /* ------------------------------------------------------------------------ */ /* * Run the askfile dialog in the Web UI process. This sends a pipe request * to the Web UI process asking it to show the file selector, and returns * the result. */ int osnet_askfile(const char *prompt, char *fname_buf, int fname_buf_len, int prompt_type, int file_type) { /* presume failure */ int ret = 1; if (comm_thread != 0) { /* allocate space for the quoted prompt, and quote it */ size_t qplen = quote_askfile_prompt(0, prompt); char *qprompt = lib_alloc_str(qplen); quote_askfile_prompt(qprompt, prompt); /* send the request */ char *reply; if (comm_thread->send_cmd( OS_FOREVER, reply, "askfile %s,%d,%d", qprompt, prompt_type, file_type)) { /* * Got a reply. The return code is the first character of the * buffer, as a digit giving the OS_AFE_xxx value. */ ret = reply[0] - '0'; /* the rest is the filename string */ lib_strcpy(fname_buf, fname_buf_len, reply + 1); /* free the reply */ lib_free_str(reply); } /* delete the allocated buffer */ lib_free_str(qprompt); } /* return the result */ return ret; }
{ "pile_set_name": "Github" }
<?php /** * Quack Compiler and toolkit * Copyright (C) 2015-2017 Quack and CONTRIBUTORS * * This file is part of Quack. * * Quack 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. * * Quack 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 Quack. If not, see <http://www.gnu.org/licenses/>. */ namespace QuackCompiler\Parser; use \QuackCompiler\Lexer\Tag; use \QuackCompiler\Parselets\Expr\BinaryOperatorParselet; use \QuackCompiler\Parselets\Expr\LiteralParselet; use \QuackCompiler\Parselets\Expr\NameParselet; use \QuackCompiler\Parselets\Expr\PostfixOperatorParselet; use \QuackCompiler\Parselets\Expr\PrefixOperatorParselet; use \QuackCompiler\Parselets\Expr\TernaryParselet; use \QuackCompiler\Parselets\Expr\GroupParselet; use \QuackCompiler\Parselets\Expr\LambdaParselet; use \QuackCompiler\Parselets\Expr\ListParselet; use \QuackCompiler\Parselets\Expr\MemberAccessParselet; use \QuackCompiler\Parselets\Expr\CallParselet; use \QuackCompiler\Parselets\Expr\AccessParselet; use \QuackCompiler\Parselets\Expr\RangeParselet; use \QuackCompiler\Parselets\Expr\PartialFuncParselet; use \QuackCompiler\Parselets\Expr\WhereParselet; use \QuackCompiler\Parselets\Expr\MapParselet; use \QuackCompiler\Parselets\Expr\ObjectParselet; use \QuackCompiler\Parselets\Expr\BlockParselet; use \QuackCompiler\Parselets\Expr\TupleParselet; use \QuackCompiler\Parselets\Expr\MatchParselet; use \QuackCompiler\Parselets\Parselet; class ExprParser { use Attachable; use Parselet; public $reader; public function __construct($reader) { $this->reader = $reader; $this->register('&(', new PartialFuncParselet); $this->register(Tag::T_INTEGER, new LiteralParselet); $this->register(Tag::T_INT_HEX, new LiteralParselet); $this->register(Tag::T_INT_OCT, new LiteralParselet); $this->register(Tag::T_INT_BIN, new LiteralParselet); $this->register(Tag::T_DOUBLE, new LiteralParselet); $this->register(Tag::T_DOUBLE_EXP, new LiteralParselet); $this->register(Tag::T_STRING, new LiteralParselet); $this->register(Tag::T_REGEX, new LiteralParselet); $this->register(Tag::T_IDENT, new NameParselet); $this->register(Tag::T_TYPENAME, new NameParselet); $this->register(Tag::T_THEN, new TernaryParselet); $this->register('..', new RangeParselet); $this->register('(', new GroupParselet); $this->register('(', new CallParselet); $this->register('{', new ListParselet); $this->register('{', new AccessParselet); $this->register('%{', new ObjectParselet); $this->register('#{', new MapParselet); $this->register('#(', new TupleParselet); $this->register('&{', new BlockParselet); $this->register('&', new LambdaParselet); $this->register('.', new MemberAccessParselet); $this->register(Tag::T_ATOM, new LiteralParselet); $this->register(Tag::T_WHERE, new WhereParselet); $this->register(Tag::T_MATCH, new MatchParselet); $this->prefix('+'); $this->prefix('-'); $this->prefix('^^'); $this->prefix('*'); $this->prefix('~'); $this->prefix(Tag::T_NOT); $this->infixLeft('+', Precedence::ADDITIVE); $this->infixLeft('-', Precedence::ADDITIVE); $this->infixLeft('*', Precedence::MULTIPLICATIVE); $this->infixLeft('/', Precedence::MULTIPLICATIVE); $this->infixLeft(Tag::T_MOD, Precedence::MULTIPLICATIVE); $this->infixLeft(Tag::T_AND, Precedence::LOGICAL_AND); $this->infixLeft(Tag::T_OR, Precedence::LOGICAL_OR); $this->infixLeft(Tag::T_XOR, Precedence::LOGICAL_XOR); $this->infixLeft('|', Precedence::BITWISE_OR); $this->infixLeft('&', Precedence::BITWISE_AND); $this->infixLeft('<<', Precedence::BITWISE_SHIFT); $this->infixLeft('>>', Precedence::BITWISE_SHIFT); $this->infixLeft('=', Precedence::VALUE_COMPARATOR); $this->infixLeft('=~', Precedence::VALUE_COMPARATOR); $this->infixLeft('<>', Precedence::VALUE_COMPARATOR); $this->infixLeft('<=', Precedence::SIZE_COMPARATOR); $this->infixLeft('<', Precedence::SIZE_COMPARATOR); $this->infixLeft('>=', Precedence::SIZE_COMPARATOR); $this->infixLeft('>', Precedence::SIZE_COMPARATOR); $this->infixLeft('|', Precedence::PIPELINE); $this->infixRight('**', Precedence::EXPONENT); $this->infixRight(':-', Precedence::ASSIGNMENT); } public function _expr($precedence = 0, $opt = false) { $token = $this->reader->lookahead; $prefix = $this->prefixParseletForToken($token); if (is_null($prefix)) { if (!$opt) { $error_params = [ 'expected' => 'expression', 'found' => $token, 'parser' => $this->reader ]; if ($this->reader->isEOF()) { throw new EOFError($error_params); } throw new SyntaxError($error_params); } return null; } // We consume the token only when ensure it has a parselet, thus, // avoiding to rollback in the tape $this->reader->consume(); $left = $prefix->parse($this, $token); while ($precedence < $this->getPrecedence()) { $token = $this->reader->consumeAndFetch(); $infix = $this->infixParseletForToken($token); $left = $infix->parse($this, $left, $token); } return $left; } private function postfix($tag, $precedence) { $this->register($tag, new PostfixOperatorParselet($precedence)); } private function prefix($tag) { $this->register($tag, new PrefixOperatorParselet()); } private function infixLeft($tag, $precedence) { $this->register($tag, new BinaryOperatorParselet($precedence, false)); } private function infixRight($tag, $precedence) { $this->register($tag, new BinaryOperatorParselet($precedence, true)); } public function _optExpr() { return $this->_expr(0, true); } }
{ "pile_set_name": "Github" }
/* * reserved comment block * DO NOT REMOVE OR ALTER! */ /* * 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. */ package com.sun.org.apache.xalan.internal.xsltc.compiler; import java.io.OutputStreamWriter; import java.util.Properties; import java.util.StringTokenizer; import javax.xml.transform.OutputKeys; import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen; import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL; import com.sun.org.apache.bcel.internal.generic.InstructionList; import com.sun.org.apache.bcel.internal.generic.PUSH; import com.sun.org.apache.bcel.internal.generic.PUTFIELD; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator; import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Util; import com.sun.org.apache.xml.internal.serializer.Encodings; import com.sun.org.apache.xml.internal.utils.XML11Char; /** * @author Jacek Ambroziak * @author Santiago Pericas-Geertsen * @author Morten Jorgensen */ final class Output extends TopLevelElement { // TODO: use three-value variables for boolean values: true/false/default // These attributes are extracted from the xsl:output element. They also // appear as fields (with the same type, only public) in the translet private String _version; private String _method; private String _encoding; private boolean _omitHeader = false; private String _standalone; private String _doctypePublic; private String _doctypeSystem; private String _cdata; private boolean _indent = false; private String _mediaType; private String _indentamount; // Disables this output element (when other element has higher precedence) private boolean _disabled = false; // Some global constants private final static String STRING_SIG = "Ljava/lang/String;"; private final static String XML_VERSION = "1.0"; private final static String HTML_VERSION = "4.0"; /** * Displays the contents of this element (for debugging) */ public void display(int indent) { indent(indent); Util.println("Output " + _method); } /** * Disables this <xsl:output> element in case where there are some other * <xsl:output> element (from a different imported/included stylesheet) * with higher precedence. */ public void disable() { _disabled = true; } public boolean enabled() { return !_disabled; } public String getCdata() { return _cdata; } public String getOutputMethod() { return _method; } private void transferAttribute(Output previous, String qname) { if (!hasAttribute(qname) && previous.hasAttribute(qname)) { addAttribute(qname, previous.getAttribute(qname)); } } public void mergeOutput(Output previous) { // Transfer attributes from previous xsl:output transferAttribute(previous, "version"); transferAttribute(previous, "method"); transferAttribute(previous, "encoding"); transferAttribute(previous, "doctype-system"); transferAttribute(previous, "doctype-public"); transferAttribute(previous, "media-type"); transferAttribute(previous, "indent"); transferAttribute(previous, "omit-xml-declaration"); transferAttribute(previous, "standalone"); // Merge cdata-section-elements if (previous.hasAttribute("cdata-section-elements")) { // addAttribute works as a setter if it already exists addAttribute("cdata-section-elements", previous.getAttribute("cdata-section-elements") + ' ' + getAttribute("cdata-section-elements")); } // Transfer non-standard attributes as well String prefix = lookupPrefix("http://xml.apache.org/xalan"); if (prefix != null) { transferAttribute(previous, prefix + ':' + "indent-amount"); } prefix = lookupPrefix("http://xml.apache.org/xslt"); if (prefix != null) { transferAttribute(previous, prefix + ':' + "indent-amount"); } } /** * Scans the attribute list for the xsl:output instruction */ public void parseContents(Parser parser) { final Properties outputProperties = new Properties(); // Ask the parser if it wants this <xsl:output> element parser.setOutput(this); // Do nothing if other <xsl:output> element has higher precedence if (_disabled) return; String attrib = null; // Get the output version _version = getAttribute("version"); if (_version.equals(Constants.EMPTYSTRING)) { _version = null; } else { outputProperties.setProperty(OutputKeys.VERSION, _version); } // Get the output method - "xml", "html", "text" or <qname> (but not ncname) _method = getAttribute("method"); if (_method.equals(Constants.EMPTYSTRING)) { _method = null; } if (_method != null) { _method = _method.toLowerCase(); if ((_method.equals("xml"))|| (_method.equals("html"))|| (_method.equals("text"))|| ((XML11Char.isXML11ValidQName(_method)&&(_method.indexOf(":") > 0)))) { outputProperties.setProperty(OutputKeys.METHOD, _method); } else { reportError(this, parser, ErrorMsg.INVALID_METHOD_IN_OUTPUT, _method); } } // Get the output encoding - any value accepted here _encoding = getAttribute("encoding"); if (_encoding.equals(Constants.EMPTYSTRING)) { _encoding = null; } else { try { // Create a write to verify encoding support String canonicalEncoding; canonicalEncoding = Encodings.convertMime2JavaEncoding(_encoding); OutputStreamWriter writer = new OutputStreamWriter(System.out, canonicalEncoding); } catch (java.io.UnsupportedEncodingException e) { ErrorMsg msg = new ErrorMsg(ErrorMsg.UNSUPPORTED_ENCODING, _encoding, this); parser.reportError(Constants.WARNING, msg); } outputProperties.setProperty(OutputKeys.ENCODING, _encoding); } // Should the XML header be omitted - translate to true/false attrib = getAttribute("omit-xml-declaration"); if (!attrib.equals(Constants.EMPTYSTRING)) { if (attrib.equals("yes")) { _omitHeader = true; } outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, attrib); } // Add 'standalone' decaration to output - use text as is _standalone = getAttribute("standalone"); if (_standalone.equals(Constants.EMPTYSTRING)) { _standalone = null; } else { outputProperties.setProperty(OutputKeys.STANDALONE, _standalone); } // Get system/public identifiers for output DOCTYPE declaration _doctypeSystem = getAttribute("doctype-system"); if (_doctypeSystem.equals(Constants.EMPTYSTRING)) { _doctypeSystem = null; } else { outputProperties.setProperty(OutputKeys.DOCTYPE_SYSTEM, _doctypeSystem); } _doctypePublic = getAttribute("doctype-public"); if (_doctypePublic.equals(Constants.EMPTYSTRING)) { _doctypePublic = null; } else { outputProperties.setProperty(OutputKeys.DOCTYPE_PUBLIC, _doctypePublic); } // Names the elements of whose text contents should be output as CDATA _cdata = getAttribute("cdata-section-elements"); if (_cdata.equals(Constants.EMPTYSTRING)) { _cdata = null; } else { StringBuffer expandedNames = new StringBuffer(); StringTokenizer tokens = new StringTokenizer(_cdata); // Make sure to store names in expanded form while (tokens.hasMoreTokens()) { String qname = tokens.nextToken(); if (!XML11Char.isXML11ValidQName(qname)) { ErrorMsg err = new ErrorMsg(ErrorMsg.INVALID_QNAME_ERR, qname, this); parser.reportError(Constants.ERROR, err); } expandedNames.append( parser.getQName(qname).toString()).append(' '); } _cdata = expandedNames.toString(); outputProperties.setProperty(OutputKeys.CDATA_SECTION_ELEMENTS, _cdata); } // Get the indent setting - only has effect for xml and html output attrib = getAttribute("indent"); if (!attrib.equals(EMPTYSTRING)) { if (attrib.equals("yes")) { _indent = true; } outputProperties.setProperty(OutputKeys.INDENT, attrib); } else if (_method != null && _method.equals("html")) { _indent = true; } // indent-amount: extension attribute of xsl:output _indentamount = getAttribute( lookupPrefix("http://xml.apache.org/xalan"), "indent-amount"); // Hack for supporting Old Namespace URI. if (_indentamount.equals(EMPTYSTRING)){ _indentamount = getAttribute( lookupPrefix("http://xml.apache.org/xslt"), "indent-amount"); } if (!_indentamount.equals(EMPTYSTRING)) { outputProperties.setProperty("indent_amount", _indentamount); } // Get the MIME type for the output file _mediaType = getAttribute("media-type"); if (_mediaType.equals(Constants.EMPTYSTRING)) { _mediaType = null; } else { outputProperties.setProperty(OutputKeys.MEDIA_TYPE, _mediaType); } // Implied properties if (_method != null) { if (_method.equals("html")) { if (_version == null) { _version = HTML_VERSION; } if (_mediaType == null) { _mediaType = "text/html"; } } else if (_method.equals("text")) { if (_mediaType == null) { _mediaType = "text/plain"; } } } // Set output properties in current stylesheet parser.getCurrentStylesheet().setOutputProperties(outputProperties); } /** * Compile code that passes the information in this <xsl:output> element * to the appropriate fields in the translet */ public void translate(ClassGenerator classGen, MethodGenerator methodGen) { // Do nothing if other <xsl:output> element has higher precedence if (_disabled) return; ConstantPoolGen cpg = classGen.getConstantPool(); InstructionList il = methodGen.getInstructionList(); int field = 0; il.append(classGen.loadTranslet()); // Only update _version field if set and different from default if ((_version != null) && (!_version.equals(XML_VERSION))) { field = cpg.addFieldref(TRANSLET_CLASS, "_version", STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _version)); il.append(new PUTFIELD(field)); } // Only update _method field if "method" attribute used if (_method != null) { field = cpg.addFieldref(TRANSLET_CLASS, "_method", STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _method)); il.append(new PUTFIELD(field)); } // Only update if _encoding field is "encoding" attribute used if (_encoding != null) { field = cpg.addFieldref(TRANSLET_CLASS, "_encoding", STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _encoding)); il.append(new PUTFIELD(field)); } // Only update if "omit-xml-declaration" used and set to 'yes' if (_omitHeader) { field = cpg.addFieldref(TRANSLET_CLASS, "_omitHeader", "Z"); il.append(DUP); il.append(new PUSH(cpg, _omitHeader)); il.append(new PUTFIELD(field)); } // Add 'standalone' decaration to output - use text as is if (_standalone != null) { field = cpg.addFieldref(TRANSLET_CLASS, "_standalone", STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _standalone)); il.append(new PUTFIELD(field)); } // Set system/public doctype only if both are set field = cpg.addFieldref(TRANSLET_CLASS,"_doctypeSystem",STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _doctypeSystem)); il.append(new PUTFIELD(field)); field = cpg.addFieldref(TRANSLET_CLASS,"_doctypePublic",STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _doctypePublic)); il.append(new PUTFIELD(field)); // Add 'medye-type' decaration to output - if used if (_mediaType != null) { field = cpg.addFieldref(TRANSLET_CLASS, "_mediaType", STRING_SIG); il.append(DUP); il.append(new PUSH(cpg, _mediaType)); il.append(new PUTFIELD(field)); } // Compile code to set output indentation on/off if (_indent) { field = cpg.addFieldref(TRANSLET_CLASS, "_indent", "Z"); il.append(DUP); il.append(new PUSH(cpg, _indent)); il.append(new PUTFIELD(field)); } //Compile code to set indent amount. if(_indentamount != null && !_indentamount.equals(EMPTYSTRING)){ field = cpg.addFieldref(TRANSLET_CLASS, "_indentamount", "I"); il.append(DUP); il.append(new PUSH(cpg, Integer.parseInt(_indentamount))); il.append(new PUTFIELD(field)); } // Forward to the translet any elements that should be output as CDATA if (_cdata != null) { int index = cpg.addMethodref(TRANSLET_CLASS, "addCdataElement", "(Ljava/lang/String;)V"); StringTokenizer tokens = new StringTokenizer(_cdata); while (tokens.hasMoreTokens()) { il.append(DUP); il.append(new PUSH(cpg, tokens.nextToken())); il.append(new INVOKEVIRTUAL(index)); } } il.append(POP); // Cleanup - pop last translet reference off stack } }
{ "pile_set_name": "Github" }
/* $Id: sportster.c,v 1.16.2.4 2004/01/13 23:48:39 keil Exp $ * * low level stuff for USR Sportster internal TA * * Author Karsten Keil * Copyright by Karsten Keil <[email protected]> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * * Thanks to Christian "naddy" Weisgerber (3Com, US Robotics) for documentation * * */ #include <linux/init.h> #include "hisax.h" #include "isac.h" #include "hscx.h" #include "isdnl1.h" static const char *sportster_revision = "$Revision: 1.16.2.4 $"; #define byteout(addr, val) outb(val, addr) #define bytein(addr) inb(addr) #define SPORTSTER_ISAC 0xC000 #define SPORTSTER_HSCXA 0x0000 #define SPORTSTER_HSCXB 0x4000 #define SPORTSTER_RES_IRQ 0x8000 #define SPORTSTER_RESET 0x80 #define SPORTSTER_INTE 0x40 static inline int calc_off(unsigned int base, unsigned int off) { return (base + ((off & 0xfc) << 8) + ((off & 3) << 1)); } static inline void read_fifo(unsigned int adr, u_char *data, int size) { insb(adr, data, size); } static void write_fifo(unsigned int adr, u_char *data, int size) { outsb(adr, data, size); } /* Interface functions */ static u_char ReadISAC(struct IsdnCardState *cs, u_char offset) { return (bytein(calc_off(cs->hw.spt.isac, offset))); } static void WriteISAC(struct IsdnCardState *cs, u_char offset, u_char value) { byteout(calc_off(cs->hw.spt.isac, offset), value); } static void ReadISACfifo(struct IsdnCardState *cs, u_char *data, int size) { read_fifo(cs->hw.spt.isac, data, size); } static void WriteISACfifo(struct IsdnCardState *cs, u_char *data, int size) { write_fifo(cs->hw.spt.isac, data, size); } static u_char ReadHSCX(struct IsdnCardState *cs, int hscx, u_char offset) { return (bytein(calc_off(cs->hw.spt.hscx[hscx], offset))); } static void WriteHSCX(struct IsdnCardState *cs, int hscx, u_char offset, u_char value) { byteout(calc_off(cs->hw.spt.hscx[hscx], offset), value); } /* * fast interrupt HSCX stuff goes here */ #define READHSCX(cs, nr, reg) bytein(calc_off(cs->hw.spt.hscx[nr], reg)) #define WRITEHSCX(cs, nr, reg, data) byteout(calc_off(cs->hw.spt.hscx[nr], reg), data) #define READHSCXFIFO(cs, nr, ptr, cnt) read_fifo(cs->hw.spt.hscx[nr], ptr, cnt) #define WRITEHSCXFIFO(cs, nr, ptr, cnt) write_fifo(cs->hw.spt.hscx[nr], ptr, cnt) #include "hscx_irq.c" static irqreturn_t sportster_interrupt(int intno, void *dev_id) { struct IsdnCardState *cs = dev_id; u_char val; u_long flags; spin_lock_irqsave(&cs->lock, flags); val = READHSCX(cs, 1, HSCX_ISTA); Start_HSCX: if (val) hscx_int_main(cs, val); val = ReadISAC(cs, ISAC_ISTA); Start_ISAC: if (val) isac_interrupt(cs, val); val = READHSCX(cs, 1, HSCX_ISTA); if (val) { if (cs->debug & L1_DEB_HSCX) debugl1(cs, "HSCX IntStat after IntRoutine"); goto Start_HSCX; } val = ReadISAC(cs, ISAC_ISTA); if (val) { if (cs->debug & L1_DEB_ISAC) debugl1(cs, "ISAC IntStat after IntRoutine"); goto Start_ISAC; } /* get a new irq impulse if there any pending */ bytein(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ + 1); spin_unlock_irqrestore(&cs->lock, flags); return IRQ_HANDLED; } static void release_io_sportster(struct IsdnCardState *cs) { int i, adr; byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, 0); for (i = 0; i < 64; i++) { adr = cs->hw.spt.cfg_reg + i * 1024; release_region(adr, 8); } } static void reset_sportster(struct IsdnCardState *cs) { cs->hw.spt.res_irq |= SPORTSTER_RESET; /* Reset On */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); mdelay(10); cs->hw.spt.res_irq &= ~SPORTSTER_RESET; /* Reset Off */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); mdelay(10); } static int Sportster_card_msg(struct IsdnCardState *cs, int mt, void *arg) { u_long flags; switch (mt) { case CARD_RESET: spin_lock_irqsave(&cs->lock, flags); reset_sportster(cs); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_RELEASE: release_io_sportster(cs); return (0); case CARD_INIT: spin_lock_irqsave(&cs->lock, flags); reset_sportster(cs); inithscxisac(cs, 1); cs->hw.spt.res_irq |= SPORTSTER_INTE; /* IRQ On */ byteout(cs->hw.spt.cfg_reg + SPORTSTER_RES_IRQ, cs->hw.spt.res_irq); inithscxisac(cs, 2); spin_unlock_irqrestore(&cs->lock, flags); return (0); case CARD_TEST: return (0); } return (0); } static int get_io_range(struct IsdnCardState *cs) { int i, j, adr; for (i = 0; i < 64; i++) { adr = cs->hw.spt.cfg_reg + i * 1024; if (!request_region(adr, 8, "sportster")) { printk(KERN_WARNING "HiSax: USR Sportster config port " "%x-%x already in use\n", adr, adr + 8); break; } } if (i == 64) return (1); else { for (j = 0; j < i; j++) { adr = cs->hw.spt.cfg_reg + j * 1024; release_region(adr, 8); } return (0); } } int setup_sportster(struct IsdnCard *card) { struct IsdnCardState *cs = card->cs; char tmp[64]; strcpy(tmp, sportster_revision); printk(KERN_INFO "HiSax: USR Sportster driver Rev. %s\n", HiSax_getrev(tmp)); if (cs->typ != ISDN_CTYPE_SPORTSTER) return (0); cs->hw.spt.cfg_reg = card->para[1]; cs->irq = card->para[0]; if (!get_io_range(cs)) return (0); cs->hw.spt.isac = cs->hw.spt.cfg_reg + SPORTSTER_ISAC; cs->hw.spt.hscx[0] = cs->hw.spt.cfg_reg + SPORTSTER_HSCXA; cs->hw.spt.hscx[1] = cs->hw.spt.cfg_reg + SPORTSTER_HSCXB; switch (cs->irq) { case 5: cs->hw.spt.res_irq = 1; break; case 7: cs->hw.spt.res_irq = 2; break; case 10:cs->hw.spt.res_irq = 3; break; case 11:cs->hw.spt.res_irq = 4; break; case 12:cs->hw.spt.res_irq = 5; break; case 14:cs->hw.spt.res_irq = 6; break; case 15:cs->hw.spt.res_irq = 7; break; default:release_io_sportster(cs); printk(KERN_WARNING "Sportster: wrong IRQ\n"); return (0); } printk(KERN_INFO "HiSax: USR Sportster config irq:%d cfg:0x%X\n", cs->irq, cs->hw.spt.cfg_reg); setup_isac(cs); cs->readisac = &ReadISAC; cs->writeisac = &WriteISAC; cs->readisacfifo = &ReadISACfifo; cs->writeisacfifo = &WriteISACfifo; cs->BC_Read_Reg = &ReadHSCX; cs->BC_Write_Reg = &WriteHSCX; cs->BC_Send_Data = &hscx_fill_fifo; cs->cardmsg = &Sportster_card_msg; cs->irq_func = &sportster_interrupt; ISACVersion(cs, "Sportster:"); if (HscxVersion(cs, "Sportster:")) { printk(KERN_WARNING "Sportster: wrong HSCX versions check IO address\n"); release_io_sportster(cs); return (0); } return (1); }
{ "pile_set_name": "Github" }
// Copyright 2019 The go-interpreter Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !appengine package compile import "unsafe" func jitcall(asm unsafe.Pointer, stack, locals, globals *[]uint64, mem *[]byte) uint64
{ "pile_set_name": "Github" }
#!/bin/bash echo "Uploading code coverage results" bash <(curl -s https://codecov.io/bash)
{ "pile_set_name": "Github" }
OneOps Web Application ====================== pg gem install issue on osx: gem install pg -v 0.17.0 -- --with-pg-config=/Library/PostgreSQL/9.1/bin/pg_config export DYLD_LIBRARY_PATH=/library/PostgreSQL/9.1/lib:$DYLD_LIBRARY_PATH
{ "pile_set_name": "Github" }
--- %YAML:1.0 test: Strings brief: > Any group of characters beginning with an alphabetic or numeric character is a string, unless it belongs to one of the groups below (such as an Integer or Time). yaml: | String php: | 'String' --- test: String characters brief: > A string can contain any alphabetic or numeric character, along with many punctuation characters, including the period, dash, space, quotes, exclamation, and question mark. yaml: | - What's Yaml? - It's for writing data structures in plain text. - And? - And what? That's not good enough for you? - No, I mean, "And what about Yaml?" - Oh, oh yeah. Uh.. Yaml for Ruby. php: | array( "What's Yaml?", "It's for writing data structures in plain text.", "And?", "And what? That's not good enough for you?", "No, I mean, \"And what about Yaml?\"", "Oh, oh yeah. Uh.. Yaml for Ruby." ) --- test: Indicators in Strings brief: > Be careful using indicators in strings. In particular, the comma, colon, and pound sign must be used carefully. yaml: | the colon followed by space is an indicator: but is a string:right here same for the pound sign: here we have it#in a string the comma can, honestly, be used in most cases: [ but not in, inline collections ] php: | array( 'the colon followed by space is an indicator' => 'but is a string:right here', 'same for the pound sign' => 'here we have it#in a string', 'the comma can, honestly, be used in most cases' => array('but not in', 'inline collections') ) --- test: Forcing Strings brief: > Any YAML type can be forced into a string using the explicit !str method. yaml: | date string: !str 2001-08-01 number string: !str 192 php: | array( 'date string' => '2001-08-01', 'number string' => '192' ) --- test: Single-quoted Strings brief: > You can also enclose your strings within single quotes, which allows use of slashes, colons, and other indicators freely. Inside single quotes, you can represent a single quote in your string by using two single quotes next to each other. yaml: | all my favorite symbols: '#:!/%.)' a few i hate: '&(*' why do i hate them?: 'it''s very hard to explain' entities: '&pound; me' php: | array( 'all my favorite symbols' => '#:!/%.)', 'a few i hate' => '&(*', 'why do i hate them?' => 'it\'s very hard to explain', 'entities' => '&pound; me' ) --- test: Double-quoted Strings brief: > Enclosing strings in double quotes allows you to use escapings to represent ASCII and Unicode characters. yaml: | i know where i want my line breaks: "one here\nand another here\n" php: | array( 'i know where i want my line breaks' => "one here\nand another here\n" ) --- test: Multi-line Quoted Strings todo: true brief: > Both single- and double-quoted strings may be carried on to new lines in your YAML document. They must be indented a step and indentation is interpreted as a single space. yaml: | i want a long string: "so i'm going to let it go on and on to other lines until i end it with a quote." php: | array('i want a long string' => "so i'm going to ". "let it go on and on to other lines ". "until i end it with a quote." ) --- test: Plain scalars todo: true brief: > Unquoted strings may also span multiple lines, if they are free of YAML space indicators and indented. yaml: | - My little toe is broken in two places; - I'm crazy to have skied this way; - I'm not the craziest he's seen, since there was always the German guy who skied for 3 hours on a broken shin bone (just below the kneecap); - Nevertheless, second place is respectable, and he doesn't recommend going for the record; - He's going to put my foot in plaster for a month; - This would impair my skiing ability somewhat for the duration, as can be imagined. php: | array( "My little toe is broken in two places;", "I'm crazy to have skied this way;", "I'm not the craziest he's seen, since there was always ". "the German guy who skied for 3 hours on a broken shin ". "bone (just below the kneecap);", "Nevertheless, second place is respectable, and he doesn't ". "recommend going for the record;", "He's going to put my foot in plaster for a month;", "This would impair my skiing ability somewhat for the duration, ". "as can be imagined." ) --- test: 'Null' brief: > You can use the tilde '~' character for a null value. yaml: | name: Mr. Show hosted by: Bob and David date of next season: ~ php: | array( 'name' => 'Mr. Show', 'hosted by' => 'Bob and David', 'date of next season' => null ) --- test: Boolean brief: > You can use 'true' and 'false' for Boolean values. yaml: | Is Gus a Liar?: true Do I rely on Gus for Sustenance?: false php: | array( 'Is Gus a Liar?' => true, 'Do I rely on Gus for Sustenance?' => false ) --- test: Integers dump_skip: true brief: > An integer is a series of numbers, optionally starting with a positive or negative sign. Integers may also contain commas for readability. yaml: | zero: 0 simple: 12 one-thousand: 1,000 negative one-thousand: -1,000 php: | array( 'zero' => 0, 'simple' => 12, 'one-thousand' => 1000, 'negative one-thousand' => -1000 ) --- test: Integers as Map Keys brief: > An integer can be used a dictionary key. yaml: | 1: one 2: two 3: three php: | array( 1 => 'one', 2 => 'two', 3 => 'three' ) --- test: Floats dump_skip: true brief: > Floats are represented by numbers with decimals, allowing for scientific notation, as well as positive and negative infinity and "not a number." yaml: | a simple float: 2.00 larger float: 1,000.09 scientific notation: 1.00009e+3 php: | array( 'a simple float' => 2.0, 'larger float' => 1000.09, 'scientific notation' => 1000.09 ) --- test: Time todo: true brief: > You can represent timestamps by using ISO8601 format, or a variation which allows spaces between the date, time and time zone. yaml: | iso8601: 2001-12-14t21:59:43.10-05:00 space seperated: 2001-12-14 21:59:43.10 -05:00 php: | array( 'iso8601' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), 'space seperated' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ) ) --- test: Date todo: true brief: > A date can be represented by its year, month and day in ISO8601 order. yaml: | 1976-07-31 php: | date( 1976, 7, 31 )
{ "pile_set_name": "Github" }
Friends University
{ "pile_set_name": "Github" }
#!/bin/bash # Online recovery 2nd stage script set -o xtrace DATADIR=$1 # main dabatase cluster DEST=$2 # hostname of the DB node to be recovered DESTDIR=$3 # database cluster of the DB node to be recovered PORT=$4 # PostgreSQL port number PGHOME=/usr/pgsql-13 ARCHIVEDIR=/var/lib/pgsql/archivedir # archive log directory # Force to flush current value of sequences to xlog ${PGHOME}/bin/psql -p $PORT -t -c 'SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn' template1| while read i do if [ "$i" != "" ]; then psql -p $PORT -c "SELECT setval(oid, nextval(oid)) FROM pg_class WHERE relkind = 'S'" $i fi done psql -p $PORT -c "SELECT pgpool_switch_xlog('$ARCHIVEDIR')" template1
{ "pile_set_name": "Github" }
context("test-show-lsm") test_that("show_lsm returns a plot", { patches_area <- show_lsm(landscape, what = "lsm_p_area") expect_is(patches_area, "ggplot") }) test_that("show_lsm returns a facet plot", { patches_area <- show_lsm(landscape, what = "lsm_p_area", class = c(1, 3), labels = FALSE) expect_is(patches_area$facet, "FacetWrap") }) test_that("show_lsm can handle stacks, bricks and lists", { plots_list <- show_lsm(landscape_list, what = "lsm_p_area") plots_stack <- show_lsm(landscape_stack, what = "lsm_p_area") plots_brick <- show_lsm(landscape_brick, what = "lsm_p_area") expect_is(plots_list[[1]], "ggplot") expect_is(plots_list[[2]], "ggplot") expect_is(plots_stack[[1]], "ggplot") expect_is(plots_stack[[2]], "ggplot") expect_is(plots_brick[[1]], "ggplot") expect_is(plots_brick[[2]], "ggplot") }) test_that("show_lsm returns warnings and errors", { expect_warning(show_lsm(landscape, what = "lsm_p_area", class = c(1, "global")), regexp = "'global' and 'all' can't be combined with any other class-argument.", fixed = TRUE) expect_error(show_lsm(landscape, what = "lsm_p_invented_metric"), regexp = "Please provide one patch level metric only. To list available metrics, run list_lsm(level = 'patch').", fixed = TRUE) expect_error(show_lsm(landscape, what = "lsm_p_area", class = 5), regexp = "'class' must contain at least one value of a class existing in the landscape.", fixed = TRUE) })
{ "pile_set_name": "Github" }
namespace :shoulda do # From http://blog.internautdesign.com/2007/11/2/a-yaml_to_shoulda-rake-task # [email protected] desc "Converts a YAML file (FILE=./path/to/yaml) into a Shoulda skeleton" task :from_yaml do require 'yaml' def yaml_to_context(hash, indent = 0) indent1 = ' ' * indent indent2 = ' ' * (indent + 1) hash.each_pair do |context, shoulds| puts indent1 + "context \"#{context}\" do" puts shoulds.each do |should| yaml_to_context( should, indent + 1 ) and next if should.is_a?( Hash ) puts indent2 + "should_eventually \"" + should.gsub(/^should +/,'') + "\" do" puts indent2 + "end" puts end puts indent1 + "end" end end puts("Please pass in a FILE argument.") and exit unless ENV['FILE'] yaml_to_context( YAML.load_file( ENV['FILE'] ) ) end end
{ "pile_set_name": "Github" }
% Generated by roxygen2: do not edit by hand % Please edit documentation in R/eForce.R \name{eForce} \alias{eForce} \title{Force network graph} \usage{ eForce(networkMatrix, propertyDf = NULL, size = NULL, maxR = 25, minR = 15, density = 0.05, attractiveness = 1.2, showLabel = TRUE, theme = "default", title = NULL, subtitle = NULL, title.x = "center", title.y = "top", legend = TRUE, legend.x = "left", legend.y = "top", legend.orient = "horizontal", toolbox = TRUE, toolbox.orient = "horizontal", toolbox.x = "right", toolbox.y = "top", dataView = FALSE, readOnly = TRUE, mark = TRUE, dataZoom = FALSE, tooltip = TRUE, tooltip.trigger = "item", formatter = "", calculable = FALSE, xlab = NULL, ylab = NULL, opt = list()) } \arguments{ \item{networkMatrix}{required, a symmetric matrix, each cell value indicates the weight of the two nodes and the 0 or NA cell would not be counted in. The matrix should have colnames or rownames.} \item{propertyDf}{optional, dataframe which contain the metadata for the nodes. It could contain category, value and color columns. The colnames and rownames are required.} \item{opt}{力导向图选项.} } \value{ The HTML code as a character string. } \description{ ECharts style 力导向图 graph visulize the social network matrix data. } \examples{ testData <- matrix(1:25, nrow=5) #测试中文 eForce(testData) }
{ "pile_set_name": "Github" }
easyblock = 'ConfigureMake' name = 'MIRA' version = '4.0.2' homepage = 'https://sourceforge.net/p/mira-assembler/wiki/Home/' description = """MIRA is a whole genome shotgun and EST sequence assembler for Sanger, 454, Solexa (Illumina), IonTorrent data and PacBio (the latter at the moment only CCS and error-corrected CLR reads).""" toolchain = {'name': 'foss', 'version': '2018b'} toolchainopts = {'cstd': 'c++03'} sources = ['%(namelower)s-%(version)s.tar.bz2'] source_urls = [('https://sourceforge.net/projects/mira-assembler/files/MIRA/stable/', 'download')] patches = [ 'MIRA-4.0.2-quirks.patch', 'MIRA-4.0.2_fix-ads-include.patch', ] checksums = [ 'a32cb2b21e0968a5536446287c895fe9e03d11d78957554e355c1080b7b92a80', # src 'fd8d3bebdbdb198ecbe472a998d63978ac54ab8f68cf1fdc69b5842a6411979f', # MIRA-4.0.2-quirks.patch '3d8f14e261e421407ccc1aedd39b51c618529f351ced638b8c7e887a790412a8', # MIRA-4.0.2_fix-ads-include.patch ] builddependencies = [('flex', '2.5.39')] dependencies = [ ('Boost', '1.67.0'), ('expat', '2.2.5'), ('zlib', '1.2.11'), ('gperftools', '2.6.3'), ] preconfigopts = 'export CFLAGS="$CFLAGS -fpermissive" && ' preconfigopts += 'export CXXFLAGS="$CXXFLAGS -fpermissive" && ' configopts = '--with-boost=$EBROOTBOOST --with-expat=$EBROOTEXPAT --with-zlib=$EBROOTZLIB ' configopts += '--with-tcmalloc-dir=$EBROOTGPERFTOOLS/lib ' sanity_check_paths = { 'files': ['bin/mira', 'bin/mirabait', 'bin/miraconvert', 'bin/miramem'], 'dirs': ['share/mira'], } moduleclass = 'bio'
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup /> </Project>
{ "pile_set_name": "Github" }
/** * 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. * * @providesModule isTextNode * @typechecks */ var isNode = require('isNode'); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode;
{ "pile_set_name": "Github" }
PACKAGES += nodefinder pkg_nodefinder_name = nodefinder pkg_nodefinder_description = automatic node discovery via UDP multicast pkg_nodefinder_homepage = https://github.com/erlanger/nodefinder pkg_nodefinder_fetch = git pkg_nodefinder_repo = https://github.com/okeuday/nodefinder pkg_nodefinder_commit = master
{ "pile_set_name": "Github" }
/* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include <stdbool.h> #include <stdint.h> #include "twi_master.h" #include "synaptics_touchpad.h" /*lint ++flb "Enter library region" */ #define PRODUCT_ID_BYTES 10U //!< Number of bytes to expect to be in product ID static uint8_t m_device_address; //!< Device address in bits [7:1] static const uint8_t expected_product_id[PRODUCT_ID_BYTES] = {'T', 'M', '1', '9', '4', '4', '-', '0', '0', '2'}; //!< Product ID expected to get from product ID query bool touchpad_init(uint8_t device_address) { bool transfer_succeeded = true; m_device_address = (uint8_t)(device_address << 1); // Do a soft reset uint8_t reset_command = 0x01; transfer_succeeded &= touchpad_write_register(TOUCHPAD_RESET, reset_command); // Page select 0 uint8_t page_to_select = 0x00; transfer_succeeded &= touchpad_write_register(TOUCHPAD_PAGESELECT, page_to_select); // Read and verify product ID transfer_succeeded &= touchpad_product_id_verify(); return transfer_succeeded; } bool touchpad_product_id_verify(void) { bool transfer_succeeded = true; uint8_t product_id[PRODUCT_ID_BYTES]; transfer_succeeded &= touchpad_product_id_read(product_id, PRODUCT_ID_BYTES); for (uint8_t i = 0; i < 10; i++) { if (product_id[i] != expected_product_id[i]) { transfer_succeeded = false; } } return transfer_succeeded; } bool touchpad_reset(void) { uint8_t w2_data[2] = {TOUCHPAD_COMMAND, 0x01}; return twi_master_transfer(m_device_address, w2_data, 2, TWI_ISSUE_STOP); } bool touchpad_interrupt_status_read(uint8_t *interrupt_status) { return touchpad_read_register(TOUCHPAD_INT_STATUS, interrupt_status); } bool touchpad_set_sleep_mode(TouchpadSleepMode_t mode) { return touchpad_write_register(TOUCHPAD_CONTROL, (uint8_t)mode); } bool touchpad_read_register(uint8_t register_address, uint8_t *value) { bool transfer_succeeded = true; transfer_succeeded &= twi_master_transfer(m_device_address, &register_address, 1, TWI_DONT_ISSUE_STOP); if (transfer_succeeded) { transfer_succeeded &= twi_master_transfer(m_device_address | TWI_READ_BIT, value, 1, TWI_ISSUE_STOP); } return transfer_succeeded; } bool touchpad_write_register(uint8_t register_address, const uint8_t value) { uint8_t w2_data[2]; w2_data[0] = register_address; w2_data[1] = value; return twi_master_transfer(m_device_address, w2_data, 2, TWI_ISSUE_STOP); } bool touchpad_product_id_read(uint8_t *product_id, uint8_t product_id_bytes) { uint8_t w2_data[1]; bool transfer_succeeded = true; w2_data[0] = TOUCHPAD_PRODUCT_ID; transfer_succeeded &= twi_master_transfer(m_device_address, w2_data, 1, TWI_DONT_ISSUE_STOP); if (transfer_succeeded) { transfer_succeeded &= twi_master_transfer(m_device_address | TWI_READ_BIT, product_id, product_id_bytes, TWI_ISSUE_STOP); } return transfer_succeeded; } /*lint --flb "Leave library region" */
{ "pile_set_name": "Github" }
/*! * Copyright (c) 2016 by Contributors * \file array_view.h * \brief Read only data structure to reference array */ #ifndef DMLC_ARRAY_VIEW_H_ #define DMLC_ARRAY_VIEW_H_ #include <vector> #include <array> namespace dmlc { /*! * \brief Read only data structure to reference continuous memory region of array. * Provide unified view for vector, array and C style array. * This data structure do not guarantee aliveness of referenced array. * * Make sure do not use array_view to record data in async function closures. * Also do not use array_view to create reference to temporary data structure. * * \tparam ValueType The value * * \code * std::vector<int> myvec{1,2,3}; * dmlc::array_view<int> view(myvec); * // indexed visit to the view. * LOG(INFO) << view[0]; * * for (int v : view) { * // visit each element in the view * } * \endcode */ template<typename ValueType> class array_view { public: /*! \brief default constructor */ array_view() = default; /*! * \brief default copy constructor * \param other another array view. */ array_view(const array_view<ValueType> &other) = default; // NOLINT(*) #ifndef _MSC_VER /*! * \brief default move constructor * \param other another array view. */ array_view(array_view<ValueType>&& other) = default; // NOLINT(*) #else /*! * \brief default move constructor * \param other another array view. */ array_view(array_view<ValueType>&& other) { // NOLINT(*) begin_ = other.begin_; size_ = other.size_; other.begin_ = nullptr; } #endif /*! * \brief default assign constructor * \param other another array view. * \return self. */ array_view<ValueType>& operator=(const array_view<ValueType>& other) = default; // NOLINT(*) /*! * \brief construct array view std::vector * \param other vector container */ array_view(const std::vector<ValueType>& other) { // NOLINT(*) if (other.size() != 0) { begin_ = &other[0]; size_ = other.size(); } } /*! * \brief construct array std::array * \param other another array view. */ template<std::size_t size> array_view(const std::array<ValueType, size>& other) { // NOLINT(*) if (size != 0) { begin_ = &other[0]; size_ = size; } } /*! * \brief construct array view from continuous segment * \param begin beginning pointre * \param end end pointer */ array_view(const ValueType* begin, const ValueType* end) { if (begin < end) { begin_ = begin; size_ = end - begin; } } /*! \return size of the array */ inline size_t size() const { return size_; } /*! \return begin of the array */ inline const ValueType* begin() const { return begin_; } /*! \return end point of the array */ inline const ValueType* end() const { return begin_ + size_; } /*! * \brief get i-th element from the view * \param i The index. * \return const reference to i-th element. */ inline const ValueType& operator[](size_t i) const { return begin_[i]; } private: /*! \brief the begin of the view */ const ValueType* begin_{nullptr}; /*! \brief The size of the view */ size_t size_{0}; }; } // namespace dmlc #endif // DMLC_ARRAY_VIEW_H_
{ "pile_set_name": "Github" }
<html> <head> <meta charset="utf-8"> <title>ECharts</title> <!-- 引入 echarts.js --> <script src="echarts.js"></script> </head> <body> <div id="showhere" style="width:800px; height:600px;"></div> <script> var myChart = echarts.init(document.getElementById('showhere')); var option = { title: { text: '十九大工作报告', }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: { data: ['报告词频'] }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', boundaryGap: [0, 0.01] }, yAxis: { type: 'category', data: ['民主', '更加', '创新', '安全', '推动', '现代化', '我国', '完善', '伟大', '经济', '必须', '时代', '我们', '文化', '体系', '加强', '新', '特色', '政治', '社会', '推进', '制度', '实现', '全面', '国家', '党', '坚持', '社会主义', '建设', '人民', '中国', '发展'] }, series: [ { name: '报告词频', type: 'bar', data: [44, 44, 44, 46, 47, 47, 50, 51, 58, 59, 61, 63, 64, 66, 68, 71, 77, 79, 80, 80, 81, 83, 83, 88, 90, 103, 130, 146, 148, 157, 168, 212] } ] }; myChart.setOption(option); </script> </body> </html>
{ "pile_set_name": "Github" }
package kubetest import ( osapps_v1 "github.com/openshift/api/apps/v1" osproject_v1 "github.com/openshift/api/project/v1" osroutes_v1 "github.com/openshift/api/route/v1" ) func (o *K8SClientMock) GetRoute(namespace, name string) (*osroutes_v1.Route, error) { args := o.Called(namespace, name) return args.Get(0).(*osroutes_v1.Route), args.Error(1) } func (o *K8SClientMock) GetDeploymentConfig(namespace string, deploymentName string) (*osapps_v1.DeploymentConfig, error) { args := o.Called(namespace, deploymentName) return args.Get(0).(*osapps_v1.DeploymentConfig), args.Error(1) } func (o *K8SClientMock) GetDeploymentConfigs(namespace string) ([]osapps_v1.DeploymentConfig, error) { args := o.Called(namespace) return args.Get(0).([]osapps_v1.DeploymentConfig), args.Error(1) } func (o *K8SClientMock) GetProject(project string) (*osproject_v1.Project, error) { args := o.Called(project) return args.Get(0).(*osproject_v1.Project), args.Error(1) } func (o *K8SClientMock) GetProjects(labelSelector string) ([]osproject_v1.Project, error) { args := o.Called(labelSelector) return args.Get(0).([]osproject_v1.Project), args.Error(1) } func (o *K8SClientMock) UpdateProject(project string, jsonPatch string) (*osproject_v1.Project, error) { args := o.Called(project) return args.Get(0).(*osproject_v1.Project), args.Error(1) }
{ "pile_set_name": "Github" }
import logging logger = logging.getLogger(__name__) import gi gi.require_version('Gst', '1.0') from gi.repository import GObject, Gst GObject.threads_init() Gst.init(None) logger.debug("Loading") class Recognizer(GObject.GObject): __gsignals__ = { 'finished' : (GObject.SIGNAL_RUN_LAST, GObject.TYPE_NONE, (GObject.TYPE_STRING,)) } def __init__(self, config): GObject.GObject.__init__(self) self.commands = {} logger.debug("Initializing Recognizer") logger.debug(config) logger.debug(config.options) # Configure Audio Source src = config.options['microphone'] if src: #audio_src = 'alsasrc device="hw:{0},0"'.format(src) audio_src = 'autoaudiosrc device="hw:{0},0"'.format(src) else: audio_src = 'autoaudiosrc' # Build Pipeline cmd = ( audio_src + ' ! audioconvert' + ' ! audioresample' + ' ! pocketsphinx {}'.format(' '.join([ '{}={}'.format(opt, val) for opt, val in [ ('lm', config.lang_file), ('dict', config.dic_file), ('fsg', config.fsg_file) ] if val is not None ])) + ' ! appsink sync=false' ) logger.debug(cmd) try: self.pipeline = Gst.parse_launch(cmd) except Exception as e: print(e.message) print("You may need to install gstreamer1.0-pocketsphinx") raise e # Process Results From Pipeline With 'self.result()' bus = self.pipeline.get_bus() bus.add_signal_watch() bus.connect('message::element', self.result) def listen(self): self.pipeline.set_state(Gst.State.PLAYING) def pause(self): self.pipeline.set_state(Gst.State.PAUSED) def result(self, bus, msg): msg_struct = msg.get_structure() # Ignore Messages That Aren't From Pocketsphinx msgtype = msg_struct.get_name() if msgtype != 'pocketsphinx': return # If We Have A Final Command, Send It For Processing command = msg_struct.get_string('hypothesis') if command != '' and msg_struct.get_boolean('final')[1]: self.emit("finished", command)
{ "pile_set_name": "Github" }
From d48bebc211cc216aaa78bdf25d7f0b0143d6333b Mon Sep 17 00:00:00 2001 Author: Unrecognisable Format Date: Wed, 12 Oct 2016 19:03:51 -0700 Subject: [PATCH 1/5] Subject line --- mode change 100755 => 100644 l.php diff --git a/l.php b/l.php old mode 100755 new mode 100644
{ "pile_set_name": "Github" }
<!DOCTYPE html><html><head> <title>Universal selector (no namespaces)</title> <style type="text/css">* { color : lime } ul, p { color : red } *.t1 { color : lime } </style> <link rel="author" title="Daniel Glazman" href="http://glazman.org/"> <link rel="author" title="Ian Hickson" href="mailto:[email protected]"> <link rel="help" href="https://www.w3.org/TR/css3-selectors/#selectors"> <!-- bogus link to make sure it gets found --> <meta name="flags" content=""> </head> <body> <p><!--Replaced (ul, p) --></p> <ul><!--Replaced (ul, p) --></ul> </body></html>
{ "pile_set_name": "Github" }
export function isArray(obj) { return Object.prototype.toString.call(obj) === "[object Array]" } // Checks if an object has a property. export function has(obj, propName) { return Object.prototype.hasOwnProperty.call(obj, propName) }
{ "pile_set_name": "Github" }
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <time.h> #include <string.h> #include "md5.h" /* Prints message digest buffer in mdContext as 32 hexadecimal digits. Order is from low-order byte to high-order byte of digest. Each byte is printed with high-order hexadecimal digit first. */ static void MDPrint (MD5_CTX *mdContext) { int i; for (i = 0; i < 16; i++) printf ("%02x", mdContext->digest[i]); } /* size of test block */ #define TEST_BLOCK_SIZE 1000 /* number of blocks to process */ #define TEST_BLOCKS 10000 /* number of test bytes = TEST_BLOCK_SIZE * TEST_BLOCKS */ static long TEST_BYTES = (long)TEST_BLOCK_SIZE * (long)TEST_BLOCKS; /* A time trial routine, to measure the speed of MD5. Measures wall time required to digest TEST_BLOCKS * TEST_BLOCK_SIZE characters. */ static void MDTimeTrial () { MD5_CTX mdContext; time_t endTime, startTime; unsigned char data[TEST_BLOCK_SIZE]; unsigned int i; /* initialize test data */ for (i = 0; i < TEST_BLOCK_SIZE; i++) data[i] = (unsigned char)(i & 0xFF); /* start timer */ printf ("MD5 time trial. Processing %ld characters...\n", TEST_BYTES); time (&startTime); /* digest data in TEST_BLOCK_SIZE byte blocks */ MD5Init (&mdContext); for (i = TEST_BLOCKS; i > 0; i--) MD5Update (&mdContext, data, TEST_BLOCK_SIZE); MD5Final (&mdContext); /* stop timer, get time difference */ time (&endTime); MDPrint (&mdContext); printf (" is digest of test input.\n"); printf ("Seconds to process test input: %ld\n", (long)(endTime-startTime)); printf ("Characters processed per second: %ld\n", TEST_BYTES/(endTime-startTime)); } /* Computes the message digest for string inString. Prints out message digest, a space, the string (in quotes) and a carriage return. */ static void MDString(const char *inString) { MD5_CTX mdContext; unsigned int len = strlen (inString); MD5Init (&mdContext); MD5Update (&mdContext, (unsigned char *)inString, len); MD5Final (&mdContext); MDPrint (&mdContext); printf (" \"%s\"\n\n", inString); } /* Computes the message digest for a specified file. Prints out message digest, a space, the file name, and a carriage return. */ static void MDFile (const char *filename) { FILE *inFile = fopen (filename, "rb"); MD5_CTX mdContext; int bytes; unsigned char data[1024]; if (inFile == NULL) { printf ("%s can't be opened.\n", filename); return; } MD5Init (&mdContext); while ((bytes = fread (data, 1, 1024, inFile)) != 0) MD5Update (&mdContext, data, bytes); MD5Final (&mdContext); MDPrint (&mdContext); printf (" %s\n", filename); fclose (inFile); } /* Writes the message digest of the data from stdin onto stdout, followed by a carriage return. */ static void MDFilter () { MD5_CTX mdContext; int bytes; unsigned char data[16]; MD5Init (&mdContext); while ((bytes = fread (data, 1, 16, stdin)) != 0) MD5Update (&mdContext, data, bytes); MD5Final (&mdContext); MDPrint (&mdContext); printf ("\n"); } /* Runs a standard suite of test data. */ static void MDTestSuite () { printf ("MD5 test suite results:\n\n"); MDString (""); MDString ("a"); MDString ("abc"); MDString ("message digest"); MDString ("abcdefghijklmnopqrstuvwxyz"); MDString ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"); MDString ("1234567890123456789012345678901234567890\ 1234567890123456789012345678901234567890"); /* Contents of file foo are "abc" */ MDFile ("foo"); } int main (int argc, char *argv[]) { int i; /* For each command line argument in turn: ** filename -- prints message digest and name of file ** -sstring -- prints message digest and contents of string ** -t -- prints time trial statistics for 1M characters ** -x -- execute a standard suite of test data ** (no args) -- writes messages digest of stdin onto stdout */ if (argc == 1) MDFilter (); else for (i = 1; i < argc; i++) if (argv[i][0] == '-' && argv[i][1] == 's') MDString (argv[i] + 2); else if (strcmp (argv[i], "-t") == 0) MDTimeTrial (); else if (strcmp (argv[i], "-x") == 0) MDTestSuite (); else MDFile (argv[i]); exit(0); }
{ "pile_set_name": "Github" }
#import "GPUImageFilter.h" @interface GPUImageFalseColorFilter : GPUImageFilter { GLint firstColorUniform, secondColorUniform; } // The first and second colors specify what colors replace the dark and light areas of the image, respectively. The defaults are (0.0, 0.0, 0.5) amd (1.0, 0.0, 0.0). @property(readwrite, nonatomic) GPUVector4 firstColor; @property(readwrite, nonatomic) GPUVector4 secondColor; - (void)setFirstColorRed:(GLfloat)redComponent green:(GLfloat)greenComponent blue:(GLfloat)blueComponent; - (void)setSecondColorRed:(GLfloat)redComponent green:(GLfloat)greenComponent blue:(GLfloat)blueComponent; @end
{ "pile_set_name": "Github" }
function enum() {}
{ "pile_set_name": "Github" }
all: $(MAKE) -f ../Makefile.lib clean: $(MAKE) -f ../Makefile.lib clean clean_tmp: $(MAKE) -f ../Makefile.lib clean_tmp
{ "pile_set_name": "Github" }
<?php /* * This file is part of Contao. * * (c) Leo Feyer * * @license LGPL-3.0-or-later */ namespace Contao; /** * Provide methods to handle text fields with unit drop down menu. * * @property integer $maxlength * @property boolean $mandatory * @property string $placeholder * @property array $options * * @author Leo Feyer <https://github.com/leofeyer> */ class InputUnit extends \Widget { /** * Submit user input * @var boolean */ protected $blnSubmitInput = true; /** * Template * @var string */ protected $strTemplate = 'be_widget'; /** * Units * @var array */ protected $arrUnits = array(); /** * Add specific attributes * * @param string $strKey * @param mixed $varValue */ public function __set($strKey, $varValue) { switch ($strKey) { case 'maxlength': if ($varValue > 0) { $this->arrAttributes['maxlength'] = $varValue; } break; case 'mandatory': if ($varValue) { $this->arrAttributes['required'] = 'required'; } else { unset($this->arrAttributes['required']); } parent::__set($strKey, $varValue); break; case 'placeholder': $this->arrAttributes['placeholder'] = $varValue; break; case 'options': $this->arrUnits = deserialize($varValue); break; default: parent::__set($strKey, $varValue); break; } } /** * Do not validate unit fields * * @param mixed $varInput * * @return mixed */ protected function validator($varInput) { foreach ($varInput as $k=>$v) { if ($k != 'unit') { $varInput[$k] = parent::validator($v); } } return $varInput; } /** * Only check against the unit values (see #7246) * * @param array $arrOption The options array * * @return string The "selected" attribute or an empty string */ protected function isSelected($arrOption) { if (empty($this->varValue) && empty($_POST) && $arrOption['default']) { return parent::optionSelected(1, 1); } if (empty($this->varValue) || !is_array($this->varValue)) { return ''; } return parent::optionSelected($arrOption['value'], $this->varValue['unit']); } /** * Generate the widget and return it as string * * @return string */ public function generate() { $arrUnits = array(); foreach ($this->arrUnits as $arrUnit) { $arrUnits[] = sprintf('<option value="%s"%s>%s</option>', specialchars($arrUnit['value']), $this->isSelected($arrUnit), $arrUnit['label']); } if (!is_array($this->varValue)) { $this->varValue = array('value'=>$this->varValue); } return sprintf('<input type="text" name="%s[value]" id="ctrl_%s" class="tl_text_unit%s" value="%s"%s onfocus="Backend.getScrollOffset()"> <select name="%s[unit]" class="tl_select_unit" onfocus="Backend.getScrollOffset()"%s>%s</select>%s', $this->strName, $this->strId, (strlen($this->strClass) ? ' ' . $this->strClass : ''), specialchars($this->varValue['value']), $this->getAttributes(), $this->strName, $this->getAttribute('disabled'), implode('', $arrUnits), $this->wizard); } }
{ "pile_set_name": "Github" }
package keeper import ( "github.com/cosmos/cosmos-sdk/codec" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/sdk-tutorials/starport-blog/blog/x/blog/types" ) func (k Keeper) CreatePost(ctx sdk.Context, post types.Post) { store := ctx.KVStore(k.storeKey) key := []byte(types.PostPrefix + post.ID) value := k.cdc.MustMarshalBinaryLengthPrefixed(post) store.Set(key, value) } func listPost(ctx sdk.Context, k Keeper) ([]byte, error) { var postList []types.Post store := ctx.KVStore(k.storeKey) iterator := sdk.KVStorePrefixIterator(store, []byte(types.PostPrefix)) for ; iterator.Valid(); iterator.Next() { var post types.Post k.cdc.MustUnmarshalBinaryLengthPrefixed(store.Get(iterator.Key()), &post) postList = append(postList, post) } res := codec.MustMarshalJSONIndent(k.cdc, postList) return res, nil }
{ "pile_set_name": "Github" }
{ "description": "Decimal128", "bson_type": "0x13", "test_key": "d", "valid": [ { "description": "[basx023] conform to rules and exponent will be in permitted range).", "canonical_bson": "1800000013640001000000000000000000000000003EB000", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"-0.1\"}}" }, { "description": "[basx045] strings without E cannot generate E in result", "canonical_bson": "1800000013640003000000000000000000000000003A3000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"+0.003\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.003\"}}" }, { "description": "[basx610] Zeros", "canonical_bson": "1800000013640000000000000000000000000000003E3000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \".0\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.0\"}}" }, { "description": "[basx612] Zeros", "canonical_bson": "1800000013640000000000000000000000000000003EB000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"-.0\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"-0.0\"}}" }, { "description": "[basx043] strings without E cannot generate E in result", "canonical_bson": "18000000136400FC040000000000000000000000003C3000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"+12.76\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"12.76\"}}" }, { "description": "[basx055] strings without E cannot generate E in result", "canonical_bson": "180000001364000500000000000000000000000000303000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.00000005\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"5E-8\"}}" }, { "description": "[basx054] strings without E cannot generate E in result", "canonical_bson": "180000001364000500000000000000000000000000323000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.0000005\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"5E-7\"}}" }, { "description": "[basx052] strings without E cannot generate E in result", "canonical_bson": "180000001364000500000000000000000000000000343000", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.000005\"}}" }, { "description": "[basx051] strings without E cannot generate E in result", "canonical_bson": "180000001364000500000000000000000000000000363000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"00.00005\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.00005\"}}" }, { "description": "[basx050] strings without E cannot generate E in result", "canonical_bson": "180000001364000500000000000000000000000000383000", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.0005\"}}" }, { "description": "[basx047] strings without E cannot generate E in result", "canonical_bson": "1800000013640005000000000000000000000000003E3000", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \".5\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.5\"}}" }, { "description": "[dqbsr431] check rounding modes heeded (Rounded)", "canonical_bson": "1800000013640099761CC7B548F377DC80A131C836FE2F00", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \"1.1111111111111111111111111111123450\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"1.111111111111111111111111111112345\"}}" }, { "description": "OK2", "canonical_bson": "18000000136400000000000A5BC138938D44C64D31FC2F00", "degenerate_extjson": "{\"d\" : {\"$numberDecimal\" : \".100000000000000000000000000000000000000000000000000000000000\"}}", "canonical_extjson": "{\"d\" : {\"$numberDecimal\" : \"0.1000000000000000000000000000000000\"}}" } ], "parseErrors": [ { "description": "[basx564] Near-specials (Conversion_syntax)", "string": "Infi" }, { "description": "[basx565] Near-specials (Conversion_syntax)", "string": "Infin" }, { "description": "[basx566] Near-specials (Conversion_syntax)", "string": "Infini" }, { "description": "[basx567] Near-specials (Conversion_syntax)", "string": "Infinit" }, { "description": "[basx568] Near-specials (Conversion_syntax)", "string": "-Infinit" }, { "description": "[basx590] some baddies with dots and Es and dots and specials (Conversion_syntax)", "string": ".Infinity" }, { "description": "[basx562] Near-specials (Conversion_syntax)", "string": "NaNq" }, { "description": "[basx563] Near-specials (Conversion_syntax)", "string": "NaNs" }, { "description": "[dqbas939] overflow results at different rounding modes (Overflow & Inexact & Rounded)", "string": "-7e10000" }, { "description": "[dqbsr534] negatives (Rounded & Inexact)", "string": "-1.11111111111111111111111111111234650" }, { "description": "[dqbsr535] negatives (Rounded & Inexact)", "string": "-1.11111111111111111111111111111234551" }, { "description": "[dqbsr533] negatives (Rounded & Inexact)", "string": "-1.11111111111111111111111111111234550" }, { "description": "[dqbsr532] negatives (Rounded & Inexact)", "string": "-1.11111111111111111111111111111234549" }, { "description": "[dqbsr432] check rounding modes heeded (Rounded & Inexact)", "string": "1.11111111111111111111111111111234549" }, { "description": "[dqbsr433] check rounding modes heeded (Rounded & Inexact)", "string": "1.11111111111111111111111111111234550" }, { "description": "[dqbsr435] check rounding modes heeded (Rounded & Inexact)", "string": "1.11111111111111111111111111111234551" }, { "description": "[dqbsr434] check rounding modes heeded (Rounded & Inexact)", "string": "1.11111111111111111111111111111234650" }, { "description": "[dqbas938] overflow results at different rounding modes (Overflow & Inexact & Rounded)", "string": "7e10000" }, { "description": "Inexact rounding#1", "string": "100000000000000000000000000000000000000000000000000000000001" }, { "description": "Inexact rounding#2", "string": "1E-6177" } ] }
{ "pile_set_name": "Github" }